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/ASTDiagnostic.h"
16#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/ExprObjC.h"
23#include "clang/AST/Type.h"
24#include "clang/Basic/Diagnostic.h"
25#include "clang/Basic/DiagnosticOptions.h"
26#include "clang/Basic/OperatorKinds.h"
27#include "clang/Basic/PartialDiagnostic.h"
28#include "clang/Basic/SourceManager.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Sema/EnterExpressionEvaluationContext.h"
31#include "clang/Sema/Initialization.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/Overload.h"
34#include "clang/Sema/SemaAMDGPU.h"
35#include "clang/Sema/SemaARM.h"
36#include "clang/Sema/SemaCUDA.h"
37#include "clang/Sema/SemaInternal.h"
38#include "clang/Sema/SemaObjC.h"
39#include "clang/Sema/Template.h"
40#include "clang/Sema/TemplateDeduction.h"
41#include "llvm/ADT/DenseSet.h"
42#include "llvm/ADT/STLExtras.h"
43#include "llvm/ADT/STLForwardCompat.h"
44#include "llvm/ADT/ScopeExit.h"
45#include "llvm/ADT/SmallPtrSet.h"
46#include "llvm/ADT/SmallVector.h"
47#include <algorithm>
48#include <cassert>
49#include <cstddef>
50#include <cstdlib>
51#include <optional>
52
53using namespace clang;
54using namespace sema;
55
56using AllowedExplicit = Sema::AllowedExplicit;
57
58static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
59 return llvm::any_of(Range: FD->parameters(), P: [](const ParmVarDecl *P) {
60 return P->hasAttr<PassObjectSizeAttr>();
61 });
62}
63
64/// A convenience routine for creating a decayed reference to a function.
65static ExprResult CreateFunctionRefExpr(
66 Sema &S, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
67 FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
68 bool HadMultipleCandidates, const DeclarationNameInfo &NameInfo,
69 const TemplateArgumentListInfo *TemplateArgs) {
70 SourceLocation Loc = NameInfo.getLoc();
71
72 if (S.DiagnoseUseOfDecl(D: FoundDecl, Locs: Loc))
73 return ExprError();
74 // If FoundDecl is different from Fn (such as if one is a template
75 // and the other a specialization), make sure DiagnoseUseOfDecl is
76 // called on both.
77 // FIXME: This would be more comprehensively addressed by modifying
78 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
79 // being used.
80 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(D: Fn, Locs: Loc))
81 return ExprError();
82 auto *DRE = DeclRefExpr::Create(Context: S.Context, QualifierLoc, TemplateKWLoc, D: Fn,
83 /*RefersToEnclosingVariableOrCapture=*/false,
84 NameInfo, T: Fn->getType(), VK: VK_LValue, FoundD: FoundDecl,
85 TemplateArgs);
86 if (HadMultipleCandidates)
87 DRE->setHadMultipleCandidates(true);
88
89 S.MarkDeclRefReferenced(E: DRE, Base);
90 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
91 if (isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType())) {
92 S.ResolveExceptionSpec(Loc, FPT);
93 DRE->setType(Fn->getType());
94 }
95 }
96 return S.ImpCastExprToType(E: DRE, Type: S.Context.getPointerType(T: DRE->getType()),
97 CK: CK_FunctionToPointerDecay);
98}
99
100static ExprResult CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn,
101 NamedDecl *FoundDecl, const Expr *Base,
102 bool HadMultipleCandidates,
103 const DeclarationNameInfo &NameInfo) {
104 return CreateFunctionRefExpr(S, /*QualifierLoc=*/{}, /*TemplateKWLoc=*/{}, Fn,
105 FoundDecl, Base, HadMultipleCandidates, NameInfo,
106 /*TemplateArgs=*/nullptr);
107}
108
109static ExprResult CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn,
110 NamedDecl *FoundDecl, const Expr *Base,
111 bool HadMultipleCandidates,
112 SourceLocation Loc) {
113 return CreateFunctionRefExpr(S, Fn, FoundDecl, Base, HadMultipleCandidates,
114 NameInfo: DeclarationNameInfo(Fn->getDeclName(), Loc));
115}
116
117static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
118 bool InOverloadResolution,
119 StandardConversionSequence &SCS,
120 bool CStyle,
121 bool AllowObjCWritebackConversion);
122
123static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
124 QualType &ToType,
125 bool InOverloadResolution,
126 StandardConversionSequence &SCS,
127 bool CStyle);
128static OverloadingResult
129IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
130 UserDefinedConversionSequence& User,
131 OverloadCandidateSet& Conversions,
132 AllowedExplicit AllowExplicit,
133 bool AllowObjCConversionOnExplicit);
134
135static ImplicitConversionSequence::CompareKind
136CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
137 const StandardConversionSequence& SCS1,
138 const StandardConversionSequence& SCS2);
139
140static ImplicitConversionSequence::CompareKind
141CompareQualificationConversions(Sema &S,
142 const StandardConversionSequence& SCS1,
143 const StandardConversionSequence& SCS2);
144
145static ImplicitConversionSequence::CompareKind
146CompareOverflowBehaviorConversions(Sema &S,
147 const StandardConversionSequence &SCS1,
148 const StandardConversionSequence &SCS2);
149
150static ImplicitConversionSequence::CompareKind
151CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
152 const StandardConversionSequence& SCS1,
153 const StandardConversionSequence& SCS2);
154
155/// GetConversionRank - Retrieve the implicit conversion rank
156/// corresponding to the given implicit conversion kind.
157ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
158 static const ImplicitConversionRank Rank[] = {
159 ICR_Exact_Match,
160 ICR_Exact_Match,
161 ICR_Exact_Match,
162 ICR_Exact_Match,
163 ICR_Exact_Match,
164 ICR_Exact_Match,
165 ICR_Promotion,
166 ICR_Promotion,
167 ICR_Promotion,
168 ICR_Conversion,
169 ICR_Conversion,
170 ICR_Conversion,
171 ICR_Conversion,
172 ICR_Conversion,
173 ICR_Conversion,
174 ICR_Conversion,
175 ICR_Conversion,
176 ICR_Conversion,
177 ICR_Conversion,
178 ICR_Conversion,
179 ICR_Conversion,
180 ICR_OCL_Scalar_Widening,
181 ICR_Complex_Real_Conversion,
182 ICR_Conversion,
183 ICR_Conversion,
184 ICR_Writeback_Conversion,
185 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
186 // it was omitted by the patch that added
187 // ICK_Zero_Event_Conversion
188 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
189 // it was omitted by the patch that added
190 // ICK_Zero_Queue_Conversion
191 ICR_C_Conversion,
192 ICR_C_Conversion_Extension,
193 ICR_Conversion,
194 ICR_HLSL_Dimension_Reduction,
195 ICR_HLSL_Dimension_Reduction,
196 ICR_Conversion,
197 ICR_HLSL_Scalar_Widening,
198 ICR_HLSL_Scalar_Widening,
199 ICR_Conversion,
200 };
201 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
202 return Rank[(int)Kind];
203}
204
205ImplicitConversionRank
206clang::GetDimensionConversionRank(ImplicitConversionRank Base,
207 ImplicitConversionKind Dimension) {
208 ImplicitConversionRank Rank = GetConversionRank(Kind: Dimension);
209 if (Rank == ICR_HLSL_Scalar_Widening) {
210 if (Base == ICR_Promotion)
211 return ICR_HLSL_Scalar_Widening_Promotion;
212 if (Base == ICR_Conversion)
213 return ICR_HLSL_Scalar_Widening_Conversion;
214 }
215 if (Rank == ICR_HLSL_Dimension_Reduction) {
216 if (Base == ICR_Promotion)
217 return ICR_HLSL_Dimension_Reduction_Promotion;
218 if (Base == ICR_Conversion)
219 return ICR_HLSL_Dimension_Reduction_Conversion;
220 }
221 return Rank;
222}
223
224/// GetImplicitConversionName - Return the name of this kind of
225/// implicit conversion.
226static const char *GetImplicitConversionName(ImplicitConversionKind Kind) {
227 static const char *const Name[] = {
228 "No conversion",
229 "Lvalue-to-rvalue",
230 "Array-to-pointer",
231 "Function-to-pointer",
232 "Function pointer conversion",
233 "Qualification",
234 "Integral promotion",
235 "Floating point promotion",
236 "Complex promotion",
237 "Integral conversion",
238 "Floating conversion",
239 "Complex conversion",
240 "Floating-integral conversion",
241 "Pointer conversion",
242 "Pointer-to-member conversion",
243 "Boolean conversion",
244 "Compatible-types conversion",
245 "Derived-to-base conversion",
246 "Vector conversion",
247 "SVE Vector conversion",
248 "RVV Vector conversion",
249 "Vector splat",
250 "Complex-real conversion",
251 "Block Pointer conversion",
252 "Transparent Union Conversion",
253 "Writeback conversion",
254 "OpenCL Zero Event Conversion",
255 "OpenCL Zero Queue Conversion",
256 "C specific type conversion",
257 "Incompatible pointer conversion",
258 "Fixed point conversion",
259 "HLSL vector truncation",
260 "HLSL matrix truncation",
261 "Non-decaying array conversion",
262 "HLSL vector splat",
263 "HLSL matrix splat",
264 "HLSL packed type conversion",
265 };
266 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
267 return Name[Kind];
268}
269
270/// StandardConversionSequence - Set the standard conversion
271/// sequence to the identity conversion.
272void StandardConversionSequence::setAsIdentityConversion() {
273 First = ICK_Identity;
274 Second = ICK_Identity;
275 Dimension = ICK_Identity;
276 Third = ICK_Identity;
277 DeprecatedStringLiteralToCharPtr = false;
278 QualificationIncludesObjCLifetime = false;
279 ReferenceBinding = false;
280 DirectBinding = false;
281 IsLvalueReference = true;
282 BindsToFunctionLvalue = false;
283 BindsToRvalue = false;
284 BindsImplicitObjectArgumentWithoutRefQualifier = false;
285 ObjCLifetimeConversionBinding = false;
286 FromBracedInitList = false;
287 CopyConstructor = nullptr;
288}
289
290/// getRank - Retrieve the rank of this standard conversion sequence
291/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
292/// implicit conversions.
293ImplicitConversionRank StandardConversionSequence::getRank() const {
294 ImplicitConversionRank Rank = ICR_Exact_Match;
295 if (GetConversionRank(Kind: First) > Rank)
296 Rank = GetConversionRank(Kind: First);
297 if (GetConversionRank(Kind: Second) > Rank)
298 Rank = GetConversionRank(Kind: Second);
299 if (GetDimensionConversionRank(Base: Rank, Dimension) > Rank)
300 Rank = GetDimensionConversionRank(Base: Rank, Dimension);
301 if (GetConversionRank(Kind: Third) > Rank)
302 Rank = GetConversionRank(Kind: Third);
303 return Rank;
304}
305
306/// isPointerConversionToBool - Determines whether this conversion is
307/// a conversion of a pointer or pointer-to-member to bool. This is
308/// used as part of the ranking of standard conversion sequences
309/// (C++ 13.3.3.2p4).
310bool StandardConversionSequence::isPointerConversionToBool() const {
311 // Note that FromType has not necessarily been transformed by the
312 // array-to-pointer or function-to-pointer implicit conversions, so
313 // check for their presence as well as checking whether FromType is
314 // a pointer.
315 if (getToType(Idx: 1)->isBooleanType() &&
316 (getFromType()->isPointerType() ||
317 getFromType()->isMemberPointerType() ||
318 getFromType()->isObjCObjectPointerType() ||
319 getFromType()->isBlockPointerType() ||
320 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
321 return true;
322
323 return false;
324}
325
326/// isPointerConversionToVoidPointer - Determines whether this
327/// conversion is a conversion of a pointer to a void pointer. This is
328/// used as part of the ranking of standard conversion sequences (C++
329/// 13.3.3.2p4).
330bool
331StandardConversionSequence::
332isPointerConversionToVoidPointer(ASTContext& Context) const {
333 QualType FromType = getFromType();
334 QualType ToType = getToType(Idx: 1);
335
336 // Note that FromType has not necessarily been transformed by the
337 // array-to-pointer implicit conversion, so check for its presence
338 // and redo the conversion to get a pointer.
339 if (First == ICK_Array_To_Pointer)
340 FromType = Context.getArrayDecayedType(T: FromType);
341
342 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
343 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
344 return ToPtrType->getPointeeType()->isVoidType();
345
346 return false;
347}
348
349/// Skip any implicit casts which could be either part of a narrowing conversion
350/// or after one in an implicit conversion.
351static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
352 const Expr *Converted) {
353 // We can have cleanups wrapping the converted expression; these need to be
354 // preserved so that destructors run if necessary.
355 if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: Converted)) {
356 Expr *Inner =
357 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, Converted: EWC->getSubExpr()));
358 return ExprWithCleanups::Create(C: Ctx, subexpr: Inner, CleanupsHaveSideEffects: EWC->cleanupsHaveSideEffects(),
359 objects: EWC->getObjects());
360 }
361
362 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Converted)) {
363 switch (ICE->getCastKind()) {
364 case CK_NoOp:
365 case CK_IntegralCast:
366 case CK_IntegralToBoolean:
367 case CK_IntegralToFloating:
368 case CK_BooleanToSignedIntegral:
369 case CK_FloatingToIntegral:
370 case CK_FloatingToBoolean:
371 case CK_FloatingCast:
372 Converted = ICE->getSubExpr();
373 continue;
374
375 default:
376 return Converted;
377 }
378 }
379
380 return Converted;
381}
382
383/// Check if this standard conversion sequence represents a narrowing
384/// conversion, according to C++11 [dcl.init.list]p7.
385///
386/// \param Ctx The AST context.
387/// \param Converted The result of applying this standard conversion sequence.
388/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
389/// value of the expression prior to the narrowing conversion.
390/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
391/// type of the expression prior to the narrowing conversion.
392/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
393/// from floating point types to integral types should be ignored.
394/// \param AllowRelaxedEval If true constant expression evaluation is relaxed
395/// to conform MSVC compiler behavior.
396NarrowingKind StandardConversionSequence::getNarrowingKind(
397 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
398 QualType &ConstantType, bool IgnoreFloatToIntegralConversion,
399 bool AllowRelaxedEval) const {
400 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
401 "narrowing check outside C++");
402
403 // C++11 [dcl.init.list]p7:
404 // A narrowing conversion is an implicit conversion ...
405 QualType FromType = getToType(Idx: 0);
406 QualType ToType = getToType(Idx: 1);
407
408 // A conversion to an enumeration type is narrowing if the conversion to
409 // the underlying type is narrowing. This only arises for expressions of
410 // the form 'Enum{init}'.
411 if (const auto *ED = ToType->getAsEnumDecl())
412 ToType = ED->getIntegerType();
413
414 switch (Second) {
415 // 'bool' is an integral type; dispatch to the right place to handle it.
416 case ICK_Boolean_Conversion:
417 if (FromType->isRealFloatingType())
418 goto FloatingIntegralConversion;
419 if (FromType->isIntegralOrUnscopedEnumerationType())
420 goto IntegralConversion;
421 // -- from a pointer type or pointer-to-member type to bool, or
422 return NK_Type_Narrowing;
423
424 // -- from a floating-point type to an integer type, or
425 //
426 // -- from an integer type or unscoped enumeration type to a floating-point
427 // type, except where the source is a constant expression and the actual
428 // value after conversion will fit into the target type and will produce
429 // the original value when converted back to the original type, or
430 case ICK_Floating_Integral:
431 FloatingIntegralConversion:
432 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
433 return NK_Type_Narrowing;
434 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
435 ToType->isRealFloatingType()) {
436 if (IgnoreFloatToIntegralConversion)
437 return NK_Not_Narrowing;
438 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
439 assert(Initializer && "Unknown conversion expression");
440
441 // If it's value-dependent, we can't tell whether it's narrowing.
442 if (Initializer->isValueDependent())
443 return NK_Dependent_Narrowing;
444
445 if (std::optional<llvm::APSInt> IntConstantValue =
446 Initializer->getIntegerConstantExpr(Ctx)) {
447 // Convert the integer to the floating type.
448 llvm::APFloat Result(Ctx.getFloatTypeSemantics(T: ToType));
449 Result.convertFromAPInt(Input: *IntConstantValue, IsSigned: IntConstantValue->isSigned(),
450 RM: llvm::APFloat::rmNearestTiesToEven);
451 // And back.
452 llvm::APSInt ConvertedValue = *IntConstantValue;
453 bool ignored;
454 llvm::APFloat::opStatus Status = Result.convertToInteger(
455 Result&: ConvertedValue, RM: llvm::APFloat::rmTowardZero, IsExact: &ignored);
456 // If the converted-back integer has unspecified value, or if the
457 // resulting value is different, this was a narrowing conversion.
458 if (Status == llvm::APFloat::opInvalidOp ||
459 *IntConstantValue != ConvertedValue) {
460 ConstantValue = APValue(*IntConstantValue);
461 ConstantType = Initializer->getType();
462 return NK_Constant_Narrowing;
463 }
464 } else {
465 // Variables are always narrowings.
466 return NK_Variable_Narrowing;
467 }
468 }
469 return NK_Not_Narrowing;
470
471 // -- from long double to double or float, or from double to float, except
472 // where the source is a constant expression and the actual value after
473 // conversion is within the range of values that can be represented (even
474 // if it cannot be represented exactly), or
475 case ICK_Floating_Conversion:
476 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
477 Ctx.getFloatingTypeOrder(LHS: FromType, RHS: ToType) == 1) {
478 // FromType is larger than ToType.
479 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
480
481 // If it's value-dependent, we can't tell whether it's narrowing.
482 if (Initializer->isValueDependent())
483 return NK_Dependent_Narrowing;
484
485 Expr::EvalResult R;
486 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(Result&: R, Ctx)) ||
487 ((Ctx.getLangOpts().CPlusPlus &&
488 Initializer->isCXX11ConstantExpr(Ctx, Result&: ConstantValue,
489 AllowRelaxedEval)))) {
490 // Constant!
491 if (Ctx.getLangOpts().C23)
492 ConstantValue = R.Val;
493 assert(ConstantValue.isFloat());
494 llvm::APFloat FloatVal = ConstantValue.getFloat();
495 // Convert the source value into the target type.
496 bool ignored;
497 llvm::APFloat Converted = FloatVal;
498 llvm::APFloat::opStatus ConvertStatus =
499 Converted.convert(ToSemantics: Ctx.getFloatTypeSemantics(T: ToType),
500 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
501 Converted.convert(ToSemantics: Ctx.getFloatTypeSemantics(T: FromType),
502 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
503 if (Ctx.getLangOpts().C23) {
504 if (FloatVal.isNaN() && Converted.isNaN() &&
505 !FloatVal.isSignaling() && !Converted.isSignaling()) {
506 // Quiet NaNs are considered the same value, regardless of
507 // payloads.
508 return NK_Not_Narrowing;
509 }
510 // For normal values, check exact equality.
511 if (!Converted.bitwiseIsEqual(RHS: FloatVal)) {
512 ConstantType = Initializer->getType();
513 return NK_Constant_Narrowing;
514 }
515 } else {
516 // If there was no overflow, the source value is within the range of
517 // values that can be represented.
518 if (ConvertStatus & llvm::APFloat::opOverflow) {
519 ConstantType = Initializer->getType();
520 return NK_Constant_Narrowing;
521 }
522 }
523 } else {
524 return NK_Variable_Narrowing;
525 }
526 }
527 return NK_Not_Narrowing;
528
529 // -- from an integer type or unscoped enumeration type to an integer type
530 // that cannot represent all the values of the original type, except where
531 // (CWG2627) -- the source is a bit-field whose width w is less than that
532 // of its type (or, for an enumeration type, its underlying type) and the
533 // target type can represent all the values of a hypothetical extended
534 // integer type with width w and with the same signedness as the original
535 // type or
536 // -- the source is a constant expression and the actual value after
537 // conversion will fit into the target type and will produce the original
538 // value when converted back to the original type.
539 case ICK_Integral_Conversion:
540 IntegralConversion: {
541 assert(FromType->isIntegralOrUnscopedEnumerationType());
542 assert(ToType->isIntegralOrUnscopedEnumerationType());
543 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
544 unsigned FromWidth = Ctx.getIntWidth(T: FromType);
545 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
546 const unsigned ToWidth = Ctx.getIntWidth(T: ToType);
547
548 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
549 bool ToSigned, unsigned ToWidth) {
550 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
551 !(FromSigned && !ToSigned);
552 };
553
554 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
555 return NK_Not_Narrowing;
556
557 // Not all values of FromType can be represented in ToType.
558 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
559
560 bool DependentBitField = false;
561 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
562 if (BitField->getBitWidth()->isValueDependent())
563 DependentBitField = true;
564 else if (unsigned BitFieldWidth = BitField->getBitWidthValue();
565 BitFieldWidth < FromWidth) {
566 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
567 return NK_Not_Narrowing;
568
569 // The initializer will be truncated to the bit-field width
570 FromWidth = BitFieldWidth;
571 }
572 }
573
574 // If it's value-dependent, we can't tell whether it's narrowing.
575 if (Initializer->isValueDependent())
576 return NK_Dependent_Narrowing;
577
578 std::optional<llvm::APSInt> OptInitializerValue =
579 Initializer->getIntegerConstantExpr(Ctx, AllowRelaxedEval);
580 if (!OptInitializerValue) {
581 // If the bit-field width was dependent, it might end up being small
582 // enough to fit in the target type (unless the target type is unsigned
583 // and the source type is signed, in which case it will never fit)
584 if (DependentBitField && !(FromSigned && !ToSigned))
585 return NK_Dependent_Narrowing;
586
587 // Otherwise, such a conversion is always narrowing
588 return NK_Variable_Narrowing;
589 }
590 llvm::APSInt &InitializerValue = *OptInitializerValue;
591 bool Narrowing = false;
592 if (FromWidth < ToWidth) {
593 // Negative -> unsigned is narrowing. Otherwise, more bits is never
594 // narrowing.
595 if (InitializerValue.isSigned() && InitializerValue.isNegative())
596 Narrowing = true;
597 } else {
598 // Add a bit to the InitializerValue so we don't have to worry about
599 // signed vs. unsigned comparisons.
600 InitializerValue =
601 InitializerValue.extend(width: InitializerValue.getBitWidth() + 1);
602 // Convert the initializer to and from the target width and signed-ness.
603 llvm::APSInt ConvertedValue = InitializerValue;
604 ConvertedValue = ConvertedValue.trunc(width: ToWidth);
605 ConvertedValue.setIsSigned(ToSigned);
606 ConvertedValue = ConvertedValue.extend(width: InitializerValue.getBitWidth());
607 ConvertedValue.setIsSigned(InitializerValue.isSigned());
608 // If the result is different, this was a narrowing conversion.
609 if (ConvertedValue != InitializerValue)
610 Narrowing = true;
611 }
612 if (Narrowing) {
613 ConstantType = Initializer->getType();
614 ConstantValue = APValue(InitializerValue);
615 return NK_Constant_Narrowing;
616 }
617
618 return NK_Not_Narrowing;
619 }
620 case ICK_Complex_Real:
621 if (FromType->isComplexType() && !ToType->isComplexType())
622 return NK_Type_Narrowing;
623 return NK_Not_Narrowing;
624
625 case ICK_Floating_Promotion:
626 if (Ctx.getLangOpts().C23) {
627 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
628 Expr::EvalResult R;
629 if (Initializer->EvaluateAsRValue(Result&: R, Ctx)) {
630 ConstantValue = R.Val;
631 assert(ConstantValue.isFloat());
632 llvm::APFloat FloatVal = ConstantValue.getFloat();
633 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
634 // value, the unqualified versions of the type of the initializer and
635 // the corresponding real type of the object declared shall be
636 // compatible.
637 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
638 ConstantType = Initializer->getType();
639 return NK_Constant_Narrowing;
640 }
641 }
642 }
643 return NK_Not_Narrowing;
644 default:
645 // Other kinds of conversions are not narrowings.
646 return NK_Not_Narrowing;
647 }
648}
649
650/// dump - Print this standard conversion sequence to standard
651/// error. Useful for debugging overloading issues.
652LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
653 raw_ostream &OS = llvm::errs();
654 bool PrintedSomething = false;
655 if (First != ICK_Identity) {
656 OS << GetImplicitConversionName(Kind: First);
657 PrintedSomething = true;
658 }
659
660 if (Second != ICK_Identity) {
661 if (PrintedSomething) {
662 OS << " -> ";
663 }
664 OS << GetImplicitConversionName(Kind: Second);
665
666 if (CopyConstructor) {
667 OS << " (by copy constructor)";
668 } else if (DirectBinding) {
669 OS << " (direct reference binding)";
670 } else if (ReferenceBinding) {
671 OS << " (reference binding)";
672 }
673 PrintedSomething = true;
674 }
675
676 if (Third != ICK_Identity) {
677 if (PrintedSomething) {
678 OS << " -> ";
679 }
680 OS << GetImplicitConversionName(Kind: Third);
681 PrintedSomething = true;
682 }
683
684 if (!PrintedSomething) {
685 OS << "No conversions required";
686 }
687}
688
689/// dump - Print this user-defined conversion sequence to standard
690/// error. Useful for debugging overloading issues.
691void UserDefinedConversionSequence::dump() const {
692 raw_ostream &OS = llvm::errs();
693 if (Before.First || Before.Second || Before.Third) {
694 Before.dump();
695 OS << " -> ";
696 }
697 if (ConversionFunction)
698 OS << '\'' << *ConversionFunction << '\'';
699 else
700 OS << "aggregate initialization";
701 if (After.First || After.Second || After.Third) {
702 OS << " -> ";
703 After.dump();
704 }
705}
706
707/// dump - Print this implicit conversion sequence to standard
708/// error. Useful for debugging overloading issues.
709void ImplicitConversionSequence::dump() const {
710 raw_ostream &OS = llvm::errs();
711 if (hasInitializerListContainerType())
712 OS << "Worst list element conversion: ";
713 switch (ConversionKind) {
714 case StandardConversion:
715 OS << "Standard conversion: ";
716 Standard.dump();
717 break;
718 case UserDefinedConversion:
719 OS << "User-defined conversion: ";
720 UserDefined.dump();
721 break;
722 case EllipsisConversion:
723 OS << "Ellipsis conversion";
724 break;
725 case AmbiguousConversion:
726 OS << "Ambiguous conversion";
727 break;
728 case BadConversion:
729 OS << "Bad conversion";
730 break;
731 }
732
733 OS << "\n";
734}
735
736void AmbiguousConversionSequence::construct() {
737 new (&conversions()) ConversionSet();
738}
739
740void AmbiguousConversionSequence::destruct() {
741 conversions().~ConversionSet();
742}
743
744void
745AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
746 FromTypePtr = O.FromTypePtr;
747 ToTypePtr = O.ToTypePtr;
748 new (&conversions()) ConversionSet(O.conversions());
749}
750
751namespace {
752 // Structure used by DeductionFailureInfo to store
753 // template argument information.
754 struct DFIArguments {
755 TemplateArgument FirstArg;
756 TemplateArgument SecondArg;
757 };
758 // Structure used by DeductionFailureInfo to store
759 // template parameter and template argument information.
760 struct DFIParamWithArguments : DFIArguments {
761 TemplateParameter Param;
762 };
763 // Structure used by DeductionFailureInfo to store template argument
764 // information and the index of the problematic call argument.
765 struct DFIDeducedMismatchArgs : DFIArguments {
766 TemplateArgumentList *TemplateArgs;
767 unsigned CallArgIndex;
768 };
769 // Structure used by DeductionFailureInfo to store information about
770 // unsatisfied constraints.
771 struct CNSInfo {
772 TemplateArgumentList *TemplateArgs;
773 ConstraintSatisfaction Satisfaction;
774 };
775}
776
777/// Convert from Sema's representation of template deduction information
778/// to the form used in overload-candidate information.
779DeductionFailureInfo
780clang::MakeDeductionFailureInfo(ASTContext &Context,
781 TemplateDeductionResult TDK,
782 TemplateDeductionInfo &Info) {
783 DeductionFailureInfo Result;
784 Result.Result = static_cast<unsigned>(TDK);
785 Result.HasDiagnostic = false;
786 switch (TDK) {
787 case TemplateDeductionResult::Invalid:
788 case TemplateDeductionResult::InstantiationDepth:
789 case TemplateDeductionResult::TooManyArguments:
790 case TemplateDeductionResult::TooFewArguments:
791 case TemplateDeductionResult::MiscellaneousDeductionFailure:
792 case TemplateDeductionResult::CUDATargetMismatch:
793 Result.Data = nullptr;
794 break;
795
796 case TemplateDeductionResult::Incomplete:
797 Result.Data = Info.Param.getOpaqueValue();
798 break;
799 case TemplateDeductionResult::InvalidExplicitArguments:
800 Result.Data = Info.Param.getOpaqueValue();
801 if (Info.hasSFINAEDiagnostic()) {
802 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
803 SourceLocation(), PartialDiagnostic::NullDiagnostic());
804 Info.takeSFINAEDiagnostic(PD&: *Diag);
805 Result.HasDiagnostic = true;
806 }
807 break;
808
809 case TemplateDeductionResult::DeducedMismatch:
810 case TemplateDeductionResult::DeducedMismatchNested: {
811 // FIXME: Should allocate from normal heap so that we can free this later.
812 auto *Saved = new (Context) DFIDeducedMismatchArgs;
813 Saved->FirstArg = Info.FirstArg;
814 Saved->SecondArg = Info.SecondArg;
815 Saved->TemplateArgs = Info.takeSugared();
816 Saved->CallArgIndex = Info.CallArgIndex;
817 Result.Data = Saved;
818 break;
819 }
820
821 case TemplateDeductionResult::NonDeducedMismatch: {
822 // FIXME: Should allocate from normal heap so that we can free this later.
823 DFIArguments *Saved = new (Context) DFIArguments;
824 Saved->FirstArg = Info.FirstArg;
825 Saved->SecondArg = Info.SecondArg;
826 Result.Data = Saved;
827 break;
828 }
829
830 case TemplateDeductionResult::IncompletePack:
831 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
832 case TemplateDeductionResult::Inconsistent:
833 case TemplateDeductionResult::Underqualified: {
834 // FIXME: Should allocate from normal heap so that we can free this later.
835 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
836 Saved->Param = Info.Param;
837 Saved->FirstArg = Info.FirstArg;
838 Saved->SecondArg = Info.SecondArg;
839 Result.Data = Saved;
840 break;
841 }
842
843 case TemplateDeductionResult::SubstitutionFailure:
844 Result.Data = Info.takeSugared();
845 if (Info.hasSFINAEDiagnostic()) {
846 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
847 SourceLocation(), PartialDiagnostic::NullDiagnostic());
848 Info.takeSFINAEDiagnostic(PD&: *Diag);
849 Result.HasDiagnostic = true;
850 }
851 break;
852
853 case TemplateDeductionResult::ConstraintsNotSatisfied: {
854 CNSInfo *Saved = new (Context) CNSInfo;
855 Saved->TemplateArgs = Info.takeSugared();
856 Saved->Satisfaction = std::move(Info.AssociatedConstraintsSatisfaction);
857 Result.Data = Saved;
858 break;
859 }
860
861 case TemplateDeductionResult::Success:
862 case TemplateDeductionResult::NonDependentConversionFailure:
863 case TemplateDeductionResult::AlreadyDiagnosed:
864 llvm_unreachable("not a deduction failure");
865 }
866
867 return Result;
868}
869
870void DeductionFailureInfo::Destroy() {
871 switch (static_cast<TemplateDeductionResult>(Result)) {
872 case TemplateDeductionResult::Success:
873 case TemplateDeductionResult::Invalid:
874 case TemplateDeductionResult::InstantiationDepth:
875 case TemplateDeductionResult::Incomplete:
876 case TemplateDeductionResult::TooManyArguments:
877 case TemplateDeductionResult::TooFewArguments:
878 case TemplateDeductionResult::CUDATargetMismatch:
879 case TemplateDeductionResult::NonDependentConversionFailure:
880 break;
881
882 case TemplateDeductionResult::IncompletePack:
883 case TemplateDeductionResult::Inconsistent:
884 case TemplateDeductionResult::Underqualified:
885 case TemplateDeductionResult::DeducedMismatch:
886 case TemplateDeductionResult::DeducedMismatchNested:
887 case TemplateDeductionResult::NonDeducedMismatch:
888 // FIXME: Destroy the data?
889 Data = nullptr;
890 break;
891
892 case TemplateDeductionResult::InvalidExplicitArguments:
893 case TemplateDeductionResult::SubstitutionFailure:
894 // FIXME: Destroy the template argument list?
895 Data = nullptr;
896 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
897 Diag->~PartialDiagnosticAt();
898 HasDiagnostic = false;
899 }
900 break;
901
902 case TemplateDeductionResult::ConstraintsNotSatisfied:
903 // FIXME: Destroy the template argument list?
904 static_cast<CNSInfo *>(Data)->Satisfaction.~ConstraintSatisfaction();
905 Data = nullptr;
906 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
907 Diag->~PartialDiagnosticAt();
908 HasDiagnostic = false;
909 }
910 break;
911
912 // Unhandled
913 case TemplateDeductionResult::MiscellaneousDeductionFailure:
914 case TemplateDeductionResult::AlreadyDiagnosed:
915 break;
916 }
917}
918
919PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
920 if (HasDiagnostic)
921 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
922 return nullptr;
923}
924
925TemplateParameter DeductionFailureInfo::getTemplateParameter() {
926 switch (static_cast<TemplateDeductionResult>(Result)) {
927 case TemplateDeductionResult::Success:
928 case TemplateDeductionResult::Invalid:
929 case TemplateDeductionResult::InstantiationDepth:
930 case TemplateDeductionResult::TooManyArguments:
931 case TemplateDeductionResult::TooFewArguments:
932 case TemplateDeductionResult::SubstitutionFailure:
933 case TemplateDeductionResult::DeducedMismatch:
934 case TemplateDeductionResult::DeducedMismatchNested:
935 case TemplateDeductionResult::NonDeducedMismatch:
936 case TemplateDeductionResult::CUDATargetMismatch:
937 case TemplateDeductionResult::NonDependentConversionFailure:
938 case TemplateDeductionResult::ConstraintsNotSatisfied:
939 return TemplateParameter();
940
941 case TemplateDeductionResult::Incomplete:
942 case TemplateDeductionResult::InvalidExplicitArguments:
943 return TemplateParameter::getFromOpaqueValue(VP: Data);
944
945 case TemplateDeductionResult::IncompletePack:
946 case TemplateDeductionResult::Inconsistent:
947 case TemplateDeductionResult::Underqualified:
948 return static_cast<DFIParamWithArguments*>(Data)->Param;
949
950 // Unhandled
951 case TemplateDeductionResult::MiscellaneousDeductionFailure:
952 case TemplateDeductionResult::AlreadyDiagnosed:
953 break;
954 }
955
956 return TemplateParameter();
957}
958
959TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
960 switch (static_cast<TemplateDeductionResult>(Result)) {
961 case TemplateDeductionResult::Success:
962 case TemplateDeductionResult::Invalid:
963 case TemplateDeductionResult::InstantiationDepth:
964 case TemplateDeductionResult::TooManyArguments:
965 case TemplateDeductionResult::TooFewArguments:
966 case TemplateDeductionResult::Incomplete:
967 case TemplateDeductionResult::IncompletePack:
968 case TemplateDeductionResult::InvalidExplicitArguments:
969 case TemplateDeductionResult::Inconsistent:
970 case TemplateDeductionResult::Underqualified:
971 case TemplateDeductionResult::NonDeducedMismatch:
972 case TemplateDeductionResult::CUDATargetMismatch:
973 case TemplateDeductionResult::NonDependentConversionFailure:
974 return nullptr;
975
976 case TemplateDeductionResult::DeducedMismatch:
977 case TemplateDeductionResult::DeducedMismatchNested:
978 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
979
980 case TemplateDeductionResult::SubstitutionFailure:
981 return static_cast<TemplateArgumentList*>(Data);
982
983 case TemplateDeductionResult::ConstraintsNotSatisfied:
984 return static_cast<CNSInfo*>(Data)->TemplateArgs;
985
986 // Unhandled
987 case TemplateDeductionResult::MiscellaneousDeductionFailure:
988 case TemplateDeductionResult::AlreadyDiagnosed:
989 break;
990 }
991
992 return nullptr;
993}
994
995const TemplateArgument *DeductionFailureInfo::getFirstArg() {
996 switch (static_cast<TemplateDeductionResult>(Result)) {
997 case TemplateDeductionResult::Success:
998 case TemplateDeductionResult::Invalid:
999 case TemplateDeductionResult::InstantiationDepth:
1000 case TemplateDeductionResult::Incomplete:
1001 case TemplateDeductionResult::TooManyArguments:
1002 case TemplateDeductionResult::TooFewArguments:
1003 case TemplateDeductionResult::InvalidExplicitArguments:
1004 case TemplateDeductionResult::SubstitutionFailure:
1005 case TemplateDeductionResult::CUDATargetMismatch:
1006 case TemplateDeductionResult::NonDependentConversionFailure:
1007 case TemplateDeductionResult::ConstraintsNotSatisfied:
1008 return nullptr;
1009
1010 case TemplateDeductionResult::IncompletePack:
1011 case TemplateDeductionResult::Inconsistent:
1012 case TemplateDeductionResult::Underqualified:
1013 case TemplateDeductionResult::DeducedMismatch:
1014 case TemplateDeductionResult::DeducedMismatchNested:
1015 case TemplateDeductionResult::NonDeducedMismatch:
1016 return &static_cast<DFIArguments*>(Data)->FirstArg;
1017
1018 // Unhandled
1019 case TemplateDeductionResult::MiscellaneousDeductionFailure:
1020 case TemplateDeductionResult::AlreadyDiagnosed:
1021 break;
1022 }
1023
1024 return nullptr;
1025}
1026
1027const TemplateArgument *DeductionFailureInfo::getSecondArg() {
1028 switch (static_cast<TemplateDeductionResult>(Result)) {
1029 case TemplateDeductionResult::Success:
1030 case TemplateDeductionResult::Invalid:
1031 case TemplateDeductionResult::InstantiationDepth:
1032 case TemplateDeductionResult::Incomplete:
1033 case TemplateDeductionResult::IncompletePack:
1034 case TemplateDeductionResult::TooManyArguments:
1035 case TemplateDeductionResult::TooFewArguments:
1036 case TemplateDeductionResult::InvalidExplicitArguments:
1037 case TemplateDeductionResult::SubstitutionFailure:
1038 case TemplateDeductionResult::CUDATargetMismatch:
1039 case TemplateDeductionResult::NonDependentConversionFailure:
1040 case TemplateDeductionResult::ConstraintsNotSatisfied:
1041 return nullptr;
1042
1043 case TemplateDeductionResult::Inconsistent:
1044 case TemplateDeductionResult::Underqualified:
1045 case TemplateDeductionResult::DeducedMismatch:
1046 case TemplateDeductionResult::DeducedMismatchNested:
1047 case TemplateDeductionResult::NonDeducedMismatch:
1048 return &static_cast<DFIArguments*>(Data)->SecondArg;
1049
1050 // Unhandled
1051 case TemplateDeductionResult::MiscellaneousDeductionFailure:
1052 case TemplateDeductionResult::AlreadyDiagnosed:
1053 break;
1054 }
1055
1056 return nullptr;
1057}
1058
1059UnsignedOrNone DeductionFailureInfo::getCallArgIndex() {
1060 switch (static_cast<TemplateDeductionResult>(Result)) {
1061 case TemplateDeductionResult::DeducedMismatch:
1062 case TemplateDeductionResult::DeducedMismatchNested:
1063 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1064
1065 default:
1066 return std::nullopt;
1067 }
1068}
1069
1070static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X,
1071 const FunctionDecl *Y) {
1072 if (!X || !Y)
1073 return false;
1074 if (X->getNumParams() != Y->getNumParams())
1075 return false;
1076 // FIXME: when do rewritten comparison operators
1077 // with explicit object parameters correspond?
1078 // https://cplusplus.github.io/CWG/issues/2797.html
1079 for (unsigned I = 0; I < X->getNumParams(); ++I)
1080 if (!Ctx.hasSameUnqualifiedType(T1: X->getParamDecl(i: I)->getType(),
1081 T2: Y->getParamDecl(i: I)->getType()))
1082 return false;
1083 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1084 auto *FTY = Y->getDescribedFunctionTemplate();
1085 if (!FTY)
1086 return false;
1087 if (!Ctx.isSameTemplateParameterList(X: FTX->getTemplateParameters(),
1088 Y: FTY->getTemplateParameters()))
1089 return false;
1090 }
1091 return true;
1092}
1093
1094static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc,
1095 Expr *FirstOperand, FunctionDecl *EqFD) {
1096 assert(EqFD->getOverloadedOperator() ==
1097 OverloadedOperatorKind::OO_EqualEqual);
1098 // C++2a [over.match.oper]p4:
1099 // A non-template function or function template F named operator== is a
1100 // rewrite target with first operand o unless a search for the name operator!=
1101 // in the scope S from the instantiation context of the operator expression
1102 // finds a function or function template that would correspond
1103 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1104 // scope of the class type of o if F is a class member, and the namespace
1105 // scope of which F is a member otherwise. A function template specialization
1106 // named operator== is a rewrite target if its function template is a rewrite
1107 // target.
1108 DeclarationName NotEqOp = S.Context.DeclarationNames.getCXXOperatorName(
1109 Op: OverloadedOperatorKind::OO_ExclaimEqual);
1110 if (isa<CXXMethodDecl>(Val: EqFD)) {
1111 // If F is a class member, search scope is class type of first operand.
1112 QualType RHS = FirstOperand->getType();
1113 auto *RHSRec = RHS->getAsCXXRecordDecl();
1114 if (!RHSRec)
1115 return true;
1116 LookupResult Members(S, NotEqOp, OpLoc,
1117 Sema::LookupNameKind::LookupMemberName);
1118 S.LookupQualifiedName(R&: Members, LookupCtx: RHSRec);
1119 Members.suppressAccessDiagnostics();
1120 for (NamedDecl *Op : Members)
1121 if (FunctionsCorrespond(Ctx&: S.Context, X: EqFD, Y: Op->getAsFunction()))
1122 return false;
1123 return true;
1124 }
1125 // Otherwise the search scope is the namespace scope of which F is a member.
1126 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(Name: NotEqOp)) {
1127 auto *NotEqFD = Op->getAsFunction();
1128 if (auto *UD = dyn_cast<UsingShadowDecl>(Val: Op))
1129 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1130 if (FunctionsCorrespond(Ctx&: S.Context, X: EqFD, Y: NotEqFD) && S.isVisible(D: NotEqFD) &&
1131 declaresSameEntity(D1: cast<Decl>(Val: EqFD->getEnclosingNamespaceContext()),
1132 D2: cast<Decl>(Val: Op->getLexicalDeclContext())))
1133 return false;
1134 }
1135 return true;
1136}
1137
1138bool OverloadCandidateSet::OperatorRewriteInfo::allowsReversed(
1139 OverloadedOperatorKind Op) const {
1140 if (!AllowRewrittenCandidates)
1141 return false;
1142 return Op == OO_EqualEqual || Op == OO_Spaceship;
1143}
1144
1145bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
1146 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) const {
1147 auto Op = FD->getOverloadedOperator();
1148 if (!allowsReversed(Op))
1149 return false;
1150 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1151 assert(OriginalArgs.size() == 2);
1152 if (!shouldAddReversedEqEq(
1153 S, OpLoc, /*FirstOperand in reversed args*/ FirstOperand: OriginalArgs[1], EqFD: FD))
1154 return false;
1155 }
1156 // Don't bother adding a reversed candidate that can never be a better
1157 // match than the non-reversed version.
1158 return FD->getNumNonObjectParams() != 2 ||
1159 !S.Context.hasSameUnqualifiedType(T1: FD->getParamDecl(i: 0)->getType(),
1160 T2: FD->getParamDecl(i: 1)->getType()) ||
1161 FD->hasAttr<EnableIfAttr>();
1162}
1163
1164void OverloadCandidateSet::destroyCandidates() {
1165 for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {
1166 for (auto &C : i->Conversions)
1167 C.~ImplicitConversionSequence();
1168 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1169 i->DeductionFailure.Destroy();
1170 }
1171}
1172
1173void OverloadCandidateSet::clear(CandidateSetKind CSK) {
1174 destroyCandidates();
1175 SlabAllocator.Reset();
1176 NumInlineBytesUsed = 0;
1177 Candidates.clear();
1178 Functions.clear();
1179 Kind = CSK;
1180 FirstDeferredCandidate = nullptr;
1181 DeferredCandidatesCount = 0;
1182 HasDeferredTemplateConstructors = false;
1183 ResolutionByPerfectCandidateIsDisabled = false;
1184}
1185
1186namespace {
1187 class UnbridgedCastsSet {
1188 struct Entry {
1189 Expr **Addr;
1190 Expr *Saved;
1191 };
1192 SmallVector<Entry, 2> Entries;
1193
1194 public:
1195 void save(Sema &S, Expr *&E) {
1196 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1197 Entry entry = { .Addr: &E, .Saved: E };
1198 Entries.push_back(Elt: entry);
1199 E = S.ObjC().stripARCUnbridgedCast(e: E);
1200 }
1201
1202 void restore() {
1203 for (SmallVectorImpl<Entry>::iterator
1204 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1205 *i->Addr = i->Saved;
1206 }
1207 };
1208}
1209
1210/// checkPlaceholderForOverload - Do any interesting placeholder-like
1211/// preprocessing on the given expression.
1212///
1213/// \param unbridgedCasts a collection to which to add unbridged casts;
1214/// without this, they will be immediately diagnosed as errors
1215///
1216/// Return true on unrecoverable error.
1217static bool
1218checkPlaceholderForOverload(Sema &S, Expr *&E,
1219 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1220 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1221 // We can't handle overloaded expressions here because overload
1222 // resolution might reasonably tweak them.
1223 if (placeholder->getKind() == BuiltinType::Overload) return false;
1224
1225 // If the context potentially accepts unbridged ARC casts, strip
1226 // the unbridged cast and add it to the collection for later restoration.
1227 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1228 unbridgedCasts) {
1229 unbridgedCasts->save(S, E);
1230 return false;
1231 }
1232
1233 // Go ahead and check everything else.
1234 ExprResult result = S.CheckPlaceholderExpr(E);
1235 if (result.isInvalid())
1236 return true;
1237
1238 E = result.get();
1239 return false;
1240 }
1241
1242 // Nothing to do.
1243 return false;
1244}
1245
1246/// checkArgPlaceholdersForOverload - Check a set of call operands for
1247/// placeholders.
1248static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args,
1249 UnbridgedCastsSet &unbridged) {
1250 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1251 if (checkPlaceholderForOverload(S, E&: Args[i], unbridgedCasts: &unbridged))
1252 return true;
1253
1254 return false;
1255}
1256
1257OverloadKind Sema::CheckOverload(Scope *S, FunctionDecl *New,
1258 const LookupResult &Old, NamedDecl *&Match,
1259 bool NewIsUsingDecl) {
1260 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1261 I != E; ++I) {
1262 NamedDecl *OldD = *I;
1263
1264 bool OldIsUsingDecl = false;
1265 if (isa<UsingShadowDecl>(Val: OldD)) {
1266 OldIsUsingDecl = true;
1267
1268 // We can always introduce two using declarations into the same
1269 // context, even if they have identical signatures.
1270 if (NewIsUsingDecl) continue;
1271
1272 OldD = cast<UsingShadowDecl>(Val: OldD)->getTargetDecl();
1273 }
1274
1275 // A using-declaration does not conflict with another declaration
1276 // if one of them is hidden.
1277 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(D: *I))
1278 continue;
1279
1280 // If either declaration was introduced by a using declaration,
1281 // we'll need to use slightly different rules for matching.
1282 // Essentially, these rules are the normal rules, except that
1283 // function templates hide function templates with different
1284 // return types or template parameter lists.
1285 bool UseMemberUsingDeclRules =
1286 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1287 !New->getFriendObjectKind();
1288
1289 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1290 if (!IsOverload(New, Old: OldF, UseMemberUsingDeclRules)) {
1291 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1292 HideUsingShadowDecl(S, Shadow: cast<UsingShadowDecl>(Val: *I));
1293 continue;
1294 }
1295
1296 if (!isa<FunctionTemplateDecl>(Val: OldD) &&
1297 !shouldLinkPossiblyHiddenDecl(Old: *I, New))
1298 continue;
1299
1300 Match = *I;
1301 return OverloadKind::Match;
1302 }
1303
1304 // Builtins that have custom typechecking or have a reference should
1305 // not be overloadable or redeclarable.
1306 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1307 Match = *I;
1308 return OverloadKind::NonFunction;
1309 }
1310 } else if (isa<UsingDecl>(Val: OldD) || isa<UsingPackDecl>(Val: OldD)) {
1311 // We can overload with these, which can show up when doing
1312 // redeclaration checks for UsingDecls.
1313 assert(Old.getLookupKind() == LookupUsingDeclName);
1314 } else if (isa<TagDecl>(Val: OldD)) {
1315 // We can always overload with tags by hiding them.
1316 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(Val: OldD)) {
1317 // Optimistically assume that an unresolved using decl will
1318 // overload; if it doesn't, we'll have to diagnose during
1319 // template instantiation.
1320 //
1321 // Exception: if the scope is dependent and this is not a class
1322 // member, the using declaration can only introduce an enumerator.
1323 if (UUD->getQualifier().isDependent() && !UUD->isCXXClassMember()) {
1324 Match = *I;
1325 return OverloadKind::NonFunction;
1326 }
1327 } else {
1328 // (C++ 13p1):
1329 // Only function declarations can be overloaded; object and type
1330 // declarations cannot be overloaded.
1331 Match = *I;
1332 return OverloadKind::NonFunction;
1333 }
1334 }
1335
1336 // C++ [temp.friend]p1:
1337 // For a friend function declaration that is not a template declaration:
1338 // -- if the name of the friend is a qualified or unqualified template-id,
1339 // [...], otherwise
1340 // -- if the name of the friend is a qualified-id and a matching
1341 // non-template function is found in the specified class or namespace,
1342 // the friend declaration refers to that function, otherwise,
1343 // -- if the name of the friend is a qualified-id and a matching function
1344 // template is found in the specified class or namespace, the friend
1345 // declaration refers to the deduced specialization of that function
1346 // template, otherwise
1347 // -- the name shall be an unqualified-id [...]
1348 // If we get here for a qualified friend declaration, we've just reached the
1349 // third bullet. If the type of the friend is dependent, skip this lookup
1350 // until instantiation.
1351 if (New->getFriendObjectKind() && New->getQualifier() &&
1352 !New->getDescribedFunctionTemplate() &&
1353 !New->getDependentSpecializationInfo() &&
1354 !New->getType()->isDependentType()) {
1355 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1356 TemplateSpecResult.addAllDecls(Other: Old);
1357 if (CheckFunctionTemplateSpecialization(FD: New, ExplicitTemplateArgs: nullptr, Previous&: TemplateSpecResult,
1358 /*QualifiedFriend*/true)) {
1359 New->setInvalidDecl();
1360 return OverloadKind::Overload;
1361 }
1362
1363 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1364 return OverloadKind::Match;
1365 }
1366
1367 return OverloadKind::Overload;
1368}
1369
1370template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1371 assert(D && "function decl should not be null");
1372 if (auto *A = D->getAttr<AttrT>())
1373 return !A->isImplicit();
1374 return false;
1375}
1376
1377static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New,
1378 FunctionDecl *Old,
1379 bool UseMemberUsingDeclRules,
1380 bool ConsiderCudaAttrs,
1381 bool UseOverrideRules = false) {
1382 // C++ [basic.start.main]p2: This function shall not be overloaded.
1383 if (New->isMain())
1384 return false;
1385
1386 // MSVCRT user defined entry points cannot be overloaded.
1387 if (New->isMSVCRTEntryPoint())
1388 return false;
1389
1390 NamedDecl *OldDecl = Old;
1391 NamedDecl *NewDecl = New;
1392 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1393 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1394
1395 // C++ [temp.fct]p2:
1396 // A function template can be overloaded with other function templates
1397 // and with normal (non-template) functions.
1398 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1399 return true;
1400
1401 // Is the function New an overload of the function Old?
1402 QualType OldQType = SemaRef.Context.getCanonicalType(T: Old->getType());
1403 QualType NewQType = SemaRef.Context.getCanonicalType(T: New->getType());
1404
1405 // Compare the signatures (C++ 1.3.10) of the two functions to
1406 // determine whether they are overloads. If we find any mismatch
1407 // in the signature, they are overloads.
1408
1409 // If either of these functions is a K&R-style function (no
1410 // prototype), then we consider them to have matching signatures.
1411 if (isa<FunctionNoProtoType>(Val: OldQType.getTypePtr()) ||
1412 isa<FunctionNoProtoType>(Val: NewQType.getTypePtr()))
1413 return false;
1414
1415 const auto *OldType = cast<FunctionProtoType>(Val&: OldQType);
1416 const auto *NewType = cast<FunctionProtoType>(Val&: NewQType);
1417
1418 // The signature of a function includes the types of its
1419 // parameters (C++ 1.3.10), which includes the presence or absence
1420 // of the ellipsis; see C++ DR 357).
1421 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1422 return true;
1423
1424 // For member-like friends, the enclosing class is part of the signature.
1425 if ((New->isMemberLikeConstrainedFriend() ||
1426 Old->isMemberLikeConstrainedFriend()) &&
1427 !New->getLexicalDeclContext()->Equals(DC: Old->getLexicalDeclContext()))
1428 return true;
1429
1430 // Compare the parameter lists.
1431 // This can only be done once we have establish that friend functions
1432 // inhabit the same context, otherwise we might tried to instantiate
1433 // references to non-instantiated entities during constraint substitution.
1434 // GH78101.
1435 if (NewTemplate) {
1436 OldDecl = OldTemplate;
1437 NewDecl = NewTemplate;
1438 // C++ [temp.over.link]p4:
1439 // The signature of a function template consists of its function
1440 // signature, its return type and its template parameter list. The names
1441 // of the template parameters are significant only for establishing the
1442 // relationship between the template parameters and the rest of the
1443 // signature.
1444 //
1445 // We check the return type and template parameter lists for function
1446 // templates first; the remaining checks follow.
1447 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1448 NewInstFrom: NewTemplate, New: NewTemplate->getTemplateParameters(), OldInstFrom: OldTemplate,
1449 Old: OldTemplate->getTemplateParameters(), Complain: false, Kind: Sema::TPL_TemplateMatch);
1450 bool SameReturnType = SemaRef.Context.hasSameType(
1451 T1: Old->getDeclaredReturnType(), T2: New->getDeclaredReturnType());
1452 // FIXME(GH58571): Match template parameter list even for non-constrained
1453 // template heads. This currently ensures that the code prior to C++20 is
1454 // not newly broken.
1455 bool ConstraintsInTemplateHead =
1456 NewTemplate->getTemplateParameters()->hasAssociatedConstraints() ||
1457 OldTemplate->getTemplateParameters()->hasAssociatedConstraints();
1458 // C++ [namespace.udecl]p11:
1459 // The set of declarations named by a using-declarator that inhabits a
1460 // class C does not include member functions and member function
1461 // templates of a base class that "correspond" to (and thus would
1462 // conflict with) a declaration of a function or function template in
1463 // C.
1464 // Comparing return types is not required for the "correspond" check to
1465 // decide whether a member introduced by a shadow declaration is hidden.
1466 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1467 !SameTemplateParameterList)
1468 return true;
1469 if (!UseMemberUsingDeclRules &&
1470 (!SameTemplateParameterList || !SameReturnType))
1471 return true;
1472 }
1473
1474 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Val: Old);
1475 const auto *NewMethod = dyn_cast<CXXMethodDecl>(Val: New);
1476
1477 int OldParamsOffset = 0;
1478 int NewParamsOffset = 0;
1479
1480 // When determining if a method is an overload from a base class, act as if
1481 // the implicit object parameter are of the same type.
1482
1483 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1484 if (M->isExplicitObjectMemberFunction()) {
1485 auto ThisType = M->getFunctionObjectParameterReferenceType();
1486 if (ThisType.isConstQualified())
1487 Q.removeConst();
1488 return Q;
1489 }
1490
1491 // We do not allow overloading based off of '__restrict'.
1492 Q.removeRestrict();
1493
1494 // We may not have applied the implicit const for a constexpr member
1495 // function yet (because we haven't yet resolved whether this is a static
1496 // or non-static member function). Add it now, on the assumption that this
1497 // is a redeclaration of OldMethod.
1498 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1499 (M->isConstexpr() || M->isConsteval()) &&
1500 !isa<CXXConstructorDecl>(Val: NewMethod))
1501 Q.addConst();
1502 return Q;
1503 };
1504
1505 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1506 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1507 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1508
1509 if (OldMethod->isExplicitObjectMemberFunction()) {
1510 BS.Quals.removeVolatile();
1511 DS.Quals.removeVolatile();
1512 }
1513
1514 return BS.Quals == DS.Quals;
1515 };
1516
1517 auto CompareType = [&](QualType Base, QualType D) {
1518 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1519 auto DS = D.getNonReferenceType().getCanonicalType().split();
1520
1521 if (!AreQualifiersEqual(BS, DS))
1522 return false;
1523
1524 if (OldMethod->isImplicitObjectMemberFunction() &&
1525 OldMethod->getParent() != NewMethod->getParent()) {
1526 CanQualType ParentType =
1527 SemaRef.Context.getCanonicalTagType(TD: OldMethod->getParent());
1528 if (ParentType.getTypePtr() != BS.Ty)
1529 return false;
1530 BS.Ty = DS.Ty;
1531 }
1532
1533 // FIXME: should we ignore some type attributes here?
1534 if (BS.Ty != DS.Ty)
1535 return false;
1536
1537 if (Base->isLValueReferenceType())
1538 return D->isLValueReferenceType();
1539 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1540 };
1541
1542 // If the function is a class member, its signature includes the
1543 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1544 auto DiagnoseInconsistentRefQualifiers = [&]() {
1545 if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)
1546 return false;
1547 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1548 return false;
1549 if (OldMethod->isExplicitObjectMemberFunction() ||
1550 NewMethod->isExplicitObjectMemberFunction())
1551 return false;
1552 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1553 NewMethod->getRefQualifier() == RQ_None)) {
1554 SemaRef.Diag(Loc: NewMethod->getLocation(), DiagID: diag::err_ref_qualifier_overload)
1555 << OldMethod->getRefQualifier() << NewMethod->getRefQualifier();
1556 SemaRef.Diag(Loc: OldMethod->getLocation(), DiagID: diag::note_previous_declaration);
1557 return true;
1558 }
1559 return false;
1560 };
1561
1562 // We look at the parameters first, as it is the common case.
1563 // However we should not emit diagnostic before checking
1564 // the overloads do not differ by constraints or other discriminant.
1565 bool ShouldDiagnoseInconsistentRefQualifiers = false;
1566 bool HaveInconsistentQualifiers = false;
1567
1568 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1569 OldParamsOffset++;
1570 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1571 NewParamsOffset++;
1572
1573 if (OldType->getNumParams() - OldParamsOffset !=
1574 NewType->getNumParams() - NewParamsOffset ||
1575 !SemaRef.FunctionParamTypesAreEqual(
1576 Old: {OldType->param_type_begin() + OldParamsOffset,
1577 OldType->param_type_end()},
1578 New: {NewType->param_type_begin() + NewParamsOffset,
1579 NewType->param_type_end()},
1580 ArgPos: nullptr)) {
1581 return true;
1582 }
1583
1584 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1585 !NewMethod->isStatic()) {
1586 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1587 const CXXMethodDecl *New) {
1588 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1589 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1590
1591 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1592 return F->getRefQualifier() == RQ_None &&
1593 !F->isExplicitObjectMemberFunction();
1594 };
1595
1596 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1597 CompareType(OldObjectType.getNonReferenceType(),
1598 NewObjectType.getNonReferenceType()))
1599 return true;
1600 return CompareType(OldObjectType, NewObjectType);
1601 }(OldMethod, NewMethod);
1602
1603 if (!HaveCorrespondingObjectParameters) {
1604 ShouldDiagnoseInconsistentRefQualifiers = true;
1605 // CWG2554
1606 // and, if at least one is an explicit object member function, ignoring
1607 // object parameters
1608 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1609 !OldMethod->isExplicitObjectMemberFunction()))
1610 HaveInconsistentQualifiers = true;
1611 }
1612 }
1613
1614 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1615 NewMethod->isImplicitObjectMemberFunction())
1616 ShouldDiagnoseInconsistentRefQualifiers = true;
1617
1618 if (!UseOverrideRules &&
1619 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1620 AssociatedConstraint NewRC = New->getTrailingRequiresClause(),
1621 OldRC = Old->getTrailingRequiresClause();
1622 if (!NewRC != !OldRC)
1623 return true;
1624 if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)
1625 return true;
1626 if (NewRC &&
1627 !SemaRef.AreConstraintExpressionsEqual(Old: OldDecl, OldConstr: OldRC.ConstraintExpr,
1628 New: NewDecl, NewConstr: NewRC.ConstraintExpr))
1629 return true;
1630 }
1631
1632 // Though pass_object_size is placed on parameters and takes an argument, we
1633 // consider it to be a function-level modifier for the sake of function
1634 // identity. Either the function has one or more parameters with
1635 // pass_object_size or it doesn't.
1636 if (functionHasPassObjectSizeParams(FD: New) !=
1637 functionHasPassObjectSizeParams(FD: Old))
1638 return true;
1639
1640 // enable_if attributes are an order-sensitive part of the signature.
1641 for (specific_attr_iterator<EnableIfAttr>
1642 NewI = New->specific_attr_begin<EnableIfAttr>(),
1643 NewE = New->specific_attr_end<EnableIfAttr>(),
1644 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1645 OldE = Old->specific_attr_end<EnableIfAttr>();
1646 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1647 if (NewI == NewE || OldI == OldE)
1648 return true;
1649 llvm::FoldingSetNodeID NewID, OldID;
1650 NewI->getCond()->Profile(ID&: NewID, Context: SemaRef.Context, Canonical: true);
1651 OldI->getCond()->Profile(ID&: OldID, Context: SemaRef.Context, Canonical: true);
1652 if (NewID != OldID)
1653 return true;
1654 }
1655
1656 if ((ShouldDiagnoseInconsistentRefQualifiers &&
1657 DiagnoseInconsistentRefQualifiers()) ||
1658 HaveInconsistentQualifiers)
1659 return true;
1660
1661 // At this point, it is known that the two functions have the same signature.
1662 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1663 // Don't allow overloading of destructors. (In theory we could, but it
1664 // would be a giant change to clang.)
1665 if (!isa<CXXDestructorDecl>(Val: New)) {
1666 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(D: New),
1667 OldTarget = SemaRef.CUDA().IdentifyTarget(D: Old);
1668 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1669 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1670 "Unexpected invalid target.");
1671
1672 // Allow overloading of functions with same signature and different CUDA
1673 // target attributes.
1674 if (NewTarget != OldTarget) {
1675 // Special case: non-constexpr function is allowed to override
1676 // constexpr virtual function
1677 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1678 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1679 !hasExplicitAttr<CUDAHostAttr>(D: Old) &&
1680 !hasExplicitAttr<CUDADeviceAttr>(D: Old) &&
1681 !hasExplicitAttr<CUDAHostAttr>(D: New) &&
1682 !hasExplicitAttr<CUDADeviceAttr>(D: New)) {
1683 return false;
1684 }
1685 return true;
1686 }
1687 }
1688 }
1689 }
1690
1691 // The signatures match; this is not an overload.
1692 return false;
1693}
1694
1695bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1696 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1697 return IsOverloadOrOverrideImpl(SemaRef&: *this, New, Old, UseMemberUsingDeclRules,
1698 ConsiderCudaAttrs);
1699}
1700
1701bool Sema::IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
1702 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1703 return IsOverloadOrOverrideImpl(SemaRef&: *this, New: MD, Old: BaseMD,
1704 /*UseMemberUsingDeclRules=*/false,
1705 /*ConsiderCudaAttrs=*/true,
1706 /*UseOverrideRules=*/true);
1707}
1708
1709/// Tries a user-defined conversion from From to ToType.
1710///
1711/// Produces an implicit conversion sequence for when a standard conversion
1712/// is not an option. See TryImplicitConversion for more information.
1713static ImplicitConversionSequence
1714TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1715 bool SuppressUserConversions,
1716 AllowedExplicit AllowExplicit,
1717 bool InOverloadResolution,
1718 bool CStyle,
1719 bool AllowObjCWritebackConversion,
1720 bool AllowObjCConversionOnExplicit) {
1721 ImplicitConversionSequence ICS;
1722
1723 if (SuppressUserConversions) {
1724 // We're not in the case above, so there is no conversion that
1725 // we can perform.
1726 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1727 return ICS;
1728 }
1729
1730 // Attempt user-defined conversion.
1731 OverloadCandidateSet Conversions(From->getExprLoc(),
1732 OverloadCandidateSet::CSK_Normal);
1733 switch (IsUserDefinedConversion(S, From, ToType, User&: ICS.UserDefined,
1734 Conversions, AllowExplicit,
1735 AllowObjCConversionOnExplicit)) {
1736 case OR_Success:
1737 case OR_Deleted:
1738 ICS.setUserDefined();
1739 // C++ [over.ics.user]p4:
1740 // A conversion of an expression of class type to the same class
1741 // type is given Exact Match rank, and a conversion of an
1742 // expression of class type to a base class of that type is
1743 // given Conversion rank, in spite of the fact that a copy
1744 // constructor (i.e., a user-defined conversion function) is
1745 // called for those cases.
1746 if (CXXConstructorDecl *Constructor
1747 = dyn_cast<CXXConstructorDecl>(Val: ICS.UserDefined.ConversionFunction)) {
1748 QualType FromType;
1749 SourceLocation FromLoc;
1750 // C++11 [over.ics.list]p6, per DR2137:
1751 // C++17 [over.ics.list]p6:
1752 // If C is not an initializer-list constructor and the initializer list
1753 // has a single element of type cv U, where U is X or a class derived
1754 // from X, the implicit conversion sequence has Exact Match rank if U is
1755 // X, or Conversion rank if U is derived from X.
1756 bool FromListInit = false;
1757 if (const auto *InitList = dyn_cast<InitListExpr>(Val: From);
1758 InitList && InitList->getNumInits() == 1 &&
1759 !S.isInitListConstructor(Ctor: Constructor)) {
1760 const Expr *SingleInit = InitList->getInit(Init: 0);
1761 FromType = SingleInit->getType();
1762 FromLoc = SingleInit->getBeginLoc();
1763 FromListInit = true;
1764 } else {
1765 FromType = From->getType();
1766 FromLoc = From->getBeginLoc();
1767 }
1768 QualType FromCanon =
1769 S.Context.getCanonicalType(T: FromType.getUnqualifiedType());
1770 QualType ToCanon
1771 = S.Context.getCanonicalType(T: ToType).getUnqualifiedType();
1772 if ((FromCanon == ToCanon ||
1773 S.IsDerivedFrom(Loc: FromLoc, Derived: FromCanon, Base: ToCanon))) {
1774 // Turn this into a "standard" conversion sequence, so that it
1775 // gets ranked with standard conversion sequences.
1776 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1777 ICS.setStandard();
1778 ICS.Standard.setAsIdentityConversion();
1779 ICS.Standard.setFromType(FromType);
1780 ICS.Standard.setAllToTypes(ToType);
1781 ICS.Standard.FromBracedInitList = FromListInit;
1782 ICS.Standard.CopyConstructor = Constructor;
1783 ICS.Standard.FoundCopyConstructor = Found;
1784 if (ToCanon != FromCanon)
1785 ICS.Standard.Second = ICK_Derived_To_Base;
1786 }
1787 }
1788 break;
1789
1790 case OR_Ambiguous:
1791 ICS.setAmbiguous();
1792 ICS.Ambiguous.setFromType(From->getType());
1793 ICS.Ambiguous.setToType(ToType);
1794 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1795 Cand != Conversions.end(); ++Cand)
1796 if (Cand->Best)
1797 ICS.Ambiguous.addConversion(Found: Cand->FoundDecl, D: Cand->Function);
1798 break;
1799
1800 // Fall through.
1801 case OR_No_Viable_Function:
1802 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1803 break;
1804 }
1805
1806 return ICS;
1807}
1808
1809/// TryImplicitConversion - Attempt to perform an implicit conversion
1810/// from the given expression (Expr) to the given type (ToType). This
1811/// function returns an implicit conversion sequence that can be used
1812/// to perform the initialization. Given
1813///
1814/// void f(float f);
1815/// void g(int i) { f(i); }
1816///
1817/// this routine would produce an implicit conversion sequence to
1818/// describe the initialization of f from i, which will be a standard
1819/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1820/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1821//
1822/// Note that this routine only determines how the conversion can be
1823/// performed; it does not actually perform the conversion. As such,
1824/// it will not produce any diagnostics if no conversion is available,
1825/// but will instead return an implicit conversion sequence of kind
1826/// "BadConversion".
1827///
1828/// If @p SuppressUserConversions, then user-defined conversions are
1829/// not permitted.
1830/// If @p AllowExplicit, then explicit user-defined conversions are
1831/// permitted.
1832///
1833/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1834/// writeback conversion, which allows __autoreleasing id* parameters to
1835/// be initialized with __strong id* or __weak id* arguments.
1836static ImplicitConversionSequence
1837TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1838 bool SuppressUserConversions,
1839 AllowedExplicit AllowExplicit,
1840 bool InOverloadResolution,
1841 bool CStyle,
1842 bool AllowObjCWritebackConversion,
1843 bool AllowObjCConversionOnExplicit) {
1844 ImplicitConversionSequence ICS;
1845 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1846 SCS&: ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1847 ICS.setStandard();
1848 return ICS;
1849 }
1850
1851 if (!S.getLangOpts().CPlusPlus) {
1852 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1853 return ICS;
1854 }
1855
1856 // C++ [over.ics.user]p4:
1857 // A conversion of an expression of class type to the same class
1858 // type is given Exact Match rank, and a conversion of an
1859 // expression of class type to a base class of that type is
1860 // given Conversion rank, in spite of the fact that a copy/move
1861 // constructor (i.e., a user-defined conversion function) is
1862 // called for those cases.
1863 QualType FromType = From->getType();
1864 if (ToType->isRecordType() &&
1865 (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType) ||
1866 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: FromType, Base: ToType))) {
1867 ICS.setStandard();
1868 ICS.Standard.setAsIdentityConversion();
1869 ICS.Standard.setFromType(FromType);
1870 ICS.Standard.setAllToTypes(ToType);
1871
1872 // We don't actually check at this point whether there is a valid
1873 // copy/move constructor, since overloading just assumes that it
1874 // exists. When we actually perform initialization, we'll find the
1875 // appropriate constructor to copy the returned object, if needed.
1876 ICS.Standard.CopyConstructor = nullptr;
1877
1878 // In HLSL, a conversion of an expression of class type to the same class
1879 // type needs implicit LvaluetoRvalue conversion.
1880 if (S.getLangOpts().HLSL)
1881 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
1882
1883 // Determine whether this is considered a derived-to-base conversion.
1884 if (!S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
1885 ICS.Standard.Second = ICK_Derived_To_Base;
1886
1887 return ICS;
1888 }
1889
1890 if (S.getLangOpts().HLSL) {
1891 // Handle conversion of the HLSL resource types.
1892 const Type *FromTy = FromType->getUnqualifiedDesugaredType();
1893 if (FromTy->isHLSLAttributedResourceType()) {
1894 // Attributed resource types can convert to other attributed
1895 // resource types with the same attributes and contained types,
1896 // or to __hlsl_resource_t without any attributes.
1897 bool CanConvert = false;
1898 const Type *ToTy = ToType->getUnqualifiedDesugaredType();
1899 if (ToTy->isHLSLAttributedResourceType()) {
1900 auto *ToResType = cast<HLSLAttributedResourceType>(Val: ToTy);
1901 auto *FromResType = cast<HLSLAttributedResourceType>(Val: FromTy);
1902 if (S.Context.hasSameUnqualifiedType(T1: ToResType->getWrappedType(),
1903 T2: FromResType->getWrappedType()) &&
1904 S.Context.hasSameUnqualifiedType(T1: ToResType->getContainedType(),
1905 T2: FromResType->getContainedType()) &&
1906 ToResType->getAttrs() == FromResType->getAttrs())
1907 CanConvert = true;
1908 } else if (ToTy->isHLSLResourceType()) {
1909 CanConvert = true;
1910 }
1911 if (CanConvert) {
1912 ICS.setStandard();
1913 ICS.Standard.setAsIdentityConversion();
1914 ICS.Standard.setFromType(FromType);
1915 ICS.Standard.setAllToTypes(ToType);
1916 return ICS;
1917 }
1918 }
1919 }
1920
1921 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1922 AllowExplicit, InOverloadResolution, CStyle,
1923 AllowObjCWritebackConversion,
1924 AllowObjCConversionOnExplicit);
1925}
1926
1927ImplicitConversionSequence
1928Sema::TryImplicitConversion(Expr *From, QualType ToType,
1929 bool SuppressUserConversions,
1930 AllowedExplicit AllowExplicit,
1931 bool InOverloadResolution,
1932 bool CStyle,
1933 bool AllowObjCWritebackConversion) {
1934 return ::TryImplicitConversion(S&: *this, From, ToType, SuppressUserConversions,
1935 AllowExplicit, InOverloadResolution, CStyle,
1936 AllowObjCWritebackConversion,
1937 /*AllowObjCConversionOnExplicit=*/false);
1938}
1939
1940ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1941 AssignmentAction Action,
1942 bool AllowExplicit) {
1943 if (checkPlaceholderForOverload(S&: *this, E&: From))
1944 return ExprError();
1945
1946 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1947 bool AllowObjCWritebackConversion =
1948 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1949 Action == AssignmentAction::Sending);
1950 if (getLangOpts().ObjC)
1951 ObjC().CheckObjCBridgeRelatedConversions(Loc: From->getBeginLoc(), DestType: ToType,
1952 SrcType: From->getType(), SrcExpr&: From);
1953 ImplicitConversionSequence ICS = ::TryImplicitConversion(
1954 S&: *this, From, ToType,
1955 /*SuppressUserConversions=*/false,
1956 AllowExplicit: AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1957 /*InOverloadResolution=*/false,
1958 /*CStyle=*/false, AllowObjCWritebackConversion,
1959 /*AllowObjCConversionOnExplicit=*/false);
1960 return PerformImplicitConversion(From, ToType, ICS, Action);
1961}
1962
1963bool Sema::TryFunctionConversion(QualType FromType, QualType ToType,
1964 QualType &ResultTy) const {
1965 bool Changed = IsFunctionConversion(FromType, ToType);
1966 if (Changed)
1967 ResultTy = ToType;
1968 return Changed;
1969}
1970
1971bool Sema::IsFunctionConversion(QualType FromType, QualType ToType) const {
1972 if (Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
1973 return false;
1974
1975 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1976 // or F(t noexcept) -> F(t)
1977 // where F adds one of the following at most once:
1978 // - a pointer
1979 // - a member pointer
1980 // - a block pointer
1981 // Changes here need matching changes in FindCompositePointerType.
1982 CanQualType CanTo = Context.getCanonicalType(T: ToType);
1983 CanQualType CanFrom = Context.getCanonicalType(T: FromType);
1984 Type::TypeClass TyClass = CanTo->getTypeClass();
1985 if (TyClass != CanFrom->getTypeClass()) return false;
1986 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1987 if (TyClass == Type::Pointer) {
1988 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1989 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1990 } else if (TyClass == Type::BlockPointer) {
1991 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1992 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1993 } else if (TyClass == Type::MemberPointer) {
1994 auto ToMPT = CanTo.castAs<MemberPointerType>();
1995 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1996 // A function pointer conversion cannot change the class of the function.
1997 if (!declaresSameEntity(D1: ToMPT->getMostRecentCXXRecordDecl(),
1998 D2: FromMPT->getMostRecentCXXRecordDecl()))
1999 return false;
2000 CanTo = ToMPT->getPointeeType();
2001 CanFrom = FromMPT->getPointeeType();
2002 } else {
2003 return false;
2004 }
2005
2006 TyClass = CanTo->getTypeClass();
2007 if (TyClass != CanFrom->getTypeClass()) return false;
2008 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
2009 return false;
2010 }
2011
2012 const auto *FromFn = cast<FunctionType>(Val&: CanFrom);
2013 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
2014
2015 const auto *ToFn = cast<FunctionType>(Val&: CanTo);
2016 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
2017
2018 bool Changed = false;
2019
2020 // Drop 'noreturn' if not present in target type.
2021 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
2022 FromFn = Context.adjustFunctionType(Fn: FromFn, EInfo: FromEInfo.withNoReturn(noReturn: false));
2023 Changed = true;
2024 }
2025
2026 const auto *FromFPT = dyn_cast<FunctionProtoType>(Val: FromFn);
2027 const auto *ToFPT = dyn_cast<FunctionProtoType>(Val: ToFn);
2028
2029 if (FromFPT && ToFPT) {
2030 if (FromFPT->hasCFIUncheckedCallee() != ToFPT->hasCFIUncheckedCallee()) {
2031 QualType NewTy = Context.getFunctionType(
2032 ResultTy: FromFPT->getReturnType(), Args: FromFPT->getParamTypes(),
2033 EPI: FromFPT->getExtProtoInfo().withCFIUncheckedCallee(
2034 CFIUncheckedCallee: ToFPT->hasCFIUncheckedCallee()));
2035 FromFPT = cast<FunctionProtoType>(Val: NewTy.getTypePtr());
2036 FromFn = FromFPT;
2037 Changed = true;
2038 }
2039 }
2040
2041 // Drop 'noexcept' if not present in target type.
2042 if (FromFPT && ToFPT) {
2043 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
2044 FromFn = cast<FunctionType>(
2045 Val: Context.getFunctionTypeWithExceptionSpec(Orig: QualType(FromFPT, 0),
2046 ESI: EST_None)
2047 .getTypePtr());
2048 Changed = true;
2049 }
2050
2051 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
2052 // only if the ExtParameterInfo lists of the two function prototypes can be
2053 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
2054 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2055 bool CanUseToFPT, CanUseFromFPT;
2056 if (Context.mergeExtParameterInfo(FirstFnType: ToFPT, SecondFnType: FromFPT, CanUseFirst&: CanUseToFPT,
2057 CanUseSecond&: CanUseFromFPT, NewParamInfos) &&
2058 CanUseToFPT && !CanUseFromFPT) {
2059 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2060 ExtInfo.ExtParameterInfos =
2061 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
2062 QualType QT = Context.getFunctionType(ResultTy: FromFPT->getReturnType(),
2063 Args: FromFPT->getParamTypes(), EPI: ExtInfo);
2064 FromFn = QT->getAs<FunctionType>();
2065 Changed = true;
2066 }
2067
2068 if (Context.hasAnyFunctionEffects()) {
2069 FromFPT = cast<FunctionProtoType>(Val: FromFn); // in case FromFn changed above
2070
2071 // Transparently add/drop effects; here we are concerned with
2072 // language rules/canonicalization. Adding/dropping effects is a warning.
2073 const auto FromFX = FromFPT->getFunctionEffects();
2074 const auto ToFX = ToFPT->getFunctionEffects();
2075 if (FromFX != ToFX) {
2076 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2077 ExtInfo.FunctionEffects = ToFX;
2078 QualType QT = Context.getFunctionType(
2079 ResultTy: FromFPT->getReturnType(), Args: FromFPT->getParamTypes(), EPI: ExtInfo);
2080 FromFn = QT->getAs<FunctionType>();
2081 Changed = true;
2082 }
2083 }
2084 }
2085
2086 if (!Changed)
2087 return false;
2088
2089 assert(QualType(FromFn, 0).isCanonical());
2090 if (QualType(FromFn, 0) != CanTo) return false;
2091
2092 return true;
2093}
2094
2095/// Determine whether the conversion from FromType to ToType is a valid
2096/// floating point conversion.
2097///
2098static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2099 QualType ToType) {
2100 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2101 return false;
2102 // FIXME: disable conversions between long double, __ibm128 and __float128
2103 // if their representation is different until there is back end support
2104 // We of course allow this conversion if long double is really double.
2105
2106 // Conversions between bfloat16 and float16 are currently not supported.
2107 if ((FromType->isBFloat16Type() &&
2108 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2109 (ToType->isBFloat16Type() &&
2110 (FromType->isFloat16Type() || FromType->isHalfType())))
2111 return false;
2112
2113 // Conversions between IEEE-quad and IBM-extended semantics are not
2114 // permitted.
2115 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(T: FromType);
2116 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(T: ToType);
2117 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2118 &ToSem == &llvm::APFloat::IEEEquad()) ||
2119 (&FromSem == &llvm::APFloat::IEEEquad() &&
2120 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2121 return false;
2122 return true;
2123}
2124
2125static bool IsVectorOrMatrixElementConversion(Sema &S, QualType FromType,
2126 QualType ToType,
2127 ImplicitConversionKind &ICK,
2128 Expr *From) {
2129 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
2130 return true;
2131
2132 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2133 ICK = ICK_Floating_Promotion;
2134 return true;
2135 }
2136
2137 if (IsFloatingPointConversion(S, FromType, ToType)) {
2138 ICK = ICK_Floating_Conversion;
2139 return true;
2140 }
2141
2142 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2143 ICK = ICK_Boolean_Conversion;
2144 return true;
2145 }
2146
2147 if ((FromType->isRealFloatingType() && ToType->isIntegralType(Ctx: S.Context)) ||
2148 (FromType->isIntegralOrUnscopedEnumerationType() &&
2149 ToType->isRealFloatingType())) {
2150 ICK = ICK_Floating_Integral;
2151 return true;
2152 }
2153
2154 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2155 ICK = ICK_Integral_Promotion;
2156 return true;
2157 }
2158
2159 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2160 ToType->isIntegralType(Ctx: S.Context)) {
2161 ICK = ICK_Integral_Conversion;
2162 return true;
2163 }
2164
2165 return false;
2166}
2167
2168/// Determine whether the conversion from FromType to ToType is a valid
2169/// matrix conversion.
2170///
2171/// \param ICK Will be set to the matrix conversion kind, if this is a matrix
2172/// conversion.
2173static bool IsMatrixConversion(Sema &S, QualType FromType, QualType ToType,
2174 ImplicitConversionKind &ICK,
2175 ImplicitConversionKind &ElConv, Expr *From,
2176 bool InOverloadResolution, bool CStyle) {
2177 // Implicit conversions for matrices are an HLSL feature not present in C/C++.
2178 if (!S.getLangOpts().HLSL)
2179 return false;
2180
2181 auto *ToMatrixType = ToType->getAs<ConstantMatrixType>();
2182 auto *FromMatrixType = FromType->getAs<ConstantMatrixType>();
2183
2184 // If both arguments are matrix, handle possible matrix truncation and
2185 // element conversion.
2186 if (ToMatrixType && FromMatrixType) {
2187 unsigned FromCols = FromMatrixType->getNumColumns();
2188 unsigned ToCols = ToMatrixType->getNumColumns();
2189 if (FromCols < ToCols)
2190 return false;
2191
2192 unsigned FromRows = FromMatrixType->getNumRows();
2193 unsigned ToRows = ToMatrixType->getNumRows();
2194 if (FromRows < ToRows)
2195 return false;
2196
2197 if (FromRows == ToRows && FromCols == ToCols)
2198 ElConv = ICK_Identity;
2199 else
2200 ElConv = ICK_HLSL_Matrix_Truncation;
2201
2202 QualType FromElTy = FromMatrixType->getElementType();
2203 QualType ToElTy = ToMatrixType->getElementType();
2204 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToElTy))
2205 return true;
2206 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType: ToElTy, ICK, From);
2207 }
2208
2209 // Matrix splat from any arithmetic type to a matrix.
2210 if (ToMatrixType && FromType->isArithmeticType()) {
2211 ElConv = ICK_HLSL_Matrix_Splat;
2212 QualType ToElTy = ToMatrixType->getElementType();
2213 return IsVectorOrMatrixElementConversion(S, FromType, ToType: ToElTy, ICK, From);
2214 }
2215 if (FromMatrixType && !ToMatrixType) {
2216 ElConv = ICK_HLSL_Matrix_Truncation;
2217 QualType FromElTy = FromMatrixType->getElementType();
2218 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToType))
2219 return true;
2220 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType, ICK, From);
2221 }
2222
2223 return false;
2224}
2225
2226/// Determine whether the conversion from FromType to ToType is a valid
2227/// vector conversion.
2228///
2229/// \param ICK Will be set to the vector conversion kind, if this is a vector
2230/// conversion.
2231static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2232 ImplicitConversionKind &ICK,
2233 ImplicitConversionKind &ElConv, Expr *From,
2234 bool InOverloadResolution, bool CStyle) {
2235 // We need at least one of these types to be a vector type to have a vector
2236 // conversion.
2237 if (!ToType->isVectorType() && !FromType->isVectorType())
2238 return false;
2239
2240 // Identical types require no conversions.
2241 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
2242 return false;
2243
2244 // HLSL allows implicit truncation of vector types.
2245 if (S.getLangOpts().HLSL) {
2246 auto *ToExtType = ToType->getAs<ExtVectorType>();
2247 auto *FromExtType = FromType->getAs<ExtVectorType>();
2248
2249 // If both arguments are vectors, handle possible vector truncation and
2250 // element conversion.
2251 if (ToExtType && FromExtType) {
2252 unsigned FromElts = FromExtType->getNumElements();
2253 unsigned ToElts = ToExtType->getNumElements();
2254 if (FromElts < ToElts)
2255 return false;
2256 if (FromElts == ToElts)
2257 ElConv = ICK_Identity;
2258 else
2259 ElConv = ICK_HLSL_Vector_Truncation;
2260
2261 QualType FromElTy = FromExtType->getElementType();
2262 QualType ToElTy = ToExtType->getElementType();
2263 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToElTy))
2264 return true;
2265 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType: ToElTy, ICK, From);
2266 }
2267 if (FromExtType && !ToExtType) {
2268 ElConv = ICK_HLSL_Vector_Truncation;
2269 QualType FromElTy = FromExtType->getElementType();
2270 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToType))
2271 return true;
2272 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType, ICK, From);
2273 }
2274 // Fallthrough for the case where ToType is a vector and FromType is not.
2275 }
2276
2277 // There are no conversions between extended vector types, only identity.
2278 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2279 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {
2280 // Implicit conversions require the same number of elements.
2281 if (ToExtType->getNumElements() != FromExtType->getNumElements())
2282 return false;
2283
2284 // Permit implicit conversions from integral values to boolean vectors.
2285 if (ToType->isExtVectorBoolType() &&
2286 FromExtType->getElementType()->isIntegerType()) {
2287 ICK = ICK_Boolean_Conversion;
2288 return true;
2289 }
2290 // There are no other conversions between extended vector types.
2291 return false;
2292 }
2293
2294 // Vector splat from any arithmetic type to a vector.
2295 if (FromType->isArithmeticType()) {
2296 if (S.getLangOpts().HLSL) {
2297 ElConv = ICK_HLSL_Vector_Splat;
2298 QualType ToElTy = ToExtType->getElementType();
2299 return IsVectorOrMatrixElementConversion(S, FromType, ToType: ToElTy, ICK,
2300 From);
2301 }
2302 ICK = ICK_Vector_Splat;
2303 return true;
2304 }
2305 }
2306
2307 if (ToType->isSVESizelessBuiltinType() ||
2308 FromType->isSVESizelessBuiltinType())
2309 if (S.ARM().areCompatibleSveTypes(FirstType: FromType, SecondType: ToType) ||
2310 S.ARM().areLaxCompatibleSveTypes(FirstType: FromType, SecondType: ToType)) {
2311 ICK = ICK_SVE_Vector_Conversion;
2312 return true;
2313 }
2314
2315 if (ToType->isRVVSizelessBuiltinType() ||
2316 FromType->isRVVSizelessBuiltinType())
2317 if (S.Context.areCompatibleRVVTypes(FirstType: FromType, SecondType: ToType) ||
2318 S.Context.areLaxCompatibleRVVTypes(FirstType: FromType, SecondType: ToType)) {
2319 ICK = ICK_RVV_Vector_Conversion;
2320 return true;
2321 }
2322
2323 // We can perform the conversion between vector types in the following cases:
2324 // 1)vector types are equivalent AltiVec and GCC vector types
2325 // 2)lax vector conversions are permitted and the vector types are of the
2326 // same size
2327 // 3)the destination type does not have the ARM MVE strict-polymorphism
2328 // attribute, which inhibits lax vector conversion for overload resolution
2329 // only
2330 if (ToType->isVectorType() && FromType->isVectorType()) {
2331 if (S.Context.areCompatibleVectorTypes(FirstVec: FromType, SecondVec: ToType) ||
2332 (S.isLaxVectorConversion(srcType: FromType, destType: ToType) &&
2333 !ToType->hasAttr(AK: attr::ArmMveStrictPolymorphism))) {
2334 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2335 S.isLaxVectorConversion(srcType: FromType, destType: ToType) &&
2336 S.anyAltivecTypes(srcType: FromType, destType: ToType) &&
2337 !S.Context.areCompatibleVectorTypes(FirstVec: FromType, SecondVec: ToType) &&
2338 !InOverloadResolution && !CStyle) {
2339 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all)
2340 << FromType << ToType;
2341 }
2342 ICK = ICK_Vector_Conversion;
2343 return true;
2344 }
2345 }
2346
2347 return false;
2348}
2349
2350static bool IsHLSLPackedTypeConversion(Sema &S, QualType FromType,
2351 QualType ToType,
2352 ImplicitConversionKind &ICK,
2353 ImplicitConversionKind &DimensionICK,
2354 Expr *From) {
2355 if (!S.getLangOpts().HLSL)
2356 return false;
2357 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
2358 return false;
2359
2360 const bool FromPacked = FromType->isHLSLBuiltinPackedType();
2361 const bool ToPacked = ToType->isHLSLBuiltinPackedType();
2362
2363 if (FromPacked && ToPacked) {
2364 ICK = ICK_Integral_Conversion;
2365 DimensionICK = ICK_Identity;
2366 return true;
2367 }
2368
2369 // Only convert packed types to and from uint
2370 QualType UIntTy = S.Context.UnsignedIntTy;
2371 const bool ToIsUint = S.Context.hasSameUnqualifiedType(T1: ToType, T2: UIntTy);
2372 if (FromPacked && !ToIsUint)
2373 return false;
2374
2375 const bool FromIsUint = S.Context.hasSameUnqualifiedType(T1: FromType, T2: UIntTy);
2376 if (ToPacked && !FromIsUint)
2377 return false;
2378
2379 // Converting to or from uint
2380 if (FromIsUint || ToIsUint) {
2381 ICK = ICK_HLSL_Packed_Type_Conversion;
2382 DimensionICK = ICK_Identity;
2383 return true;
2384 }
2385
2386 return false;
2387}
2388
2389static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2390 bool InOverloadResolution,
2391 StandardConversionSequence &SCS,
2392 bool CStyle);
2393
2394static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From,
2395 QualType ToType,
2396 bool InOverloadResolution,
2397 StandardConversionSequence &SCS,
2398 bool CStyle);
2399
2400/// IsStandardConversion - Determines whether there is a standard
2401/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2402/// expression From to the type ToType. Standard conversion sequences
2403/// only consider non-class types; for conversions that involve class
2404/// types, use TryImplicitConversion. If a conversion exists, SCS will
2405/// contain the standard conversion sequence required to perform this
2406/// conversion and this routine will return true. Otherwise, this
2407/// routine will return false and the value of SCS is unspecified.
2408static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2409 bool InOverloadResolution,
2410 StandardConversionSequence &SCS,
2411 bool CStyle,
2412 bool AllowObjCWritebackConversion) {
2413 QualType FromType = From->getType();
2414
2415 // Standard conversions (C++ [conv])
2416 SCS.setAsIdentityConversion();
2417 SCS.IncompatibleObjC = false;
2418 SCS.setFromType(FromType);
2419 SCS.CopyConstructor = nullptr;
2420
2421 // There are no standard conversions for class types in C++, so
2422 // abort early. When overloading in C, however, we do permit them.
2423 if (S.getLangOpts().CPlusPlus &&
2424 (FromType->isRecordType() || ToType->isRecordType()))
2425 return false;
2426
2427 // The first conversion can be an lvalue-to-rvalue conversion,
2428 // array-to-pointer conversion, or function-to-pointer conversion
2429 // (C++ 4p1).
2430
2431 if (FromType == S.Context.OverloadTy) {
2432 DeclAccessPair AccessPair;
2433 if (FunctionDecl *Fn
2434 = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: From, TargetType: ToType, Complain: false,
2435 Found&: AccessPair)) {
2436 // We were able to resolve the address of the overloaded function,
2437 // so we can convert to the type of that function.
2438 FromType = Fn->getType();
2439 SCS.setFromType(FromType);
2440
2441 // we can sometimes resolve &foo<int> regardless of ToType, so check
2442 // if the type matches (identity) or we are converting to bool
2443 if (!S.Context.hasSameUnqualifiedType(
2444 T1: S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: ToType), T2: FromType)) {
2445 // if the function type matches except for [[noreturn]], it's ok
2446 if (!S.IsFunctionConversion(FromType,
2447 ToType: S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: ToType)))
2448 // otherwise, only a boolean conversion is standard
2449 if (!ToType->isBooleanType())
2450 return false;
2451 }
2452
2453 // Check if the "from" expression is taking the address of an overloaded
2454 // function and recompute the FromType accordingly. Take advantage of the
2455 // fact that non-static member functions *must* have such an address-of
2456 // expression.
2457 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn);
2458 if (Method && !Method->isStatic() &&
2459 !Method->isExplicitObjectMemberFunction()) {
2460 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2461 "Non-unary operator on non-static member address");
2462 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2463 == UO_AddrOf &&
2464 "Non-address-of operator on non-static member address");
2465 FromType = S.Context.getMemberPointerType(
2466 T: FromType, /*Qualifier=*/std::nullopt, Cls: Method->getParent());
2467 } else if (isa<UnaryOperator>(Val: From->IgnoreParens())) {
2468 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2469 UO_AddrOf &&
2470 "Non-address-of operator for overloaded function expression");
2471 FromType = S.Context.getPointerType(T: FromType);
2472 }
2473 } else {
2474 return false;
2475 }
2476 }
2477
2478 bool argIsLValue = From->isGLValue();
2479 // To handle conversion from ArrayParameterType to ConstantArrayType
2480 // this block must be above the one below because Array parameters
2481 // do not decay and when handling HLSLOutArgExprs and
2482 // the From expression is an LValue.
2483 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2484 ToType->isConstantArrayType()) {
2485 // HLSL constant array parameters do not decay, so if the argument is a
2486 // constant array and the parameter is an ArrayParameterType we have special
2487 // handling here.
2488 if (ToType->isArrayParameterType()) {
2489 FromType = S.Context.getArrayParameterType(Ty: FromType);
2490 } else if (FromType->isArrayParameterType()) {
2491 const ArrayParameterType *APT = cast<ArrayParameterType>(Val&: FromType);
2492 FromType = APT->getConstantArrayType(Ctx: S.Context);
2493 }
2494
2495 SCS.First = ICK_HLSL_Array_RValue;
2496
2497 // Don't consider qualifiers, which include things like address spaces
2498 if (FromType.getCanonicalType().getUnqualifiedType() !=
2499 ToType.getCanonicalType().getUnqualifiedType())
2500 return false;
2501
2502 SCS.setAllToTypes(ToType);
2503 return true;
2504 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2505 S.Context.getCanonicalType(T: FromType) != S.Context.OverloadTy) {
2506 // Lvalue-to-rvalue conversion (C++11 4.1):
2507 // A glvalue (3.10) of a non-function, non-array type T can
2508 // be converted to a prvalue.
2509
2510 SCS.First = ICK_Lvalue_To_Rvalue;
2511
2512 // C11 6.3.2.1p2:
2513 // ... if the lvalue has atomic type, the value has the non-atomic version
2514 // of the type of the lvalue ...
2515 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2516 FromType = Atomic->getValueType();
2517
2518 // If T is a non-class type, the type of the rvalue is the
2519 // cv-unqualified version of T. Otherwise, the type of the rvalue
2520 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2521 // just strip the qualifiers because they don't matter.
2522 FromType = FromType.getUnqualifiedType();
2523 } else if (FromType->isArrayType()) {
2524 // Array-to-pointer conversion (C++ 4.2)
2525 SCS.First = ICK_Array_To_Pointer;
2526
2527 // An lvalue or rvalue of type "array of N T" or "array of unknown
2528 // bound of T" can be converted to an rvalue of type "pointer to
2529 // T" (C++ 4.2p1).
2530 FromType = S.Context.getArrayDecayedType(T: FromType);
2531
2532 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2533 // This conversion is deprecated in C++03 (D.4)
2534 SCS.DeprecatedStringLiteralToCharPtr = true;
2535
2536 // For the purpose of ranking in overload resolution
2537 // (13.3.3.1.1), this conversion is considered an
2538 // array-to-pointer conversion followed by a qualification
2539 // conversion (4.4). (C++ 4.2p2)
2540 SCS.Second = ICK_Identity;
2541 SCS.Third = ICK_Qualification;
2542 SCS.QualificationIncludesObjCLifetime = false;
2543 SCS.setAllToTypes(FromType);
2544 return true;
2545 }
2546 } else if (FromType->isFunctionType() && argIsLValue) {
2547 // Function-to-pointer conversion (C++ 4.3).
2548 SCS.First = ICK_Function_To_Pointer;
2549
2550 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: From->IgnoreParenCasts()))
2551 if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl()))
2552 if (!S.checkAddressOfFunctionIsAvailable(Function: FD))
2553 return false;
2554
2555 // An lvalue of function type T can be converted to an rvalue of
2556 // type "pointer to T." The result is a pointer to the
2557 // function. (C++ 4.3p1).
2558 FromType = S.Context.getPointerType(T: FromType);
2559 } else {
2560 // We don't require any conversions for the first step.
2561 SCS.First = ICK_Identity;
2562 }
2563 SCS.setToType(Idx: 0, T: FromType);
2564
2565 // The second conversion can be an integral promotion, floating
2566 // point promotion, integral conversion, floating point conversion,
2567 // floating-integral conversion, pointer conversion,
2568 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2569 // For overloading in C, this can also be a "compatible-type"
2570 // conversion.
2571 bool IncompatibleObjC = false;
2572 ImplicitConversionKind SecondICK = ICK_Identity;
2573 ImplicitConversionKind DimensionICK = ICK_Identity;
2574 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType)) {
2575 // The unqualified versions of the types are the same: there's no
2576 // conversion to do.
2577 SCS.Second = ICK_Identity;
2578 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2579 // Integral promotion (C++ 4.5).
2580 SCS.Second = ICK_Integral_Promotion;
2581 FromType = ToType.getUnqualifiedType();
2582 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2583 // Floating point promotion (C++ 4.6).
2584 SCS.Second = ICK_Floating_Promotion;
2585 FromType = ToType.getUnqualifiedType();
2586 } else if (S.IsComplexPromotion(FromType, ToType)) {
2587 // Complex promotion (Clang extension)
2588 SCS.Second = ICK_Complex_Promotion;
2589 FromType = ToType.getUnqualifiedType();
2590 } else if (S.IsOverflowBehaviorTypePromotion(FromType, ToType)) {
2591 // OverflowBehaviorType promotions
2592 SCS.Second = ICK_Integral_Promotion;
2593 FromType = ToType.getUnqualifiedType();
2594 } else if (S.IsOverflowBehaviorTypeConversion(FromType, ToType)) {
2595 // OverflowBehaviorType conversions
2596 SCS.Second = ICK_Integral_Conversion;
2597 FromType = ToType.getUnqualifiedType();
2598 } else if (ToType->isBooleanType() &&
2599 (FromType->isArithmeticType() || FromType->isAnyPointerType() ||
2600 FromType->isBlockPointerType() ||
2601 FromType->isMemberPointerType())) {
2602 // Boolean conversions (C++ 4.12).
2603 SCS.Second = ICK_Boolean_Conversion;
2604 FromType = S.Context.BoolTy;
2605 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2606 ToType->isIntegralType(Ctx: S.Context)) {
2607 // Integral conversions (C++ 4.7).
2608 SCS.Second = ICK_Integral_Conversion;
2609 FromType = ToType.getUnqualifiedType();
2610 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2611 // Complex conversions (C99 6.3.1.6)
2612 SCS.Second = ICK_Complex_Conversion;
2613 FromType = ToType.getUnqualifiedType();
2614 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2615 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2616 // Complex-real conversions (C99 6.3.1.7)
2617 SCS.Second = ICK_Complex_Real;
2618 FromType = ToType.getUnqualifiedType();
2619 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2620 // Floating point conversions (C++ 4.8).
2621 SCS.Second = ICK_Floating_Conversion;
2622 FromType = ToType.getUnqualifiedType();
2623 } else if ((FromType->isRealFloatingType() &&
2624 ToType->isIntegralType(Ctx: S.Context)) ||
2625 (FromType->isIntegralOrUnscopedEnumerationType() &&
2626 ToType->isRealFloatingType())) {
2627
2628 // Floating-integral conversions (C++ 4.9).
2629 SCS.Second = ICK_Floating_Integral;
2630 FromType = ToType.getUnqualifiedType();
2631 } else if (S.IsBlockPointerConversion(FromType, ToType, ConvertedType&: FromType)) {
2632 SCS.Second = ICK_Block_Pointer_Conversion;
2633 } else if (AllowObjCWritebackConversion &&
2634 S.ObjC().isObjCWritebackConversion(FromType, ToType, ConvertedType&: FromType)) {
2635 SCS.Second = ICK_Writeback_Conversion;
2636 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2637 ConvertedType&: FromType, IncompatibleObjC)) {
2638 // Pointer conversions (C++ 4.10).
2639 SCS.Second = ICK_Pointer_Conversion;
2640 SCS.IncompatibleObjC = IncompatibleObjC;
2641 FromType = FromType.getUnqualifiedType();
2642 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2643 InOverloadResolution, ConvertedType&: FromType)) {
2644 // Pointer to member conversions (4.11).
2645 SCS.Second = ICK_Pointer_Member;
2646 } else if (IsVectorConversion(S, FromType, ToType, ICK&: SecondICK, ElConv&: DimensionICK,
2647 From, InOverloadResolution, CStyle)) {
2648 SCS.Second = SecondICK;
2649 SCS.Dimension = DimensionICK;
2650 FromType = ToType.getUnqualifiedType();
2651 } else if (IsMatrixConversion(S, FromType, ToType, ICK&: SecondICK, ElConv&: DimensionICK,
2652 From, InOverloadResolution, CStyle)) {
2653 SCS.Second = SecondICK;
2654 SCS.Dimension = DimensionICK;
2655 FromType = ToType.getUnqualifiedType();
2656 } else if (IsHLSLPackedTypeConversion(S, FromType, ToType, ICK&: SecondICK,
2657 DimensionICK, From)) {
2658 SCS.Second = SecondICK;
2659 SCS.Dimension = DimensionICK;
2660 FromType = ToType.getUnqualifiedType();
2661 } else if (!S.getLangOpts().CPlusPlus &&
2662 S.Context.typesAreCompatible(T1: ToType, T2: FromType)) {
2663 // Compatible conversions (Clang extension for C function overloading)
2664 SCS.Second = ICK_Compatible_Conversion;
2665 FromType = ToType.getUnqualifiedType();
2666 } else if (IsTransparentUnionStandardConversion(
2667 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2668 SCS.Second = ICK_TransparentUnionConversion;
2669 FromType = ToType;
2670 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2671 CStyle)) {
2672 // tryAtomicConversion has updated the standard conversion sequence
2673 // appropriately.
2674 return true;
2675 } else if (tryOverflowBehaviorTypeConversion(
2676 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2677 return true;
2678 } else if (ToType->isEventT() &&
2679 From->isIntegerConstantExpr(Ctx: S.getASTContext()) &&
2680 From->EvaluateKnownConstInt(Ctx: S.getASTContext()) == 0) {
2681 SCS.Second = ICK_Zero_Event_Conversion;
2682 FromType = ToType;
2683 } else if (ToType->isQueueT() &&
2684 From->isIntegerConstantExpr(Ctx: S.getASTContext()) &&
2685 (From->EvaluateKnownConstInt(Ctx: S.getASTContext()) == 0)) {
2686 SCS.Second = ICK_Zero_Queue_Conversion;
2687 FromType = ToType;
2688 } else if (ToType->isSamplerT() &&
2689 From->isIntegerConstantExpr(Ctx: S.getASTContext())) {
2690 SCS.Second = ICK_Compatible_Conversion;
2691 FromType = ToType;
2692 } else if ((ToType->isFixedPointType() &&
2693 FromType->isConvertibleToFixedPointType()) ||
2694 (FromType->isFixedPointType() &&
2695 ToType->isConvertibleToFixedPointType())) {
2696 SCS.Second = ICK_Fixed_Point_Conversion;
2697 FromType = ToType;
2698 } else {
2699 // No second conversion required.
2700 SCS.Second = ICK_Identity;
2701 }
2702 SCS.setToType(Idx: 1, T: FromType);
2703
2704 // The third conversion can be a function pointer conversion or a
2705 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2706 bool ObjCLifetimeConversion;
2707 if (S.TryFunctionConversion(FromType, ToType, ResultTy&: FromType)) {
2708 // Function pointer conversions (removing 'noexcept') including removal of
2709 // 'noreturn' (Clang extension).
2710 SCS.Third = ICK_Function_Conversion;
2711 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2712 ObjCLifetimeConversion)) {
2713 SCS.Third = ICK_Qualification;
2714 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2715 FromType = ToType;
2716 } else {
2717 // No conversion required
2718 SCS.Third = ICK_Identity;
2719 }
2720
2721 // C++ [over.best.ics]p6:
2722 // [...] Any difference in top-level cv-qualification is
2723 // subsumed by the initialization itself and does not constitute
2724 // a conversion. [...]
2725 QualType CanonFrom = S.Context.getCanonicalType(T: FromType);
2726 QualType CanonTo = S.Context.getCanonicalType(T: ToType);
2727 if (CanonFrom.getLocalUnqualifiedType()
2728 == CanonTo.getLocalUnqualifiedType() &&
2729 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2730 FromType = ToType;
2731 CanonFrom = CanonTo;
2732 }
2733
2734 SCS.setToType(Idx: 2, T: FromType);
2735
2736 if (CanonFrom == CanonTo)
2737 return true;
2738
2739 // If we have not converted the argument type to the parameter type,
2740 // this is a bad conversion sequence, unless we're resolving an overload in C.
2741 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2742 return false;
2743
2744 ExprResult ER = ExprResult{From};
2745 AssignConvertType Conv =
2746 S.CheckSingleAssignmentConstraints(LHSType: ToType, RHS&: ER,
2747 /*Diagnose=*/false,
2748 /*DiagnoseCFAudited=*/false,
2749 /*ConvertRHS=*/false);
2750 ImplicitConversionKind SecondConv;
2751 switch (Conv) {
2752 case AssignConvertType::Compatible:
2753 case AssignConvertType::
2754 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2755 SecondConv = ICK_C_Only_Conversion;
2756 break;
2757 // For our purposes, discarding qualifiers is just as bad as using an
2758 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2759 // qualifiers, as well.
2760 case AssignConvertType::CompatiblePointerDiscardsQualifiers:
2761 case AssignConvertType::IncompatiblePointer:
2762 case AssignConvertType::IncompatiblePointerSign:
2763 SecondConv = ICK_Incompatible_Pointer_Conversion;
2764 break;
2765 default:
2766 return false;
2767 }
2768
2769 // First can only be an lvalue conversion, so we pretend that this was the
2770 // second conversion. First should already be valid from earlier in the
2771 // function.
2772 SCS.Second = SecondConv;
2773 SCS.setToType(Idx: 1, T: ToType);
2774
2775 // Third is Identity, because Second should rank us worse than any other
2776 // conversion. This could also be ICK_Qualification, but it's simpler to just
2777 // lump everything in with the second conversion, and we don't gain anything
2778 // from making this ICK_Qualification.
2779 SCS.Third = ICK_Identity;
2780 SCS.setToType(Idx: 2, T: ToType);
2781 return true;
2782}
2783
2784static bool
2785IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2786 QualType &ToType,
2787 bool InOverloadResolution,
2788 StandardConversionSequence &SCS,
2789 bool CStyle) {
2790
2791 const RecordType *UT = ToType->getAsUnionType();
2792 if (!UT)
2793 return false;
2794 // The field to initialize within the transparent union.
2795 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2796 if (!UD->hasAttr<TransparentUnionAttr>())
2797 return false;
2798 // It's compatible if the expression matches any of the fields.
2799 for (const auto *it : UD->fields()) {
2800 if (IsStandardConversion(S, From, ToType: it->getType(), InOverloadResolution, SCS,
2801 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2802 ToType = it->getType();
2803 return true;
2804 }
2805 }
2806 return false;
2807}
2808
2809bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2810 const BuiltinType *To = ToType->getAs<BuiltinType>();
2811 // All integers are built-in.
2812 if (!To) {
2813 return false;
2814 }
2815
2816 // An rvalue of type char, signed char, unsigned char, short int, or
2817 // unsigned short int can be converted to an rvalue of type int if
2818 // int can represent all the values of the source type; otherwise,
2819 // the source rvalue can be converted to an rvalue of type unsigned
2820 // int (C++ 4.5p1).
2821 if (Context.isPromotableIntegerType(T: FromType) && !FromType->isBooleanType() &&
2822 !FromType->isEnumeralType()) {
2823 if ( // We can promote any signed, promotable integer type to an int
2824 (FromType->isSignedIntegerType() ||
2825 // We can promote any unsigned integer type whose size is
2826 // less than int to an int.
2827 Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType))) {
2828 return To->getKind() == BuiltinType::Int;
2829 }
2830
2831 return To->getKind() == BuiltinType::UInt;
2832 }
2833
2834 // C++11 [conv.prom]p3:
2835 // A prvalue of an unscoped enumeration type whose underlying type is not
2836 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2837 // following types that can represent all the values of the enumeration
2838 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2839 // unsigned int, long int, unsigned long int, long long int, or unsigned
2840 // long long int. If none of the types in that list can represent all the
2841 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2842 // type can be converted to an rvalue a prvalue of the extended integer type
2843 // with lowest integer conversion rank (4.13) greater than the rank of long
2844 // long in which all the values of the enumeration can be represented. If
2845 // there are two such extended types, the signed one is chosen.
2846 // C++11 [conv.prom]p4:
2847 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2848 // can be converted to a prvalue of its underlying type. Moreover, if
2849 // integral promotion can be applied to its underlying type, a prvalue of an
2850 // unscoped enumeration type whose underlying type is fixed can also be
2851 // converted to a prvalue of the promoted underlying type.
2852 if (const auto *FromED = FromType->getAsEnumDecl()) {
2853 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2854 // provided for a scoped enumeration.
2855 if (FromED->isScoped())
2856 return false;
2857
2858 // We can perform an integral promotion to the underlying type of the enum,
2859 // even if that's not the promoted type. Note that the check for promoting
2860 // the underlying type is based on the type alone, and does not consider
2861 // the bitfield-ness of the actual source expression.
2862 if (FromED->isFixed()) {
2863 QualType Underlying = FromED->getIntegerType();
2864 return Context.hasSameUnqualifiedType(T1: Underlying, T2: ToType) ||
2865 IsIntegralPromotion(From: nullptr, FromType: Underlying, ToType);
2866 }
2867
2868 // We have already pre-calculated the promotion type, so this is trivial.
2869 if (ToType->isIntegerType() &&
2870 isCompleteType(Loc: From->getBeginLoc(), T: FromType))
2871 return Context.hasSameUnqualifiedType(T1: ToType, T2: FromED->getPromotionType());
2872
2873 // C++ [conv.prom]p5:
2874 // If the bit-field has an enumerated type, it is treated as any other
2875 // value of that type for promotion purposes.
2876 //
2877 // ... so do not fall through into the bit-field checks below in C++.
2878 if (getLangOpts().CPlusPlus)
2879 return false;
2880 }
2881
2882 // C++0x [conv.prom]p2:
2883 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2884 // to an rvalue a prvalue of the first of the following types that can
2885 // represent all the values of its underlying type: int, unsigned int,
2886 // long int, unsigned long int, long long int, or unsigned long long int.
2887 // If none of the types in that list can represent all the values of its
2888 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2889 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2890 // type.
2891 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2892 ToType->isIntegerType()) {
2893 // Determine whether the type we're converting from is signed or
2894 // unsigned.
2895 bool FromIsSigned = FromType->isSignedIntegerType();
2896 uint64_t FromSize = Context.getTypeSize(T: FromType);
2897
2898 // The types we'll try to promote to, in the appropriate
2899 // order. Try each of these types.
2900 QualType PromoteTypes[6] = {
2901 Context.IntTy, Context.UnsignedIntTy,
2902 Context.LongTy, Context.UnsignedLongTy ,
2903 Context.LongLongTy, Context.UnsignedLongLongTy
2904 };
2905 for (int Idx = 0; Idx < 6; ++Idx) {
2906 uint64_t ToSize = Context.getTypeSize(T: PromoteTypes[Idx]);
2907 if (FromSize < ToSize ||
2908 (FromSize == ToSize &&
2909 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2910 // We found the type that we can promote to. If this is the
2911 // type we wanted, we have a promotion. Otherwise, no
2912 // promotion.
2913 return Context.hasSameUnqualifiedType(T1: ToType, T2: PromoteTypes[Idx]);
2914 }
2915 }
2916 }
2917
2918 // An rvalue for an integral bit-field (9.6) can be converted to an
2919 // rvalue of type int if int can represent all the values of the
2920 // bit-field; otherwise, it can be converted to unsigned int if
2921 // unsigned int can represent all the values of the bit-field. If
2922 // the bit-field is larger yet, no integral promotion applies to
2923 // it. If the bit-field has an enumerated type, it is treated as any
2924 // other value of that type for promotion purposes (C++ 4.5p3).
2925 // FIXME: We should delay checking of bit-fields until we actually perform the
2926 // conversion.
2927 //
2928 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2929 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2930 // bit-fields and those whose underlying type is larger than int) for GCC
2931 // compatibility.
2932 if (From) {
2933 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2934 std::optional<llvm::APSInt> BitWidth;
2935 if (FromType->isIntegralType(Ctx: Context) &&
2936 (BitWidth =
2937 MemberDecl->getBitWidth()->getIntegerConstantExpr(Ctx: Context))) {
2938 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2939 ToSize = Context.getTypeSize(T: ToType);
2940
2941 // Are we promoting to an int from a bitfield that fits in an int?
2942 if (*BitWidth < ToSize ||
2943 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2944 return To->getKind() == BuiltinType::Int;
2945 }
2946
2947 // Are we promoting to an unsigned int from an unsigned bitfield
2948 // that fits into an unsigned int?
2949 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2950 return To->getKind() == BuiltinType::UInt;
2951 }
2952
2953 return false;
2954 }
2955 }
2956 }
2957
2958 // An rvalue of type bool can be converted to an rvalue of type int,
2959 // with false becoming zero and true becoming one (C++ 4.5p4).
2960 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2961 return true;
2962 }
2963
2964 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2965 // integral type.
2966 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2967 ToType->isIntegerType())
2968 return Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType);
2969
2970 return false;
2971}
2972
2973bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2974 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2975 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2976 /// An rvalue of type float can be converted to an rvalue of type
2977 /// double. (C++ 4.6p1).
2978 if (FromBuiltin->getKind() == BuiltinType::Float &&
2979 ToBuiltin->getKind() == BuiltinType::Double)
2980 return true;
2981
2982 // C99 6.3.1.5p1:
2983 // When a float is promoted to double or long double, or a
2984 // double is promoted to long double [...].
2985 if (!getLangOpts().CPlusPlus &&
2986 (FromBuiltin->getKind() == BuiltinType::Float ||
2987 FromBuiltin->getKind() == BuiltinType::Double) &&
2988 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2989 ToBuiltin->getKind() == BuiltinType::Float128 ||
2990 ToBuiltin->getKind() == BuiltinType::Ibm128))
2991 return true;
2992
2993 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2994 // or not native half types are enabled.
2995 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2996 (ToBuiltin->getKind() == BuiltinType::Float ||
2997 ToBuiltin->getKind() == BuiltinType::Double))
2998 return true;
2999
3000 // Half can be promoted to float.
3001 if (!getLangOpts().NativeHalfType &&
3002 FromBuiltin->getKind() == BuiltinType::Half &&
3003 ToBuiltin->getKind() == BuiltinType::Float)
3004 return true;
3005 }
3006
3007 return false;
3008}
3009
3010bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
3011 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
3012 if (!FromComplex)
3013 return false;
3014
3015 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
3016 if (!ToComplex)
3017 return false;
3018
3019 return IsFloatingPointPromotion(FromType: FromComplex->getElementType(),
3020 ToType: ToComplex->getElementType()) ||
3021 IsIntegralPromotion(From: nullptr, FromType: FromComplex->getElementType(),
3022 ToType: ToComplex->getElementType());
3023}
3024
3025bool Sema::IsOverflowBehaviorTypePromotion(QualType FromType, QualType ToType) {
3026 if (!getLangOpts().OverflowBehaviorTypes)
3027 return false;
3028
3029 if (!FromType->isOverflowBehaviorType() || !ToType->isOverflowBehaviorType())
3030 return false;
3031
3032 return Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType);
3033}
3034
3035bool Sema::IsOverflowBehaviorTypeConversion(QualType FromType,
3036 QualType ToType) {
3037 if (!getLangOpts().OverflowBehaviorTypes)
3038 return false;
3039
3040 if (FromType->isOverflowBehaviorType() && !ToType->isOverflowBehaviorType()) {
3041 if (ToType->isBooleanType())
3042 return false;
3043 // Don't allow implicit conversion from OverflowBehaviorType to scoped enum
3044 if (const EnumType *ToEnumType = ToType->getAs<EnumType>()) {
3045 const EnumDecl *ToED = ToEnumType->getDecl()->getDefinitionOrSelf();
3046 if (ToED->isScoped())
3047 return false;
3048 }
3049 return true;
3050 }
3051
3052 if (!FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
3053 return true;
3054
3055 if (FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
3056 return Context.getTypeSize(T: FromType) > Context.getTypeSize(T: ToType);
3057
3058 return false;
3059}
3060
3061/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
3062/// the pointer type FromPtr to a pointer to type ToPointee, with the
3063/// same type qualifiers as FromPtr has on its pointee type. ToType,
3064/// if non-empty, will be a pointer to ToType that may or may not have
3065/// the right set of qualifiers on its pointee.
3066///
3067static QualType
3068BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
3069 QualType ToPointee, QualType ToType,
3070 ASTContext &Context,
3071 bool StripObjCLifetime = false) {
3072 assert((FromPtr->getTypeClass() == Type::Pointer ||
3073 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
3074 "Invalid similarly-qualified pointer type");
3075
3076 /// Conversions to 'id' subsume cv-qualifier conversions.
3077 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
3078 return ToType.getUnqualifiedType();
3079
3080 QualType CanonFromPointee
3081 = Context.getCanonicalType(T: FromPtr->getPointeeType());
3082 QualType CanonToPointee = Context.getCanonicalType(T: ToPointee);
3083 Qualifiers Quals = CanonFromPointee.getQualifiers();
3084
3085 if (StripObjCLifetime)
3086 Quals.removeObjCLifetime();
3087
3088 // Exact qualifier match -> return the pointer type we're converting to.
3089 if (CanonToPointee.getLocalQualifiers() == Quals) {
3090 // ToType is exactly what we need. Return it.
3091 if (!ToType.isNull())
3092 return ToType.getUnqualifiedType();
3093
3094 // Build a pointer to ToPointee. It has the right qualifiers
3095 // already.
3096 if (isa<ObjCObjectPointerType>(Val: ToType))
3097 return Context.getObjCObjectPointerType(OIT: ToPointee);
3098 return Context.getPointerType(T: ToPointee);
3099 }
3100
3101 // Just build a canonical type that has the right qualifiers.
3102 QualType QualifiedCanonToPointee
3103 = Context.getQualifiedType(T: CanonToPointee.getLocalUnqualifiedType(), Qs: Quals);
3104
3105 if (isa<ObjCObjectPointerType>(Val: ToType))
3106 return Context.getObjCObjectPointerType(OIT: QualifiedCanonToPointee);
3107 return Context.getPointerType(T: QualifiedCanonToPointee);
3108}
3109
3110static bool isNullPointerConstantForConversion(Expr *Expr,
3111 bool InOverloadResolution,
3112 ASTContext &Context) {
3113 // Handle value-dependent integral null pointer constants correctly.
3114 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
3115 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
3116 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
3117 return !InOverloadResolution;
3118
3119 return Expr->isNullPointerConstant(Ctx&: Context,
3120 NPC: InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3121 : Expr::NPC_ValueDependentIsNull);
3122}
3123
3124bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
3125 bool InOverloadResolution,
3126 QualType& ConvertedType,
3127 bool &IncompatibleObjC) {
3128 IncompatibleObjC = false;
3129 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
3130 IncompatibleObjC))
3131 return true;
3132
3133 // Conversion from a null pointer constant to any Objective-C pointer type.
3134 if (ToType->isObjCObjectPointerType() &&
3135 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3136 ConvertedType = ToType;
3137 return true;
3138 }
3139
3140 // Blocks: Block pointers can be converted to void*.
3141 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
3142 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
3143 ConvertedType = ToType;
3144 return true;
3145 }
3146 // Blocks: A null pointer constant can be converted to a block
3147 // pointer type.
3148 if (ToType->isBlockPointerType() &&
3149 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3150 ConvertedType = ToType;
3151 return true;
3152 }
3153
3154 // If the left-hand-side is nullptr_t, the right side can be a null
3155 // pointer constant.
3156 if (ToType->isNullPtrType() &&
3157 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3158 ConvertedType = ToType;
3159 return true;
3160 }
3161
3162 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
3163 if (!ToTypePtr)
3164 return false;
3165
3166 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
3167 if (isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3168 ConvertedType = ToType;
3169 return true;
3170 }
3171
3172 // Beyond this point, both types need to be pointers
3173 // , including objective-c pointers.
3174 QualType ToPointeeType = ToTypePtr->getPointeeType();
3175 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
3176 !getLangOpts().ObjCAutoRefCount) {
3177 ConvertedType = BuildSimilarlyQualifiedPointerType(
3178 FromPtr: FromType->castAs<ObjCObjectPointerType>(), ToPointee: ToPointeeType, ToType,
3179 Context);
3180 return true;
3181 }
3182 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
3183 if (!FromTypePtr)
3184 return false;
3185
3186 QualType FromPointeeType = FromTypePtr->getPointeeType();
3187
3188 // If the unqualified pointee types are the same, this can't be a
3189 // pointer conversion, so don't do all of the work below.
3190 if (Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType))
3191 return false;
3192
3193 // An rvalue of type "pointer to cv T," where T is an object type,
3194 // can be converted to an rvalue of type "pointer to cv void" (C++
3195 // 4.10p2).
3196 if (FromPointeeType->isIncompleteOrObjectType() &&
3197 ToPointeeType->isVoidType()) {
3198 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3199 ToPointee: ToPointeeType,
3200 ToType, Context,
3201 /*StripObjCLifetime=*/true);
3202 return true;
3203 }
3204
3205 // MSVC allows implicit function to void* type conversion.
3206 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
3207 ToPointeeType->isVoidType()) {
3208 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3209 ToPointee: ToPointeeType,
3210 ToType, Context);
3211 return true;
3212 }
3213
3214 // When we're overloading in C, we allow a special kind of pointer
3215 // conversion for compatible-but-not-identical pointee types.
3216 if (!getLangOpts().CPlusPlus &&
3217 Context.typesAreCompatible(T1: FromPointeeType, T2: ToPointeeType)) {
3218 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3219 ToPointee: ToPointeeType,
3220 ToType, Context);
3221 return true;
3222 }
3223
3224 // C++ [conv.ptr]p3:
3225 //
3226 // An rvalue of type "pointer to cv D," where D is a class type,
3227 // can be converted to an rvalue of type "pointer to cv B," where
3228 // B is a base class (clause 10) of D. If B is an inaccessible
3229 // (clause 11) or ambiguous (10.2) base class of D, a program that
3230 // necessitates this conversion is ill-formed. The result of the
3231 // conversion is a pointer to the base class sub-object of the
3232 // derived class object. The null pointer value is converted to
3233 // the null pointer value of the destination type.
3234 //
3235 // Note that we do not check for ambiguity or inaccessibility
3236 // here. That is handled by CheckPointerConversion.
3237 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3238 ToPointeeType->isRecordType() &&
3239 !Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType) &&
3240 IsDerivedFrom(Loc: From->getBeginLoc(), Derived: FromPointeeType, Base: ToPointeeType)) {
3241 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3242 ToPointee: ToPointeeType,
3243 ToType, Context);
3244 return true;
3245 }
3246
3247 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3248 Context.areCompatibleVectorTypes(FirstVec: FromPointeeType, SecondVec: ToPointeeType)) {
3249 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3250 ToPointee: ToPointeeType,
3251 ToType, Context);
3252 return true;
3253 }
3254
3255 return false;
3256}
3257
3258/// Adopt the given qualifiers for the given type.
3259static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
3260 Qualifiers TQs = T.getQualifiers();
3261
3262 // Check whether qualifiers already match.
3263 if (TQs == Qs)
3264 return T;
3265
3266 if (Qs.compatiblyIncludes(other: TQs, Ctx: Context))
3267 return Context.getQualifiedType(T, Qs);
3268
3269 return Context.getQualifiedType(T: T.getUnqualifiedType(), Qs);
3270}
3271
3272bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
3273 QualType& ConvertedType,
3274 bool &IncompatibleObjC) {
3275 if (!getLangOpts().ObjC)
3276 return false;
3277
3278 // The set of qualifiers on the type we're converting from.
3279 Qualifiers FromQualifiers = FromType.getQualifiers();
3280
3281 // First, we handle all conversions on ObjC object pointer types.
3282 const ObjCObjectPointerType* ToObjCPtr =
3283 ToType->getAs<ObjCObjectPointerType>();
3284 const ObjCObjectPointerType *FromObjCPtr =
3285 FromType->getAs<ObjCObjectPointerType>();
3286
3287 if (ToObjCPtr && FromObjCPtr) {
3288 // If the pointee types are the same (ignoring qualifications),
3289 // then this is not a pointer conversion.
3290 if (Context.hasSameUnqualifiedType(T1: ToObjCPtr->getPointeeType(),
3291 T2: FromObjCPtr->getPointeeType()))
3292 return false;
3293
3294 // Conversion between Objective-C pointers.
3295 if (Context.canAssignObjCInterfaces(LHSOPT: ToObjCPtr, RHSOPT: FromObjCPtr)) {
3296 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3297 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3298 if (getLangOpts().CPlusPlus && LHS && RHS &&
3299 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
3300 other: FromObjCPtr->getPointeeType(), Ctx: getASTContext()))
3301 return false;
3302 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromObjCPtr,
3303 ToPointee: ToObjCPtr->getPointeeType(),
3304 ToType, Context);
3305 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3306 return true;
3307 }
3308
3309 if (Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr, RHSOPT: ToObjCPtr)) {
3310 // Okay: this is some kind of implicit downcast of Objective-C
3311 // interfaces, which is permitted. However, we're going to
3312 // complain about it.
3313 IncompatibleObjC = true;
3314 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromObjCPtr,
3315 ToPointee: ToObjCPtr->getPointeeType(),
3316 ToType, Context);
3317 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3318 return true;
3319 }
3320 }
3321 // Beyond this point, both types need to be C pointers or block pointers.
3322 QualType ToPointeeType;
3323 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3324 ToPointeeType = ToCPtr->getPointeeType();
3325 else if (const BlockPointerType *ToBlockPtr =
3326 ToType->getAs<BlockPointerType>()) {
3327 // Objective C++: We're able to convert from a pointer to any object
3328 // to a block pointer type.
3329 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3330 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3331 return true;
3332 }
3333 ToPointeeType = ToBlockPtr->getPointeeType();
3334 }
3335 else if (FromType->getAs<BlockPointerType>() &&
3336 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3337 // Objective C++: We're able to convert from a block pointer type to a
3338 // pointer to any object.
3339 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3340 return true;
3341 }
3342 else
3343 return false;
3344
3345 QualType FromPointeeType;
3346 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3347 FromPointeeType = FromCPtr->getPointeeType();
3348 else if (const BlockPointerType *FromBlockPtr =
3349 FromType->getAs<BlockPointerType>())
3350 FromPointeeType = FromBlockPtr->getPointeeType();
3351 else
3352 return false;
3353
3354 // If we have pointers to pointers, recursively check whether this
3355 // is an Objective-C conversion.
3356 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3357 isObjCPointerConversion(FromType: FromPointeeType, ToType: ToPointeeType, ConvertedType,
3358 IncompatibleObjC)) {
3359 // We always complain about this conversion.
3360 IncompatibleObjC = true;
3361 ConvertedType = Context.getPointerType(T: ConvertedType);
3362 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3363 return true;
3364 }
3365 // Allow conversion of pointee being objective-c pointer to another one;
3366 // as in I* to id.
3367 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3368 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3369 isObjCPointerConversion(FromType: FromPointeeType, ToType: ToPointeeType, ConvertedType,
3370 IncompatibleObjC)) {
3371
3372 ConvertedType = Context.getPointerType(T: ConvertedType);
3373 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3374 return true;
3375 }
3376
3377 // If we have pointers to functions or blocks, check whether the only
3378 // differences in the argument and result types are in Objective-C
3379 // pointer conversions. If so, we permit the conversion (but
3380 // complain about it).
3381 const FunctionProtoType *FromFunctionType
3382 = FromPointeeType->getAs<FunctionProtoType>();
3383 const FunctionProtoType *ToFunctionType
3384 = ToPointeeType->getAs<FunctionProtoType>();
3385 if (FromFunctionType && ToFunctionType) {
3386 // If the function types are exactly the same, this isn't an
3387 // Objective-C pointer conversion.
3388 if (Context.getCanonicalType(T: FromPointeeType)
3389 == Context.getCanonicalType(T: ToPointeeType))
3390 return false;
3391
3392 // Perform the quick checks that will tell us whether these
3393 // function types are obviously different.
3394 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3395 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3396 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3397 return false;
3398
3399 bool HasObjCConversion = false;
3400 if (Context.getCanonicalType(T: FromFunctionType->getReturnType()) ==
3401 Context.getCanonicalType(T: ToFunctionType->getReturnType())) {
3402 // Okay, the types match exactly. Nothing to do.
3403 } else if (isObjCPointerConversion(FromType: FromFunctionType->getReturnType(),
3404 ToType: ToFunctionType->getReturnType(),
3405 ConvertedType, IncompatibleObjC)) {
3406 // Okay, we have an Objective-C pointer conversion.
3407 HasObjCConversion = true;
3408 } else {
3409 // Function types are too different. Abort.
3410 return false;
3411 }
3412
3413 // Check argument types.
3414 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3415 ArgIdx != NumArgs; ++ArgIdx) {
3416 QualType FromArgType = FromFunctionType->getParamType(i: ArgIdx);
3417 QualType ToArgType = ToFunctionType->getParamType(i: ArgIdx);
3418 if (Context.getCanonicalType(T: FromArgType)
3419 == Context.getCanonicalType(T: ToArgType)) {
3420 // Okay, the types match exactly. Nothing to do.
3421 } else if (isObjCPointerConversion(FromType: FromArgType, ToType: ToArgType,
3422 ConvertedType, IncompatibleObjC)) {
3423 // Okay, we have an Objective-C pointer conversion.
3424 HasObjCConversion = true;
3425 } else {
3426 // Argument types are too different. Abort.
3427 return false;
3428 }
3429 }
3430
3431 if (HasObjCConversion) {
3432 // We had an Objective-C conversion. Allow this pointer
3433 // conversion, but complain about it.
3434 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3435 IncompatibleObjC = true;
3436 return true;
3437 }
3438 }
3439
3440 return false;
3441}
3442
3443bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
3444 QualType& ConvertedType) {
3445 QualType ToPointeeType;
3446 if (const BlockPointerType *ToBlockPtr =
3447 ToType->getAs<BlockPointerType>())
3448 ToPointeeType = ToBlockPtr->getPointeeType();
3449 else
3450 return false;
3451
3452 QualType FromPointeeType;
3453 if (const BlockPointerType *FromBlockPtr =
3454 FromType->getAs<BlockPointerType>())
3455 FromPointeeType = FromBlockPtr->getPointeeType();
3456 else
3457 return false;
3458 // We have pointer to blocks, check whether the only
3459 // differences in the argument and result types are in Objective-C
3460 // pointer conversions. If so, we permit the conversion.
3461
3462 const FunctionProtoType *FromFunctionType
3463 = FromPointeeType->getAs<FunctionProtoType>();
3464 const FunctionProtoType *ToFunctionType
3465 = ToPointeeType->getAs<FunctionProtoType>();
3466
3467 if (!FromFunctionType || !ToFunctionType)
3468 return false;
3469
3470 if (Context.hasSameType(T1: FromPointeeType, T2: ToPointeeType))
3471 return true;
3472
3473 // Perform the quick checks that will tell us whether these
3474 // function types are obviously different.
3475 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3476 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3477 return false;
3478
3479 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3480 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3481 if (FromEInfo != ToEInfo)
3482 return false;
3483
3484 bool IncompatibleObjC = false;
3485 if (Context.hasSameType(T1: FromFunctionType->getReturnType(),
3486 T2: ToFunctionType->getReturnType())) {
3487 // Okay, the types match exactly. Nothing to do.
3488 } else {
3489 QualType RHS = FromFunctionType->getReturnType();
3490 QualType LHS = ToFunctionType->getReturnType();
3491 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3492 !RHS.hasQualifiers() && LHS.hasQualifiers())
3493 LHS = LHS.getUnqualifiedType();
3494
3495 if (Context.hasSameType(T1: RHS,T2: LHS)) {
3496 // OK exact match.
3497 } else if (isObjCPointerConversion(FromType: RHS, ToType: LHS,
3498 ConvertedType, IncompatibleObjC)) {
3499 if (IncompatibleObjC)
3500 return false;
3501 // Okay, we have an Objective-C pointer conversion.
3502 }
3503 else
3504 return false;
3505 }
3506
3507 // Check argument types.
3508 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3509 ArgIdx != NumArgs; ++ArgIdx) {
3510 IncompatibleObjC = false;
3511 QualType FromArgType = FromFunctionType->getParamType(i: ArgIdx);
3512 QualType ToArgType = ToFunctionType->getParamType(i: ArgIdx);
3513 if (Context.hasSameType(T1: FromArgType, T2: ToArgType)) {
3514 // Okay, the types match exactly. Nothing to do.
3515 } else if (isObjCPointerConversion(FromType: ToArgType, ToType: FromArgType,
3516 ConvertedType, IncompatibleObjC)) {
3517 if (IncompatibleObjC)
3518 return false;
3519 // Okay, we have an Objective-C pointer conversion.
3520 } else
3521 // Argument types are too different. Abort.
3522 return false;
3523 }
3524
3525 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
3526 bool CanUseToFPT, CanUseFromFPT;
3527 if (!Context.mergeExtParameterInfo(FirstFnType: ToFunctionType, SecondFnType: FromFunctionType,
3528 CanUseFirst&: CanUseToFPT, CanUseSecond&: CanUseFromFPT,
3529 NewParamInfos))
3530 return false;
3531
3532 ConvertedType = ToType;
3533 return true;
3534}
3535
3536enum {
3537 ft_default,
3538 ft_different_class,
3539 ft_parameter_arity,
3540 ft_parameter_mismatch,
3541 ft_return_type,
3542 ft_qualifer_mismatch,
3543 ft_noexcept
3544};
3545
3546/// Attempts to get the FunctionProtoType from a Type. Handles
3547/// MemberFunctionPointers properly.
3548static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
3549 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3550 return FPT;
3551
3552 if (auto *MPT = FromType->getAs<MemberPointerType>())
3553 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3554
3555 return nullptr;
3556}
3557
3558void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
3559 QualType FromType, QualType ToType) {
3560 // If either type is not valid, include no extra info.
3561 if (FromType.isNull() || ToType.isNull()) {
3562 PDiag << ft_default;
3563 return;
3564 }
3565
3566 // Get the function type from the pointers.
3567 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3568 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3569 *ToMember = ToType->castAs<MemberPointerType>();
3570 if (!declaresSameEntity(D1: FromMember->getMostRecentCXXRecordDecl(),
3571 D2: ToMember->getMostRecentCXXRecordDecl())) {
3572 PDiag << ft_different_class;
3573 if (ToMember->isSugared())
3574 PDiag << Context.getCanonicalTagType(
3575 TD: ToMember->getMostRecentCXXRecordDecl());
3576 else
3577 PDiag << ToMember->getQualifier();
3578 if (FromMember->isSugared())
3579 PDiag << Context.getCanonicalTagType(
3580 TD: FromMember->getMostRecentCXXRecordDecl());
3581 else
3582 PDiag << FromMember->getQualifier();
3583 return;
3584 }
3585 FromType = FromMember->getPointeeType();
3586 ToType = ToMember->getPointeeType();
3587 }
3588
3589 if (FromType->isPointerType())
3590 FromType = FromType->getPointeeType();
3591 if (ToType->isPointerType())
3592 ToType = ToType->getPointeeType();
3593
3594 // Remove references.
3595 FromType = FromType.getNonReferenceType();
3596 ToType = ToType.getNonReferenceType();
3597
3598 // Don't print extra info for non-specialized template functions.
3599 if (FromType->isInstantiationDependentType() &&
3600 !FromType->getAs<TemplateSpecializationType>()) {
3601 PDiag << ft_default;
3602 return;
3603 }
3604
3605 // No extra info for same types.
3606 if (Context.hasSameType(T1: FromType, T2: ToType)) {
3607 PDiag << ft_default;
3608 return;
3609 }
3610
3611 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3612 *ToFunction = tryGetFunctionProtoType(FromType: ToType);
3613
3614 // Both types need to be function types.
3615 if (!FromFunction || !ToFunction) {
3616 PDiag << ft_default;
3617 return;
3618 }
3619
3620 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3621 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3622 << FromFunction->getNumParams();
3623 return;
3624 }
3625
3626 // Handle different parameter types.
3627 unsigned ArgPos;
3628 if (!FunctionParamTypesAreEqual(OldType: FromFunction, NewType: ToFunction, ArgPos: &ArgPos)) {
3629 PDiag << ft_parameter_mismatch << ArgPos + 1
3630 << ToFunction->getParamType(i: ArgPos)
3631 << FromFunction->getParamType(i: ArgPos);
3632 return;
3633 }
3634
3635 // Handle different return type.
3636 if (!Context.hasSameType(T1: FromFunction->getReturnType(),
3637 T2: ToFunction->getReturnType())) {
3638 PDiag << ft_return_type << ToFunction->getReturnType()
3639 << FromFunction->getReturnType();
3640 return;
3641 }
3642
3643 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3644 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3645 << FromFunction->getMethodQuals();
3646 return;
3647 }
3648
3649 // Handle exception specification differences on canonical type (in C++17
3650 // onwards).
3651 if (cast<FunctionProtoType>(Val: FromFunction->getCanonicalTypeUnqualified())
3652 ->isNothrow() !=
3653 cast<FunctionProtoType>(Val: ToFunction->getCanonicalTypeUnqualified())
3654 ->isNothrow()) {
3655 PDiag << ft_noexcept;
3656 return;
3657 }
3658
3659 // Unable to find a difference, so add no extra info.
3660 PDiag << ft_default;
3661}
3662
3663bool Sema::FunctionParamTypesAreEqual(ArrayRef<QualType> Old,
3664 ArrayRef<QualType> New, unsigned *ArgPos,
3665 bool Reversed) {
3666 assert(llvm::size(Old) == llvm::size(New) &&
3667 "Can't compare parameters of functions with different number of "
3668 "parameters!");
3669
3670 for (auto &&[Idx, Type] : llvm::enumerate(First&: Old)) {
3671 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3672 size_t J = Reversed ? (llvm::size(Range&: New) - Idx - 1) : Idx;
3673
3674 // Ignore address spaces in pointee type. This is to disallow overloading
3675 // on __ptr32/__ptr64 address spaces.
3676 QualType OldType =
3677 Context.removePtrSizeAddrSpace(T: Type.getUnqualifiedType());
3678 QualType NewType =
3679 Context.removePtrSizeAddrSpace(T: (New.begin() + J)->getUnqualifiedType());
3680
3681 if (!Context.hasSameType(T1: OldType, T2: NewType)) {
3682 if (ArgPos)
3683 *ArgPos = Idx;
3684 return false;
3685 }
3686 }
3687 return true;
3688}
3689
3690bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3691 const FunctionProtoType *NewType,
3692 unsigned *ArgPos, bool Reversed) {
3693 return FunctionParamTypesAreEqual(Old: OldType->param_types(),
3694 New: NewType->param_types(), ArgPos, Reversed);
3695}
3696
3697bool Sema::FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
3698 const FunctionDecl *NewFunction,
3699 unsigned *ArgPos,
3700 bool Reversed) {
3701
3702 if (OldFunction->getNumNonObjectParams() !=
3703 NewFunction->getNumNonObjectParams())
3704 return false;
3705
3706 unsigned OldIgnore =
3707 unsigned(OldFunction->hasCXXExplicitFunctionObjectParameter());
3708 unsigned NewIgnore =
3709 unsigned(NewFunction->hasCXXExplicitFunctionObjectParameter());
3710
3711 auto *OldPT = cast<FunctionProtoType>(Val: OldFunction->getFunctionType());
3712 auto *NewPT = cast<FunctionProtoType>(Val: NewFunction->getFunctionType());
3713
3714 return FunctionParamTypesAreEqual(Old: OldPT->param_types().slice(N: OldIgnore),
3715 New: NewPT->param_types().slice(N: NewIgnore),
3716 ArgPos, Reversed);
3717}
3718
3719bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
3720 CastKind &Kind,
3721 CXXCastPath& BasePath,
3722 bool IgnoreBaseAccess,
3723 bool Diagnose) {
3724 QualType FromType = From->getType();
3725 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3726
3727 Kind = CK_BitCast;
3728
3729 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3730 From->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull) ==
3731 Expr::NPCK_ZeroExpression) {
3732 if (Context.hasSameUnqualifiedType(T1: From->getType(), T2: Context.BoolTy))
3733 DiagRuntimeBehavior(Loc: From->getExprLoc(), Statement: From,
3734 PD: PDiag(DiagID: diag::warn_impcast_bool_to_null_pointer)
3735 << ToType << From->getSourceRange());
3736 else if (!isUnevaluatedContext())
3737 Diag(Loc: From->getExprLoc(), DiagID: diag::warn_non_literal_null_pointer)
3738 << ToType << From->getSourceRange();
3739 }
3740 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3741 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3742 QualType FromPointeeType = FromPtrType->getPointeeType(),
3743 ToPointeeType = ToPtrType->getPointeeType();
3744
3745 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3746 !Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType)) {
3747 // We must have a derived-to-base conversion. Check an
3748 // ambiguous or inaccessible conversion.
3749 unsigned InaccessibleID = 0;
3750 unsigned AmbiguousID = 0;
3751 if (Diagnose) {
3752 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3753 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3754 }
3755 if (CheckDerivedToBaseConversion(
3756 Derived: FromPointeeType, Base: ToPointeeType, InaccessibleBaseID: InaccessibleID, AmbiguousBaseConvID: AmbiguousID,
3757 Loc: From->getExprLoc(), Range: From->getSourceRange(), Name: DeclarationName(),
3758 BasePath: &BasePath, IgnoreAccess: IgnoreBaseAccess))
3759 return true;
3760
3761 // The conversion was successful.
3762 Kind = CK_DerivedToBase;
3763 }
3764
3765 if (Diagnose && !IsCStyleOrFunctionalCast &&
3766 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3767 assert(getLangOpts().MSVCCompat &&
3768 "this should only be possible with MSVCCompat!");
3769 Diag(Loc: From->getExprLoc(), DiagID: diag::ext_ms_impcast_fn_obj)
3770 << From->getSourceRange();
3771 }
3772 }
3773 } else if (const ObjCObjectPointerType *ToPtrType =
3774 ToType->getAs<ObjCObjectPointerType>()) {
3775 if (const ObjCObjectPointerType *FromPtrType =
3776 FromType->getAs<ObjCObjectPointerType>()) {
3777 // Objective-C++ conversions are always okay.
3778 // FIXME: We should have a different class of conversions for the
3779 // Objective-C++ implicit conversions.
3780 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3781 return false;
3782 } else if (FromType->isBlockPointerType()) {
3783 Kind = CK_BlockPointerToObjCPointerCast;
3784 } else {
3785 Kind = CK_CPointerToObjCPointerCast;
3786 }
3787 } else if (ToType->isBlockPointerType()) {
3788 if (!FromType->isBlockPointerType())
3789 Kind = CK_AnyPointerToBlockPointerCast;
3790 }
3791
3792 // We shouldn't fall into this case unless it's valid for other
3793 // reasons.
3794 if (From->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull))
3795 Kind = CK_NullToPointer;
3796
3797 return false;
3798}
3799
3800bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3801 QualType ToType,
3802 bool InOverloadResolution,
3803 QualType &ConvertedType) {
3804 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3805 if (!ToTypePtr)
3806 return false;
3807
3808 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3809 if (From->isNullPointerConstant(Ctx&: Context,
3810 NPC: InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3811 : Expr::NPC_ValueDependentIsNull)) {
3812 ConvertedType = ToType;
3813 return true;
3814 }
3815
3816 // Otherwise, both types have to be member pointers.
3817 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3818 if (!FromTypePtr)
3819 return false;
3820
3821 // A pointer to member of B can be converted to a pointer to member of D,
3822 // where D is derived from B (C++ 4.11p2).
3823 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3824 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3825
3826 if (!declaresSameEntity(D1: FromClass, D2: ToClass) &&
3827 IsDerivedFrom(Loc: From->getBeginLoc(), Derived: ToClass, Base: FromClass)) {
3828 ConvertedType = Context.getMemberPointerType(
3829 T: FromTypePtr->getPointeeType(), Qualifier: FromTypePtr->getQualifier(), Cls: ToClass);
3830 return true;
3831 }
3832
3833 return false;
3834}
3835
3836Sema::MemberPointerConversionResult Sema::CheckMemberPointerConversion(
3837 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3838 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3839 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3840 // Lock down the inheritance model right now in MS ABI, whether or not the
3841 // pointee types are the same.
3842 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3843 (void)isCompleteType(Loc: CheckLoc, T: FromType);
3844 (void)isCompleteType(Loc: CheckLoc, T: QualType(ToPtrType, 0));
3845 }
3846
3847 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3848 if (!FromPtrType) {
3849 // This must be a null pointer to member pointer conversion
3850 Kind = CK_NullToMemberPointer;
3851 return MemberPointerConversionResult::Success;
3852 }
3853
3854 // T == T, modulo cv
3855 if (Direction == MemberPointerConversionDirection::Upcast &&
3856 !Context.hasSameUnqualifiedType(T1: FromPtrType->getPointeeType(),
3857 T2: ToPtrType->getPointeeType()))
3858 return MemberPointerConversionResult::DifferentPointee;
3859
3860 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3861 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3862
3863 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,
3864 const CXXRecordDecl *Cls) {
3865 if (declaresSameEntity(D1: Qual.getAsRecordDecl(), D2: Cls))
3866 PD << Qual;
3867 else
3868 PD << Context.getCanonicalTagType(TD: Cls);
3869 };
3870 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3871 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3872 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3873 return PD;
3874 };
3875
3876 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3877 if (Direction == MemberPointerConversionDirection::Upcast)
3878 std::swap(a&: Base, b&: Derived);
3879
3880 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3881 /*DetectVirtual=*/true);
3882 if (!IsDerivedFrom(Loc: OpRange.getBegin(), Derived, Base, Paths))
3883 return MemberPointerConversionResult::NotDerived;
3884
3885 if (Paths.isAmbiguous(BaseType: Context.getCanonicalTagType(TD: Base))) {
3886 PartialDiagnostic PD = PDiag(DiagID: diag::err_ambiguous_memptr_conv);
3887 PD << int(Direction);
3888 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3889 Diag(Loc: CheckLoc, PD);
3890 return MemberPointerConversionResult::Ambiguous;
3891 }
3892
3893 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3894 PartialDiagnostic PD = PDiag(DiagID: diag::err_memptr_conv_via_virtual);
3895 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3896 Diag(Loc: CheckLoc, PD);
3897 return MemberPointerConversionResult::Virtual;
3898 }
3899
3900 // Must be a base to derived member conversion.
3901 BuildBasePathArray(Paths, BasePath);
3902 Kind = Direction == MemberPointerConversionDirection::Upcast
3903 ? CK_DerivedToBaseMemberPointer
3904 : CK_BaseToDerivedMemberPointer;
3905
3906 if (!IgnoreBaseAccess)
3907 switch (CheckBaseClassAccess(
3908 AccessLoc: CheckLoc, Base, Derived, Path: Paths.front(),
3909 DiagID: Direction == MemberPointerConversionDirection::Upcast
3910 ? diag::err_upcast_to_inaccessible_base
3911 : diag::err_downcast_from_inaccessible_base,
3912 SetupPDiag: [&](PartialDiagnostic &PD) {
3913 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),
3914 DerivedQual = ToPtrType->getQualifier();
3915 if (Direction == MemberPointerConversionDirection::Upcast)
3916 std::swap(a&: BaseQual, b&: DerivedQual);
3917 DiagCls(PD, DerivedQual, Derived);
3918 DiagCls(PD, BaseQual, Base);
3919 })) {
3920 case Sema::AR_accessible:
3921 case Sema::AR_delayed:
3922 case Sema::AR_dependent:
3923 // Optimistically assume that the delayed and dependent cases
3924 // will work out.
3925 break;
3926
3927 case Sema::AR_inaccessible:
3928 return MemberPointerConversionResult::Inaccessible;
3929 }
3930
3931 return MemberPointerConversionResult::Success;
3932}
3933
3934/// Determine whether the lifetime conversion between the two given
3935/// qualifiers sets is nontrivial.
3936static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3937 Qualifiers ToQuals) {
3938 // Converting anything to const __unsafe_unretained is trivial.
3939 if (ToQuals.hasConst() &&
3940 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3941 return false;
3942
3943 return true;
3944}
3945
3946/// Perform a single iteration of the loop for checking if a qualification
3947/// conversion is valid.
3948///
3949/// Specifically, check whether any change between the qualifiers of \p
3950/// FromType and \p ToType is permissible, given knowledge about whether every
3951/// outer layer is const-qualified.
3952static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3953 bool CStyle, bool IsTopLevel,
3954 bool &PreviousToQualsIncludeConst,
3955 bool &ObjCLifetimeConversion,
3956 const ASTContext &Ctx) {
3957 Qualifiers FromQuals = FromType.getQualifiers();
3958 Qualifiers ToQuals = ToType.getQualifiers();
3959
3960 // Ignore __unaligned qualifier.
3961 FromQuals.removeUnaligned();
3962
3963 // Objective-C ARC:
3964 // Check Objective-C lifetime conversions.
3965 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3966 if (ToQuals.compatiblyIncludesObjCLifetime(other: FromQuals)) {
3967 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3968 ObjCLifetimeConversion = true;
3969 FromQuals.removeObjCLifetime();
3970 ToQuals.removeObjCLifetime();
3971 } else {
3972 // Qualification conversions cannot cast between different
3973 // Objective-C lifetime qualifiers.
3974 return false;
3975 }
3976 }
3977
3978 // Allow addition/removal of GC attributes but not changing GC attributes.
3979 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3980 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3981 FromQuals.removeObjCGCAttr();
3982 ToQuals.removeObjCGCAttr();
3983 }
3984
3985 // __ptrauth qualifiers must match exactly.
3986 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3987 return false;
3988
3989 // -- for every j > 0, if const is in cv 1,j then const is in cv
3990 // 2,j, and similarly for volatile.
3991 if (!CStyle && !ToQuals.compatiblyIncludes(other: FromQuals, Ctx))
3992 return false;
3993
3994 // If address spaces mismatch:
3995 // - in top level it is only valid to convert to addr space that is a
3996 // superset in all cases apart from C-style casts where we allow
3997 // conversions between overlapping address spaces.
3998 // - in non-top levels it is not a valid conversion.
3999 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
4000 (!IsTopLevel ||
4001 !(ToQuals.isAddressSpaceSupersetOf(other: FromQuals, Ctx) ||
4002 (CStyle && FromQuals.isAddressSpaceSupersetOf(other: ToQuals, Ctx)))))
4003 return false;
4004
4005 // -- if the cv 1,j and cv 2,j are different, then const is in
4006 // every cv for 0 < k < j.
4007 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
4008 !PreviousToQualsIncludeConst)
4009 return false;
4010
4011 // The following wording is from C++20, where the result of the conversion
4012 // is T3, not T2.
4013 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
4014 // "array of unknown bound of"
4015 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
4016 return false;
4017
4018 // -- if the resulting P3,i is different from P1,i [...], then const is
4019 // added to every cv 3_k for 0 < k < i.
4020 if (!CStyle && FromType->isConstantArrayType() &&
4021 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
4022 return false;
4023
4024 // Keep track of whether all prior cv-qualifiers in the "to" type
4025 // include const.
4026 PreviousToQualsIncludeConst =
4027 PreviousToQualsIncludeConst && ToQuals.hasConst();
4028 return true;
4029}
4030
4031bool
4032Sema::IsQualificationConversion(QualType FromType, QualType ToType,
4033 bool CStyle, bool &ObjCLifetimeConversion) {
4034 FromType = Context.getCanonicalType(T: FromType);
4035 ToType = Context.getCanonicalType(T: ToType);
4036 ObjCLifetimeConversion = false;
4037
4038 // If FromType and ToType are the same type, this is not a
4039 // qualification conversion.
4040 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
4041 return false;
4042
4043 // (C++ 4.4p4):
4044 // A conversion can add cv-qualifiers at levels other than the first
4045 // in multi-level pointers, subject to the following rules: [...]
4046 bool PreviousToQualsIncludeConst = true;
4047 bool UnwrappedAnyPointer = false;
4048 while (Context.UnwrapSimilarTypes(T1&: FromType, T2&: ToType)) {
4049 if (!isQualificationConversionStep(FromType, ToType, CStyle,
4050 IsTopLevel: !UnwrappedAnyPointer,
4051 PreviousToQualsIncludeConst,
4052 ObjCLifetimeConversion, Ctx: getASTContext()))
4053 return false;
4054 UnwrappedAnyPointer = true;
4055 }
4056
4057 // We are left with FromType and ToType being the pointee types
4058 // after unwrapping the original FromType and ToType the same number
4059 // of times. If we unwrapped any pointers, and if FromType and
4060 // ToType have the same unqualified type (since we checked
4061 // qualifiers above), then this is a qualification conversion.
4062 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(T1: FromType,T2: ToType);
4063}
4064
4065/// - Determine whether this is a conversion from a scalar type to an
4066/// atomic type.
4067///
4068/// If successful, updates \c SCS's second and third steps in the conversion
4069/// sequence to finish the conversion.
4070static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
4071 bool InOverloadResolution,
4072 StandardConversionSequence &SCS,
4073 bool CStyle) {
4074 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
4075 if (!ToAtomic)
4076 return false;
4077
4078 StandardConversionSequence InnerSCS;
4079 if (!IsStandardConversion(S, From, ToType: ToAtomic->getValueType(),
4080 InOverloadResolution, SCS&: InnerSCS,
4081 CStyle, /*AllowObjCWritebackConversion=*/false))
4082 return false;
4083
4084 SCS.Second = InnerSCS.Second;
4085 SCS.setToType(Idx: 1, T: InnerSCS.getToType(Idx: 1));
4086 SCS.Third = InnerSCS.Third;
4087 SCS.QualificationIncludesObjCLifetime
4088 = InnerSCS.QualificationIncludesObjCLifetime;
4089 SCS.setToType(Idx: 2, T: InnerSCS.getToType(Idx: 2));
4090 return true;
4091}
4092
4093static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From,
4094 QualType ToType,
4095 bool InOverloadResolution,
4096 StandardConversionSequence &SCS,
4097 bool CStyle) {
4098 const OverflowBehaviorType *ToOBT = ToType->getAs<OverflowBehaviorType>();
4099 if (!ToOBT)
4100 return false;
4101
4102 // Check for incompatible OBT kinds (e.g., trap vs wrap)
4103 QualType FromType = From->getType();
4104 if (!S.Context.areCompatibleOverflowBehaviorTypes(LHS: FromType, RHS: ToType))
4105 return false;
4106
4107 StandardConversionSequence InnerSCS;
4108 if (!IsStandardConversion(S, From, ToType: ToOBT->getUnderlyingType(),
4109 InOverloadResolution, SCS&: InnerSCS, CStyle,
4110 /*AllowObjCWritebackConversion=*/false))
4111 return false;
4112
4113 SCS.Second = InnerSCS.Second;
4114 SCS.setToType(Idx: 1, T: InnerSCS.getToType(Idx: 1));
4115 SCS.Third = InnerSCS.Third;
4116 SCS.QualificationIncludesObjCLifetime =
4117 InnerSCS.QualificationIncludesObjCLifetime;
4118 SCS.setToType(Idx: 2, T: InnerSCS.getToType(Idx: 2));
4119 return true;
4120}
4121
4122static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
4123 CXXConstructorDecl *Constructor,
4124 QualType Type) {
4125 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
4126 if (CtorType->getNumParams() > 0) {
4127 QualType FirstArg = CtorType->getParamType(i: 0);
4128 if (Context.hasSameUnqualifiedType(T1: Type, T2: FirstArg.getNonReferenceType()))
4129 return true;
4130 }
4131 return false;
4132}
4133
4134static OverloadingResult
4135IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
4136 CXXRecordDecl *To,
4137 UserDefinedConversionSequence &User,
4138 OverloadCandidateSet &CandidateSet,
4139 bool AllowExplicit) {
4140 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4141 for (auto *D : S.LookupConstructors(Class: To)) {
4142 auto Info = getConstructorInfo(ND: D);
4143 if (!Info)
4144 continue;
4145
4146 bool Usable = !Info.Constructor->isInvalidDecl() &&
4147 S.isInitListConstructor(Ctor: Info.Constructor);
4148 if (Usable) {
4149 bool SuppressUserConversions = false;
4150 if (Info.ConstructorTmpl)
4151 S.AddTemplateOverloadCandidate(FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
4152 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: From,
4153 CandidateSet, SuppressUserConversions,
4154 /*PartialOverloading*/ false,
4155 AllowExplicit);
4156 else
4157 S.AddOverloadCandidate(Function: Info.Constructor, FoundDecl: Info.FoundDecl, Args: From,
4158 CandidateSet, SuppressUserConversions,
4159 /*PartialOverloading*/ false, AllowExplicit);
4160 }
4161 }
4162
4163 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4164
4165 OverloadCandidateSet::iterator Best;
4166 switch (auto Result =
4167 CandidateSet.BestViableFunction(S, Loc: From->getBeginLoc(), Best)) {
4168 case OR_Deleted:
4169 case OR_Success: {
4170 // Record the standard conversion we used and the conversion function.
4171 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Val: Best->Function);
4172 QualType ThisType = Constructor->getFunctionObjectParameterType();
4173 // Initializer lists don't have conversions as such.
4174 User.Before.setAsIdentityConversion();
4175 User.HadMultipleCandidates = HadMultipleCandidates;
4176 User.ConversionFunction = Constructor;
4177 User.FoundConversionFunction = Best->FoundDecl;
4178 User.After.setAsIdentityConversion();
4179 User.After.setFromType(ThisType);
4180 User.After.setAllToTypes(ToType);
4181 return Result;
4182 }
4183
4184 case OR_No_Viable_Function:
4185 return OR_No_Viable_Function;
4186 case OR_Ambiguous:
4187 return OR_Ambiguous;
4188 }
4189
4190 llvm_unreachable("Invalid OverloadResult!");
4191}
4192
4193/// Determines whether there is a user-defined conversion sequence
4194/// (C++ [over.ics.user]) that converts expression From to the type
4195/// ToType. If such a conversion exists, User will contain the
4196/// user-defined conversion sequence that performs such a conversion
4197/// and this routine will return true. Otherwise, this routine returns
4198/// false and User is unspecified.
4199///
4200/// \param AllowExplicit true if the conversion should consider C++0x
4201/// "explicit" conversion functions as well as non-explicit conversion
4202/// functions (C++0x [class.conv.fct]p2).
4203///
4204/// \param AllowObjCConversionOnExplicit true if the conversion should
4205/// allow an extra Objective-C pointer conversion on uses of explicit
4206/// constructors. Requires \c AllowExplicit to also be set.
4207static OverloadingResult
4208IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
4209 UserDefinedConversionSequence &User,
4210 OverloadCandidateSet &CandidateSet,
4211 AllowedExplicit AllowExplicit,
4212 bool AllowObjCConversionOnExplicit) {
4213 assert(AllowExplicit != AllowedExplicit::None ||
4214 !AllowObjCConversionOnExplicit);
4215 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4216
4217 // Whether we will only visit constructors.
4218 bool ConstructorsOnly = false;
4219
4220 // If the type we are conversion to is a class type, enumerate its
4221 // constructors.
4222 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {
4223 // C++ [over.match.ctor]p1:
4224 // When objects of class type are direct-initialized (8.5), or
4225 // copy-initialized from an expression of the same or a
4226 // derived class type (8.5), overload resolution selects the
4227 // constructor. [...] For copy-initialization, the candidate
4228 // functions are all the converting constructors (12.3.1) of
4229 // that class. The argument list is the expression-list within
4230 // the parentheses of the initializer.
4231 if (S.Context.hasSameUnqualifiedType(T1: ToType, T2: From->getType()) ||
4232 (From->getType()->isRecordType() &&
4233 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: From->getType(), Base: ToType)))
4234 ConstructorsOnly = true;
4235
4236 if (!S.isCompleteType(Loc: From->getExprLoc(), T: ToType)) {
4237 // We're not going to find any constructors.
4238 } else if (auto *ToRecordDecl =
4239 dyn_cast<CXXRecordDecl>(Val: ToRecordType->getDecl())) {
4240 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();
4241
4242 Expr **Args = &From;
4243 unsigned NumArgs = 1;
4244 bool ListInitializing = false;
4245 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Val: From)) {
4246 // But first, see if there is an init-list-constructor that will work.
4247 OverloadingResult Result = IsInitializerListConstructorConversion(
4248 S, From, ToType, To: ToRecordDecl, User, CandidateSet,
4249 AllowExplicit: AllowExplicit == AllowedExplicit::All);
4250 if (Result != OR_No_Viable_Function)
4251 return Result;
4252 // Never mind.
4253 CandidateSet.clear(
4254 CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4255
4256 // If we're list-initializing, we pass the individual elements as
4257 // arguments, not the entire list.
4258 Args = InitList->getInits();
4259 NumArgs = InitList->getNumInits();
4260 ListInitializing = true;
4261 }
4262
4263 for (auto *D : S.LookupConstructors(Class: ToRecordDecl)) {
4264 auto Info = getConstructorInfo(ND: D);
4265 if (!Info)
4266 continue;
4267
4268 bool Usable = !Info.Constructor->isInvalidDecl();
4269 if (!ListInitializing)
4270 Usable = Usable && Info.Constructor->isConvertingConstructor(
4271 /*AllowExplicit*/ true);
4272 if (Usable) {
4273 bool SuppressUserConversions = !ConstructorsOnly;
4274 // C++20 [over.best.ics.general]/4.5:
4275 // if the target is the first parameter of a constructor [of class
4276 // X] and the constructor [...] is a candidate by [...] the second
4277 // phase of [over.match.list] when the initializer list has exactly
4278 // one element that is itself an initializer list, [...] and the
4279 // conversion is to X or reference to cv X, user-defined conversion
4280 // sequences are not considered.
4281 if (SuppressUserConversions && ListInitializing) {
4282 SuppressUserConversions =
4283 NumArgs == 1 && isa<InitListExpr>(Val: Args[0]) &&
4284 isFirstArgumentCompatibleWithType(Context&: S.Context, Constructor: Info.Constructor,
4285 Type: ToType);
4286 }
4287 if (Info.ConstructorTmpl)
4288 S.AddTemplateOverloadCandidate(
4289 FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
4290 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: llvm::ArrayRef(Args, NumArgs),
4291 CandidateSet, SuppressUserConversions,
4292 /*PartialOverloading*/ false,
4293 AllowExplicit: AllowExplicit == AllowedExplicit::All);
4294 else
4295 // Allow one user-defined conversion when user specifies a
4296 // From->ToType conversion via an static cast (c-style, etc).
4297 S.AddOverloadCandidate(Function: Info.Constructor, FoundDecl: Info.FoundDecl,
4298 Args: llvm::ArrayRef(Args, NumArgs), CandidateSet,
4299 SuppressUserConversions,
4300 /*PartialOverloading*/ false,
4301 AllowExplicit: AllowExplicit == AllowedExplicit::All);
4302 }
4303 }
4304 }
4305 }
4306
4307 // Enumerate conversion functions, if we're allowed to.
4308 if (ConstructorsOnly || isa<InitListExpr>(Val: From)) {
4309 } else if (!S.isCompleteType(Loc: From->getBeginLoc(), T: From->getType())) {
4310 // No conversion functions from incomplete types.
4311 } else if (const RecordType *FromRecordType =
4312 From->getType()->getAsCanonical<RecordType>()) {
4313 if (auto *FromRecordDecl =
4314 dyn_cast<CXXRecordDecl>(Val: FromRecordType->getDecl())) {
4315 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();
4316 // Add all of the conversion functions as candidates.
4317 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4318 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4319 DeclAccessPair FoundDecl = I.getPair();
4320 NamedDecl *D = FoundDecl.getDecl();
4321 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
4322 if (isa<UsingShadowDecl>(Val: D))
4323 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
4324
4325 CXXConversionDecl *Conv;
4326 FunctionTemplateDecl *ConvTemplate;
4327 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)))
4328 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
4329 else
4330 Conv = cast<CXXConversionDecl>(Val: D);
4331
4332 if (ConvTemplate)
4333 S.AddTemplateConversionCandidate(
4334 FunctionTemplate: ConvTemplate, FoundDecl, ActingContext, From, ToType,
4335 CandidateSet, AllowObjCConversionOnExplicit,
4336 AllowExplicit: AllowExplicit != AllowedExplicit::None);
4337 else
4338 S.AddConversionCandidate(Conversion: Conv, FoundDecl, ActingContext, From, ToType,
4339 CandidateSet, AllowObjCConversionOnExplicit,
4340 AllowExplicit: AllowExplicit != AllowedExplicit::None);
4341 }
4342 }
4343 }
4344
4345 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4346
4347 OverloadCandidateSet::iterator Best;
4348 switch (auto Result =
4349 CandidateSet.BestViableFunction(S, Loc: From->getBeginLoc(), Best)) {
4350 case OR_Success:
4351 case OR_Deleted:
4352 // Record the standard conversion we used and the conversion function.
4353 if (CXXConstructorDecl *Constructor
4354 = dyn_cast<CXXConstructorDecl>(Val: Best->Function)) {
4355 // C++ [over.ics.user]p1:
4356 // If the user-defined conversion is specified by a
4357 // constructor (12.3.1), the initial standard conversion
4358 // sequence converts the source type to the type required by
4359 // the argument of the constructor.
4360 //
4361 if (isa<InitListExpr>(Val: From)) {
4362 // Initializer lists don't have conversions as such.
4363 User.Before.setAsIdentityConversion();
4364 User.Before.FromBracedInitList = true;
4365 } else {
4366 if (Best->Conversions[0].isEllipsis())
4367 User.EllipsisConversion = true;
4368 else {
4369 User.Before = Best->Conversions[0].Standard;
4370 User.EllipsisConversion = false;
4371 }
4372 }
4373 User.HadMultipleCandidates = HadMultipleCandidates;
4374 User.ConversionFunction = Constructor;
4375 User.FoundConversionFunction = Best->FoundDecl;
4376 User.After.setAsIdentityConversion();
4377 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4378 User.After.setAllToTypes(ToType);
4379 return Result;
4380 }
4381 if (CXXConversionDecl *Conversion
4382 = dyn_cast<CXXConversionDecl>(Val: Best->Function)) {
4383
4384 assert(Best->HasFinalConversion);
4385
4386 // C++ [over.ics.user]p1:
4387 //
4388 // [...] If the user-defined conversion is specified by a
4389 // conversion function (12.3.2), the initial standard
4390 // conversion sequence converts the source type to the
4391 // implicit object parameter of the conversion function.
4392 User.Before = Best->Conversions[0].Standard;
4393 User.HadMultipleCandidates = HadMultipleCandidates;
4394 User.ConversionFunction = Conversion;
4395 User.FoundConversionFunction = Best->FoundDecl;
4396 User.EllipsisConversion = false;
4397
4398 // C++ [over.ics.user]p2:
4399 // The second standard conversion sequence converts the
4400 // result of the user-defined conversion to the target type
4401 // for the sequence. Since an implicit conversion sequence
4402 // is an initialization, the special rules for
4403 // initialization by user-defined conversion apply when
4404 // selecting the best user-defined conversion for a
4405 // user-defined conversion sequence (see 13.3.3 and
4406 // 13.3.3.1).
4407 User.After = Best->FinalConversion;
4408 return Result;
4409 }
4410 llvm_unreachable("Not a constructor or conversion function?");
4411
4412 case OR_No_Viable_Function:
4413 return OR_No_Viable_Function;
4414
4415 case OR_Ambiguous:
4416 return OR_Ambiguous;
4417 }
4418
4419 llvm_unreachable("Invalid OverloadResult!");
4420}
4421
4422bool
4423Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
4424 ImplicitConversionSequence ICS;
4425 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4426 OverloadCandidateSet::CSK_Normal);
4427 OverloadingResult OvResult =
4428 IsUserDefinedConversion(S&: *this, From, ToType, User&: ICS.UserDefined,
4429 CandidateSet, AllowExplicit: AllowedExplicit::None, AllowObjCConversionOnExplicit: false);
4430
4431 if (!(OvResult == OR_Ambiguous ||
4432 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4433 return false;
4434
4435 auto Cands = CandidateSet.CompleteCandidates(
4436 S&: *this,
4437 OCD: OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
4438 Args: From);
4439 if (OvResult == OR_Ambiguous)
4440 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_ambiguous_condition)
4441 << From->getType() << ToType << From->getSourceRange();
4442 else { // OR_No_Viable_Function && !CandidateSet.empty()
4443 if (!RequireCompleteType(Loc: From->getBeginLoc(), T: ToType,
4444 DiagID: diag::err_typecheck_nonviable_condition_incomplete,
4445 Args: From->getType(), Args: From->getSourceRange()))
4446 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_nonviable_condition)
4447 << false << From->getType() << From->getSourceRange() << ToType;
4448 }
4449
4450 CandidateSet.NoteCandidates(
4451 S&: *this, Args: From, Cands);
4452 return true;
4453}
4454
4455// Helper for compareConversionFunctions that gets the FunctionType that the
4456// conversion-operator return value 'points' to, or nullptr.
4457static const FunctionType *
4458getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
4459 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4460 const PointerType *RetPtrTy =
4461 ConvFuncTy->getReturnType()->getAs<PointerType>();
4462
4463 if (!RetPtrTy)
4464 return nullptr;
4465
4466 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4467}
4468
4469/// Compare the user-defined conversion functions or constructors
4470/// of two user-defined conversion sequences to determine whether any ordering
4471/// is possible.
4472static ImplicitConversionSequence::CompareKind
4473compareConversionFunctions(Sema &S, FunctionDecl *Function1,
4474 FunctionDecl *Function2) {
4475 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Val: Function1);
4476 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Val: Function2);
4477 if (!Conv1 || !Conv2)
4478 return ImplicitConversionSequence::Indistinguishable;
4479
4480 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4481 return ImplicitConversionSequence::Indistinguishable;
4482
4483 // Objective-C++:
4484 // If both conversion functions are implicitly-declared conversions from
4485 // a lambda closure type to a function pointer and a block pointer,
4486 // respectively, always prefer the conversion to a function pointer,
4487 // because the function pointer is more lightweight and is more likely
4488 // to keep code working.
4489 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4490 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4491 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4492 if (Block1 != Block2)
4493 return Block1 ? ImplicitConversionSequence::Worse
4494 : ImplicitConversionSequence::Better;
4495 }
4496
4497 // In order to support multiple calling conventions for the lambda conversion
4498 // operator (such as when the free and member function calling convention is
4499 // different), prefer the 'free' mechanism, followed by the calling-convention
4500 // of operator(). The latter is in place to support the MSVC-like solution of
4501 // defining ALL of the possible conversions in regards to calling-convention.
4502 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv: Conv1);
4503 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv: Conv2);
4504
4505 if (Conv1FuncRet && Conv2FuncRet &&
4506 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4507 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4508 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4509
4510 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4511 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4512
4513 CallingConv CallOpCC =
4514 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4515 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
4516 IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4517 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
4518 IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4519
4520 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4521 for (CallingConv CC : PrefOrder) {
4522 if (Conv1CC == CC)
4523 return ImplicitConversionSequence::Better;
4524 if (Conv2CC == CC)
4525 return ImplicitConversionSequence::Worse;
4526 }
4527 }
4528
4529 return ImplicitConversionSequence::Indistinguishable;
4530}
4531
4532static bool hasDeprecatedStringLiteralToCharPtrConversion(
4533 const ImplicitConversionSequence &ICS) {
4534 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
4535 (ICS.isUserDefined() &&
4536 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
4537}
4538
4539/// CompareImplicitConversionSequences - Compare two implicit
4540/// conversion sequences to determine whether one is better than the
4541/// other or if they are indistinguishable (C++ 13.3.3.2).
4542static ImplicitConversionSequence::CompareKind
4543CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
4544 const ImplicitConversionSequence& ICS1,
4545 const ImplicitConversionSequence& ICS2)
4546{
4547 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4548 // conversion sequences (as defined in 13.3.3.1)
4549 // -- a standard conversion sequence (13.3.3.1.1) is a better
4550 // conversion sequence than a user-defined conversion sequence or
4551 // an ellipsis conversion sequence, and
4552 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4553 // conversion sequence than an ellipsis conversion sequence
4554 // (13.3.3.1.3).
4555 //
4556 // C++0x [over.best.ics]p10:
4557 // For the purpose of ranking implicit conversion sequences as
4558 // described in 13.3.3.2, the ambiguous conversion sequence is
4559 // treated as a user-defined sequence that is indistinguishable
4560 // from any other user-defined conversion sequence.
4561
4562 // String literal to 'char *' conversion has been deprecated in C++03. It has
4563 // been removed from C++11. We still accept this conversion, if it happens at
4564 // the best viable function. Otherwise, this conversion is considered worse
4565 // than ellipsis conversion. Consider this as an extension; this is not in the
4566 // standard. For example:
4567 //
4568 // int &f(...); // #1
4569 // void f(char*); // #2
4570 // void g() { int &r = f("foo"); }
4571 //
4572 // In C++03, we pick #2 as the best viable function.
4573 // In C++11, we pick #1 as the best viable function, because ellipsis
4574 // conversion is better than string-literal to char* conversion (since there
4575 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4576 // convert arguments, #2 would be the best viable function in C++11.
4577 // If the best viable function has this conversion, a warning will be issued
4578 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4579
4580 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4581 hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS1) !=
4582 hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS2) &&
4583 // Ill-formedness must not differ
4584 ICS1.isBad() == ICS2.isBad())
4585 return hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS1)
4586 ? ImplicitConversionSequence::Worse
4587 : ImplicitConversionSequence::Better;
4588
4589 if (ICS1.getKindRank() < ICS2.getKindRank())
4590 return ImplicitConversionSequence::Better;
4591 if (ICS2.getKindRank() < ICS1.getKindRank())
4592 return ImplicitConversionSequence::Worse;
4593
4594 // The following checks require both conversion sequences to be of
4595 // the same kind.
4596 if (ICS1.getKind() != ICS2.getKind())
4597 return ImplicitConversionSequence::Indistinguishable;
4598
4599 ImplicitConversionSequence::CompareKind Result =
4600 ImplicitConversionSequence::Indistinguishable;
4601
4602 // Two implicit conversion sequences of the same form are
4603 // indistinguishable conversion sequences unless one of the
4604 // following rules apply: (C++ 13.3.3.2p3):
4605
4606 // List-initialization sequence L1 is a better conversion sequence than
4607 // list-initialization sequence L2 if:
4608 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4609 // if not that,
4610 // — L1 and L2 convert to arrays of the same element type, and either the
4611 // number of elements n_1 initialized by L1 is less than the number of
4612 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4613 // an array of unknown bound and L1 does not,
4614 // even if one of the other rules in this paragraph would otherwise apply.
4615 if (!ICS1.isBad()) {
4616 bool StdInit1 = false, StdInit2 = false;
4617 if (ICS1.hasInitializerListContainerType())
4618 StdInit1 = S.isStdInitializerList(Ty: ICS1.getInitializerListContainerType(),
4619 Element: nullptr);
4620 if (ICS2.hasInitializerListContainerType())
4621 StdInit2 = S.isStdInitializerList(Ty: ICS2.getInitializerListContainerType(),
4622 Element: nullptr);
4623 if (StdInit1 != StdInit2)
4624 return StdInit1 ? ImplicitConversionSequence::Better
4625 : ImplicitConversionSequence::Worse;
4626
4627 if (ICS1.hasInitializerListContainerType() &&
4628 ICS2.hasInitializerListContainerType())
4629 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4630 T: ICS1.getInitializerListContainerType()))
4631 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4632 T: ICS2.getInitializerListContainerType())) {
4633 if (S.Context.hasSameUnqualifiedType(T1: CAT1->getElementType(),
4634 T2: CAT2->getElementType())) {
4635 // Both to arrays of the same element type
4636 if (CAT1->getSize() != CAT2->getSize())
4637 // Different sized, the smaller wins
4638 return CAT1->getSize().ult(RHS: CAT2->getSize())
4639 ? ImplicitConversionSequence::Better
4640 : ImplicitConversionSequence::Worse;
4641 if (ICS1.isInitializerListOfIncompleteArray() !=
4642 ICS2.isInitializerListOfIncompleteArray())
4643 // One is incomplete, it loses
4644 return ICS2.isInitializerListOfIncompleteArray()
4645 ? ImplicitConversionSequence::Better
4646 : ImplicitConversionSequence::Worse;
4647 }
4648 }
4649 }
4650
4651 if (ICS1.isStandard())
4652 // Standard conversion sequence S1 is a better conversion sequence than
4653 // standard conversion sequence S2 if [...]
4654 Result = CompareStandardConversionSequences(S, Loc,
4655 SCS1: ICS1.Standard, SCS2: ICS2.Standard);
4656 else if (ICS1.isUserDefined()) {
4657 // With lazy template loading, it is possible to find non-canonical
4658 // FunctionDecls, depending on when redecl chains are completed. Make sure
4659 // to compare the canonical decls of conversion functions. This avoids
4660 // ambiguity problems for templated conversion operators.
4661 const FunctionDecl *ConvFunc1 = ICS1.UserDefined.ConversionFunction;
4662 if (ConvFunc1)
4663 ConvFunc1 = ConvFunc1->getCanonicalDecl();
4664 const FunctionDecl *ConvFunc2 = ICS2.UserDefined.ConversionFunction;
4665 if (ConvFunc2)
4666 ConvFunc2 = ConvFunc2->getCanonicalDecl();
4667 // User-defined conversion sequence U1 is a better conversion
4668 // sequence than another user-defined conversion sequence U2 if
4669 // they contain the same user-defined conversion function or
4670 // constructor and if the second standard conversion sequence of
4671 // U1 is better than the second standard conversion sequence of
4672 // U2 (C++ 13.3.3.2p3).
4673 if (ConvFunc1 == ConvFunc2)
4674 Result = CompareStandardConversionSequences(S, Loc,
4675 SCS1: ICS1.UserDefined.After,
4676 SCS2: ICS2.UserDefined.After);
4677 else
4678 Result = compareConversionFunctions(S,
4679 Function1: ICS1.UserDefined.ConversionFunction,
4680 Function2: ICS2.UserDefined.ConversionFunction);
4681 }
4682
4683 return Result;
4684}
4685
4686// Per 13.3.3.2p3, compare the given standard conversion sequences to
4687// determine if one is a proper subset of the other.
4688static ImplicitConversionSequence::CompareKind
4689compareStandardConversionSubsets(ASTContext &Context,
4690 const StandardConversionSequence& SCS1,
4691 const StandardConversionSequence& SCS2) {
4692 ImplicitConversionSequence::CompareKind Result
4693 = ImplicitConversionSequence::Indistinguishable;
4694
4695 // the identity conversion sequence is considered to be a subsequence of
4696 // any non-identity conversion sequence
4697 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4698 return ImplicitConversionSequence::Better;
4699 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4700 return ImplicitConversionSequence::Worse;
4701
4702 if (SCS1.Second != SCS2.Second) {
4703 if (SCS1.Second == ICK_Identity)
4704 Result = ImplicitConversionSequence::Better;
4705 else if (SCS2.Second == ICK_Identity)
4706 Result = ImplicitConversionSequence::Worse;
4707 else
4708 return ImplicitConversionSequence::Indistinguishable;
4709 } else if (!Context.hasSimilarType(T1: SCS1.getToType(Idx: 1), T2: SCS2.getToType(Idx: 1)))
4710 return ImplicitConversionSequence::Indistinguishable;
4711
4712 if (SCS1.Third == SCS2.Third) {
4713 return Context.hasSameType(T1: SCS1.getToType(Idx: 2), T2: SCS2.getToType(Idx: 2))? Result
4714 : ImplicitConversionSequence::Indistinguishable;
4715 }
4716
4717 if (SCS1.Third == ICK_Identity)
4718 return Result == ImplicitConversionSequence::Worse
4719 ? ImplicitConversionSequence::Indistinguishable
4720 : ImplicitConversionSequence::Better;
4721
4722 if (SCS2.Third == ICK_Identity)
4723 return Result == ImplicitConversionSequence::Better
4724 ? ImplicitConversionSequence::Indistinguishable
4725 : ImplicitConversionSequence::Worse;
4726
4727 return ImplicitConversionSequence::Indistinguishable;
4728}
4729
4730/// Determine whether one of the given reference bindings is better
4731/// than the other based on what kind of bindings they are.
4732static bool
4733isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
4734 const StandardConversionSequence &SCS2) {
4735 // C++0x [over.ics.rank]p3b4:
4736 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4737 // implicit object parameter of a non-static member function declared
4738 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4739 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4740 // lvalue reference to a function lvalue and S2 binds an rvalue
4741 // reference*.
4742 //
4743 // FIXME: Rvalue references. We're going rogue with the above edits,
4744 // because the semantics in the current C++0x working paper (N3225 at the
4745 // time of this writing) break the standard definition of std::forward
4746 // and std::reference_wrapper when dealing with references to functions.
4747 // Proposed wording changes submitted to CWG for consideration.
4748 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
4749 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
4750 return false;
4751
4752 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4753 SCS2.IsLvalueReference) ||
4754 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
4755 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
4756}
4757
4758enum class FixedEnumPromotion {
4759 None,
4760 ToUnderlyingType,
4761 ToPromotedUnderlyingType
4762};
4763
4764/// Returns kind of fixed enum promotion the \a SCS uses.
4765static FixedEnumPromotion
4766getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
4767
4768 if (SCS.Second != ICK_Integral_Promotion)
4769 return FixedEnumPromotion::None;
4770
4771 const auto *Enum = SCS.getFromType()->getAsEnumDecl();
4772 if (!Enum)
4773 return FixedEnumPromotion::None;
4774
4775 if (!Enum->isFixed())
4776 return FixedEnumPromotion::None;
4777
4778 QualType UnderlyingType = Enum->getIntegerType();
4779 if (S.Context.hasSameType(T1: SCS.getToType(Idx: 1), T2: UnderlyingType))
4780 return FixedEnumPromotion::ToUnderlyingType;
4781
4782 return FixedEnumPromotion::ToPromotedUnderlyingType;
4783}
4784
4785/// CompareStandardConversionSequences - Compare two standard
4786/// conversion sequences to determine whether one is better than the
4787/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4788static ImplicitConversionSequence::CompareKind
4789CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
4790 const StandardConversionSequence& SCS1,
4791 const StandardConversionSequence& SCS2)
4792{
4793 // Standard conversion sequence S1 is a better conversion sequence
4794 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4795
4796 // -- S1 is a proper subsequence of S2 (comparing the conversion
4797 // sequences in the canonical form defined by 13.3.3.1.1,
4798 // excluding any Lvalue Transformation; the identity conversion
4799 // sequence is considered to be a subsequence of any
4800 // non-identity conversion sequence) or, if not that,
4801 if (ImplicitConversionSequence::CompareKind CK
4802 = compareStandardConversionSubsets(Context&: S.Context, SCS1, SCS2))
4803 return CK;
4804
4805 // -- the rank of S1 is better than the rank of S2 (by the rules
4806 // defined below), or, if not that,
4807 ImplicitConversionRank Rank1 = SCS1.getRank();
4808 ImplicitConversionRank Rank2 = SCS2.getRank();
4809 if (Rank1 < Rank2)
4810 return ImplicitConversionSequence::Better;
4811 else if (Rank2 < Rank1)
4812 return ImplicitConversionSequence::Worse;
4813
4814 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4815 // are indistinguishable unless one of the following rules
4816 // applies:
4817
4818 // A conversion that is not a conversion of a pointer, or
4819 // pointer to member, to bool is better than another conversion
4820 // that is such a conversion.
4821 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4822 return SCS2.isPointerConversionToBool()
4823 ? ImplicitConversionSequence::Better
4824 : ImplicitConversionSequence::Worse;
4825
4826 // C++14 [over.ics.rank]p4b2:
4827 // This is retroactively applied to C++11 by CWG 1601.
4828 //
4829 // A conversion that promotes an enumeration whose underlying type is fixed
4830 // to its underlying type is better than one that promotes to the promoted
4831 // underlying type, if the two are different.
4832 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS: SCS1);
4833 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS: SCS2);
4834 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4835 FEP1 != FEP2)
4836 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4837 ? ImplicitConversionSequence::Better
4838 : ImplicitConversionSequence::Worse;
4839
4840 // C++ [over.ics.rank]p4b2:
4841 //
4842 // If class B is derived directly or indirectly from class A,
4843 // conversion of B* to A* is better than conversion of B* to
4844 // void*, and conversion of A* to void* is better than conversion
4845 // of B* to void*.
4846 bool SCS1ConvertsToVoid
4847 = SCS1.isPointerConversionToVoidPointer(Context&: S.Context);
4848 bool SCS2ConvertsToVoid
4849 = SCS2.isPointerConversionToVoidPointer(Context&: S.Context);
4850 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4851 // Exactly one of the conversion sequences is a conversion to
4852 // a void pointer; it's the worse conversion.
4853 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4854 : ImplicitConversionSequence::Worse;
4855 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4856 // Neither conversion sequence converts to a void pointer; compare
4857 // their derived-to-base conversions.
4858 if (ImplicitConversionSequence::CompareKind DerivedCK
4859 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4860 return DerivedCK;
4861 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4862 !S.Context.hasSameType(T1: SCS1.getFromType(), T2: SCS2.getFromType())) {
4863 // Both conversion sequences are conversions to void
4864 // pointers. Compare the source types to determine if there's an
4865 // inheritance relationship in their sources.
4866 QualType FromType1 = SCS1.getFromType();
4867 QualType FromType2 = SCS2.getFromType();
4868
4869 // Adjust the types we're converting from via the array-to-pointer
4870 // conversion, if we need to.
4871 if (SCS1.First == ICK_Array_To_Pointer)
4872 FromType1 = S.Context.getArrayDecayedType(T: FromType1);
4873 if (SCS2.First == ICK_Array_To_Pointer)
4874 FromType2 = S.Context.getArrayDecayedType(T: FromType2);
4875
4876 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4877 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4878
4879 if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
4880 return ImplicitConversionSequence::Better;
4881 else if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
4882 return ImplicitConversionSequence::Worse;
4883
4884 // Objective-C++: If one interface is more specific than the
4885 // other, it is the better one.
4886 const ObjCObjectPointerType* FromObjCPtr1
4887 = FromType1->getAs<ObjCObjectPointerType>();
4888 const ObjCObjectPointerType* FromObjCPtr2
4889 = FromType2->getAs<ObjCObjectPointerType>();
4890 if (FromObjCPtr1 && FromObjCPtr2) {
4891 bool AssignLeft = S.Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr1,
4892 RHSOPT: FromObjCPtr2);
4893 bool AssignRight = S.Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr2,
4894 RHSOPT: FromObjCPtr1);
4895 if (AssignLeft != AssignRight) {
4896 return AssignLeft? ImplicitConversionSequence::Better
4897 : ImplicitConversionSequence::Worse;
4898 }
4899 }
4900 }
4901
4902 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4903 // Check for a better reference binding based on the kind of bindings.
4904 if (isBetterReferenceBindingKind(SCS1, SCS2))
4905 return ImplicitConversionSequence::Better;
4906 else if (isBetterReferenceBindingKind(SCS1: SCS2, SCS2: SCS1))
4907 return ImplicitConversionSequence::Worse;
4908 }
4909
4910 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4911 // bullet 3).
4912 if (ImplicitConversionSequence::CompareKind QualCK
4913 = CompareQualificationConversions(S, SCS1, SCS2))
4914 return QualCK;
4915
4916 if (ImplicitConversionSequence::CompareKind ObtCK =
4917 CompareOverflowBehaviorConversions(S, SCS1, SCS2))
4918 return ObtCK;
4919
4920 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4921 // C++ [over.ics.rank]p3b4:
4922 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4923 // which the references refer are the same type except for
4924 // top-level cv-qualifiers, and the type to which the reference
4925 // initialized by S2 refers is more cv-qualified than the type
4926 // to which the reference initialized by S1 refers.
4927 QualType T1 = SCS1.getToType(Idx: 2);
4928 QualType T2 = SCS2.getToType(Idx: 2);
4929 T1 = S.Context.getCanonicalType(T: T1);
4930 T2 = S.Context.getCanonicalType(T: T2);
4931 Qualifiers T1Quals, T2Quals;
4932 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
4933 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
4934 if (UnqualT1 == UnqualT2) {
4935 // Objective-C++ ARC: If the references refer to objects with different
4936 // lifetimes, prefer bindings that don't change lifetime.
4937 if (SCS1.ObjCLifetimeConversionBinding !=
4938 SCS2.ObjCLifetimeConversionBinding) {
4939 return SCS1.ObjCLifetimeConversionBinding
4940 ? ImplicitConversionSequence::Worse
4941 : ImplicitConversionSequence::Better;
4942 }
4943
4944 // If the type is an array type, promote the element qualifiers to the
4945 // type for comparison.
4946 if (isa<ArrayType>(Val: T1) && T1Quals)
4947 T1 = S.Context.getQualifiedType(T: UnqualT1, Qs: T1Quals);
4948 if (isa<ArrayType>(Val: T2) && T2Quals)
4949 T2 = S.Context.getQualifiedType(T: UnqualT2, Qs: T2Quals);
4950 if (T2.isMoreQualifiedThan(other: T1, Ctx: S.getASTContext()))
4951 return ImplicitConversionSequence::Better;
4952 if (T1.isMoreQualifiedThan(other: T2, Ctx: S.getASTContext()))
4953 return ImplicitConversionSequence::Worse;
4954 }
4955 }
4956
4957 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4958 // floating-to-integral conversion if the integral conversion
4959 // is between types of the same size.
4960 // For example:
4961 // void f(float);
4962 // void f(int);
4963 // int main {
4964 // long a;
4965 // f(a);
4966 // }
4967 // Here, MSVC will call f(int) instead of generating a compile error
4968 // as clang will do in standard mode.
4969 if (S.getLangOpts().MSVCCompat &&
4970 !S.getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2019_8) &&
4971 SCS1.Second == ICK_Integral_Conversion &&
4972 SCS2.Second == ICK_Floating_Integral &&
4973 S.Context.getTypeSize(T: SCS1.getFromType()) ==
4974 S.Context.getTypeSize(T: SCS1.getToType(Idx: 2)))
4975 return ImplicitConversionSequence::Better;
4976
4977 // Prefer a compatible vector conversion over a lax vector conversion
4978 // For example:
4979 //
4980 // typedef float __v4sf __attribute__((__vector_size__(16)));
4981 // void f(vector float);
4982 // void f(vector signed int);
4983 // int main() {
4984 // __v4sf a;
4985 // f(a);
4986 // }
4987 // Here, we'd like to choose f(vector float) and not
4988 // report an ambiguous call error
4989 if (SCS1.Second == ICK_Vector_Conversion &&
4990 SCS2.Second == ICK_Vector_Conversion) {
4991 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4992 FirstVec: SCS1.getFromType(), SecondVec: SCS1.getToType(Idx: 2));
4993 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4994 FirstVec: SCS2.getFromType(), SecondVec: SCS2.getToType(Idx: 2));
4995
4996 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4997 return SCS1IsCompatibleVectorConversion
4998 ? ImplicitConversionSequence::Better
4999 : ImplicitConversionSequence::Worse;
5000 }
5001
5002 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
5003 SCS2.Second == ICK_SVE_Vector_Conversion) {
5004 bool SCS1IsCompatibleSVEVectorConversion =
5005 S.ARM().areCompatibleSveTypes(FirstType: SCS1.getFromType(), SecondType: SCS1.getToType(Idx: 2));
5006 bool SCS2IsCompatibleSVEVectorConversion =
5007 S.ARM().areCompatibleSveTypes(FirstType: SCS2.getFromType(), SecondType: SCS2.getToType(Idx: 2));
5008
5009 if (SCS1IsCompatibleSVEVectorConversion !=
5010 SCS2IsCompatibleSVEVectorConversion)
5011 return SCS1IsCompatibleSVEVectorConversion
5012 ? ImplicitConversionSequence::Better
5013 : ImplicitConversionSequence::Worse;
5014 }
5015
5016 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
5017 SCS2.Second == ICK_RVV_Vector_Conversion) {
5018 bool SCS1IsCompatibleRVVVectorConversion =
5019 S.Context.areCompatibleRVVTypes(FirstType: SCS1.getFromType(), SecondType: SCS1.getToType(Idx: 2));
5020 bool SCS2IsCompatibleRVVVectorConversion =
5021 S.Context.areCompatibleRVVTypes(FirstType: SCS2.getFromType(), SecondType: SCS2.getToType(Idx: 2));
5022
5023 if (SCS1IsCompatibleRVVVectorConversion !=
5024 SCS2IsCompatibleRVVVectorConversion)
5025 return SCS1IsCompatibleRVVVectorConversion
5026 ? ImplicitConversionSequence::Better
5027 : ImplicitConversionSequence::Worse;
5028 }
5029 return ImplicitConversionSequence::Indistinguishable;
5030}
5031
5032/// CompareOverflowBehaviorConversions - Compares two standard conversion
5033/// sequences to determine whether they can be ranked based on their
5034/// OverflowBehaviorType's underlying type.
5035static ImplicitConversionSequence::CompareKind
5036CompareOverflowBehaviorConversions(Sema &S,
5037 const StandardConversionSequence &SCS1,
5038 const StandardConversionSequence &SCS2) {
5039
5040 if (SCS1.getFromType()->isOverflowBehaviorType() &&
5041 SCS1.getToType(Idx: 2)->isOverflowBehaviorType())
5042 return ImplicitConversionSequence::Better;
5043
5044 if (SCS2.getFromType()->isOverflowBehaviorType() &&
5045 SCS2.getToType(Idx: 2)->isOverflowBehaviorType())
5046 return ImplicitConversionSequence::Worse;
5047
5048 return ImplicitConversionSequence::Indistinguishable;
5049}
5050
5051/// CompareQualificationConversions - Compares two standard conversion
5052/// sequences to determine whether they can be ranked based on their
5053/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
5054static ImplicitConversionSequence::CompareKind
5055CompareQualificationConversions(Sema &S,
5056 const StandardConversionSequence& SCS1,
5057 const StandardConversionSequence& SCS2) {
5058 // C++ [over.ics.rank]p3:
5059 // -- S1 and S2 differ only in their qualification conversion and
5060 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
5061 // [C++98]
5062 // [...] and the cv-qualification signature of type T1 is a proper subset
5063 // of the cv-qualification signature of type T2, and S1 is not the
5064 // deprecated string literal array-to-pointer conversion (4.2).
5065 // [C++2a]
5066 // [...] where T1 can be converted to T2 by a qualification conversion.
5067 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
5068 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
5069 return ImplicitConversionSequence::Indistinguishable;
5070
5071 // FIXME: the example in the standard doesn't use a qualification
5072 // conversion (!)
5073 QualType T1 = SCS1.getToType(Idx: 2);
5074 QualType T2 = SCS2.getToType(Idx: 2);
5075 T1 = S.Context.getCanonicalType(T: T1);
5076 T2 = S.Context.getCanonicalType(T: T2);
5077 assert(!T1->isReferenceType() && !T2->isReferenceType());
5078 Qualifiers T1Quals, T2Quals;
5079 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
5080 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
5081
5082 // If the types are the same, we won't learn anything by unwrapping
5083 // them.
5084 if (UnqualT1 == UnqualT2)
5085 return ImplicitConversionSequence::Indistinguishable;
5086
5087 // Don't ever prefer a standard conversion sequence that uses the deprecated
5088 // string literal array to pointer conversion.
5089 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
5090 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
5091
5092 // Objective-C++ ARC:
5093 // Prefer qualification conversions not involving a change in lifetime
5094 // to qualification conversions that do change lifetime.
5095 if (SCS1.QualificationIncludesObjCLifetime &&
5096 !SCS2.QualificationIncludesObjCLifetime)
5097 CanPick1 = false;
5098 if (SCS2.QualificationIncludesObjCLifetime &&
5099 !SCS1.QualificationIncludesObjCLifetime)
5100 CanPick2 = false;
5101
5102 bool ObjCLifetimeConversion;
5103 if (CanPick1 &&
5104 !S.IsQualificationConversion(FromType: T1, ToType: T2, CStyle: false, ObjCLifetimeConversion))
5105 CanPick1 = false;
5106 // FIXME: In Objective-C ARC, we can have qualification conversions in both
5107 // directions, so we can't short-cut this second check in general.
5108 if (CanPick2 &&
5109 !S.IsQualificationConversion(FromType: T2, ToType: T1, CStyle: false, ObjCLifetimeConversion))
5110 CanPick2 = false;
5111
5112 if (CanPick1 != CanPick2)
5113 return CanPick1 ? ImplicitConversionSequence::Better
5114 : ImplicitConversionSequence::Worse;
5115 return ImplicitConversionSequence::Indistinguishable;
5116}
5117
5118/// CompareDerivedToBaseConversions - Compares two standard conversion
5119/// sequences to determine whether they can be ranked based on their
5120/// various kinds of derived-to-base conversions (C++
5121/// [over.ics.rank]p4b3). As part of these checks, we also look at
5122/// conversions between Objective-C interface types.
5123static ImplicitConversionSequence::CompareKind
5124CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
5125 const StandardConversionSequence& SCS1,
5126 const StandardConversionSequence& SCS2) {
5127 QualType FromType1 = SCS1.getFromType();
5128 QualType ToType1 = SCS1.getToType(Idx: 1);
5129 QualType FromType2 = SCS2.getFromType();
5130 QualType ToType2 = SCS2.getToType(Idx: 1);
5131
5132 // Adjust the types we're converting from via the array-to-pointer
5133 // conversion, if we need to.
5134 if (SCS1.First == ICK_Array_To_Pointer)
5135 FromType1 = S.Context.getArrayDecayedType(T: FromType1);
5136 if (SCS2.First == ICK_Array_To_Pointer)
5137 FromType2 = S.Context.getArrayDecayedType(T: FromType2);
5138
5139 // Canonicalize all of the types.
5140 FromType1 = S.Context.getCanonicalType(T: FromType1);
5141 ToType1 = S.Context.getCanonicalType(T: ToType1);
5142 FromType2 = S.Context.getCanonicalType(T: FromType2);
5143 ToType2 = S.Context.getCanonicalType(T: ToType2);
5144
5145 // C++ [over.ics.rank]p4b3:
5146 //
5147 // If class B is derived directly or indirectly from class A and
5148 // class C is derived directly or indirectly from B,
5149 //
5150 // Compare based on pointer conversions.
5151 if (SCS1.Second == ICK_Pointer_Conversion &&
5152 SCS2.Second == ICK_Pointer_Conversion &&
5153 /*FIXME: Remove if Objective-C id conversions get their own rank*/
5154 FromType1->isPointerType() && FromType2->isPointerType() &&
5155 ToType1->isPointerType() && ToType2->isPointerType()) {
5156 QualType FromPointee1 =
5157 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5158 QualType ToPointee1 =
5159 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5160 QualType FromPointee2 =
5161 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5162 QualType ToPointee2 =
5163 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5164
5165 // -- conversion of C* to B* is better than conversion of C* to A*,
5166 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5167 if (S.IsDerivedFrom(Loc, Derived: ToPointee1, Base: ToPointee2))
5168 return ImplicitConversionSequence::Better;
5169 else if (S.IsDerivedFrom(Loc, Derived: ToPointee2, Base: ToPointee1))
5170 return ImplicitConversionSequence::Worse;
5171 }
5172
5173 // -- conversion of B* to A* is better than conversion of C* to A*,
5174 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
5175 if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
5176 return ImplicitConversionSequence::Better;
5177 else if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
5178 return ImplicitConversionSequence::Worse;
5179 }
5180 } else if (SCS1.Second == ICK_Pointer_Conversion &&
5181 SCS2.Second == ICK_Pointer_Conversion) {
5182 const ObjCObjectPointerType *FromPtr1
5183 = FromType1->getAs<ObjCObjectPointerType>();
5184 const ObjCObjectPointerType *FromPtr2
5185 = FromType2->getAs<ObjCObjectPointerType>();
5186 const ObjCObjectPointerType *ToPtr1
5187 = ToType1->getAs<ObjCObjectPointerType>();
5188 const ObjCObjectPointerType *ToPtr2
5189 = ToType2->getAs<ObjCObjectPointerType>();
5190
5191 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
5192 // Apply the same conversion ranking rules for Objective-C pointer types
5193 // that we do for C++ pointers to class types. However, we employ the
5194 // Objective-C pseudo-subtyping relationship used for assignment of
5195 // Objective-C pointer types.
5196 bool FromAssignLeft
5197 = S.Context.canAssignObjCInterfaces(LHSOPT: FromPtr1, RHSOPT: FromPtr2);
5198 bool FromAssignRight
5199 = S.Context.canAssignObjCInterfaces(LHSOPT: FromPtr2, RHSOPT: FromPtr1);
5200 bool ToAssignLeft
5201 = S.Context.canAssignObjCInterfaces(LHSOPT: ToPtr1, RHSOPT: ToPtr2);
5202 bool ToAssignRight
5203 = S.Context.canAssignObjCInterfaces(LHSOPT: ToPtr2, RHSOPT: ToPtr1);
5204
5205 // A conversion to an a non-id object pointer type or qualified 'id'
5206 // type is better than a conversion to 'id'.
5207 if (ToPtr1->isObjCIdType() &&
5208 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
5209 return ImplicitConversionSequence::Worse;
5210 if (ToPtr2->isObjCIdType() &&
5211 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
5212 return ImplicitConversionSequence::Better;
5213
5214 // A conversion to a non-id object pointer type is better than a
5215 // conversion to a qualified 'id' type
5216 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
5217 return ImplicitConversionSequence::Worse;
5218 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
5219 return ImplicitConversionSequence::Better;
5220
5221 // A conversion to an a non-Class object pointer type or qualified 'Class'
5222 // type is better than a conversion to 'Class'.
5223 if (ToPtr1->isObjCClassType() &&
5224 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
5225 return ImplicitConversionSequence::Worse;
5226 if (ToPtr2->isObjCClassType() &&
5227 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
5228 return ImplicitConversionSequence::Better;
5229
5230 // A conversion to a non-Class object pointer type is better than a
5231 // conversion to a qualified 'Class' type.
5232 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
5233 return ImplicitConversionSequence::Worse;
5234 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
5235 return ImplicitConversionSequence::Better;
5236
5237 // -- "conversion of C* to B* is better than conversion of C* to A*,"
5238 if (S.Context.hasSameType(T1: FromType1, T2: FromType2) &&
5239 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
5240 (ToAssignLeft != ToAssignRight)) {
5241 if (FromPtr1->isSpecialized()) {
5242 // "conversion of B<A> * to B * is better than conversion of B * to
5243 // C *.
5244 bool IsFirstSame =
5245 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
5246 bool IsSecondSame =
5247 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
5248 if (IsFirstSame) {
5249 if (!IsSecondSame)
5250 return ImplicitConversionSequence::Better;
5251 } else if (IsSecondSame)
5252 return ImplicitConversionSequence::Worse;
5253 }
5254 return ToAssignLeft? ImplicitConversionSequence::Worse
5255 : ImplicitConversionSequence::Better;
5256 }
5257
5258 // -- "conversion of B* to A* is better than conversion of C* to A*,"
5259 if (S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2) &&
5260 (FromAssignLeft != FromAssignRight))
5261 return FromAssignLeft? ImplicitConversionSequence::Better
5262 : ImplicitConversionSequence::Worse;
5263 }
5264 }
5265
5266 // Ranking of member-pointer types.
5267 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
5268 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
5269 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
5270 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
5271 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
5272 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
5273 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
5274 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
5275 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
5276 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
5277 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
5278 // conversion of A::* to B::* is better than conversion of A::* to C::*,
5279 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5280 if (S.IsDerivedFrom(Loc, Derived: ToPointee1, Base: ToPointee2))
5281 return ImplicitConversionSequence::Worse;
5282 else if (S.IsDerivedFrom(Loc, Derived: ToPointee2, Base: ToPointee1))
5283 return ImplicitConversionSequence::Better;
5284 }
5285 // conversion of B::* to C::* is better than conversion of A::* to C::*
5286 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5287 if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
5288 return ImplicitConversionSequence::Better;
5289 else if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
5290 return ImplicitConversionSequence::Worse;
5291 }
5292 }
5293
5294 if (SCS1.Second == ICK_Derived_To_Base) {
5295 // -- conversion of C to B is better than conversion of C to A,
5296 // -- binding of an expression of type C to a reference of type
5297 // B& is better than binding an expression of type C to a
5298 // reference of type A&,
5299 if (S.Context.hasSameUnqualifiedType(T1: FromType1, T2: FromType2) &&
5300 !S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2)) {
5301 if (S.IsDerivedFrom(Loc, Derived: ToType1, Base: ToType2))
5302 return ImplicitConversionSequence::Better;
5303 else if (S.IsDerivedFrom(Loc, Derived: ToType2, Base: ToType1))
5304 return ImplicitConversionSequence::Worse;
5305 }
5306
5307 // -- conversion of B to A is better than conversion of C to A.
5308 // -- binding of an expression of type B to a reference of type
5309 // A& is better than binding an expression of type C to a
5310 // reference of type A&,
5311 if (!S.Context.hasSameUnqualifiedType(T1: FromType1, T2: FromType2) &&
5312 S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2)) {
5313 if (S.IsDerivedFrom(Loc, Derived: FromType2, Base: FromType1))
5314 return ImplicitConversionSequence::Better;
5315 else if (S.IsDerivedFrom(Loc, Derived: FromType1, Base: FromType2))
5316 return ImplicitConversionSequence::Worse;
5317 }
5318 }
5319
5320 return ImplicitConversionSequence::Indistinguishable;
5321}
5322
5323static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
5324 if (!T.getQualifiers().hasUnaligned())
5325 return T;
5326
5327 Qualifiers Q;
5328 T = Ctx.getUnqualifiedArrayType(T, Quals&: Q);
5329 Q.removeUnaligned();
5330 return Ctx.getQualifiedType(T, Qs: Q);
5331}
5332
5333Sema::ReferenceCompareResult
5334Sema::CompareReferenceRelationship(SourceLocation Loc,
5335 QualType OrigT1, QualType OrigT2,
5336 ReferenceConversions *ConvOut) {
5337 assert(!OrigT1->isReferenceType() &&
5338 "T1 must be the pointee type of the reference type");
5339 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5340
5341 QualType T1 = Context.getCanonicalType(T: OrigT1);
5342 QualType T2 = Context.getCanonicalType(T: OrigT2);
5343 Qualifiers T1Quals, T2Quals;
5344 QualType UnqualT1 = Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
5345 QualType UnqualT2 = Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
5346
5347 ReferenceConversions ConvTmp;
5348 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5349 Conv = ReferenceConversions();
5350
5351 // C++2a [dcl.init.ref]p4:
5352 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5353 // reference-related to "cv2 T2" if T1 is similar to T2, or
5354 // T1 is a base class of T2.
5355 // "cv1 T1" is reference-compatible with "cv2 T2" if
5356 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5357 // "pointer to cv1 T1" via a standard conversion sequence.
5358
5359 // Check for standard conversions we can apply to pointers: derived-to-base
5360 // conversions, ObjC pointer conversions, and function pointer conversions.
5361 // (Qualification conversions are checked last.)
5362 if (UnqualT1 == UnqualT2) {
5363 // Nothing to do.
5364 } else if (isCompleteType(Loc, T: OrigT2) &&
5365 IsDerivedFrom(Loc, Derived: UnqualT2, Base: UnqualT1))
5366 Conv |= ReferenceConversions::DerivedToBase;
5367 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5368 UnqualT2->isObjCObjectOrInterfaceType() &&
5369 Context.canBindObjCObjectType(To: UnqualT1, From: UnqualT2))
5370 Conv |= ReferenceConversions::ObjC;
5371 else if (UnqualT2->isFunctionType() &&
5372 IsFunctionConversion(FromType: UnqualT2, ToType: UnqualT1)) {
5373 Conv |= ReferenceConversions::Function;
5374 // No need to check qualifiers; function types don't have them.
5375 return Ref_Compatible;
5376 }
5377 bool ConvertedReferent = Conv != 0;
5378
5379 // We can have a qualification conversion. Compute whether the types are
5380 // similar at the same time.
5381 bool PreviousToQualsIncludeConst = true;
5382 bool TopLevel = true;
5383 do {
5384 if (T1 == T2)
5385 break;
5386
5387 // We will need a qualification conversion.
5388 Conv |= ReferenceConversions::Qualification;
5389
5390 // Track whether we performed a qualification conversion anywhere other
5391 // than the top level. This matters for ranking reference bindings in
5392 // overload resolution.
5393 if (!TopLevel)
5394 Conv |= ReferenceConversions::NestedQualification;
5395
5396 // MS compiler ignores __unaligned qualifier for references; do the same.
5397 T1 = withoutUnaligned(Ctx&: Context, T: T1);
5398 T2 = withoutUnaligned(Ctx&: Context, T: T2);
5399
5400 // If we find a qualifier mismatch, the types are not reference-compatible,
5401 // but are still be reference-related if they're similar.
5402 bool ObjCLifetimeConversion = false;
5403 if (!isQualificationConversionStep(FromType: T2, ToType: T1, /*CStyle=*/false, IsTopLevel: TopLevel,
5404 PreviousToQualsIncludeConst,
5405 ObjCLifetimeConversion, Ctx: getASTContext()))
5406 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5407 ? Ref_Related
5408 : Ref_Incompatible;
5409
5410 // FIXME: Should we track this for any level other than the first?
5411 if (ObjCLifetimeConversion)
5412 Conv |= ReferenceConversions::ObjCLifetime;
5413
5414 TopLevel = false;
5415 } while (Context.UnwrapSimilarTypes(T1, T2));
5416
5417 // At this point, if the types are reference-related, we must either have the
5418 // same inner type (ignoring qualifiers), or must have already worked out how
5419 // to convert the referent.
5420 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5421 ? Ref_Compatible
5422 : Ref_Incompatible;
5423}
5424
5425/// Look for a user-defined conversion to a value reference-compatible
5426/// with DeclType. Return true if something definite is found.
5427static bool
5428FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
5429 QualType DeclType, SourceLocation DeclLoc,
5430 Expr *Init, QualType T2, bool AllowRvalues,
5431 bool AllowExplicit) {
5432 assert(T2->isRecordType() && "Can only find conversions of record types.");
5433 auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5434 OverloadCandidateSet CandidateSet(
5435 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
5436 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5437 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5438 NamedDecl *D = *I;
5439 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: D->getDeclContext());
5440 if (isa<UsingShadowDecl>(Val: D))
5441 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
5442
5443 FunctionTemplateDecl *ConvTemplate
5444 = dyn_cast<FunctionTemplateDecl>(Val: D);
5445 CXXConversionDecl *Conv;
5446 if (ConvTemplate)
5447 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
5448 else
5449 Conv = cast<CXXConversionDecl>(Val: D);
5450
5451 if (AllowRvalues) {
5452 // If we are initializing an rvalue reference, don't permit conversion
5453 // functions that return lvalues.
5454 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5455 const ReferenceType *RefType
5456 = Conv->getConversionType()->getAs<LValueReferenceType>();
5457 if (RefType && !RefType->getPointeeType()->isFunctionType())
5458 continue;
5459 }
5460
5461 if (!ConvTemplate &&
5462 S.CompareReferenceRelationship(
5463 Loc: DeclLoc,
5464 OrigT1: Conv->getConversionType()
5465 .getNonReferenceType()
5466 .getUnqualifiedType(),
5467 OrigT2: DeclType.getNonReferenceType().getUnqualifiedType()) ==
5468 Sema::Ref_Incompatible)
5469 continue;
5470 } else {
5471 // If the conversion function doesn't return a reference type,
5472 // it can't be considered for this conversion. An rvalue reference
5473 // is only acceptable if its referencee is a function type.
5474
5475 const ReferenceType *RefType =
5476 Conv->getConversionType()->getAs<ReferenceType>();
5477 if (!RefType ||
5478 (!RefType->isLValueReferenceType() &&
5479 !RefType->getPointeeType()->isFunctionType()))
5480 continue;
5481 }
5482
5483 if (ConvTemplate)
5484 S.AddTemplateConversionCandidate(
5485 FunctionTemplate: ConvTemplate, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Init, ToType: DeclType, CandidateSet,
5486 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5487 else
5488 S.AddConversionCandidate(
5489 Conversion: Conv, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Init, ToType: DeclType, CandidateSet,
5490 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5491 }
5492
5493 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5494
5495 OverloadCandidateSet::iterator Best;
5496 switch (CandidateSet.BestViableFunction(S, Loc: DeclLoc, Best)) {
5497 case OR_Success:
5498
5499 assert(Best->HasFinalConversion);
5500
5501 // C++ [over.ics.ref]p1:
5502 //
5503 // [...] If the parameter binds directly to the result of
5504 // applying a conversion function to the argument
5505 // expression, the implicit conversion sequence is a
5506 // user-defined conversion sequence (13.3.3.1.2), with the
5507 // second standard conversion sequence either an identity
5508 // conversion or, if the conversion function returns an
5509 // entity of a type that is a derived class of the parameter
5510 // type, a derived-to-base Conversion.
5511 if (!Best->FinalConversion.DirectBinding)
5512 return false;
5513
5514 ICS.setUserDefined();
5515 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5516 ICS.UserDefined.After = Best->FinalConversion;
5517 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5518 ICS.UserDefined.ConversionFunction = Best->Function;
5519 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5520 ICS.UserDefined.EllipsisConversion = false;
5521 assert(ICS.UserDefined.After.ReferenceBinding &&
5522 ICS.UserDefined.After.DirectBinding &&
5523 "Expected a direct reference binding!");
5524 return true;
5525
5526 case OR_Ambiguous:
5527 ICS.setAmbiguous();
5528 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5529 Cand != CandidateSet.end(); ++Cand)
5530 if (Cand->Best)
5531 ICS.Ambiguous.addConversion(Found: Cand->FoundDecl, D: Cand->Function);
5532 return true;
5533
5534 case OR_No_Viable_Function:
5535 case OR_Deleted:
5536 // There was no suitable conversion, or we found a deleted
5537 // conversion; continue with other checks.
5538 return false;
5539 }
5540
5541 llvm_unreachable("Invalid OverloadResult!");
5542}
5543
5544/// Compute an implicit conversion sequence for reference
5545/// initialization.
5546static ImplicitConversionSequence
5547TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
5548 SourceLocation DeclLoc,
5549 bool SuppressUserConversions,
5550 bool AllowExplicit) {
5551 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5552
5553 // Most paths end in a failed conversion.
5554 ImplicitConversionSequence ICS;
5555 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5556
5557 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5558 QualType T2 = Init->getType();
5559
5560 // If the initializer is the address of an overloaded function, try
5561 // to resolve the overloaded function. If all goes well, T2 is the
5562 // type of the resulting function.
5563 if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) {
5564 DeclAccessPair Found;
5565 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: Init, TargetType: DeclType,
5566 Complain: false, Found))
5567 T2 = Fn->getType();
5568 }
5569
5570 // Compute some basic properties of the types and the initializer.
5571 bool isRValRef = DeclType->isRValueReferenceType();
5572 Expr::Classification InitCategory = Init->Classify(Ctx&: S.Context);
5573
5574 Sema::ReferenceConversions RefConv;
5575 Sema::ReferenceCompareResult RefRelationship =
5576 S.CompareReferenceRelationship(Loc: DeclLoc, OrigT1: T1, OrigT2: T2, ConvOut: &RefConv);
5577
5578 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5579 ICS.setStandard();
5580 ICS.Standard.First = ICK_Identity;
5581 // FIXME: A reference binding can be a function conversion too. We should
5582 // consider that when ordering reference-to-function bindings.
5583 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5584 ? ICK_Derived_To_Base
5585 : (RefConv & Sema::ReferenceConversions::ObjC)
5586 ? ICK_Compatible_Conversion
5587 : ICK_Identity;
5588 ICS.Standard.Dimension = ICK_Identity;
5589 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5590 // a reference binding that performs a non-top-level qualification
5591 // conversion as a qualification conversion, not as an identity conversion.
5592 ICS.Standard.Third = (RefConv &
5593 Sema::ReferenceConversions::NestedQualification)
5594 ? ICK_Qualification
5595 : ICK_Identity;
5596 ICS.Standard.setFromType(T2);
5597 ICS.Standard.setToType(Idx: 0, T: T2);
5598 ICS.Standard.setToType(Idx: 1, T: T1);
5599 ICS.Standard.setToType(Idx: 2, T: T1);
5600 ICS.Standard.ReferenceBinding = true;
5601 ICS.Standard.DirectBinding = BindsDirectly;
5602 ICS.Standard.IsLvalueReference = !isRValRef;
5603 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
5604 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5605 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5606 ICS.Standard.ObjCLifetimeConversionBinding =
5607 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5608 ICS.Standard.FromBracedInitList = false;
5609 ICS.Standard.CopyConstructor = nullptr;
5610 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
5611 };
5612
5613 // C++0x [dcl.init.ref]p5:
5614 // A reference to type "cv1 T1" is initialized by an expression
5615 // of type "cv2 T2" as follows:
5616
5617 // -- If reference is an lvalue reference and the initializer expression
5618 if (!isRValRef) {
5619 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5620 // reference-compatible with "cv2 T2," or
5621 //
5622 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5623 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5624 // C++ [over.ics.ref]p1:
5625 // When a parameter of reference type binds directly (8.5.3)
5626 // to an argument expression, the implicit conversion sequence
5627 // is the identity conversion, unless the argument expression
5628 // has a type that is a derived class of the parameter type,
5629 // in which case the implicit conversion sequence is a
5630 // derived-to-base Conversion (13.3.3.1).
5631 SetAsReferenceBinding(/*BindsDirectly=*/true);
5632
5633 // Nothing more to do: the inaccessibility/ambiguity check for
5634 // derived-to-base conversions is suppressed when we're
5635 // computing the implicit conversion sequence (C++
5636 // [over.best.ics]p2).
5637 return ICS;
5638 }
5639
5640 // -- has a class type (i.e., T2 is a class type), where T1 is
5641 // not reference-related to T2, and can be implicitly
5642 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5643 // is reference-compatible with "cv3 T3" 92) (this
5644 // conversion is selected by enumerating the applicable
5645 // conversion functions (13.3.1.6) and choosing the best
5646 // one through overload resolution (13.3)),
5647 if (!SuppressUserConversions && T2->isRecordType() &&
5648 S.isCompleteType(Loc: DeclLoc, T: T2) &&
5649 RefRelationship == Sema::Ref_Incompatible) {
5650 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5651 Init, T2, /*AllowRvalues=*/false,
5652 AllowExplicit))
5653 return ICS;
5654 }
5655 }
5656
5657 // -- Otherwise, the reference shall be an lvalue reference to a
5658 // non-volatile const type (i.e., cv1 shall be const), or the reference
5659 // shall be an rvalue reference.
5660 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5661 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5662 ICS.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue, FromExpr: Init, ToType: DeclType);
5663 return ICS;
5664 }
5665
5666 // -- If the initializer expression
5667 //
5668 // -- is an xvalue, class prvalue, array prvalue or function
5669 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5670 if (RefRelationship == Sema::Ref_Compatible &&
5671 (InitCategory.isXValue() ||
5672 (InitCategory.isPRValue() &&
5673 (T2->isRecordType() || T2->isArrayType())) ||
5674 (InitCategory.isLValue() && T2->isFunctionType()))) {
5675 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5676 // binding unless we're binding to a class prvalue.
5677 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5678 // allow the use of rvalue references in C++98/03 for the benefit of
5679 // standard library implementors; therefore, we need the xvalue check here.
5680 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5681 !(InitCategory.isPRValue() || T2->isRecordType()));
5682 return ICS;
5683 }
5684
5685 // -- has a class type (i.e., T2 is a class type), where T1 is not
5686 // reference-related to T2, and can be implicitly converted to
5687 // an xvalue, class prvalue, or function lvalue of type
5688 // "cv3 T3", where "cv1 T1" is reference-compatible with
5689 // "cv3 T3",
5690 //
5691 // then the reference is bound to the value of the initializer
5692 // expression in the first case and to the result of the conversion
5693 // in the second case (or, in either case, to an appropriate base
5694 // class subobject).
5695 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5696 T2->isRecordType() && S.isCompleteType(Loc: DeclLoc, T: T2) &&
5697 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5698 Init, T2, /*AllowRvalues=*/true,
5699 AllowExplicit)) {
5700 // In the second case, if the reference is an rvalue reference
5701 // and the second standard conversion sequence of the
5702 // user-defined conversion sequence includes an lvalue-to-rvalue
5703 // conversion, the program is ill-formed.
5704 if (ICS.isUserDefined() && isRValRef &&
5705 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
5706 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5707
5708 return ICS;
5709 }
5710
5711 // A temporary of function type cannot be created; don't even try.
5712 if (T1->isFunctionType())
5713 return ICS;
5714
5715 // -- Otherwise, a temporary of type "cv1 T1" is created and
5716 // initialized from the initializer expression using the
5717 // rules for a non-reference copy initialization (8.5). The
5718 // reference is then bound to the temporary. If T1 is
5719 // reference-related to T2, cv1 must be the same
5720 // cv-qualification as, or greater cv-qualification than,
5721 // cv2; otherwise, the program is ill-formed.
5722 if (RefRelationship == Sema::Ref_Related) {
5723 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5724 // we would be reference-compatible or reference-compatible with
5725 // added qualification. But that wasn't the case, so the reference
5726 // initialization fails.
5727 //
5728 // Note that we only want to check address spaces and cvr-qualifiers here.
5729 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5730 Qualifiers T1Quals = T1.getQualifiers();
5731 Qualifiers T2Quals = T2.getQualifiers();
5732 T1Quals.removeObjCGCAttr();
5733 T1Quals.removeObjCLifetime();
5734 T2Quals.removeObjCGCAttr();
5735 T2Quals.removeObjCLifetime();
5736 // MS compiler ignores __unaligned qualifier for references; do the same.
5737 T1Quals.removeUnaligned();
5738 T2Quals.removeUnaligned();
5739 if (!T1Quals.compatiblyIncludes(other: T2Quals, Ctx: S.getASTContext()))
5740 return ICS;
5741 }
5742
5743 // If at least one of the types is a class type, the types are not
5744 // related, and we aren't allowed any user conversions, the
5745 // reference binding fails. This case is important for breaking
5746 // recursion, since TryImplicitConversion below will attempt to
5747 // create a temporary through the use of a copy constructor.
5748 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5749 (T1->isRecordType() || T2->isRecordType()))
5750 return ICS;
5751
5752 // If T1 is reference-related to T2 and the reference is an rvalue
5753 // reference, the initializer expression shall not be an lvalue.
5754 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5755 Init->Classify(Ctx&: S.Context).isLValue()) {
5756 ICS.setBad(Failure: BadConversionSequence::rvalue_ref_to_lvalue, FromExpr: Init, ToType: DeclType);
5757 return ICS;
5758 }
5759
5760 // C++ [over.ics.ref]p2:
5761 // When a parameter of reference type is not bound directly to
5762 // an argument expression, the conversion sequence is the one
5763 // required to convert the argument expression to the
5764 // underlying type of the reference according to
5765 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5766 // to copy-initializing a temporary of the underlying type with
5767 // the argument expression. Any difference in top-level
5768 // cv-qualification is subsumed by the initialization itself
5769 // and does not constitute a conversion.
5770 ICS = TryImplicitConversion(S, From: Init, ToType: T1, SuppressUserConversions,
5771 AllowExplicit: AllowedExplicit::None,
5772 /*InOverloadResolution=*/false,
5773 /*CStyle=*/false,
5774 /*AllowObjCWritebackConversion=*/false,
5775 /*AllowObjCConversionOnExplicit=*/false);
5776
5777 // Of course, that's still a reference binding.
5778 if (ICS.isStandard()) {
5779 ICS.Standard.ReferenceBinding = true;
5780 ICS.Standard.IsLvalueReference = !isRValRef;
5781 ICS.Standard.BindsToFunctionLvalue = false;
5782 ICS.Standard.BindsToRvalue = true;
5783 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5784 ICS.Standard.ObjCLifetimeConversionBinding = false;
5785 } else if (ICS.isUserDefined()) {
5786 const ReferenceType *LValRefType =
5787 ICS.UserDefined.ConversionFunction->getReturnType()
5788 ->getAs<LValueReferenceType>();
5789
5790 // C++ [over.ics.ref]p3:
5791 // Except for an implicit object parameter, for which see 13.3.1, a
5792 // standard conversion sequence cannot be formed if it requires [...]
5793 // binding an rvalue reference to an lvalue other than a function
5794 // lvalue.
5795 // Note that the function case is not possible here.
5796 if (isRValRef && LValRefType) {
5797 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5798 return ICS;
5799 }
5800
5801 ICS.UserDefined.After.ReferenceBinding = true;
5802 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5803 ICS.UserDefined.After.BindsToFunctionLvalue = false;
5804 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5805 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5806 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
5807 ICS.UserDefined.After.FromBracedInitList = false;
5808 }
5809
5810 return ICS;
5811}
5812
5813static ImplicitConversionSequence
5814TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5815 bool SuppressUserConversions,
5816 bool InOverloadResolution,
5817 bool AllowObjCWritebackConversion,
5818 bool AllowExplicit = false);
5819
5820/// TryListConversion - Try to copy-initialize a value of type ToType from the
5821/// initializer list From.
5822static ImplicitConversionSequence
5823TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5824 bool SuppressUserConversions,
5825 bool InOverloadResolution,
5826 bool AllowObjCWritebackConversion) {
5827 // C++11 [over.ics.list]p1:
5828 // When an argument is an initializer list, it is not an expression and
5829 // special rules apply for converting it to a parameter type.
5830
5831 ImplicitConversionSequence Result;
5832 Result.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
5833
5834 // We need a complete type for what follows. With one C++20 exception,
5835 // incomplete types can never be initialized from init lists.
5836 QualType InitTy = ToType;
5837 const ArrayType *AT = S.Context.getAsArrayType(T: ToType);
5838 if (AT && S.getLangOpts().CPlusPlus20)
5839 if (const auto *IAT = dyn_cast<IncompleteArrayType>(Val: AT))
5840 // C++20 allows list initialization of an incomplete array type.
5841 InitTy = IAT->getElementType();
5842 if (!S.isCompleteType(Loc: From->getBeginLoc(), T: InitTy))
5843 return Result;
5844
5845 // C++20 [over.ics.list]/2:
5846 // If the initializer list is a designated-initializer-list, a conversion
5847 // is only possible if the parameter has an aggregate type
5848 //
5849 // FIXME: The exception for reference initialization here is not part of the
5850 // language rules, but follow other compilers in adding it as a tentative DR
5851 // resolution.
5852 bool IsDesignatedInit = From->hasDesignatedInit();
5853 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5854 IsDesignatedInit)
5855 return Result;
5856
5857 // Per DR1467 and DR2137:
5858 // If the parameter type is an aggregate class X and the initializer list
5859 // has a single element of type cv U, where U is X or a class derived from
5860 // X, the implicit conversion sequence is the one required to convert the
5861 // element to the parameter type.
5862 //
5863 // Otherwise, if the parameter type is a character array [... ]
5864 // and the initializer list has a single element that is an
5865 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5866 // implicit conversion sequence is the identity conversion.
5867 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5868 if (ToType->isRecordType() && ToType->isAggregateType()) {
5869 QualType InitType = From->getInit(Init: 0)->getType();
5870 if (S.Context.hasSameUnqualifiedType(T1: InitType, T2: ToType) ||
5871 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: InitType, Base: ToType))
5872 return TryCopyInitialization(S, From: From->getInit(Init: 0), ToType,
5873 SuppressUserConversions,
5874 InOverloadResolution,
5875 AllowObjCWritebackConversion);
5876 }
5877
5878 if (AT && S.IsStringInit(Init: From->getInit(Init: 0), AT)) {
5879 InitializedEntity Entity =
5880 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ToType,
5881 /*Consumed=*/false);
5882 if (S.CanPerformCopyInitialization(Entity, Init: From)) {
5883 Result.setStandard();
5884 Result.Standard.setAsIdentityConversion();
5885 Result.Standard.setFromType(ToType);
5886 Result.Standard.setAllToTypes(ToType);
5887 return Result;
5888 }
5889 }
5890 }
5891
5892 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5893 // C++11 [over.ics.list]p2:
5894 // If the parameter type is std::initializer_list<X> or "array of X" and
5895 // all the elements can be implicitly converted to X, the implicit
5896 // conversion sequence is the worst conversion necessary to convert an
5897 // element of the list to X.
5898 //
5899 // C++14 [over.ics.list]p3:
5900 // Otherwise, if the parameter type is "array of N X", if the initializer
5901 // list has exactly N elements or if it has fewer than N elements and X is
5902 // default-constructible, and if all the elements of the initializer list
5903 // can be implicitly converted to X, the implicit conversion sequence is
5904 // the worst conversion necessary to convert an element of the list to X.
5905 if ((AT || S.isStdInitializerList(Ty: ToType, Element: &InitTy)) && !IsDesignatedInit) {
5906 unsigned e = From->getNumInits();
5907 ImplicitConversionSequence DfltElt;
5908 DfltElt.setBad(Failure: BadConversionSequence::no_conversion, FromType: QualType(),
5909 ToType: QualType());
5910 QualType ContTy = ToType;
5911 bool IsUnbounded = false;
5912 if (AT) {
5913 InitTy = AT->getElementType();
5914 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(Val: AT)) {
5915 if (CT->getSize().ult(RHS: e)) {
5916 // Too many inits, fatally bad
5917 Result.setBad(Failure: BadConversionSequence::too_many_initializers, FromExpr: From,
5918 ToType);
5919 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5920 return Result;
5921 }
5922 if (CT->getSize().ugt(RHS: e)) {
5923 // Need an init from empty {}, is there one?
5924 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5925 From->getEndLoc(), /*isExplicit=*/false);
5926 EmptyList.setType(S.Context.VoidTy);
5927 DfltElt = TryListConversion(
5928 S, From: &EmptyList, ToType: InitTy, SuppressUserConversions,
5929 InOverloadResolution, AllowObjCWritebackConversion);
5930 if (DfltElt.isBad()) {
5931 // No {} init, fatally bad
5932 Result.setBad(Failure: BadConversionSequence::too_few_initializers, FromExpr: From,
5933 ToType);
5934 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5935 return Result;
5936 }
5937 }
5938 } else {
5939 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5940 IsUnbounded = true;
5941 if (!e) {
5942 // Cannot convert to zero-sized.
5943 Result.setBad(Failure: BadConversionSequence::too_few_initializers, FromExpr: From,
5944 ToType);
5945 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5946 return Result;
5947 }
5948 llvm::APInt Size(S.Context.getTypeSize(T: S.Context.getSizeType()), e);
5949 ContTy = S.Context.getConstantArrayType(EltTy: InitTy, ArySize: Size, SizeExpr: nullptr,
5950 ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
5951 }
5952 }
5953
5954 Result.setStandard();
5955 Result.Standard.setAsIdentityConversion();
5956 Result.Standard.setFromType(InitTy);
5957 Result.Standard.setAllToTypes(InitTy);
5958 for (unsigned i = 0; i < e; ++i) {
5959 Expr *Init = From->getInit(Init: i);
5960 ImplicitConversionSequence ICS = TryCopyInitialization(
5961 S, From: Init, ToType: InitTy, SuppressUserConversions, InOverloadResolution,
5962 AllowObjCWritebackConversion);
5963
5964 // Keep the worse conversion seen so far.
5965 // FIXME: Sequences are not totally ordered, so 'worse' can be
5966 // ambiguous. CWG has been informed.
5967 if (CompareImplicitConversionSequences(S, Loc: From->getBeginLoc(), ICS1: ICS,
5968 ICS2: Result) ==
5969 ImplicitConversionSequence::Worse) {
5970 Result = ICS;
5971 // Bail as soon as we find something unconvertible.
5972 if (Result.isBad()) {
5973 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5974 return Result;
5975 }
5976 }
5977 }
5978
5979 // If we needed any implicit {} initialization, compare that now.
5980 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5981 // has been informed that this might not be the best thing.
5982 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5983 S, Loc: From->getEndLoc(), ICS1: DfltElt, ICS2: Result) ==
5984 ImplicitConversionSequence::Worse)
5985 Result = DfltElt;
5986 // Record the type being initialized so that we may compare sequences
5987 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5988 return Result;
5989 }
5990
5991 // C++14 [over.ics.list]p4:
5992 // C++11 [over.ics.list]p3:
5993 // Otherwise, if the parameter is a non-aggregate class X and overload
5994 // resolution chooses a single best constructor [...] the implicit
5995 // conversion sequence is a user-defined conversion sequence. If multiple
5996 // constructors are viable but none is better than the others, the
5997 // implicit conversion sequence is a user-defined conversion sequence.
5998 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5999 // This function can deal with initializer lists.
6000 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
6001 AllowExplicit: AllowedExplicit::None,
6002 InOverloadResolution, /*CStyle=*/false,
6003 AllowObjCWritebackConversion,
6004 /*AllowObjCConversionOnExplicit=*/false);
6005 }
6006
6007 // C++14 [over.ics.list]p5:
6008 // C++11 [over.ics.list]p4:
6009 // Otherwise, if the parameter has an aggregate type which can be
6010 // initialized from the initializer list [...] the implicit conversion
6011 // sequence is a user-defined conversion sequence.
6012 if (ToType->isAggregateType()) {
6013 // Type is an aggregate, argument is an init list. At this point it comes
6014 // down to checking whether the initialization works.
6015 // FIXME: Find out whether this parameter is consumed or not.
6016 InitializedEntity Entity =
6017 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ToType,
6018 /*Consumed=*/false);
6019 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
6020 From)) {
6021 Result.setUserDefined();
6022 Result.UserDefined.Before.setAsIdentityConversion();
6023 // Initializer lists don't have a type.
6024 Result.UserDefined.Before.setFromType(QualType());
6025 Result.UserDefined.Before.setAllToTypes(QualType());
6026
6027 Result.UserDefined.After.setAsIdentityConversion();
6028 Result.UserDefined.After.setFromType(ToType);
6029 Result.UserDefined.After.setAllToTypes(ToType);
6030 Result.UserDefined.ConversionFunction = nullptr;
6031 }
6032 return Result;
6033 }
6034
6035 // C++14 [over.ics.list]p6:
6036 // C++11 [over.ics.list]p5:
6037 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
6038 if (ToType->isReferenceType()) {
6039 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
6040 // mention initializer lists in any way. So we go by what list-
6041 // initialization would do and try to extrapolate from that.
6042
6043 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
6044
6045 // If the initializer list has a single element that is reference-related
6046 // to the parameter type, we initialize the reference from that.
6047 if (From->getNumInits() == 1 && !IsDesignatedInit) {
6048 Expr *Init = From->getInit(Init: 0);
6049
6050 QualType T2 = Init->getType();
6051
6052 // If the initializer is the address of an overloaded function, try
6053 // to resolve the overloaded function. If all goes well, T2 is the
6054 // type of the resulting function.
6055 if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) {
6056 DeclAccessPair Found;
6057 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
6058 AddressOfExpr: Init, TargetType: ToType, Complain: false, Found))
6059 T2 = Fn->getType();
6060 }
6061
6062 // Compute some basic properties of the types and the initializer.
6063 Sema::ReferenceCompareResult RefRelationship =
6064 S.CompareReferenceRelationship(Loc: From->getBeginLoc(), OrigT1: T1, OrigT2: T2);
6065
6066 if (RefRelationship >= Sema::Ref_Related) {
6067 return TryReferenceInit(S, Init, DeclType: ToType, /*FIXME*/ DeclLoc: From->getBeginLoc(),
6068 SuppressUserConversions,
6069 /*AllowExplicit=*/false);
6070 }
6071 }
6072
6073 // Otherwise, we bind the reference to a temporary created from the
6074 // initializer list.
6075 Result = TryListConversion(S, From, ToType: T1, SuppressUserConversions,
6076 InOverloadResolution,
6077 AllowObjCWritebackConversion);
6078 if (Result.isFailure())
6079 return Result;
6080 assert(!Result.isEllipsis() &&
6081 "Sub-initialization cannot result in ellipsis conversion.");
6082
6083 // Can we even bind to a temporary?
6084 if (ToType->isRValueReferenceType() ||
6085 (T1.isConstQualified() && !T1.isVolatileQualified())) {
6086 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
6087 Result.UserDefined.After;
6088 SCS.ReferenceBinding = true;
6089 SCS.IsLvalueReference = ToType->isLValueReferenceType();
6090 SCS.BindsToRvalue = true;
6091 SCS.BindsToFunctionLvalue = false;
6092 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
6093 SCS.ObjCLifetimeConversionBinding = false;
6094 SCS.FromBracedInitList = false;
6095
6096 } else
6097 Result.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue,
6098 FromExpr: From, ToType);
6099 return Result;
6100 }
6101
6102 // C++14 [over.ics.list]p7:
6103 // C++11 [over.ics.list]p6:
6104 // Otherwise, if the parameter type is not a class:
6105 if (!ToType->isRecordType()) {
6106 // - if the initializer list has one element that is not itself an
6107 // initializer list, the implicit conversion sequence is the one
6108 // required to convert the element to the parameter type.
6109 // Bail out on EmbedExpr as well since we never create EmbedExpr for a
6110 // single integer.
6111 unsigned NumInits = From->getNumInits();
6112 if (NumInits == 1 && !isa<InitListExpr>(Val: From->getInit(Init: 0)) &&
6113 !isa<EmbedExpr>(Val: From->getInit(Init: 0))) {
6114 Result = TryCopyInitialization(
6115 S, From: From->getInit(Init: 0), ToType, SuppressUserConversions,
6116 InOverloadResolution, AllowObjCWritebackConversion);
6117 if (Result.isStandard())
6118 Result.Standard.FromBracedInitList = true;
6119 }
6120 // - if the initializer list has no elements, the implicit conversion
6121 // sequence is the identity conversion.
6122 else if (NumInits == 0) {
6123 Result.setStandard();
6124 Result.Standard.setAsIdentityConversion();
6125 Result.Standard.setFromType(ToType);
6126 Result.Standard.setAllToTypes(ToType);
6127 }
6128 return Result;
6129 }
6130
6131 // C++14 [over.ics.list]p8:
6132 // C++11 [over.ics.list]p7:
6133 // In all cases other than those enumerated above, no conversion is possible
6134 return Result;
6135}
6136
6137/// TryCopyInitialization - Try to copy-initialize a value of type
6138/// ToType from the expression From. Return the implicit conversion
6139/// sequence required to pass this argument, which may be a bad
6140/// conversion sequence (meaning that the argument cannot be passed to
6141/// a parameter of this type). If @p SuppressUserConversions, then we
6142/// do not permit any user-defined conversion sequences.
6143static ImplicitConversionSequence
6144TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
6145 bool SuppressUserConversions,
6146 bool InOverloadResolution,
6147 bool AllowObjCWritebackConversion,
6148 bool AllowExplicit) {
6149 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(Val: From))
6150 return TryListConversion(S, From: FromInitList, ToType, SuppressUserConversions,
6151 InOverloadResolution,AllowObjCWritebackConversion);
6152
6153 if (ToType->isReferenceType())
6154 return TryReferenceInit(S, Init: From, DeclType: ToType,
6155 /*FIXME:*/ DeclLoc: From->getBeginLoc(),
6156 SuppressUserConversions, AllowExplicit);
6157
6158 return TryImplicitConversion(S, From, ToType,
6159 SuppressUserConversions,
6160 AllowExplicit: AllowedExplicit::None,
6161 InOverloadResolution,
6162 /*CStyle=*/false,
6163 AllowObjCWritebackConversion,
6164 /*AllowObjCConversionOnExplicit=*/false);
6165}
6166
6167static bool TryCopyInitialization(const CanQualType FromQTy,
6168 const CanQualType ToQTy,
6169 Sema &S,
6170 SourceLocation Loc,
6171 ExprValueKind FromVK) {
6172 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
6173 ImplicitConversionSequence ICS =
6174 TryCopyInitialization(S, From: &TmpExpr, ToType: ToQTy, SuppressUserConversions: true, InOverloadResolution: true, AllowObjCWritebackConversion: false);
6175
6176 return !ICS.isBad();
6177}
6178
6179/// TryObjectArgumentInitialization - Try to initialize the object
6180/// parameter of the given member function (@c Method) from the
6181/// expression @p From.
6182static ImplicitConversionSequence TryObjectArgumentInitialization(
6183 Sema &S, SourceLocation Loc, QualType FromType,
6184 Expr::Classification FromClassification, CXXMethodDecl *Method,
6185 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
6186 QualType ExplicitParameterType = QualType(),
6187 bool SuppressUserConversion = false) {
6188
6189 // We need to have an object of class type.
6190 if (const auto *PT = FromType->getAs<PointerType>()) {
6191 FromType = PT->getPointeeType();
6192
6193 // When we had a pointer, it's implicitly dereferenced, so we
6194 // better have an lvalue.
6195 assert(FromClassification.isLValue());
6196 }
6197
6198 auto ValueKindFromClassification = [](Expr::Classification C) {
6199 if (C.isPRValue())
6200 return clang::VK_PRValue;
6201 if (C.isXValue())
6202 return VK_XValue;
6203 return clang::VK_LValue;
6204 };
6205
6206 if (Method->isExplicitObjectMemberFunction()) {
6207 if (ExplicitParameterType.isNull())
6208 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
6209 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
6210 ValueKindFromClassification(FromClassification));
6211 ImplicitConversionSequence ICS = TryCopyInitialization(
6212 S, From: &TmpExpr, ToType: ExplicitParameterType, SuppressUserConversions: SuppressUserConversion,
6213 /*InOverloadResolution=*/true, AllowObjCWritebackConversion: false);
6214 if (ICS.isBad())
6215 ICS.Bad.FromExpr = nullptr;
6216 return ICS;
6217 }
6218
6219 assert(FromType->isRecordType());
6220
6221 CanQualType ClassType = S.Context.getCanonicalTagType(TD: ActingContext);
6222 // C++98 [class.dtor]p2:
6223 // A destructor can be invoked for a const, volatile or const volatile
6224 // object.
6225 // C++98 [over.match.funcs]p4:
6226 // For static member functions, the implicit object parameter is considered
6227 // to match any object (since if the function is selected, the object is
6228 // discarded).
6229 Qualifiers Quals = Method->getMethodQualifiers();
6230 if (isa<CXXDestructorDecl>(Val: Method) || Method->isStatic()) {
6231 Quals.addConst();
6232 Quals.addVolatile();
6233 }
6234
6235 QualType ImplicitParamType = S.Context.getQualifiedType(T: ClassType, Qs: Quals);
6236
6237 // Set up the conversion sequence as a "bad" conversion, to allow us
6238 // to exit early.
6239 ImplicitConversionSequence ICS;
6240
6241 // C++0x [over.match.funcs]p4:
6242 // For non-static member functions, the type of the implicit object
6243 // parameter is
6244 //
6245 // - "lvalue reference to cv X" for functions declared without a
6246 // ref-qualifier or with the & ref-qualifier
6247 // - "rvalue reference to cv X" for functions declared with the &&
6248 // ref-qualifier
6249 //
6250 // where X is the class of which the function is a member and cv is the
6251 // cv-qualification on the member function declaration.
6252 //
6253 // However, when finding an implicit conversion sequence for the argument, we
6254 // are not allowed to perform user-defined conversions
6255 // (C++ [over.match.funcs]p5). We perform a simplified version of
6256 // reference binding here, that allows class rvalues to bind to
6257 // non-constant references.
6258
6259 // First check the qualifiers.
6260 QualType FromTypeCanon = S.Context.getCanonicalType(T: FromType);
6261 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
6262 if (ImplicitParamType.getCVRQualifiers() !=
6263 FromTypeCanon.getLocalCVRQualifiers() &&
6264 !ImplicitParamType.isAtLeastAsQualifiedAs(
6265 other: withoutUnaligned(Ctx&: S.Context, T: FromTypeCanon), Ctx: S.getASTContext())) {
6266 ICS.setBad(Failure: BadConversionSequence::bad_qualifiers,
6267 FromType, ToType: ImplicitParamType);
6268 return ICS;
6269 }
6270
6271 if (FromTypeCanon.hasAddressSpace()) {
6272 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
6273 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
6274 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(other: QualsFromType,
6275 Ctx: S.getASTContext())) {
6276 ICS.setBad(Failure: BadConversionSequence::bad_qualifiers,
6277 FromType, ToType: ImplicitParamType);
6278 return ICS;
6279 }
6280 }
6281
6282 // Check that we have either the same type or a derived type. It
6283 // affects the conversion rank.
6284 QualType ClassTypeCanon = S.Context.getCanonicalType(T: ClassType);
6285 ImplicitConversionKind SecondKind;
6286 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6287 SecondKind = ICK_Identity;
6288 } else if (S.IsDerivedFrom(Loc, Derived: FromType, Base: ClassType)) {
6289 SecondKind = ICK_Derived_To_Base;
6290 } else if (!Method->isExplicitObjectMemberFunction()) {
6291 ICS.setBad(Failure: BadConversionSequence::unrelated_class,
6292 FromType, ToType: ImplicitParamType);
6293 return ICS;
6294 }
6295
6296 // Check the ref-qualifier.
6297 switch (Method->getRefQualifier()) {
6298 case RQ_None:
6299 // Do nothing; we don't care about lvalueness or rvalueness.
6300 break;
6301
6302 case RQ_LValue:
6303 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6304 // non-const lvalue reference cannot bind to an rvalue
6305 ICS.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue, FromType,
6306 ToType: ImplicitParamType);
6307 return ICS;
6308 }
6309 break;
6310
6311 case RQ_RValue:
6312 if (!FromClassification.isRValue()) {
6313 // rvalue reference cannot bind to an lvalue
6314 ICS.setBad(Failure: BadConversionSequence::rvalue_ref_to_lvalue, FromType,
6315 ToType: ImplicitParamType);
6316 return ICS;
6317 }
6318 break;
6319 }
6320
6321 // Success. Mark this as a reference binding.
6322 ICS.setStandard();
6323 ICS.Standard.setAsIdentityConversion();
6324 ICS.Standard.Second = SecondKind;
6325 ICS.Standard.setFromType(FromType);
6326 ICS.Standard.setAllToTypes(ImplicitParamType);
6327 ICS.Standard.ReferenceBinding = true;
6328 ICS.Standard.DirectBinding = true;
6329 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6330 ICS.Standard.BindsToFunctionLvalue = false;
6331 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6332 ICS.Standard.FromBracedInitList = false;
6333 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
6334 = (Method->getRefQualifier() == RQ_None);
6335 return ICS;
6336}
6337
6338/// PerformObjectArgumentInitialization - Perform initialization of
6339/// the implicit object parameter for the given Method with the given
6340/// expression.
6341ExprResult Sema::PerformImplicitObjectArgumentInitialization(
6342 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6343 CXXMethodDecl *Method) {
6344 QualType FromRecordType, DestType;
6345 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6346
6347 if (getLangOpts().HLSL &&
6348 From->getType().getAddressSpace() == LangAS::hlsl_constant) {
6349 QualType CastType = From->getType().getLocalUnqualifiedType().withConst();
6350 From = ImplicitCastExpr::Create(Context, T: CastType, Kind: CK_LValueToRValue, Operand: From,
6351 /*BasePath=*/nullptr, Cat: VK_PRValue,
6352 FPO: FPOptionsOverride());
6353 }
6354
6355 Expr::Classification FromClassification;
6356 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6357 FromRecordType = PT->getPointeeType();
6358 DestType = Method->getThisType();
6359 FromClassification = Expr::Classification::makeSimpleLValue();
6360 } else {
6361 FromRecordType = From->getType();
6362 DestType = ImplicitParamRecordType;
6363 FromClassification = From->Classify(Ctx&: Context);
6364
6365 // CWG2813 [expr.call]p6:
6366 // If the function is an implicit object member function, the object
6367 // expression of the class member access shall be a glvalue [...]
6368 if (From->isPRValue()) {
6369 From = CreateMaterializeTemporaryExpr(T: FromRecordType, Temporary: From,
6370 BoundToLvalueReference: Method->getRefQualifier() !=
6371 RefQualifierKind::RQ_RValue);
6372 }
6373 }
6374
6375 // Note that we always use the true parent context when performing
6376 // the actual argument initialization.
6377 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
6378 S&: *this, Loc: From->getBeginLoc(), FromType: From->getType(), FromClassification, Method,
6379 ActingContext: Method->getParent());
6380 if (ICS.isBad()) {
6381 switch (ICS.Bad.Kind) {
6382 case BadConversionSequence::bad_qualifiers: {
6383 Qualifiers FromQs = FromRecordType.getQualifiers();
6384 Qualifiers ToQs = DestType.getQualifiers();
6385 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6386 if (CVR) {
6387 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_cvr)
6388 << Method->getDeclName() << FromRecordType << (CVR - 1)
6389 << From->getSourceRange();
6390 Diag(Loc: Method->getLocation(), DiagID: diag::note_previous_decl)
6391 << Method->getDeclName();
6392 return ExprError();
6393 }
6394 break;
6395 }
6396
6397 case BadConversionSequence::lvalue_ref_to_rvalue:
6398 case BadConversionSequence::rvalue_ref_to_lvalue: {
6399 bool IsRValueQualified =
6400 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6401 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_ref)
6402 << Method->getDeclName() << FromClassification.isRValue()
6403 << IsRValueQualified;
6404 Diag(Loc: Method->getLocation(), DiagID: diag::note_previous_decl)
6405 << Method->getDeclName();
6406 return ExprError();
6407 }
6408
6409 case BadConversionSequence::no_conversion:
6410 case BadConversionSequence::unrelated_class:
6411 break;
6412
6413 case BadConversionSequence::too_few_initializers:
6414 case BadConversionSequence::too_many_initializers:
6415 llvm_unreachable("Lists are not objects");
6416 }
6417
6418 return Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_type)
6419 << ImplicitParamRecordType << FromRecordType
6420 << From->getSourceRange();
6421 }
6422
6423 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6424 ExprResult FromRes =
6425 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Member: Method);
6426 if (FromRes.isInvalid())
6427 return ExprError();
6428 From = FromRes.get();
6429 }
6430
6431 if (!Context.hasSameType(T1: From->getType(), T2: DestType)) {
6432 CastKind CK;
6433 QualType PteeTy = DestType->getPointeeType();
6434 LangAS DestAS =
6435 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6436 if (FromRecordType.getAddressSpace() != DestAS)
6437 CK = CK_AddressSpaceConversion;
6438 else
6439 CK = CK_NoOp;
6440 From = ImpCastExprToType(E: From, Type: DestType, CK, VK: From->getValueKind()).get();
6441 }
6442 return From;
6443}
6444
6445/// TryContextuallyConvertToBool - Attempt to contextually convert the
6446/// expression From to bool (C++0x [conv]p3).
6447static ImplicitConversionSequence
6448TryContextuallyConvertToBool(Sema &S, Expr *From) {
6449 // C++ [dcl.init]/17.8:
6450 // - Otherwise, if the initialization is direct-initialization, the source
6451 // type is std::nullptr_t, and the destination type is bool, the initial
6452 // value of the object being initialized is false.
6453 if (From->getType()->isNullPtrType())
6454 return ImplicitConversionSequence::getNullptrToBool(SourceType: From->getType(),
6455 DestType: S.Context.BoolTy,
6456 NeedLValToRVal: From->isGLValue());
6457
6458 // All other direct-initialization of bool is equivalent to an implicit
6459 // conversion to bool in which explicit conversions are permitted.
6460 return TryImplicitConversion(S, From, ToType: S.Context.BoolTy,
6461 /*SuppressUserConversions=*/false,
6462 AllowExplicit: AllowedExplicit::Conversions,
6463 /*InOverloadResolution=*/false,
6464 /*CStyle=*/false,
6465 /*AllowObjCWritebackConversion=*/false,
6466 /*AllowObjCConversionOnExplicit=*/false);
6467}
6468
6469ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
6470 if (checkPlaceholderForOverload(S&: *this, E&: From))
6471 return ExprError();
6472 if (From->getType() == Context.AMDGPUFeaturePredicateTy)
6473 return AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: From);
6474
6475 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(S&: *this, From);
6476 if (!ICS.isBad())
6477 return PerformImplicitConversion(From, ToType: Context.BoolTy, ICS,
6478 Action: AssignmentAction::Converting);
6479 if (!DiagnoseMultipleUserDefinedConversion(From, ToType: Context.BoolTy))
6480 return Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_bool_condition)
6481 << From->getType() << From->getSourceRange();
6482 return ExprError();
6483}
6484
6485/// Check that the specified conversion is permitted in a converted constant
6486/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6487/// is acceptable.
6488static bool CheckConvertedConstantConversions(Sema &S,
6489 StandardConversionSequence &SCS) {
6490 // Since we know that the target type is an integral or unscoped enumeration
6491 // type, most conversion kinds are impossible. All possible First and Third
6492 // conversions are fine.
6493 switch (SCS.Second) {
6494 case ICK_Identity:
6495 case ICK_Integral_Promotion:
6496 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6497 case ICK_Zero_Queue_Conversion:
6498 return true;
6499
6500 case ICK_Boolean_Conversion:
6501 // Conversion from an integral or unscoped enumeration type to bool is
6502 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6503 // conversion, so we allow it in a converted constant expression.
6504 //
6505 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6506 // a lot of popular code. We should at least add a warning for this
6507 // (non-conforming) extension.
6508 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
6509 SCS.getToType(Idx: 2)->isBooleanType();
6510
6511 case ICK_Pointer_Conversion:
6512 case ICK_Pointer_Member:
6513 // C++1z: null pointer conversions and null member pointer conversions are
6514 // only permitted if the source type is std::nullptr_t.
6515 return SCS.getFromType()->isNullPtrType();
6516
6517 case ICK_Floating_Promotion:
6518 case ICK_Complex_Promotion:
6519 case ICK_Floating_Conversion:
6520 case ICK_Complex_Conversion:
6521 case ICK_Floating_Integral:
6522 case ICK_Compatible_Conversion:
6523 case ICK_Derived_To_Base:
6524 case ICK_Vector_Conversion:
6525 case ICK_SVE_Vector_Conversion:
6526 case ICK_RVV_Vector_Conversion:
6527 case ICK_HLSL_Vector_Splat:
6528 case ICK_HLSL_Matrix_Splat:
6529 case ICK_Vector_Splat:
6530 case ICK_Complex_Real:
6531 case ICK_Block_Pointer_Conversion:
6532 case ICK_TransparentUnionConversion:
6533 case ICK_Writeback_Conversion:
6534 case ICK_Zero_Event_Conversion:
6535 case ICK_C_Only_Conversion:
6536 case ICK_Incompatible_Pointer_Conversion:
6537 case ICK_Fixed_Point_Conversion:
6538 case ICK_HLSL_Vector_Truncation:
6539 case ICK_HLSL_Matrix_Truncation:
6540 case ICK_HLSL_Packed_Type_Conversion:
6541 return false;
6542
6543 case ICK_Lvalue_To_Rvalue:
6544 case ICK_Array_To_Pointer:
6545 case ICK_Function_To_Pointer:
6546 case ICK_HLSL_Array_RValue:
6547 llvm_unreachable("found a first conversion kind in Second");
6548
6549 case ICK_Function_Conversion:
6550 case ICK_Qualification:
6551 llvm_unreachable("found a third conversion kind in Second");
6552
6553 case ICK_Num_Conversion_Kinds:
6554 break;
6555 }
6556
6557 llvm_unreachable("unknown conversion kind");
6558}
6559
6560/// BuildConvertedConstantExpression - Check that the expression From is a
6561/// converted constant expression of type T, perform the conversion but
6562/// does not evaluate the expression
6563static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From,
6564 QualType T, CCEKind CCE,
6565 NamedDecl *Dest,
6566 APValue &PreNarrowingValue) {
6567 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6568 (CCE == CCEKind::TempArgStrict || CCE == CCEKind::ExplicitBool ||
6569 CCE == CCEKind::PackIndex);
6570 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6571 "converted constant expression outside C++11 or TTP matching");
6572
6573 if (checkPlaceholderForOverload(S, E&: From))
6574 return ExprError();
6575
6576 if (From->containsErrors()) {
6577 if (S.Context.hasSameType(T1: From->getType(), T2: T))
6578 return From;
6579
6580 // The expression already has errors, so the correct cast kind can't be
6581 // determined. Use RecoveryExpr to keep the expected type T and mark the
6582 // result as invalid, preventing further cascading errors.
6583 return S.CreateRecoveryExpr(Begin: From->getBeginLoc(), End: From->getEndLoc(), SubExprs: {From},
6584 T);
6585 }
6586
6587 // C++1z [expr.const]p3:
6588 // A converted constant expression of type T is an expression,
6589 // implicitly converted to type T, where the converted
6590 // expression is a constant expression and the implicit conversion
6591 // sequence contains only [... list of conversions ...].
6592 ImplicitConversionSequence ICS =
6593 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6594 ? TryContextuallyConvertToBool(S, From)
6595 : TryCopyInitialization(S, From, ToType: T,
6596 /*SuppressUserConversions=*/false,
6597 /*InOverloadResolution=*/false,
6598 /*AllowObjCWritebackConversion=*/false,
6599 /*AllowExplicit=*/false);
6600 StandardConversionSequence *SCS = nullptr;
6601 switch (ICS.getKind()) {
6602 case ImplicitConversionSequence::StandardConversion:
6603 SCS = &ICS.Standard;
6604 break;
6605 case ImplicitConversionSequence::UserDefinedConversion:
6606 if (T->isRecordType())
6607 SCS = &ICS.UserDefined.Before;
6608 else
6609 SCS = &ICS.UserDefined.After;
6610 break;
6611 case ImplicitConversionSequence::AmbiguousConversion:
6612 case ImplicitConversionSequence::BadConversion:
6613 if (!S.DiagnoseMultipleUserDefinedConversion(From, ToType: T))
6614 return S.Diag(Loc: From->getBeginLoc(),
6615 DiagID: diag::err_typecheck_converted_constant_expression)
6616 << From->getType() << From->getSourceRange() << T;
6617 return ExprError();
6618
6619 case ImplicitConversionSequence::EllipsisConversion:
6620 case ImplicitConversionSequence::StaticObjectArgumentConversion:
6621 llvm_unreachable("bad conversion in converted constant expression");
6622 }
6623
6624 // Check that we would only use permitted conversions.
6625 if (!CheckConvertedConstantConversions(S, SCS&: *SCS)) {
6626 return S.Diag(Loc: From->getBeginLoc(),
6627 DiagID: diag::err_typecheck_converted_constant_expression_disallowed)
6628 << From->getType() << From->getSourceRange() << T;
6629 }
6630 // [...] and where the reference binding (if any) binds directly.
6631 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6632 return S.Diag(Loc: From->getBeginLoc(),
6633 DiagID: diag::err_typecheck_converted_constant_expression_indirect)
6634 << From->getType() << From->getSourceRange() << T;
6635 }
6636 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6637 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6638 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6639 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6640 // case explicitly.
6641 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6642 return S.Diag(Loc: From->getBeginLoc(),
6643 DiagID: diag::err_reference_bind_to_bitfield_in_cce)
6644 << From->getSourceRange();
6645 }
6646
6647 // Usually we can simply apply the ImplicitConversionSequence we formed
6648 // earlier, but that's not guaranteed to work when initializing an object of
6649 // class type.
6650 ExprResult Result;
6651 bool IsTemplateArgument =
6652 CCE == CCEKind::TemplateArg || CCE == CCEKind::TempArgStrict;
6653 if (T->isRecordType()) {
6654 assert(IsTemplateArgument &&
6655 "unexpected class type converted constant expr");
6656 Result = S.PerformCopyInitialization(
6657 Entity: InitializedEntity::InitializeTemplateParameter(
6658 T, Param: cast<NonTypeTemplateParmDecl>(Val: Dest)),
6659 EqualLoc: SourceLocation(), Init: From);
6660 } else {
6661 Result =
6662 S.PerformImplicitConversion(From, ToType: T, ICS, Action: AssignmentAction::Converting);
6663 }
6664 if (Result.isInvalid())
6665 return Result;
6666
6667 // C++2a [intro.execution]p5:
6668 // A full-expression is [...] a constant-expression [...]
6669 Result = S.ActOnFinishFullExpr(Expr: Result.get(), CC: From->getExprLoc(),
6670 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6671 IsTemplateArgument);
6672 if (Result.isInvalid())
6673 return Result;
6674
6675 bool AllowRelaxedEval = S.getASTContext().getLangOpts().MSVCCompat;
6676
6677 // Check for a narrowing implicit conversion.
6678 bool ReturnPreNarrowingValue = false;
6679 QualType PreNarrowingType;
6680 switch (SCS->getNarrowingKind(
6681 Ctx&: S.Context, Converted: Result.get(), ConstantValue&: PreNarrowingValue, ConstantType&: PreNarrowingType,
6682 /*IgnoreFloatToIntegralConversion*/ false, AllowRelaxedEval)) {
6683 case NK_Variable_Narrowing:
6684 // Implicit conversion to a narrower type, and the value is not a constant
6685 // expression. We'll diagnose this in a moment.
6686 case NK_Not_Narrowing:
6687 break;
6688
6689 case NK_Constant_Narrowing:
6690 if (CCE == CCEKind::ArrayBound &&
6691 PreNarrowingType->isIntegralOrEnumerationType() &&
6692 PreNarrowingValue.isInt()) {
6693 // Don't diagnose array bound narrowing here; we produce more precise
6694 // errors by allowing the un-narrowed value through.
6695 ReturnPreNarrowingValue = true;
6696 break;
6697 }
6698 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::ext_cce_narrowing)
6699 << CCE << /*Constant*/ 1
6700 << PreNarrowingValue.getAsString(Ctx: S.Context, Ty: PreNarrowingType) << T;
6701 // If this is an SFINAE Context, treat the result as invalid so it stops
6702 // substitution at this point, respecting C++26 [temp.deduct.general]p7.
6703 // FIXME: Should do this whenever the above diagnostic is an error, but
6704 // without further changes this would degrade some other diagnostics.
6705 if (S.isSFINAEContext())
6706 return ExprError();
6707 break;
6708
6709 case NK_Dependent_Narrowing:
6710 // Implicit conversion to a narrower type, but the expression is
6711 // value-dependent so we can't tell whether it's actually narrowing.
6712 // For matching the parameters of a TTP, the conversion is ill-formed
6713 // if it may narrow.
6714 if (CCE != CCEKind::TempArgStrict)
6715 break;
6716 [[fallthrough]];
6717 case NK_Type_Narrowing:
6718 // FIXME: It would be better to diagnose that the expression is not a
6719 // constant expression.
6720 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::ext_cce_narrowing)
6721 << CCE << /*Constant*/ 0 << From->getType() << T;
6722 if (S.isSFINAEContext())
6723 return ExprError();
6724 break;
6725 }
6726 if (!ReturnPreNarrowingValue)
6727 PreNarrowingValue = {};
6728
6729 return Result;
6730}
6731
6732/// CheckConvertedConstantExpression - Check that the expression From is a
6733/// converted constant expression of type T, perform the conversion and produce
6734/// the converted expression, per C++11 [expr.const]p3.
6735static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
6736 QualType T, APValue &Value,
6737 CCEKind CCE, bool RequireInt,
6738 NamedDecl *Dest) {
6739
6740 APValue PreNarrowingValue;
6741 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6742 PreNarrowingValue);
6743 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6744 Value = APValue();
6745 return Result;
6746 }
6747 return S.EvaluateConvertedConstantExpression(E: Result.get(), T, Value, CCE,
6748 RequireInt, PreNarrowingValue);
6749}
6750
6751ExprResult Sema::BuildConvertedConstantExpression(Expr *From, QualType T,
6752 CCEKind CCE,
6753 NamedDecl *Dest) {
6754 APValue PreNarrowingValue;
6755 return ::BuildConvertedConstantExpression(S&: *this, From, T, CCE, Dest,
6756 PreNarrowingValue);
6757}
6758
6759ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6760 APValue &Value, CCEKind CCE,
6761 NamedDecl *Dest) {
6762 return ::CheckConvertedConstantExpression(S&: *this, From, T, Value, CCE, RequireInt: false,
6763 Dest);
6764}
6765
6766ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6767 llvm::APSInt &Value,
6768 CCEKind CCE) {
6769 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6770
6771 APValue V;
6772 auto R = ::CheckConvertedConstantExpression(S&: *this, From, T, Value&: V, CCE, RequireInt: true,
6773 /*Dest=*/nullptr);
6774 if (!R.isInvalid() && !R.get()->isValueDependent())
6775 Value = V.getInt();
6776 return R;
6777}
6778
6779ExprResult
6780Sema::EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value,
6781 CCEKind CCE, bool RequireInt,
6782 const APValue &PreNarrowingValue) {
6783
6784 ExprResult Result = E;
6785 // Check the expression is a constant expression.
6786 SmallVector<PartialDiagnosticAt, 8> Notes;
6787 SmallVector<PartialDiagnosticAt> MSWarning;
6788 Expr::EvalResult Eval;
6789 Eval.Diag = &Notes;
6790 Eval.ExtendedDiag = &MSWarning;
6791
6792 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6793
6794 ConstantExprKind Kind;
6795 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6796 Kind = ConstantExprKind::ClassTemplateArgument;
6797 else if (CCE == CCEKind::TemplateArg)
6798 Kind = ConstantExprKind::NonClassTemplateArgument;
6799 else
6800 Kind = ConstantExprKind::Normal;
6801
6802 if (!E->EvaluateAsConstantExpr(Result&: Eval, Ctx: Context, Kind) ||
6803 (RequireInt && !Eval.Val.isInt())) {
6804 // The expression can't be folded, so we can't keep it at this position in
6805 // the AST.
6806 Result = ExprError();
6807 } else {
6808 Value = Eval.Val;
6809 // For -fms-compatibility mode we relax some requirements
6810 // for constant folding in non-SFINAE contexts
6811 bool CantFold = isSFINAEContext() && !MSWarning.empty();
6812 if (Notes.empty() && !CantFold) {
6813 for (auto &Info : MSWarning)
6814 Diag(Loc: Info.first, PD: Info.second);
6815 // It's a constant expression.
6816 Expr *E = Result.get();
6817 if (const auto *CE = dyn_cast<ConstantExpr>(Val: E)) {
6818 // We expect a ConstantExpr to have a value associated with it
6819 // by this point.
6820 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6821 "ConstantExpr has no value associated with it");
6822 (void)CE;
6823 } else {
6824 E = ConstantExpr::Create(Context, E: Result.get(), Result: Value);
6825 }
6826 if (!PreNarrowingValue.isAbsent())
6827 Value = std::move(PreNarrowingValue);
6828 return E;
6829 }
6830 }
6831
6832 // It's not a constant expression. Produce an appropriate diagnostic.
6833 if (Notes.size() == 1 &&
6834 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6835 Diag(Loc: Notes[0].first, DiagID: diag::err_expr_not_cce) << CCE;
6836 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6837 diag::note_constexpr_invalid_template_arg) {
6838 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6839 for (unsigned I = 0; I < Notes.size(); ++I)
6840 Diag(Loc: Notes[I].first, PD: Notes[I].second);
6841 } else {
6842 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_expr_not_cce)
6843 << CCE << E->getSourceRange();
6844 for (unsigned I = 0; I < Notes.size(); ++I)
6845 Diag(Loc: Notes[I].first, PD: Notes[I].second);
6846 }
6847 return ExprError();
6848}
6849
6850/// dropPointerConversions - If the given standard conversion sequence
6851/// involves any pointer conversions, remove them. This may change
6852/// the result type of the conversion sequence.
6853static void dropPointerConversion(StandardConversionSequence &SCS) {
6854 if (SCS.Second == ICK_Pointer_Conversion) {
6855 SCS.Second = ICK_Identity;
6856 SCS.Dimension = ICK_Identity;
6857 SCS.Third = ICK_Identity;
6858 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6859 }
6860}
6861
6862/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6863/// convert the expression From to an Objective-C pointer type.
6864static ImplicitConversionSequence
6865TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
6866 // Do an implicit conversion to 'id'.
6867 QualType Ty = S.Context.getObjCIdType();
6868 ImplicitConversionSequence ICS
6869 = TryImplicitConversion(S, From, ToType: Ty,
6870 // FIXME: Are these flags correct?
6871 /*SuppressUserConversions=*/false,
6872 AllowExplicit: AllowedExplicit::Conversions,
6873 /*InOverloadResolution=*/false,
6874 /*CStyle=*/false,
6875 /*AllowObjCWritebackConversion=*/false,
6876 /*AllowObjCConversionOnExplicit=*/true);
6877
6878 // Strip off any final conversions to 'id'.
6879 switch (ICS.getKind()) {
6880 case ImplicitConversionSequence::BadConversion:
6881 case ImplicitConversionSequence::AmbiguousConversion:
6882 case ImplicitConversionSequence::EllipsisConversion:
6883 case ImplicitConversionSequence::StaticObjectArgumentConversion:
6884 break;
6885
6886 case ImplicitConversionSequence::UserDefinedConversion:
6887 dropPointerConversion(SCS&: ICS.UserDefined.After);
6888 break;
6889
6890 case ImplicitConversionSequence::StandardConversion:
6891 dropPointerConversion(SCS&: ICS.Standard);
6892 break;
6893 }
6894
6895 return ICS;
6896}
6897
6898ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
6899 if (checkPlaceholderForOverload(S&: *this, E&: From))
6900 return ExprError();
6901
6902 QualType Ty = Context.getObjCIdType();
6903 ImplicitConversionSequence ICS =
6904 TryContextuallyConvertToObjCPointer(S&: *this, From);
6905 if (!ICS.isBad())
6906 return PerformImplicitConversion(From, ToType: Ty, ICS,
6907 Action: AssignmentAction::Converting);
6908 return ExprResult();
6909}
6910
6911static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6912 const Expr *Base = nullptr;
6913 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6914 "expected a member expression");
6915
6916 if (const auto M = dyn_cast<UnresolvedMemberExpr>(Val: MemExprE);
6917 M && !M->isImplicitAccess())
6918 Base = M->getBase();
6919 else if (const auto M = dyn_cast<MemberExpr>(Val: MemExprE);
6920 M && !M->isImplicitAccess())
6921 Base = M->getBase();
6922
6923 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6924
6925 if (T->isPointerType())
6926 T = T->getPointeeType();
6927
6928 return T;
6929}
6930
6931static Expr *GetExplicitObjectExpr(Sema &S, Expr *Obj,
6932 const FunctionDecl *Fun) {
6933 QualType ObjType = Obj->getType();
6934 if (ObjType->isPointerType()) {
6935 ObjType = ObjType->getPointeeType();
6936 Obj = UnaryOperator::Create(C: S.getASTContext(), input: Obj, opc: UO_Deref, type: ObjType,
6937 VK: VK_LValue, OK: OK_Ordinary, l: SourceLocation(),
6938 /*CanOverflow=*/false, FPFeatures: FPOptionsOverride());
6939 }
6940 return Obj;
6941}
6942
6943ExprResult Sema::InitializeExplicitObjectArgument(Sema &S, Expr *Obj,
6944 FunctionDecl *Fun) {
6945 Obj = GetExplicitObjectExpr(S, Obj, Fun);
6946 return S.PerformCopyInitialization(
6947 Entity: InitializedEntity::InitializeParameter(Context&: S.Context, Parm: Fun->getParamDecl(i: 0)),
6948 EqualLoc: Obj->getExprLoc(), Init: Obj);
6949}
6950
6951static bool PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method,
6952 Expr *Object, MultiExprArg &Args,
6953 SmallVectorImpl<Expr *> &NewArgs) {
6954 assert(Method->isExplicitObjectMemberFunction() &&
6955 "Method is not an explicit member function");
6956 assert(NewArgs.empty() && "NewArgs should be empty");
6957
6958 NewArgs.reserve(N: Args.size() + 1);
6959 Expr *This = GetExplicitObjectExpr(S, Obj: Object, Fun: Method);
6960 NewArgs.push_back(Elt: This);
6961 NewArgs.append(in_start: Args.begin(), in_end: Args.end());
6962 Args = NewArgs;
6963 return S.DiagnoseInvalidExplicitObjectParameterInLambda(
6964 Method, CallLoc: Object->getBeginLoc());
6965}
6966
6967/// Determine whether the provided type is an integral type, or an enumeration
6968/// type of a permitted flavor.
6969bool Sema::ICEConvertDiagnoser::match(QualType T) {
6970 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6971 : T->isIntegralOrUnscopedEnumerationType();
6972}
6973
6974static ExprResult
6975diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
6976 Sema::ContextualImplicitConverter &Converter,
6977 QualType T, UnresolvedSetImpl &ViableConversions) {
6978
6979 if (Converter.Suppress)
6980 return ExprError();
6981
6982 Converter.diagnoseAmbiguous(S&: SemaRef, Loc, T) << From->getSourceRange();
6983 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6984 CXXConversionDecl *Conv =
6985 cast<CXXConversionDecl>(Val: ViableConversions[I]->getUnderlyingDecl());
6986 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
6987 Converter.noteAmbiguous(S&: SemaRef, Conv, ConvTy);
6988 }
6989 return From;
6990}
6991
6992static bool
6993diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6994 Sema::ContextualImplicitConverter &Converter,
6995 QualType T, bool HadMultipleCandidates,
6996 UnresolvedSetImpl &ExplicitConversions) {
6997 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6998 DeclAccessPair Found = ExplicitConversions[0];
6999 CXXConversionDecl *Conversion =
7000 cast<CXXConversionDecl>(Val: Found->getUnderlyingDecl());
7001
7002 // The user probably meant to invoke the given explicit
7003 // conversion; use it.
7004 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
7005 std::string TypeStr;
7006 ConvTy.getAsStringInternal(Str&: TypeStr, Policy: SemaRef.getPrintingPolicy());
7007
7008 Converter.diagnoseExplicitConv(S&: SemaRef, Loc, T, ConvTy)
7009 << FixItHint::CreateInsertion(InsertionLoc: From->getBeginLoc(),
7010 Code: "static_cast<" + TypeStr + ">(")
7011 << FixItHint::CreateInsertion(
7012 InsertionLoc: SemaRef.getLocForEndOfToken(Loc: From->getEndLoc()), Code: ")");
7013 Converter.noteExplicitConv(S&: SemaRef, Conv: Conversion, ConvTy);
7014
7015 // If we aren't in a SFINAE context, build a call to the
7016 // explicit conversion function.
7017 if (SemaRef.isSFINAEContext())
7018 return true;
7019
7020 SemaRef.CheckMemberOperatorAccess(Loc: From->getExprLoc(), ObjectExpr: From, ArgExpr: nullptr, FoundDecl: Found);
7021 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(Exp: From, FoundDecl: Found, Method: Conversion,
7022 HadMultipleCandidates);
7023 if (Result.isInvalid())
7024 return true;
7025
7026 // Replace the conversion with a RecoveryExpr, so we don't try to
7027 // instantiate it later, but can further diagnose here.
7028 Result = SemaRef.CreateRecoveryExpr(Begin: From->getBeginLoc(), End: From->getEndLoc(),
7029 SubExprs: From, T: Result.get()->getType());
7030 if (Result.isInvalid())
7031 return true;
7032 From = Result.get();
7033 }
7034 return false;
7035}
7036
7037static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
7038 Sema::ContextualImplicitConverter &Converter,
7039 QualType T, bool HadMultipleCandidates,
7040 DeclAccessPair &Found) {
7041 CXXConversionDecl *Conversion =
7042 cast<CXXConversionDecl>(Val: Found->getUnderlyingDecl());
7043 SemaRef.CheckMemberOperatorAccess(Loc: From->getExprLoc(), ObjectExpr: From, ArgExpr: nullptr, FoundDecl: Found);
7044
7045 QualType ToType = Conversion->getConversionType().getNonReferenceType();
7046 if (!Converter.SuppressConversion) {
7047 if (SemaRef.isSFINAEContext())
7048 return true;
7049
7050 Converter.diagnoseConversion(S&: SemaRef, Loc, T, ConvTy: ToType)
7051 << From->getSourceRange();
7052 }
7053
7054 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(Exp: From, FoundDecl: Found, Method: Conversion,
7055 HadMultipleCandidates);
7056 if (Result.isInvalid())
7057 return true;
7058 // Record usage of conversion in an implicit cast.
7059 From = ImplicitCastExpr::Create(Context: SemaRef.Context, T: Result.get()->getType(),
7060 Kind: CK_UserDefinedConversion, Operand: Result.get(),
7061 BasePath: nullptr, Cat: Result.get()->getValueKind(),
7062 FPO: SemaRef.CurFPFeatureOverrides());
7063 return false;
7064}
7065
7066static ExprResult finishContextualImplicitConversion(
7067 Sema &SemaRef, SourceLocation Loc, Expr *From,
7068 Sema::ContextualImplicitConverter &Converter) {
7069 if (!Converter.match(T: From->getType()) && !Converter.Suppress)
7070 Converter.diagnoseNoMatch(S&: SemaRef, Loc, T: From->getType())
7071 << From->getSourceRange();
7072
7073 return SemaRef.DefaultLvalueConversion(E: From);
7074}
7075
7076static void
7077collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
7078 UnresolvedSetImpl &ViableConversions,
7079 OverloadCandidateSet &CandidateSet) {
7080 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
7081 NamedDecl *D = FoundDecl.getDecl();
7082 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
7083 if (isa<UsingShadowDecl>(Val: D))
7084 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
7085
7086 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)) {
7087 SemaRef.AddTemplateConversionCandidate(
7088 FunctionTemplate: ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
7089 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
7090 continue;
7091 }
7092 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
7093 SemaRef.AddConversionCandidate(
7094 Conversion: Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
7095 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
7096 }
7097}
7098
7099/// Attempt to convert the given expression to a type which is accepted
7100/// by the given converter.
7101///
7102/// This routine will attempt to convert an expression of class type to a
7103/// type accepted by the specified converter. In C++11 and before, the class
7104/// must have a single non-explicit conversion function converting to a matching
7105/// type. In C++1y, there can be multiple such conversion functions, but only
7106/// one target type.
7107///
7108/// \param Loc The source location of the construct that requires the
7109/// conversion.
7110///
7111/// \param From The expression we're converting from.
7112///
7113/// \param Converter Used to control and diagnose the conversion process.
7114///
7115/// \returns The expression, converted to an integral or enumeration type if
7116/// successful.
7117ExprResult Sema::PerformContextualImplicitConversion(
7118 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
7119 // We can't perform any more checking for type-dependent expressions.
7120 if (From->isTypeDependent())
7121 return From;
7122
7123 // Process placeholders immediately.
7124 if (From->hasPlaceholderType()) {
7125 ExprResult result = CheckPlaceholderExpr(E: From);
7126 if (result.isInvalid())
7127 return result;
7128 From = result.get();
7129 }
7130
7131 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
7132 ExprResult Converted = DefaultLvalueConversion(E: From);
7133 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
7134 From = Converted.isUsable() ? Converted.get() : nullptr;
7135 // If the expression already has a matching type, we're golden.
7136 if (Converter.match(T))
7137 return Converted;
7138
7139 // FIXME: Check for missing '()' if T is a function type?
7140
7141 // We can only perform contextual implicit conversions on objects of class
7142 // type.
7143 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
7144 if (!RecordTy || !getLangOpts().CPlusPlus) {
7145 if (!Converter.Suppress)
7146 Converter.diagnoseNoMatch(S&: *this, Loc, T) << From->getSourceRange();
7147 return From;
7148 }
7149
7150 // We must have a complete class type.
7151 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
7152 ContextualImplicitConverter &Converter;
7153 Expr *From;
7154
7155 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
7156 : Converter(Converter), From(From) {}
7157
7158 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
7159 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
7160 }
7161 } IncompleteDiagnoser(Converter, From);
7162
7163 if (Converter.Suppress ? !isCompleteType(Loc, T)
7164 : RequireCompleteType(Loc, T, Diagnoser&: IncompleteDiagnoser))
7165 return From;
7166
7167 // Look for a conversion to an integral or enumeration type.
7168 UnresolvedSet<4>
7169 ViableConversions; // These are *potentially* viable in C++1y.
7170 UnresolvedSet<4> ExplicitConversions;
7171 const auto &Conversions = cast<CXXRecordDecl>(Val: RecordTy->getDecl())
7172 ->getDefinitionOrSelf()
7173 ->getVisibleConversionFunctions();
7174
7175 bool HadMultipleCandidates =
7176 (std::distance(first: Conversions.begin(), last: Conversions.end()) > 1);
7177
7178 // To check that there is only one target type, in C++1y:
7179 QualType ToType;
7180 bool HasUniqueTargetType = true;
7181
7182 // Collect explicit or viable (potentially in C++1y) conversions.
7183 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
7184 NamedDecl *D = (*I)->getUnderlyingDecl();
7185 CXXConversionDecl *Conversion;
7186 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D);
7187 if (ConvTemplate) {
7188 if (getLangOpts().CPlusPlus14)
7189 Conversion = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
7190 else
7191 continue; // C++11 does not consider conversion operator templates(?).
7192 } else
7193 Conversion = cast<CXXConversionDecl>(Val: D);
7194
7195 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
7196 "Conversion operator templates are considered potentially "
7197 "viable in C++1y");
7198
7199 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
7200 if (Converter.match(T: CurToType) || ConvTemplate) {
7201
7202 if (Conversion->isExplicit()) {
7203 // FIXME: For C++1y, do we need this restriction?
7204 // cf. diagnoseNoViableConversion()
7205 if (!ConvTemplate)
7206 ExplicitConversions.addDecl(D: I.getDecl(), AS: I.getAccess());
7207 } else {
7208 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
7209 if (ToType.isNull())
7210 ToType = CurToType.getUnqualifiedType();
7211 else if (HasUniqueTargetType &&
7212 (CurToType.getUnqualifiedType() != ToType))
7213 HasUniqueTargetType = false;
7214 }
7215 ViableConversions.addDecl(D: I.getDecl(), AS: I.getAccess());
7216 }
7217 }
7218 }
7219
7220 if (getLangOpts().CPlusPlus14) {
7221 // C++1y [conv]p6:
7222 // ... An expression e of class type E appearing in such a context
7223 // is said to be contextually implicitly converted to a specified
7224 // type T and is well-formed if and only if e can be implicitly
7225 // converted to a type T that is determined as follows: E is searched
7226 // for conversion functions whose return type is cv T or reference to
7227 // cv T such that T is allowed by the context. There shall be
7228 // exactly one such T.
7229
7230 // If no unique T is found:
7231 if (ToType.isNull()) {
7232 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
7233 HadMultipleCandidates,
7234 ExplicitConversions))
7235 return ExprError();
7236 return finishContextualImplicitConversion(SemaRef&: *this, Loc, From, Converter);
7237 }
7238
7239 // If more than one unique Ts are found:
7240 if (!HasUniqueTargetType)
7241 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
7242 ViableConversions);
7243
7244 // If one unique T is found:
7245 // First, build a candidate set from the previously recorded
7246 // potentially viable conversions.
7247 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
7248 collectViableConversionCandidates(SemaRef&: *this, From, ToType, ViableConversions,
7249 CandidateSet);
7250
7251 // Then, perform overload resolution over the candidate set.
7252 OverloadCandidateSet::iterator Best;
7253 switch (CandidateSet.BestViableFunction(S&: *this, Loc, Best)) {
7254 case OR_Success: {
7255 // Apply this conversion.
7256 DeclAccessPair Found =
7257 DeclAccessPair::make(D: Best->Function, AS: Best->FoundDecl.getAccess());
7258 if (recordConversion(SemaRef&: *this, Loc, From, Converter, T,
7259 HadMultipleCandidates, Found))
7260 return ExprError();
7261 break;
7262 }
7263 case OR_Ambiguous:
7264 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
7265 ViableConversions);
7266 case OR_No_Viable_Function:
7267 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
7268 HadMultipleCandidates,
7269 ExplicitConversions))
7270 return ExprError();
7271 [[fallthrough]];
7272 case OR_Deleted:
7273 // We'll complain below about a non-integral condition type.
7274 break;
7275 }
7276 } else {
7277 switch (ViableConversions.size()) {
7278 case 0: {
7279 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
7280 HadMultipleCandidates,
7281 ExplicitConversions))
7282 return ExprError();
7283
7284 // We'll complain below about a non-integral condition type.
7285 break;
7286 }
7287 case 1: {
7288 // Apply this conversion.
7289 DeclAccessPair Found = ViableConversions[0];
7290 if (recordConversion(SemaRef&: *this, Loc, From, Converter, T,
7291 HadMultipleCandidates, Found))
7292 return ExprError();
7293 break;
7294 }
7295 default:
7296 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
7297 ViableConversions);
7298 }
7299 }
7300
7301 return finishContextualImplicitConversion(SemaRef&: *this, Loc, From, Converter);
7302}
7303
7304/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
7305/// an acceptable non-member overloaded operator for a call whose
7306/// arguments have types T1 (and, if non-empty, T2). This routine
7307/// implements the check in C++ [over.match.oper]p3b2 concerning
7308/// enumeration types.
7309static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
7310 FunctionDecl *Fn,
7311 ArrayRef<Expr *> Args) {
7312 QualType T1 = Args[0]->getType();
7313 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
7314
7315 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
7316 return true;
7317
7318 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
7319 return true;
7320
7321 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
7322 if (Proto->getNumParams() < 1)
7323 return false;
7324
7325 if (T1->isEnumeralType()) {
7326 QualType ArgType = Proto->getParamType(i: 0).getNonReferenceType();
7327 if (Context.hasSameUnqualifiedType(T1, T2: ArgType))
7328 return true;
7329 }
7330
7331 if (Proto->getNumParams() < 2)
7332 return false;
7333
7334 if (!T2.isNull() && T2->isEnumeralType()) {
7335 QualType ArgType = Proto->getParamType(i: 1).getNonReferenceType();
7336 if (Context.hasSameUnqualifiedType(T1: T2, T2: ArgType))
7337 return true;
7338 }
7339
7340 return false;
7341}
7342
7343static bool isNonViableMultiVersionOverload(FunctionDecl *FD) {
7344 if (FD->isTargetMultiVersionDefault())
7345 return false;
7346
7347 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7348 return FD->isTargetMultiVersion();
7349
7350 if (!FD->isMultiVersion())
7351 return false;
7352
7353 // Among multiple target versions consider either the default,
7354 // or the first non-default in the absence of default version.
7355 unsigned SeenAt = 0;
7356 unsigned I = 0;
7357 bool HasDefault = false;
7358 FD->getASTContext().forEachMultiversionedFunctionVersion(
7359 FD, Pred: [&](const FunctionDecl *CurFD) {
7360 if (FD == CurFD)
7361 SeenAt = I;
7362 else if (CurFD->isTargetMultiVersionDefault())
7363 HasDefault = true;
7364 ++I;
7365 });
7366 return HasDefault || SeenAt != 0;
7367}
7368
7369void Sema::AddOverloadCandidate(
7370 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
7371 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7372 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7373 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7374 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7375 bool StrictPackMatch) {
7376 const FunctionProtoType *Proto
7377 = dyn_cast<FunctionProtoType>(Val: Function->getType()->getAs<FunctionType>());
7378 assert(Proto && "Functions without a prototype cannot be overloaded");
7379 assert(!Function->getDescribedFunctionTemplate() &&
7380 "Use AddTemplateOverloadCandidate for function templates");
7381
7382 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Function)) {
7383 if (!isa<CXXConstructorDecl>(Val: Method)) {
7384 // If we get here, it's because we're calling a member function
7385 // that is named without a member access expression (e.g.,
7386 // "this->f") that was either written explicitly or created
7387 // implicitly. This can happen with a qualified call to a member
7388 // function, e.g., X::f(). We use an empty type for the implied
7389 // object argument (C++ [over.call.func]p3), and the acting context
7390 // is irrelevant.
7391 AddMethodCandidate(Method, FoundDecl, ActingContext: Method->getParent(), ObjectType: QualType(),
7392 ObjectClassification: Expr::Classification::makeSimpleLValue(), Args,
7393 CandidateSet, SuppressUserConversions,
7394 PartialOverloading, EarlyConversions, PO,
7395 StrictPackMatch);
7396 return;
7397 }
7398 // We treat a constructor like a non-member function, since its object
7399 // argument doesn't participate in overload resolution.
7400 }
7401
7402 if (!CandidateSet.isNewCandidate(F: Function, PO))
7403 return;
7404
7405 // C++11 [class.copy]p11: [DR1402]
7406 // A defaulted move constructor that is defined as deleted is ignored by
7407 // overload resolution.
7408 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Function);
7409 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7410 Constructor->isMoveConstructor())
7411 return;
7412
7413 // Overload resolution is always an unevaluated context.
7414 EnterExpressionEvaluationContext Unevaluated(
7415 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7416
7417 // C++ [over.match.oper]p3:
7418 // if no operand has a class type, only those non-member functions in the
7419 // lookup set that have a first parameter of type T1 or "reference to
7420 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7421 // is a right operand) a second parameter of type T2 or "reference to
7422 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7423 // candidate functions.
7424 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7425 !IsAcceptableNonMemberOperatorCandidate(Context, Fn: Function, Args))
7426 return;
7427
7428 // Add this candidate
7429 OverloadCandidate &Candidate =
7430 CandidateSet.addCandidate(NumConversions: Args.size(), Conversions: EarlyConversions);
7431 Candidate.FoundDecl = FoundDecl;
7432 Candidate.Function = Function;
7433 Candidate.Viable = true;
7434 Candidate.RewriteKind =
7435 CandidateSet.getRewriteInfo().getRewriteKind(FD: Function, PO);
7436 Candidate.IsADLCandidate = llvm::to_underlying(E: IsADLCandidate);
7437 Candidate.ExplicitCallArguments = Args.size();
7438 Candidate.StrictPackMatch = StrictPackMatch;
7439
7440 // Explicit functions are not actually candidates at all if we're not
7441 // allowing them in this context, but keep them around so we can point
7442 // to them in diagnostics.
7443 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7444 Candidate.Viable = false;
7445 Candidate.FailureKind = ovl_fail_explicit;
7446 return;
7447 }
7448
7449 // Functions with internal linkage are only viable in the same module unit.
7450 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7451 /// FIXME: Currently, the semantics of linkage in clang is slightly
7452 /// different from the semantics in C++ spec. In C++ spec, only names
7453 /// have linkage. So that all entities of the same should share one
7454 /// linkage. But in clang, different entities of the same could have
7455 /// different linkage.
7456 const NamedDecl *ND = Function;
7457 bool IsImplicitlyInstantiated = false;
7458 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7459 ND = SpecInfo->getTemplate();
7460 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7461 TSK_ImplicitInstantiation;
7462 }
7463
7464 /// Don't remove inline functions with internal linkage from the overload
7465 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7466 /// However:
7467 /// - Inline functions with internal linkage are a common pattern in
7468 /// headers to avoid ODR issues.
7469 /// - The global module is meant to be a transition mechanism for C and C++
7470 /// headers, and the current rules as written work against that goal.
7471 const bool IsInlineFunctionInGMF =
7472 Function->isFromGlobalModule() &&
7473 (IsImplicitlyInstantiated || Function->isInlined());
7474
7475 // Don't exclude internal-linkage entities from the current TU's global
7476 // module fragment.
7477 const Module *CurrentModule = getCurrentModule();
7478 const bool IsCurrentUnitGMFDecl =
7479 Function->isFromGlobalModule() && CurrentModule &&
7480 Function->getOwningModule()->getTopLevelModule() ==
7481 CurrentModule->getTopLevelModule();
7482
7483 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF &&
7484 !IsCurrentUnitGMFDecl) {
7485 Candidate.Viable = false;
7486 Candidate.FailureKind = ovl_fail_module_mismatched;
7487 return;
7488 }
7489 }
7490
7491 if (isNonViableMultiVersionOverload(FD: Function)) {
7492 Candidate.Viable = false;
7493 Candidate.FailureKind = ovl_non_default_multiversion_function;
7494 return;
7495 }
7496
7497 if (Constructor) {
7498 // C++ [class.copy]p3:
7499 // A member function template is never instantiated to perform the copy
7500 // of a class object to an object of its class type.
7501 CanQualType ClassType =
7502 Context.getCanonicalTagType(TD: Constructor->getParent());
7503 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7504 (Context.hasSameUnqualifiedType(T1: ClassType, T2: Args[0]->getType()) ||
7505 IsDerivedFrom(Loc: Args[0]->getBeginLoc(), Derived: Args[0]->getType(),
7506 Base: ClassType))) {
7507 Candidate.Viable = false;
7508 Candidate.FailureKind = ovl_fail_illegal_constructor;
7509 return;
7510 }
7511
7512 // C++ [over.match.funcs]p8: (proposed DR resolution)
7513 // A constructor inherited from class type C that has a first parameter
7514 // of type "reference to P" (including such a constructor instantiated
7515 // from a template) is excluded from the set of candidate functions when
7516 // constructing an object of type cv D if the argument list has exactly
7517 // one argument and D is reference-related to P and P is reference-related
7518 // to C.
7519 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl.getDecl());
7520 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7521 Constructor->getParamDecl(i: 0)->getType()->isReferenceType()) {
7522 QualType P = Constructor->getParamDecl(i: 0)->getType()->getPointeeType();
7523 CanQualType C = Context.getCanonicalTagType(TD: Constructor->getParent());
7524 CanQualType D = Context.getCanonicalTagType(TD: Shadow->getParent());
7525 SourceLocation Loc = Args.front()->getExprLoc();
7526 if ((Context.hasSameUnqualifiedType(T1: P, T2: C) || IsDerivedFrom(Loc, Derived: P, Base: C)) &&
7527 (Context.hasSameUnqualifiedType(T1: D, T2: P) || IsDerivedFrom(Loc, Derived: D, Base: P))) {
7528 Candidate.Viable = false;
7529 Candidate.FailureKind = ovl_fail_inhctor_slice;
7530 return;
7531 }
7532 }
7533
7534 // Check that the constructor is capable of constructing an object in the
7535 // destination address space.
7536 if (!Qualifiers::isAddressSpaceSupersetOf(
7537 A: Constructor->getMethodQualifiers().getAddressSpace(),
7538 B: CandidateSet.getDestAS(), Ctx: getASTContext())) {
7539 Candidate.Viable = false;
7540 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
7541 }
7542 }
7543
7544 unsigned NumParams = Proto->getNumParams();
7545
7546 // (C++ 13.3.2p2): A candidate function having fewer than m
7547 // parameters is viable only if it has an ellipsis in its parameter
7548 // list (8.3.5).
7549 if (TooManyArguments(NumParams, NumArgs: Args.size(), PartialOverloading) &&
7550 !Proto->isVariadic() &&
7551 shouldEnforceArgLimit(PartialOverloading, Function)) {
7552 Candidate.Viable = false;
7553 Candidate.FailureKind = ovl_fail_too_many_arguments;
7554 return;
7555 }
7556
7557 // (C++ 13.3.2p2): A candidate function having more than m parameters
7558 // is viable only if the (m+1)st parameter has a default argument
7559 // (8.3.6). For the purposes of overload resolution, the
7560 // parameter list is truncated on the right, so that there are
7561 // exactly m parameters.
7562 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7563 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7564 !PartialOverloading) {
7565 // Not enough arguments.
7566 Candidate.Viable = false;
7567 Candidate.FailureKind = ovl_fail_too_few_arguments;
7568 return;
7569 }
7570
7571 // (CUDA B.1): Check for invalid calls between targets.
7572 if (getLangOpts().CUDA) {
7573 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7574 // Skip the check for callers that are implicit members, because in this
7575 // case we may not yet know what the member's target is; the target is
7576 // inferred for the member automatically, based on the bases and fields of
7577 // the class.
7578 if (!(Caller && Caller->isImplicit()) &&
7579 !CUDA().IsAllowedCall(Caller, Callee: Function)) {
7580 Candidate.Viable = false;
7581 Candidate.FailureKind = ovl_fail_bad_target;
7582 return;
7583 }
7584 }
7585
7586 if (Function->getTrailingRequiresClause()) {
7587 ConstraintSatisfaction Satisfaction;
7588 if (CheckFunctionConstraints(FD: Function, Satisfaction, /*Loc*/ UsageLoc: {},
7589 /*ForOverloadResolution*/ true) ||
7590 !Satisfaction.IsSatisfied) {
7591 Candidate.Viable = false;
7592 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7593 return;
7594 }
7595 }
7596
7597 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7598 // Determine the implicit conversion sequences for each of the
7599 // arguments.
7600 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7601 unsigned ConvIdx =
7602 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7603 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7604 // We already formed a conversion sequence for this parameter during
7605 // template argument deduction.
7606 } else if (ArgIdx < NumParams) {
7607 // (C++ 13.3.2p3): for F to be a viable function, there shall
7608 // exist for each argument an implicit conversion sequence
7609 // (13.3.3.1) that converts that argument to the corresponding
7610 // parameter of F.
7611 QualType ParamType = Proto->getParamType(i: ArgIdx);
7612 auto ParamABI = Proto->getExtParameterInfo(I: ArgIdx).getABI();
7613 if (ParamABI == ParameterABI::HLSLOut ||
7614 ParamABI == ParameterABI::HLSLInOut) {
7615 ParamType = ParamType.getNonReferenceType();
7616 if (ParamABI == ParameterABI::HLSLInOut &&
7617 Args[ArgIdx]->getType().getAddressSpace() ==
7618 LangAS::hlsl_groupshared)
7619 Diag(Loc: Args[ArgIdx]->getBeginLoc(), DiagID: diag::warn_hlsl_groupshared_inout);
7620 }
7621 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7622 S&: *this, From: Args[ArgIdx], ToType: ParamType, SuppressUserConversions,
7623 /*InOverloadResolution=*/true,
7624 /*AllowObjCWritebackConversion=*/
7625 getLangOpts().ObjCAutoRefCount, AllowExplicit: AllowExplicitConversions);
7626 if (Candidate.Conversions[ConvIdx].isBad()) {
7627 Candidate.Viable = false;
7628 Candidate.FailureKind = ovl_fail_bad_conversion;
7629 return;
7630 }
7631 } else {
7632 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7633 // argument for which there is no corresponding parameter is
7634 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7635 Candidate.Conversions[ConvIdx].setEllipsis();
7636 }
7637 }
7638
7639 if (EnableIfAttr *FailedAttr =
7640 CheckEnableIf(Function, CallLoc: CandidateSet.getLocation(), Args)) {
7641 Candidate.Viable = false;
7642 Candidate.FailureKind = ovl_fail_enable_if;
7643 Candidate.DeductionFailure.Data = FailedAttr;
7644 return;
7645 }
7646}
7647
7648ObjCMethodDecl *
7649Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
7650 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
7651 if (Methods.size() <= 1)
7652 return nullptr;
7653
7654 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7655 bool Match = true;
7656 ObjCMethodDecl *Method = Methods[b];
7657 unsigned NumNamedArgs = Sel.getNumArgs();
7658 // Method might have more arguments than selector indicates. This is due
7659 // to addition of c-style arguments in method.
7660 if (Method->param_size() > NumNamedArgs)
7661 NumNamedArgs = Method->param_size();
7662 if (Args.size() < NumNamedArgs)
7663 continue;
7664
7665 for (unsigned i = 0; i < NumNamedArgs; i++) {
7666 // We can't do any type-checking on a type-dependent argument.
7667 if (Args[i]->isTypeDependent()) {
7668 Match = false;
7669 break;
7670 }
7671
7672 ParmVarDecl *param = Method->parameters()[i];
7673 Expr *argExpr = Args[i];
7674 assert(argExpr && "SelectBestMethod(): missing expression");
7675
7676 // Strip the unbridged-cast placeholder expression off unless it's
7677 // a consumed argument.
7678 if (argExpr->hasPlaceholderType(K: BuiltinType::ARCUnbridgedCast) &&
7679 !param->hasAttr<CFConsumedAttr>())
7680 argExpr = ObjC().stripARCUnbridgedCast(e: argExpr);
7681
7682 // If the parameter is __unknown_anytype, move on to the next method.
7683 if (param->getType() == Context.UnknownAnyTy) {
7684 Match = false;
7685 break;
7686 }
7687
7688 ImplicitConversionSequence ConversionState
7689 = TryCopyInitialization(S&: *this, From: argExpr, ToType: param->getType(),
7690 /*SuppressUserConversions*/false,
7691 /*InOverloadResolution=*/true,
7692 /*AllowObjCWritebackConversion=*/
7693 getLangOpts().ObjCAutoRefCount,
7694 /*AllowExplicit*/false);
7695 // This function looks for a reasonably-exact match, so we consider
7696 // incompatible pointer conversions to be a failure here.
7697 if (ConversionState.isBad() ||
7698 (ConversionState.isStandard() &&
7699 ConversionState.Standard.Second ==
7700 ICK_Incompatible_Pointer_Conversion)) {
7701 Match = false;
7702 break;
7703 }
7704 }
7705 // Promote additional arguments to variadic methods.
7706 if (Match && Method->isVariadic()) {
7707 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7708 if (Args[i]->isTypeDependent()) {
7709 Match = false;
7710 break;
7711 }
7712 ExprResult Arg = DefaultVariadicArgumentPromotion(
7713 E: Args[i], CT: VariadicCallType::Method, FDecl: nullptr);
7714 if (Arg.isInvalid()) {
7715 Match = false;
7716 break;
7717 }
7718 }
7719 } else {
7720 // Check for extra arguments to non-variadic methods.
7721 if (Args.size() != NumNamedArgs)
7722 Match = false;
7723 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7724 // Special case when selectors have no argument. In this case, select
7725 // one with the most general result type of 'id'.
7726 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7727 QualType ReturnT = Methods[b]->getReturnType();
7728 if (ReturnT->isObjCIdType())
7729 return Methods[b];
7730 }
7731 }
7732 }
7733
7734 if (Match)
7735 return Method;
7736 }
7737 return nullptr;
7738}
7739
7740static bool convertArgsForAvailabilityChecks(
7741 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7742 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7743 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7744 if (ThisArg) {
7745 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Function);
7746 assert(!isa<CXXConstructorDecl>(Method) &&
7747 "Shouldn't have `this` for ctors!");
7748 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7749 ExprResult R = S.PerformImplicitObjectArgumentInitialization(
7750 From: ThisArg, /*Qualifier=*/std::nullopt, FoundDecl: Method, Method);
7751 if (R.isInvalid())
7752 return false;
7753 ConvertedThis = R.get();
7754 } else {
7755 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: Function)) {
7756 (void)MD;
7757 assert((MissingImplicitThis || MD->isStatic() ||
7758 isa<CXXConstructorDecl>(MD)) &&
7759 "Expected `this` for non-ctor instance methods");
7760 }
7761 ConvertedThis = nullptr;
7762 }
7763
7764 // Ignore any variadic arguments. Converting them is pointless, since the
7765 // user can't refer to them in the function condition.
7766 unsigned ArgSizeNoVarargs = std::min(a: Function->param_size(), b: Args.size());
7767
7768 // Convert the arguments.
7769 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7770 ExprResult R;
7771 R = S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
7772 Context&: S.Context, Parm: Function->getParamDecl(i: I)),
7773 EqualLoc: SourceLocation(), Init: Args[I]);
7774
7775 if (R.isInvalid())
7776 return false;
7777
7778 ConvertedArgs.push_back(Elt: R.get());
7779 }
7780
7781 if (Trap.hasErrorOccurred())
7782 return false;
7783
7784 // Push default arguments if needed.
7785 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7786 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7787 ParmVarDecl *P = Function->getParamDecl(i);
7788 if (!P->hasDefaultArg())
7789 return false;
7790 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, FD: Function, Param: P);
7791 if (R.isInvalid())
7792 return false;
7793 ConvertedArgs.push_back(Elt: R.get());
7794 }
7795
7796 if (Trap.hasErrorOccurred())
7797 return false;
7798 }
7799 return true;
7800}
7801
7802EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
7803 SourceLocation CallLoc,
7804 ArrayRef<Expr *> Args,
7805 bool MissingImplicitThis) {
7806 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7807 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7808 return nullptr;
7809
7810 SFINAETrap Trap(*this);
7811 // Perform the access checking immediately so any access diagnostics are
7812 // caught by the SFINAE trap.
7813 llvm::scope_exit UndelayDiags(
7814 [&, CurrentState(DelayedDiagnostics.pushUndelayed())] {
7815 DelayedDiagnostics.popUndelayed(state: CurrentState);
7816 });
7817 SmallVector<Expr *, 16> ConvertedArgs;
7818 // FIXME: We should look into making enable_if late-parsed.
7819 Expr *DiscardedThis;
7820 if (!convertArgsForAvailabilityChecks(
7821 S&: *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7822 /*MissingImplicitThis=*/true, ConvertedThis&: DiscardedThis, ConvertedArgs))
7823 return *EnableIfAttrs.begin();
7824
7825 for (auto *EIA : EnableIfAttrs) {
7826 APValue Result;
7827 // FIXME: This doesn't consider value-dependent cases, because doing so is
7828 // very difficult. Ideally, we should handle them more gracefully.
7829 if (EIA->getCond()->isValueDependent() ||
7830 !EIA->getCond()->EvaluateWithSubstitution(
7831 Value&: Result, Ctx&: Context, Callee: Function, Args: llvm::ArrayRef(ConvertedArgs)))
7832 return EIA;
7833
7834 if (!Result.isInt() || !Result.getInt().getBoolValue())
7835 return EIA;
7836 }
7837 return nullptr;
7838}
7839
7840template <typename CheckFn>
7841static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
7842 bool ArgDependent, SourceLocation Loc,
7843 CheckFn &&IsSuccessful) {
7844 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
7845 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7846 if (ArgDependent == DIA->getArgDependent())
7847 Attrs.push_back(Elt: DIA);
7848 }
7849
7850 // Common case: No diagnose_if attributes, so we can quit early.
7851 if (Attrs.empty())
7852 return false;
7853
7854 auto WarningBegin = std::stable_partition(
7855 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7856 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7857 DIA->getWarningGroup().empty();
7858 });
7859
7860 // Note that diagnose_if attributes are late-parsed, so they appear in the
7861 // correct order (unlike enable_if attributes).
7862 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7863 IsSuccessful);
7864 if (ErrAttr != WarningBegin) {
7865 const DiagnoseIfAttr *DIA = *ErrAttr;
7866 S.Diag(Loc, DiagID: diag::err_diagnose_if_succeeded) << DIA->getMessage();
7867 S.Diag(Loc: DIA->getLocation(), DiagID: diag::note_from_diagnose_if)
7868 << DIA->getParent() << DIA->getCond()->getSourceRange();
7869 return true;
7870 }
7871
7872 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7873 switch (Sev) {
7874 case DiagnoseIfAttr::DS_warning:
7875 return diag::Severity::Warning;
7876 case DiagnoseIfAttr::DS_error:
7877 return diag::Severity::Error;
7878 }
7879 llvm_unreachable("Fully covered switch above!");
7880 };
7881
7882 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7883 if (IsSuccessful(DIA)) {
7884 if (DIA->getWarningGroup().empty() &&
7885 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7886 S.Diag(Loc, DiagID: diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7887 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7888 << DIA->getParent() << DIA->getCond()->getSourceRange();
7889 } else {
7890 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7891 DIA->getWarningGroup());
7892 assert(DiagGroup);
7893 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7894 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7895 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7896 S.Diag(Loc, DiagID) << DIA->getMessage();
7897 }
7898 }
7899
7900 return false;
7901}
7902
7903bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
7904 const Expr *ThisArg,
7905 ArrayRef<const Expr *> Args,
7906 SourceLocation Loc) {
7907 return diagnoseDiagnoseIfAttrsWith(
7908 S&: *this, ND: Function, /*ArgDependent=*/true, Loc,
7909 IsSuccessful: [&](const DiagnoseIfAttr *DIA) {
7910 APValue Result;
7911 // It's sane to use the same Args for any redecl of this function, since
7912 // EvaluateWithSubstitution only cares about the position of each
7913 // argument in the arg list, not the ParmVarDecl* it maps to.
7914 if (!DIA->getCond()->EvaluateWithSubstitution(
7915 Value&: Result, Ctx&: Context, Callee: cast<FunctionDecl>(Val: DIA->getParent()), Args, This: ThisArg))
7916 return false;
7917 return Result.isInt() && Result.getInt().getBoolValue();
7918 });
7919}
7920
7921bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
7922 SourceLocation Loc) {
7923 return diagnoseDiagnoseIfAttrsWith(
7924 S&: *this, ND, /*ArgDependent=*/false, Loc,
7925 IsSuccessful: [&](const DiagnoseIfAttr *DIA) {
7926 bool Result;
7927 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Ctx: Context) &&
7928 Result;
7929 });
7930}
7931
7932void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
7933 ArrayRef<Expr *> Args,
7934 OverloadCandidateSet &CandidateSet,
7935 TemplateArgumentListInfo *ExplicitTemplateArgs,
7936 bool SuppressUserConversions,
7937 bool PartialOverloading,
7938 bool FirstArgumentIsBase) {
7939 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7940 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7941 ArrayRef<Expr *> FunctionArgs = Args;
7942
7943 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D);
7944 FunctionDecl *FD =
7945 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(Val: D);
7946
7947 if (isa<CXXMethodDecl>(Val: FD) && !cast<CXXMethodDecl>(Val: FD)->isStatic()) {
7948 QualType ObjectType;
7949 Expr::Classification ObjectClassification;
7950 if (Args.size() > 0) {
7951 if (Expr *E = Args[0]) {
7952 // Use the explicit base to restrict the lookup:
7953 ObjectType = E->getType();
7954 // Pointers in the object arguments are implicitly dereferenced, so we
7955 // always classify them as l-values.
7956 if (!ObjectType.isNull() && ObjectType->isPointerType())
7957 ObjectClassification = Expr::Classification::makeSimpleLValue();
7958 else
7959 ObjectClassification = E->Classify(Ctx&: Context);
7960 } // .. else there is an implicit base.
7961 FunctionArgs = Args.slice(N: 1);
7962 }
7963 if (FunTmpl) {
7964 AddMethodTemplateCandidate(
7965 MethodTmpl: FunTmpl, FoundDecl: F.getPair(),
7966 ActingContext: cast<CXXRecordDecl>(Val: FunTmpl->getDeclContext()),
7967 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7968 Args: FunctionArgs, CandidateSet, SuppressUserConversions,
7969 PartialOverloading);
7970 } else {
7971 AddMethodCandidate(Method: cast<CXXMethodDecl>(Val: FD), FoundDecl: F.getPair(),
7972 ActingContext: cast<CXXMethodDecl>(Val: FD)->getParent(), ObjectType,
7973 ObjectClassification, Args: FunctionArgs, CandidateSet,
7974 SuppressUserConversions, PartialOverloading);
7975 }
7976 } else {
7977 // This branch handles both standalone functions and static methods.
7978
7979 // Slice the first argument (which is the base) when we access
7980 // static method as non-static.
7981 if (Args.size() > 0 &&
7982 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(Val: FD) &&
7983 !isa<CXXConstructorDecl>(Val: FD)))) {
7984 assert(cast<CXXMethodDecl>(FD)->isStatic());
7985 FunctionArgs = Args.slice(N: 1);
7986 }
7987 if (FunTmpl) {
7988 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(),
7989 ExplicitTemplateArgs, Args: FunctionArgs,
7990 CandidateSet, SuppressUserConversions,
7991 PartialOverloading);
7992 } else {
7993 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(), Args: FunctionArgs, CandidateSet,
7994 SuppressUserConversions, PartialOverloading);
7995 }
7996 }
7997 }
7998}
7999
8000void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
8001 Expr::Classification ObjectClassification,
8002 ArrayRef<Expr *> Args,
8003 OverloadCandidateSet &CandidateSet,
8004 bool SuppressUserConversions,
8005 OverloadCandidateParamOrder PO) {
8006 NamedDecl *Decl = FoundDecl.getDecl();
8007 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: Decl->getDeclContext());
8008
8009 if (isa<UsingShadowDecl>(Val: Decl))
8010 Decl = cast<UsingShadowDecl>(Val: Decl)->getTargetDecl();
8011
8012 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Val: Decl)) {
8013 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
8014 "Expected a member function template");
8015 AddMethodTemplateCandidate(MethodTmpl: TD, FoundDecl, ActingContext,
8016 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, ObjectType,
8017 ObjectClassification, Args, CandidateSet,
8018 SuppressUserConversions, PartialOverloading: false, PO);
8019 } else {
8020 AddMethodCandidate(Method: cast<CXXMethodDecl>(Val: Decl), FoundDecl, ActingContext,
8021 ObjectType, ObjectClassification, Args, CandidateSet,
8022 SuppressUserConversions, PartialOverloading: false, EarlyConversions: {}, PO);
8023 }
8024}
8025
8026void Sema::AddMethodCandidate(
8027 CXXMethodDecl *Method, DeclAccessPair FoundDecl,
8028 CXXRecordDecl *ActingContext, QualType ObjectType,
8029 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8030 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8031 bool PartialOverloading, ConversionSequenceList EarlyConversions,
8032 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
8033 const FunctionProtoType *Proto
8034 = dyn_cast<FunctionProtoType>(Val: Method->getType()->getAs<FunctionType>());
8035 assert(Proto && "Methods without a prototype cannot be overloaded");
8036 assert(!isa<CXXConstructorDecl>(Method) &&
8037 "Use AddOverloadCandidate for constructors");
8038
8039 if (!CandidateSet.isNewCandidate(F: Method, PO))
8040 return;
8041
8042 // C++11 [class.copy]p23: [DR1402]
8043 // A defaulted move assignment operator that is defined as deleted is
8044 // ignored by overload resolution.
8045 if (Method->isDefaulted() && Method->isDeleted() &&
8046 Method->isMoveAssignmentOperator())
8047 return;
8048
8049 // Overload resolution is always an unevaluated context.
8050 EnterExpressionEvaluationContext Unevaluated(
8051 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8052
8053 bool IgnoreExplicitObject =
8054 (Method->isExplicitObjectMemberFunction() &&
8055 CandidateSet.getKind() ==
8056 OverloadCandidateSet::CSK_AddressOfOverloadSet);
8057 bool ImplicitObjectMethodTreatedAsStatic =
8058 CandidateSet.getKind() ==
8059 OverloadCandidateSet::CSK_AddressOfOverloadSet &&
8060 Method->isImplicitObjectMemberFunction();
8061
8062 unsigned ExplicitOffset =
8063 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
8064
8065 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
8066 int(ImplicitObjectMethodTreatedAsStatic);
8067
8068 unsigned ExtraArgs =
8069 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet
8070 ? 0
8071 : 1;
8072
8073 // Add this candidate
8074 OverloadCandidate &Candidate =
8075 CandidateSet.addCandidate(NumConversions: Args.size() + ExtraArgs, Conversions: EarlyConversions);
8076 Candidate.FoundDecl = FoundDecl;
8077 Candidate.Function = Method;
8078 Candidate.RewriteKind =
8079 CandidateSet.getRewriteInfo().getRewriteKind(FD: Method, PO);
8080 Candidate.TookAddressOfOverload =
8081 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet;
8082 Candidate.ExplicitCallArguments = Args.size();
8083 Candidate.StrictPackMatch = StrictPackMatch;
8084
8085 // (C++ 13.3.2p2): A candidate function having fewer than m
8086 // parameters is viable only if it has an ellipsis in its parameter
8087 // list (8.3.5).
8088 if (TooManyArguments(NumParams, NumArgs: Args.size(), PartialOverloading) &&
8089 !Proto->isVariadic() &&
8090 shouldEnforceArgLimit(PartialOverloading, Function: Method)) {
8091 Candidate.Viable = false;
8092 Candidate.FailureKind = ovl_fail_too_many_arguments;
8093 return;
8094 }
8095
8096 // (C++ 13.3.2p2): A candidate function having more than m parameters
8097 // is viable only if the (m+1)st parameter has a default argument
8098 // (8.3.6). For the purposes of overload resolution, the
8099 // parameter list is truncated on the right, so that there are
8100 // exactly m parameters.
8101 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
8102 ExplicitOffset +
8103 int(ImplicitObjectMethodTreatedAsStatic);
8104
8105 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
8106 // Not enough arguments.
8107 Candidate.Viable = false;
8108 Candidate.FailureKind = ovl_fail_too_few_arguments;
8109 return;
8110 }
8111
8112 Candidate.Viable = true;
8113
8114 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8115 if (!IgnoreExplicitObject) {
8116 if (ObjectType.isNull())
8117 Candidate.IgnoreObjectArgument = true;
8118 else if (Method->isStatic()) {
8119 // [over.best.ics.general]p8
8120 // When the parameter is the implicit object parameter of a static member
8121 // function, the implicit conversion sequence is a standard conversion
8122 // sequence that is neither better nor worse than any other standard
8123 // conversion sequence.
8124 //
8125 // This is a rule that was introduced in C++23 to support static lambdas.
8126 // We apply it retroactively because we want to support static lambdas as
8127 // an extension and it doesn't hurt previous code.
8128 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
8129 } else {
8130 // Determine the implicit conversion sequence for the object
8131 // parameter.
8132 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
8133 S&: *this, Loc: CandidateSet.getLocation(), FromType: ObjectType, FromClassification: ObjectClassification,
8134 Method, ActingContext, /*InOverloadResolution=*/true);
8135 if (Candidate.Conversions[FirstConvIdx].isBad()) {
8136 Candidate.Viable = false;
8137 Candidate.FailureKind = ovl_fail_bad_conversion;
8138 return;
8139 }
8140 }
8141 }
8142
8143 // (CUDA B.1): Check for invalid calls between targets.
8144 if (getLangOpts().CUDA)
8145 if (!CUDA().IsAllowedCall(Caller: getCurFunctionDecl(/*AllowLambda=*/true),
8146 Callee: Method)) {
8147 Candidate.Viable = false;
8148 Candidate.FailureKind = ovl_fail_bad_target;
8149 return;
8150 }
8151
8152 if (Method->getTrailingRequiresClause()) {
8153 ConstraintSatisfaction Satisfaction;
8154 if (CheckFunctionConstraints(FD: Method, Satisfaction, /*Loc*/ UsageLoc: {},
8155 /*ForOverloadResolution*/ true) ||
8156 !Satisfaction.IsSatisfied) {
8157 Candidate.Viable = false;
8158 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8159 return;
8160 }
8161 }
8162
8163 // Determine the implicit conversion sequences for each of the
8164 // arguments.
8165 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
8166 unsigned ConvIdx =
8167 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
8168 if (Candidate.Conversions[ConvIdx].isInitialized()) {
8169 // We already formed a conversion sequence for this parameter during
8170 // template argument deduction.
8171 } else if (ArgIdx < NumParams) {
8172 // (C++ 13.3.2p3): for F to be a viable function, there shall
8173 // exist for each argument an implicit conversion sequence
8174 // (13.3.3.1) that converts that argument to the corresponding
8175 // parameter of F.
8176 QualType ParamType;
8177 if (ImplicitObjectMethodTreatedAsStatic) {
8178 ParamType = ArgIdx == 0
8179 ? Method->getFunctionObjectParameterReferenceType()
8180 : Proto->getParamType(i: ArgIdx - 1);
8181 } else {
8182 ParamType = Proto->getParamType(i: ArgIdx + ExplicitOffset);
8183 }
8184 Candidate.Conversions[ConvIdx]
8185 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamType,
8186 SuppressUserConversions,
8187 /*InOverloadResolution=*/true,
8188 /*AllowObjCWritebackConversion=*/
8189 getLangOpts().ObjCAutoRefCount);
8190 if (Candidate.Conversions[ConvIdx].isBad()) {
8191 Candidate.Viable = false;
8192 Candidate.FailureKind = ovl_fail_bad_conversion;
8193 return;
8194 }
8195 } else {
8196 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8197 // argument for which there is no corresponding parameter is
8198 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
8199 Candidate.Conversions[ConvIdx].setEllipsis();
8200 }
8201 }
8202
8203 if (EnableIfAttr *FailedAttr =
8204 CheckEnableIf(Function: Method, CallLoc: CandidateSet.getLocation(), Args, MissingImplicitThis: true)) {
8205 Candidate.Viable = false;
8206 Candidate.FailureKind = ovl_fail_enable_if;
8207 Candidate.DeductionFailure.Data = FailedAttr;
8208 return;
8209 }
8210
8211 if (isNonViableMultiVersionOverload(FD: Method)) {
8212 Candidate.Viable = false;
8213 Candidate.FailureKind = ovl_non_default_multiversion_function;
8214 }
8215}
8216
8217static void AddMethodTemplateCandidateImmediately(
8218 Sema &S, OverloadCandidateSet &CandidateSet,
8219 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8220 CXXRecordDecl *ActingContext,
8221 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8222 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8223 bool SuppressUserConversions, bool PartialOverloading,
8224 OverloadCandidateParamOrder PO) {
8225
8226 // C++ [over.match.funcs]p7:
8227 // In each case where a candidate is a function template, candidate
8228 // function template specializations are generated using template argument
8229 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8230 // candidate functions in the usual way.113) A given name can refer to one
8231 // or more function templates and also to a set of overloaded non-template
8232 // functions. In such a case, the candidate functions generated from each
8233 // function template are combined with the set of non-template candidate
8234 // functions.
8235 TemplateDeductionInfo Info(CandidateSet.getLocation());
8236 auto *Method = cast<CXXMethodDecl>(Val: MethodTmpl->getTemplatedDecl());
8237 FunctionDecl *Specialization = nullptr;
8238 ConversionSequenceList Conversions;
8239 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8240 FunctionTemplate: MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
8241 PartialOverloading, /*AggregateDeductionCandidate=*/false,
8242 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
8243 ForOverloadSetAddressResolution: CandidateSet.getKind() ==
8244 clang::OverloadCandidateSet::CSK_AddressOfOverloadSet,
8245 CheckNonDependent: [&](ArrayRef<QualType> ParamTypes,
8246 bool OnlyInitializeNonUserDefinedConversions) {
8247 return S.CheckNonDependentConversions(
8248 FunctionTemplate: MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
8249 UserConversionFlag: Sema::CheckNonDependentConversionsFlag(
8250 SuppressUserConversions,
8251 OnlyInitializeNonUserDefinedConversions),
8252 ActingContext, ObjectType, ObjectClassification, PO);
8253 });
8254 Result != TemplateDeductionResult::Success) {
8255 OverloadCandidate &Candidate =
8256 CandidateSet.addCandidate(NumConversions: Conversions.size(), Conversions);
8257 Candidate.FoundDecl = FoundDecl;
8258 Candidate.Function = Method;
8259 Candidate.Viable = false;
8260 Candidate.RewriteKind =
8261 CandidateSet.getRewriteInfo().getRewriteKind(FD: Candidate.Function, PO);
8262 Candidate.IsSurrogate = false;
8263 Candidate.TookAddressOfOverload =
8264 CandidateSet.getKind() ==
8265 OverloadCandidateSet::CSK_AddressOfOverloadSet;
8266
8267 Candidate.IgnoreObjectArgument =
8268 Method->isStatic() ||
8269 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
8270 Candidate.ExplicitCallArguments = Args.size();
8271 if (Result == TemplateDeductionResult::NonDependentConversionFailure)
8272 Candidate.FailureKind = ovl_fail_bad_conversion;
8273 else {
8274 Candidate.FailureKind = ovl_fail_bad_deduction;
8275 Candidate.DeductionFailure =
8276 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8277 }
8278 return;
8279 }
8280
8281 // Add the function template specialization produced by template argument
8282 // deduction as a candidate.
8283 assert(Specialization && "Missing member function template specialization?");
8284 assert(isa<CXXMethodDecl>(Specialization) &&
8285 "Specialization is not a member function?");
8286 S.AddMethodCandidate(
8287 Method: cast<CXXMethodDecl>(Val: Specialization), FoundDecl, ActingContext, ObjectType,
8288 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
8289 PartialOverloading, EarlyConversions: Conversions, PO, StrictPackMatch: Info.hasStrictPackMatch());
8290}
8291
8292void Sema::AddMethodTemplateCandidate(
8293 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8294 CXXRecordDecl *ActingContext,
8295 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8296 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8297 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8298 bool PartialOverloading, OverloadCandidateParamOrder PO) {
8299 if (!CandidateSet.isNewCandidate(F: MethodTmpl, PO))
8300 return;
8301
8302 if (ExplicitTemplateArgs ||
8303 !CandidateSet.shouldDeferTemplateArgumentDeduction(S: *this)) {
8304 AddMethodTemplateCandidateImmediately(
8305 S&: *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
8306 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
8307 SuppressUserConversions, PartialOverloading, PO);
8308 return;
8309 }
8310
8311 CandidateSet.AddDeferredMethodTemplateCandidate(
8312 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
8313 Args, SuppressUserConversions, PartialOverloading, PO);
8314}
8315
8316/// Determine whether a given function template has a simple explicit specifier
8317/// or a non-value-dependent explicit-specification that evaluates to true.
8318static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
8319 return ExplicitSpecifier::getFromDecl(Function: FTD->getTemplatedDecl()).isExplicit();
8320}
8321
8322static bool hasDependentExplicit(FunctionTemplateDecl *FTD) {
8323 return ExplicitSpecifier::getFromDecl(Function: FTD->getTemplatedDecl()).getKind() ==
8324 ExplicitSpecKind::Unresolved;
8325}
8326
8327static void AddTemplateOverloadCandidateImmediately(
8328 Sema &S, OverloadCandidateSet &CandidateSet,
8329 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8330 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8331 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
8332 Sema::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO,
8333 bool AggregateCandidateDeduction) {
8334
8335 // If the function template has a non-dependent explicit specification,
8336 // exclude it now if appropriate; we are not permitted to perform deduction
8337 // and substitution in this case.
8338 if (!AllowExplicit && isNonDependentlyExplicit(FTD: FunctionTemplate)) {
8339 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8340 Candidate.FoundDecl = FoundDecl;
8341 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8342 Candidate.Viable = false;
8343 Candidate.FailureKind = ovl_fail_explicit;
8344 return;
8345 }
8346
8347 // C++ [over.match.funcs]p7:
8348 // In each case where a candidate is a function template, candidate
8349 // function template specializations are generated using template argument
8350 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8351 // candidate functions in the usual way.113) A given name can refer to one
8352 // or more function templates and also to a set of overloaded non-template
8353 // functions. In such a case, the candidate functions generated from each
8354 // function template are combined with the set of non-template candidate
8355 // functions.
8356 TemplateDeductionInfo Info(CandidateSet.getLocation(),
8357 FunctionTemplate->getTemplateDepth());
8358 FunctionDecl *Specialization = nullptr;
8359 ConversionSequenceList Conversions;
8360 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8361 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8362 PartialOverloading, AggregateDeductionCandidate: AggregateCandidateDeduction,
8363 /*PartialOrdering=*/false,
8364 /*ObjectType=*/QualType(),
8365 /*ObjectClassification=*/Expr::Classification(),
8366 ForOverloadSetAddressResolution: CandidateSet.getKind() ==
8367 OverloadCandidateSet::CSK_AddressOfOverloadSet,
8368 CheckNonDependent: [&](ArrayRef<QualType> ParamTypes,
8369 bool OnlyInitializeNonUserDefinedConversions) {
8370 return S.CheckNonDependentConversions(
8371 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8372 UserConversionFlag: Sema::CheckNonDependentConversionsFlag(
8373 SuppressUserConversions,
8374 OnlyInitializeNonUserDefinedConversions),
8375 ActingContext: nullptr, ObjectType: QualType(), ObjectClassification: {}, PO);
8376 });
8377 Result != TemplateDeductionResult::Success) {
8378 OverloadCandidate &Candidate =
8379 CandidateSet.addCandidate(NumConversions: Conversions.size(), Conversions);
8380 Candidate.FoundDecl = FoundDecl;
8381 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8382 Candidate.Viable = false;
8383 Candidate.RewriteKind =
8384 CandidateSet.getRewriteInfo().getRewriteKind(FD: Candidate.Function, PO);
8385 Candidate.IsSurrogate = false;
8386 Candidate.IsADLCandidate = llvm::to_underlying(E: IsADLCandidate);
8387 // Ignore the object argument if there is one, since we don't have an object
8388 // type.
8389 Candidate.TookAddressOfOverload =
8390 CandidateSet.getKind() ==
8391 OverloadCandidateSet::CSK_AddressOfOverloadSet;
8392
8393 Candidate.IgnoreObjectArgument =
8394 isa<CXXMethodDecl>(Val: Candidate.Function) &&
8395 !cast<CXXMethodDecl>(Val: Candidate.Function)
8396 ->isExplicitObjectMemberFunction() &&
8397 !isa<CXXConstructorDecl>(Val: Candidate.Function);
8398
8399 Candidate.ExplicitCallArguments = Args.size();
8400 if (Result == TemplateDeductionResult::NonDependentConversionFailure)
8401 Candidate.FailureKind = ovl_fail_bad_conversion;
8402 else {
8403 Candidate.FailureKind = ovl_fail_bad_deduction;
8404 Candidate.DeductionFailure =
8405 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8406 }
8407 return;
8408 }
8409
8410 // Add the function template specialization produced by template argument
8411 // deduction as a candidate.
8412 assert(Specialization && "Missing function template specialization?");
8413 S.AddOverloadCandidate(
8414 Function: Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8415 PartialOverloading, AllowExplicit,
8416 /*AllowExplicitConversions=*/false, IsADLCandidate, EarlyConversions: Conversions, PO,
8417 AggregateCandidateDeduction: Info.AggregateDeductionCandidateHasMismatchedArity,
8418 StrictPackMatch: Info.hasStrictPackMatch());
8419}
8420
8421void Sema::AddTemplateOverloadCandidate(
8422 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8423 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8424 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8425 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8426 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8427 if (!CandidateSet.isNewCandidate(F: FunctionTemplate, PO))
8428 return;
8429
8430 bool DependentExplicitSpecifier = hasDependentExplicit(FTD: FunctionTemplate);
8431
8432 if (ExplicitTemplateArgs ||
8433 !CandidateSet.shouldDeferTemplateArgumentDeduction(S: *this) ||
8434 (isa<CXXConstructorDecl>(Val: FunctionTemplate->getTemplatedDecl()) &&
8435 DependentExplicitSpecifier)) {
8436
8437 AddTemplateOverloadCandidateImmediately(
8438 S&: *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8439 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8440 IsADLCandidate, PO, AggregateCandidateDeduction);
8441
8442 if (DependentExplicitSpecifier)
8443 CandidateSet.DisableResolutionByPerfectCandidate();
8444 return;
8445 }
8446
8447 CandidateSet.AddDeferredTemplateCandidate(
8448 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8449 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8450 AggregateCandidateDeduction);
8451}
8452
8453bool Sema::CheckNonDependentConversions(
8454 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
8455 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8456 ConversionSequenceList &Conversions,
8457 CheckNonDependentConversionsFlag UserConversionFlag,
8458 CXXRecordDecl *ActingContext, QualType ObjectType,
8459 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8460 // FIXME: The cases in which we allow explicit conversions for constructor
8461 // arguments never consider calling a constructor template. It's not clear
8462 // that is correct.
8463 const bool AllowExplicit = false;
8464
8465 bool ForOverloadSetAddressResolution =
8466 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet;
8467 auto *FD = FunctionTemplate->getTemplatedDecl();
8468 auto *Method = dyn_cast<CXXMethodDecl>(Val: FD);
8469 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8470 !isa<CXXConstructorDecl>(Val: Method);
8471 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8472
8473 if (Conversions.empty())
8474 Conversions =
8475 CandidateSet.allocateConversionSequences(NumConversions: ThisConversions + Args.size());
8476
8477 // Overload resolution is always an unevaluated context.
8478 EnterExpressionEvaluationContext Unevaluated(
8479 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8480
8481 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8482 // require that, but this check should never result in a hard error, and
8483 // overload resolution is permitted to sidestep instantiations.
8484 if (HasThisConversion && !cast<CXXMethodDecl>(Val: FD)->isStatic() &&
8485 !ObjectType.isNull()) {
8486 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8487 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8488 !ParamTypes[0]->isDependentType()) {
8489 Conversions[ConvIdx] = TryObjectArgumentInitialization(
8490 S&: *this, Loc: CandidateSet.getLocation(), FromType: ObjectType, FromClassification: ObjectClassification,
8491 Method, ActingContext, /*InOverloadResolution=*/true,
8492 ExplicitParameterType: FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8493 : QualType());
8494 if (Conversions[ConvIdx].isBad())
8495 return true;
8496 }
8497 }
8498
8499 // A speculative workaround for self-dependent constraint bugs that manifest
8500 // after CWG2369.
8501 // FIXME: Add references to the standard once P3606 is adopted.
8502 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8503 QualType ArgType) {
8504 ParamType = ParamType.getNonReferenceType();
8505 ArgType = ArgType.getNonReferenceType();
8506 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8507 if (PointerConv) {
8508 ParamType = ParamType->getPointeeType();
8509 ArgType = ArgType->getPointeeType();
8510 }
8511
8512 if (auto *RD = ParamType->getAsCXXRecordDecl();
8513 RD && RD->hasDefinition() &&
8514 llvm::any_of(Range: LookupConstructors(Class: RD), P: [](NamedDecl *ND) {
8515 auto Info = getConstructorInfo(ND);
8516 if (!Info)
8517 return false;
8518 CXXConstructorDecl *Ctor = Info.Constructor;
8519 /// isConvertingConstructor takes copy/move constructors into
8520 /// account!
8521 return !Ctor->isCopyOrMoveConstructor() &&
8522 Ctor->isConvertingConstructor(
8523 /*AllowExplicit=*/true);
8524 }))
8525 return true;
8526 if (auto *RD = ArgType->getAsCXXRecordDecl();
8527 RD && RD->hasDefinition() &&
8528 !RD->getVisibleConversionFunctions().empty())
8529 return true;
8530
8531 return false;
8532 };
8533
8534 unsigned Offset =
8535 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8536 : 0;
8537
8538 for (unsigned I = 0, N = std::min(a: ParamTypes.size() - Offset, b: Args.size());
8539 I != N; ++I) {
8540 QualType ParamType = ParamTypes[I + Offset];
8541 if (!ParamType->isDependentType()) {
8542 unsigned ConvIdx;
8543 if (PO == OverloadCandidateParamOrder::Reversed) {
8544 ConvIdx = Args.size() - 1 - I;
8545 assert(Args.size() + ThisConversions == 2 &&
8546 "number of args (including 'this') must be exactly 2 for "
8547 "reversed order");
8548 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8549 // would also be 0. 'this' got ConvIdx = 1 previously.
8550 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8551 } else {
8552 // For members, 'this' got ConvIdx = 0 previously.
8553 ConvIdx = ThisConversions + I;
8554 }
8555 if (Conversions[ConvIdx].isInitialized())
8556 continue;
8557 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8558 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8559 continue;
8560 Conversions[ConvIdx] = TryCopyInitialization(
8561 S&: *this, From: Args[I], ToType: ParamType, SuppressUserConversions: UserConversionFlag.SuppressUserConversions,
8562 /*InOverloadResolution=*/true,
8563 /*AllowObjCWritebackConversion=*/
8564 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8565 if (Conversions[ConvIdx].isBad())
8566 return true;
8567 }
8568 }
8569
8570 return false;
8571}
8572
8573/// Determine whether this is an allowable conversion from the result
8574/// of an explicit conversion operator to the expected type, per C++
8575/// [over.match.conv]p1 and [over.match.ref]p1.
8576///
8577/// \param ConvType The return type of the conversion function.
8578///
8579/// \param ToType The type we are converting to.
8580///
8581/// \param AllowObjCPointerConversion Allow a conversion from one
8582/// Objective-C pointer to another.
8583///
8584/// \returns true if the conversion is allowable, false otherwise.
8585static bool isAllowableExplicitConversion(Sema &S,
8586 QualType ConvType, QualType ToType,
8587 bool AllowObjCPointerConversion) {
8588 QualType ToNonRefType = ToType.getNonReferenceType();
8589
8590 // Easy case: the types are the same.
8591 if (S.Context.hasSameUnqualifiedType(T1: ConvType, T2: ToNonRefType))
8592 return true;
8593
8594 // Allow qualification conversions.
8595 bool ObjCLifetimeConversion;
8596 if (S.IsQualificationConversion(FromType: ConvType, ToType: ToNonRefType, /*CStyle*/false,
8597 ObjCLifetimeConversion))
8598 return true;
8599
8600 // If we're not allowed to consider Objective-C pointer conversions,
8601 // we're done.
8602 if (!AllowObjCPointerConversion)
8603 return false;
8604
8605 // Is this an Objective-C pointer conversion?
8606 bool IncompatibleObjC = false;
8607 QualType ConvertedType;
8608 return S.isObjCPointerConversion(FromType: ConvType, ToType: ToNonRefType, ConvertedType,
8609 IncompatibleObjC);
8610}
8611
8612void Sema::AddConversionCandidate(
8613 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8614 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8615 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8616 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8617 assert(!Conversion->getDescribedFunctionTemplate() &&
8618 "Conversion function templates use AddTemplateConversionCandidate");
8619 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8620 if (!CandidateSet.isNewCandidate(F: Conversion))
8621 return;
8622
8623 // If the conversion function has an undeduced return type, trigger its
8624 // deduction now.
8625 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8626 if (DeduceReturnType(FD: Conversion, Loc: From->getExprLoc()))
8627 return;
8628 ConvType = Conversion->getConversionType().getNonReferenceType();
8629 }
8630
8631 // If we don't allow any conversion of the result type, ignore conversion
8632 // functions that don't convert to exactly (possibly cv-qualified) T.
8633 if (!AllowResultConversion &&
8634 !Context.hasSameUnqualifiedType(T1: Conversion->getConversionType(), T2: ToType))
8635 return;
8636
8637 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8638 // operator is only a candidate if its return type is the target type or
8639 // can be converted to the target type with a qualification conversion.
8640 //
8641 // FIXME: Include such functions in the candidate list and explain why we
8642 // can't select them.
8643 if (Conversion->isExplicit() &&
8644 !isAllowableExplicitConversion(S&: *this, ConvType, ToType,
8645 AllowObjCPointerConversion: AllowObjCConversionOnExplicit))
8646 return;
8647
8648 // Overload resolution is always an unevaluated context.
8649 EnterExpressionEvaluationContext Unevaluated(
8650 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8651
8652 // Add this candidate
8653 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: 1);
8654 Candidate.FoundDecl = FoundDecl;
8655 Candidate.Function = Conversion;
8656 Candidate.FinalConversion.setAsIdentityConversion();
8657 Candidate.FinalConversion.setFromType(ConvType);
8658 Candidate.FinalConversion.setAllToTypes(ToType);
8659 Candidate.HasFinalConversion = true;
8660 Candidate.Viable = true;
8661 Candidate.ExplicitCallArguments = 1;
8662 Candidate.StrictPackMatch = StrictPackMatch;
8663
8664 // Explicit functions are not actually candidates at all if we're not
8665 // allowing them in this context, but keep them around so we can point
8666 // to them in diagnostics.
8667 if (!AllowExplicit && Conversion->isExplicit()) {
8668 Candidate.Viable = false;
8669 Candidate.FailureKind = ovl_fail_explicit;
8670 return;
8671 }
8672
8673 // C++ [over.match.funcs]p4:
8674 // For conversion functions, the function is considered to be a member of
8675 // the class of the implicit implied object argument for the purpose of
8676 // defining the type of the implicit object parameter.
8677 //
8678 // Determine the implicit conversion sequence for the implicit
8679 // object parameter.
8680 QualType ObjectType = From->getType();
8681 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8682 ObjectType = FromPtrType->getPointeeType();
8683 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8684 // C++23 [over.best.ics.general]
8685 // However, if the target is [...]
8686 // - the object parameter of a user-defined conversion function
8687 // [...] user-defined conversion sequences are not considered.
8688 Candidate.Conversions[0] = TryObjectArgumentInitialization(
8689 S&: *this, Loc: CandidateSet.getLocation(), FromType: From->getType(),
8690 FromClassification: From->Classify(Ctx&: Context), Method: Conversion, ActingContext: ConversionContext,
8691 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8692 /*SuppressUserConversion*/ true);
8693
8694 if (Candidate.Conversions[0].isBad()) {
8695 Candidate.Viable = false;
8696 Candidate.FailureKind = ovl_fail_bad_conversion;
8697 return;
8698 }
8699
8700 if (Conversion->getTrailingRequiresClause()) {
8701 ConstraintSatisfaction Satisfaction;
8702 if (CheckFunctionConstraints(FD: Conversion, Satisfaction) ||
8703 !Satisfaction.IsSatisfied) {
8704 Candidate.Viable = false;
8705 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8706 return;
8707 }
8708 }
8709
8710 // We won't go through a user-defined type conversion function to convert a
8711 // derived to base as such conversions are given Conversion Rank. They only
8712 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8713 QualType FromCanon
8714 = Context.getCanonicalType(T: From->getType().getUnqualifiedType());
8715 QualType ToCanon = Context.getCanonicalType(T: ToType).getUnqualifiedType();
8716 if (FromCanon == ToCanon ||
8717 IsDerivedFrom(Loc: CandidateSet.getLocation(), Derived: FromCanon, Base: ToCanon)) {
8718 Candidate.Viable = false;
8719 Candidate.FailureKind = ovl_fail_trivial_conversion;
8720 return;
8721 }
8722
8723 // To determine what the conversion from the result of calling the
8724 // conversion function to the type we're eventually trying to
8725 // convert to (ToType), we need to synthesize a call to the
8726 // conversion function and attempt copy initialization from it. This
8727 // makes sure that we get the right semantics with respect to
8728 // lvalues/rvalues and the type. Fortunately, we can allocate this
8729 // call on the stack and we don't need its arguments to be
8730 // well-formed.
8731 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8732 VK_LValue, From->getBeginLoc());
8733 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
8734 Context.getPointerType(T: Conversion->getType()),
8735 CK_FunctionToPointerDecay, &ConversionRef,
8736 VK_PRValue, FPOptionsOverride());
8737
8738 QualType ConversionType = Conversion->getConversionType();
8739 if (!isCompleteType(Loc: From->getBeginLoc(), T: ConversionType)) {
8740 Candidate.Viable = false;
8741 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8742 return;
8743 }
8744
8745 ExprValueKind VK = Expr::getValueKindForType(T: ConversionType);
8746
8747 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8748
8749 // Introduce a temporary expression with the right type and value category
8750 // that we can use for deduction purposes.
8751 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8752
8753 ImplicitConversionSequence ICS =
8754 TryCopyInitialization(S&: *this, From: &FakeCall, ToType,
8755 /*SuppressUserConversions=*/true,
8756 /*InOverloadResolution=*/false,
8757 /*AllowObjCWritebackConversion=*/false);
8758
8759 switch (ICS.getKind()) {
8760 case ImplicitConversionSequence::StandardConversion:
8761 Candidate.FinalConversion = ICS.Standard;
8762 Candidate.HasFinalConversion = true;
8763
8764 // C++ [over.ics.user]p3:
8765 // If the user-defined conversion is specified by a specialization of a
8766 // conversion function template, the second standard conversion sequence
8767 // shall have exact match rank.
8768 if (Conversion->getPrimaryTemplate() &&
8769 GetConversionRank(Kind: ICS.Standard.Second) != ICR_Exact_Match) {
8770 Candidate.Viable = false;
8771 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
8772 return;
8773 }
8774
8775 // C++0x [dcl.init.ref]p5:
8776 // In the second case, if the reference is an rvalue reference and
8777 // the second standard conversion sequence of the user-defined
8778 // conversion sequence includes an lvalue-to-rvalue conversion, the
8779 // program is ill-formed.
8780 if (ToType->isRValueReferenceType() &&
8781 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
8782 Candidate.Viable = false;
8783 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8784 return;
8785 }
8786 break;
8787
8788 case ImplicitConversionSequence::BadConversion:
8789 Candidate.Viable = false;
8790 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8791 return;
8792
8793 default:
8794 llvm_unreachable(
8795 "Can only end up with a standard conversion sequence or failure");
8796 }
8797
8798 if (EnableIfAttr *FailedAttr =
8799 CheckEnableIf(Function: Conversion, CallLoc: CandidateSet.getLocation(), Args: {})) {
8800 Candidate.Viable = false;
8801 Candidate.FailureKind = ovl_fail_enable_if;
8802 Candidate.DeductionFailure.Data = FailedAttr;
8803 return;
8804 }
8805
8806 if (isNonViableMultiVersionOverload(FD: Conversion)) {
8807 Candidate.Viable = false;
8808 Candidate.FailureKind = ovl_non_default_multiversion_function;
8809 }
8810}
8811
8812static void AddTemplateConversionCandidateImmediately(
8813 Sema &S, OverloadCandidateSet &CandidateSet,
8814 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8815 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8816 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8817 bool AllowResultConversion) {
8818
8819 // If the function template has a non-dependent explicit specification,
8820 // exclude it now if appropriate; we are not permitted to perform deduction
8821 // and substitution in this case.
8822 if (!AllowExplicit && isNonDependentlyExplicit(FTD: FunctionTemplate)) {
8823 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8824 Candidate.FoundDecl = FoundDecl;
8825 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8826 Candidate.Viable = false;
8827 Candidate.FailureKind = ovl_fail_explicit;
8828 return;
8829 }
8830
8831 QualType ObjectType = From->getType();
8832 Expr::Classification ObjectClassification = From->Classify(Ctx&: S.Context);
8833
8834 TemplateDeductionInfo Info(CandidateSet.getLocation());
8835 CXXConversionDecl *Specialization = nullptr;
8836 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8837 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8838 Specialization, Info);
8839 Result != TemplateDeductionResult::Success) {
8840 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8841 Candidate.FoundDecl = FoundDecl;
8842 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8843 Candidate.Viable = false;
8844 Candidate.FailureKind = ovl_fail_bad_deduction;
8845 Candidate.ExplicitCallArguments = 1;
8846 Candidate.DeductionFailure =
8847 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8848 return;
8849 }
8850
8851 // Add the conversion function template specialization produced by
8852 // template argument deduction as a candidate.
8853 assert(Specialization && "Missing function template specialization?");
8854 S.AddConversionCandidate(Conversion: Specialization, FoundDecl, ActingContext, From,
8855 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8856 AllowExplicit, AllowResultConversion,
8857 StrictPackMatch: Info.hasStrictPackMatch());
8858}
8859
8860void Sema::AddTemplateConversionCandidate(
8861 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8862 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8863 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8864 bool AllowExplicit, bool AllowResultConversion) {
8865 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8866 "Only conversion function templates permitted here");
8867
8868 if (!CandidateSet.isNewCandidate(F: FunctionTemplate))
8869 return;
8870
8871 if (!CandidateSet.shouldDeferTemplateArgumentDeduction(S: *this) ||
8872 CandidateSet.getKind() ==
8873 OverloadCandidateSet::CSK_InitByUserDefinedConversion ||
8874 CandidateSet.getKind() == OverloadCandidateSet::CSK_InitByConstructor) {
8875 AddTemplateConversionCandidateImmediately(
8876 S&: *this, CandidateSet, FunctionTemplate, FoundDecl, ActingContext: ActingDC, From,
8877 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8878 AllowResultConversion);
8879
8880 CandidateSet.DisableResolutionByPerfectCandidate();
8881 return;
8882 }
8883
8884 CandidateSet.AddDeferredConversionTemplateCandidate(
8885 FunctionTemplate, FoundDecl, ActingContext: ActingDC, From, ToType,
8886 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8887}
8888
8889void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
8890 DeclAccessPair FoundDecl,
8891 CXXRecordDecl *ActingContext,
8892 const FunctionProtoType *Proto,
8893 Expr *Object,
8894 ArrayRef<Expr *> Args,
8895 OverloadCandidateSet& CandidateSet) {
8896 if (!CandidateSet.isNewCandidate(F: Conversion))
8897 return;
8898
8899 // Overload resolution is always an unevaluated context.
8900 EnterExpressionEvaluationContext Unevaluated(
8901 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8902
8903 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: Args.size() + 1);
8904 Candidate.FoundDecl = FoundDecl;
8905 Candidate.Function = nullptr;
8906 Candidate.Surrogate = Conversion;
8907 Candidate.IsSurrogate = true;
8908 Candidate.Viable = true;
8909 Candidate.ExplicitCallArguments = Args.size();
8910
8911 // Determine the implicit conversion sequence for the implicit
8912 // object parameter.
8913 ImplicitConversionSequence ObjectInit;
8914 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8915 ObjectInit = TryCopyInitialization(S&: *this, From: Object,
8916 ToType: Conversion->getParamDecl(i: 0)->getType(),
8917 /*SuppressUserConversions=*/false,
8918 /*InOverloadResolution=*/true, AllowObjCWritebackConversion: false);
8919 } else {
8920 ObjectInit = TryObjectArgumentInitialization(
8921 S&: *this, Loc: CandidateSet.getLocation(), FromType: Object->getType(),
8922 FromClassification: Object->Classify(Ctx&: Context), Method: Conversion, ActingContext);
8923 }
8924
8925 if (ObjectInit.isBad()) {
8926 Candidate.Viable = false;
8927 Candidate.FailureKind = ovl_fail_bad_conversion;
8928 Candidate.Conversions[0] = ObjectInit;
8929 return;
8930 }
8931
8932 // The first conversion is actually a user-defined conversion whose
8933 // first conversion is ObjectInit's standard conversion (which is
8934 // effectively a reference binding). Record it as such.
8935 Candidate.Conversions[0].setUserDefined();
8936 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8937 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8938 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8939 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8940 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8941 Candidate.Conversions[0].UserDefined.After
8942 = Candidate.Conversions[0].UserDefined.Before;
8943 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8944
8945 // Find the
8946 unsigned NumParams = Proto->getNumParams();
8947
8948 // (C++ 13.3.2p2): A candidate function having fewer than m
8949 // parameters is viable only if it has an ellipsis in its parameter
8950 // list (8.3.5).
8951 if (Args.size() > NumParams && !Proto->isVariadic()) {
8952 Candidate.Viable = false;
8953 Candidate.FailureKind = ovl_fail_too_many_arguments;
8954 return;
8955 }
8956
8957 // Function types don't have any default arguments, so just check if
8958 // we have enough arguments.
8959 if (Args.size() < NumParams) {
8960 // Not enough arguments.
8961 Candidate.Viable = false;
8962 Candidate.FailureKind = ovl_fail_too_few_arguments;
8963 return;
8964 }
8965
8966 // Determine the implicit conversion sequences for each of the
8967 // arguments.
8968 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8969 if (ArgIdx < NumParams) {
8970 // (C++ 13.3.2p3): for F to be a viable function, there shall
8971 // exist for each argument an implicit conversion sequence
8972 // (13.3.3.1) that converts that argument to the corresponding
8973 // parameter of F.
8974 QualType ParamType = Proto->getParamType(i: ArgIdx);
8975 Candidate.Conversions[ArgIdx + 1]
8976 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamType,
8977 /*SuppressUserConversions=*/false,
8978 /*InOverloadResolution=*/false,
8979 /*AllowObjCWritebackConversion=*/
8980 getLangOpts().ObjCAutoRefCount);
8981 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8982 Candidate.Viable = false;
8983 Candidate.FailureKind = ovl_fail_bad_conversion;
8984 return;
8985 }
8986 } else {
8987 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8988 // argument for which there is no corresponding parameter is
8989 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8990 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8991 }
8992 }
8993
8994 if (Conversion->getTrailingRequiresClause()) {
8995 ConstraintSatisfaction Satisfaction;
8996 if (CheckFunctionConstraints(FD: Conversion, Satisfaction, /*Loc*/ UsageLoc: {},
8997 /*ForOverloadResolution*/ true) ||
8998 !Satisfaction.IsSatisfied) {
8999 Candidate.Viable = false;
9000 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
9001 return;
9002 }
9003 }
9004
9005 if (EnableIfAttr *FailedAttr =
9006 CheckEnableIf(Function: Conversion, CallLoc: CandidateSet.getLocation(), Args: {})) {
9007 Candidate.Viable = false;
9008 Candidate.FailureKind = ovl_fail_enable_if;
9009 Candidate.DeductionFailure.Data = FailedAttr;
9010 return;
9011 }
9012}
9013
9014void Sema::AddNonMemberOperatorCandidates(
9015 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
9016 OverloadCandidateSet &CandidateSet,
9017 TemplateArgumentListInfo *ExplicitTemplateArgs) {
9018 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
9019 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
9020 ArrayRef<Expr *> FunctionArgs = Args;
9021
9022 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D);
9023 FunctionDecl *FD =
9024 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(Val: D);
9025
9026 // Don't consider rewritten functions if we're not rewriting.
9027 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
9028 continue;
9029
9030 assert(!isa<CXXMethodDecl>(FD) &&
9031 "unqualified operator lookup found a member function");
9032
9033 if (FunTmpl) {
9034 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(), ExplicitTemplateArgs,
9035 Args: FunctionArgs, CandidateSet);
9036 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD)) {
9037
9038 // As template candidates are not deduced immediately,
9039 // persist the array in the overload set.
9040 ArrayRef<Expr *> Reversed = CandidateSet.getPersistentArgsArray(
9041 Exprs: FunctionArgs[1], Exprs: FunctionArgs[0]);
9042 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(), ExplicitTemplateArgs,
9043 Args: Reversed, CandidateSet, SuppressUserConversions: false, PartialOverloading: false, AllowExplicit: true,
9044 IsADLCandidate: ADLCallKind::NotADL,
9045 PO: OverloadCandidateParamOrder::Reversed);
9046 }
9047 } else {
9048 if (ExplicitTemplateArgs)
9049 continue;
9050 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(), Args: FunctionArgs, CandidateSet);
9051 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD))
9052 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(),
9053 Args: {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
9054 SuppressUserConversions: false, PartialOverloading: false, AllowExplicit: true, AllowExplicitConversions: false, IsADLCandidate: ADLCallKind::NotADL, EarlyConversions: {},
9055 PO: OverloadCandidateParamOrder::Reversed);
9056 }
9057 }
9058}
9059
9060void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
9061 SourceLocation OpLoc,
9062 ArrayRef<Expr *> Args,
9063 OverloadCandidateSet &CandidateSet,
9064 OverloadCandidateParamOrder PO) {
9065 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9066
9067 // C++ [over.match.oper]p3:
9068 // For a unary operator @ with an operand of a type whose
9069 // cv-unqualified version is T1, and for a binary operator @ with
9070 // a left operand of a type whose cv-unqualified version is T1 and
9071 // a right operand of a type whose cv-unqualified version is T2,
9072 // three sets of candidate functions, designated member
9073 // candidates, non-member candidates and built-in candidates, are
9074 // constructed as follows:
9075 QualType T1 = Args[0]->getType();
9076
9077 // -- If T1 is a complete class type or a class currently being
9078 // defined, the set of member candidates is the result of the
9079 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
9080 // the set of member candidates is empty.
9081 if (T1->isRecordType()) {
9082 bool IsComplete = isCompleteType(Loc: OpLoc, T: T1);
9083 auto *T1RD = T1->getAsCXXRecordDecl();
9084 // Complete the type if it can be completed.
9085 // If the type is neither complete nor being defined, bail out now.
9086 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
9087 return;
9088
9089 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
9090 LookupQualifiedName(R&: Operators, LookupCtx: T1RD);
9091 Operators.suppressAccessDiagnostics();
9092
9093 for (LookupResult::iterator Oper = Operators.begin(),
9094 OperEnd = Operators.end();
9095 Oper != OperEnd; ++Oper) {
9096 if (Oper->getAsFunction() &&
9097 PO == OverloadCandidateParamOrder::Reversed &&
9098 !CandidateSet.getRewriteInfo().shouldAddReversed(
9099 S&: *this, OriginalArgs: {Args[1], Args[0]}, FD: Oper->getAsFunction()))
9100 continue;
9101 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Args[0]->getType(),
9102 ObjectClassification: Args[0]->Classify(Ctx&: Context), Args: Args.slice(N: 1),
9103 CandidateSet, /*SuppressUserConversion=*/SuppressUserConversions: false, PO);
9104 }
9105 }
9106}
9107
9108void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
9109 OverloadCandidateSet& CandidateSet,
9110 bool IsAssignmentOperator,
9111 unsigned NumContextualBoolArguments) {
9112 // Overload resolution is always an unevaluated context.
9113 EnterExpressionEvaluationContext Unevaluated(
9114 *this, Sema::ExpressionEvaluationContext::Unevaluated);
9115
9116 // Add this candidate
9117 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: Args.size());
9118 Candidate.FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_none);
9119 Candidate.Function = nullptr;
9120 std::copy(first: ParamTys, last: ParamTys + Args.size(), result: Candidate.BuiltinParamTypes);
9121
9122 // Determine the implicit conversion sequences for each of the
9123 // arguments.
9124 Candidate.Viable = true;
9125 Candidate.ExplicitCallArguments = Args.size();
9126 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9127 // C++ [over.match.oper]p4:
9128 // For the built-in assignment operators, conversions of the
9129 // left operand are restricted as follows:
9130 // -- no temporaries are introduced to hold the left operand, and
9131 // -- no user-defined conversions are applied to the left
9132 // operand to achieve a type match with the left-most
9133 // parameter of a built-in candidate.
9134 //
9135 // We block these conversions by turning off user-defined
9136 // conversions, since that is the only way that initialization of
9137 // a reference to a non-class type can occur from something that
9138 // is not of the same type.
9139 if (ArgIdx < NumContextualBoolArguments) {
9140 assert(ParamTys[ArgIdx] == Context.BoolTy &&
9141 "Contextual conversion to bool requires bool type");
9142 Candidate.Conversions[ArgIdx]
9143 = TryContextuallyConvertToBool(S&: *this, From: Args[ArgIdx]);
9144 } else {
9145 Candidate.Conversions[ArgIdx]
9146 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamTys[ArgIdx],
9147 SuppressUserConversions: ArgIdx == 0 && IsAssignmentOperator,
9148 /*InOverloadResolution=*/false,
9149 /*AllowObjCWritebackConversion=*/
9150 getLangOpts().ObjCAutoRefCount);
9151 }
9152 if (Candidate.Conversions[ArgIdx].isBad()) {
9153 Candidate.Viable = false;
9154 Candidate.FailureKind = ovl_fail_bad_conversion;
9155 break;
9156 }
9157 }
9158}
9159
9160namespace {
9161
9162/// BuiltinCandidateTypeSet - A set of types that will be used for the
9163/// candidate operator functions for built-in operators (C++
9164/// [over.built]). The types are separated into pointer types and
9165/// enumeration types.
9166class BuiltinCandidateTypeSet {
9167 /// TypeSet - A set of types.
9168 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
9169
9170 /// PointerTypes - The set of pointer types that will be used in the
9171 /// built-in candidates.
9172 TypeSet PointerTypes;
9173
9174 /// MemberPointerTypes - The set of member pointer types that will be
9175 /// used in the built-in candidates.
9176 TypeSet MemberPointerTypes;
9177
9178 /// EnumerationTypes - The set of enumeration types that will be
9179 /// used in the built-in candidates.
9180 TypeSet EnumerationTypes;
9181
9182 /// The set of vector types that will be used in the built-in
9183 /// candidates.
9184 TypeSet VectorTypes;
9185
9186 /// The set of matrix types that will be used in the built-in
9187 /// candidates.
9188 TypeSet MatrixTypes;
9189
9190 /// The set of _BitInt types that will be used in the built-in candidates.
9191 TypeSet BitIntTypes;
9192
9193 /// A flag indicating non-record types are viable candidates
9194 bool HasNonRecordTypes;
9195
9196 /// A flag indicating whether either arithmetic or enumeration types
9197 /// were present in the candidate set.
9198 bool HasArithmeticOrEnumeralTypes;
9199
9200 /// A flag indicating whether the candidate set has a type that might
9201 /// convert to a promoted arithmetic type or to a vector type. This is
9202 /// conservative: only scoped enumerations, pointers, member pointers,
9203 /// nullptr_t, and classes that convert to nothing else are known not to.
9204 bool MayConvertToArithmetic;
9205
9206 /// A flag indicating whether the nullptr type was present in the
9207 /// candidate set.
9208 bool HasNullPtrType;
9209
9210 /// A flag indicating whether the reflection type was present in the
9211 /// candidate set.
9212 bool HasReflectionType;
9213
9214 /// Sema - The semantic analysis instance where we are building the
9215 /// candidate type set.
9216 Sema &SemaRef;
9217
9218 /// Context - The AST context in which we will build the type sets.
9219 ASTContext &Context;
9220
9221 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9222 const Qualifiers &VisibleQuals);
9223 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
9224
9225public:
9226 /// iterator - Iterates through the types that are part of the set.
9227 typedef TypeSet::iterator iterator;
9228
9229 BuiltinCandidateTypeSet(Sema &SemaRef)
9230 : HasNonRecordTypes(false), HasArithmeticOrEnumeralTypes(false),
9231 MayConvertToArithmetic(false), HasNullPtrType(false),
9232 HasReflectionType(false), SemaRef(SemaRef), Context(SemaRef.Context) {}
9233
9234 void AddTypesConvertedFrom(QualType Ty,
9235 SourceLocation Loc,
9236 bool AllowUserConversions,
9237 bool AllowExplicitConversions,
9238 const Qualifiers &VisibleTypeConversionsQuals);
9239
9240 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
9241 llvm::iterator_range<iterator> member_pointer_types() {
9242 return MemberPointerTypes;
9243 }
9244 llvm::iterator_range<iterator> enumeration_types() {
9245 return EnumerationTypes;
9246 }
9247 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
9248 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
9249 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
9250
9251 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(key: Ty); }
9252 bool hasNonRecordTypes() { return HasNonRecordTypes; }
9253 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
9254 bool mayConvertToArithmetic() const { return MayConvertToArithmetic; }
9255 bool hasNullPtrType() const { return HasNullPtrType; }
9256 bool hasReflectionType() const { return HasReflectionType; }
9257};
9258
9259} // end anonymous namespace
9260
9261/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
9262/// the set of pointer types along with any more-qualified variants of
9263/// that type. For example, if @p Ty is "int const *", this routine
9264/// will add "int const *", "int const volatile *", "int const
9265/// restrict *", and "int const volatile restrict *" to the set of
9266/// pointer types. Returns true if the add of @p Ty itself succeeded,
9267/// false otherwise.
9268///
9269/// FIXME: what to do about extended qualifiers?
9270bool
9271BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9272 const Qualifiers &VisibleQuals) {
9273
9274 // Insert this type.
9275 if (!PointerTypes.insert(X: Ty))
9276 return false;
9277
9278 QualType PointeeTy;
9279 const PointerType *PointerTy = Ty->getAs<PointerType>();
9280 bool buildObjCPtr = false;
9281 if (!PointerTy) {
9282 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
9283 PointeeTy = PTy->getPointeeType();
9284 buildObjCPtr = true;
9285 } else {
9286 PointeeTy = PointerTy->getPointeeType();
9287 }
9288
9289 // Don't add qualified variants of arrays. For one, they're not allowed
9290 // (the qualifier would sink to the element type), and for another, the
9291 // only overload situation where it matters is subscript or pointer +- int,
9292 // and those shouldn't have qualifier variants anyway.
9293 if (PointeeTy->isArrayType())
9294 return true;
9295
9296 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9297 bool hasVolatile = VisibleQuals.hasVolatile();
9298 bool hasRestrict = VisibleQuals.hasRestrict();
9299
9300 // Iterate through all strict supersets of BaseCVR.
9301 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9302 if ((CVR | BaseCVR) != CVR) continue;
9303 // Skip over volatile if no volatile found anywhere in the types.
9304 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
9305
9306 // Skip over restrict if no restrict found anywhere in the types, or if
9307 // the type cannot be restrict-qualified.
9308 if ((CVR & Qualifiers::Restrict) &&
9309 (!hasRestrict ||
9310 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
9311 continue;
9312
9313 // Build qualified pointee type.
9314 QualType QPointeeTy = Context.getCVRQualifiedType(T: PointeeTy, CVR);
9315
9316 // Build qualified pointer type.
9317 QualType QPointerTy;
9318 if (!buildObjCPtr)
9319 QPointerTy = Context.getPointerType(T: QPointeeTy);
9320 else
9321 QPointerTy = Context.getObjCObjectPointerType(OIT: QPointeeTy);
9322
9323 // Insert qualified pointer type.
9324 PointerTypes.insert(X: QPointerTy);
9325 }
9326
9327 return true;
9328}
9329
9330/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
9331/// to the set of pointer types along with any more-qualified variants of
9332/// that type. For example, if @p Ty is "int const *", this routine
9333/// will add "int const *", "int const volatile *", "int const
9334/// restrict *", and "int const volatile restrict *" to the set of
9335/// pointer types. Returns true if the add of @p Ty itself succeeded,
9336/// false otherwise.
9337///
9338/// FIXME: what to do about extended qualifiers?
9339bool
9340BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
9341 QualType Ty) {
9342 // Insert this type.
9343 if (!MemberPointerTypes.insert(X: Ty))
9344 return false;
9345
9346 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
9347 assert(PointerTy && "type was not a member pointer type!");
9348
9349 QualType PointeeTy = PointerTy->getPointeeType();
9350 // Don't add qualified variants of arrays. For one, they're not allowed
9351 // (the qualifier would sink to the element type), and for another, the
9352 // only overload situation where it matters is subscript or pointer +- int,
9353 // and those shouldn't have qualifier variants anyway.
9354 if (PointeeTy->isArrayType())
9355 return true;
9356 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
9357
9358 // Iterate through all strict supersets of the pointee type's CVR
9359 // qualifiers.
9360 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9361 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9362 if ((CVR | BaseCVR) != CVR) continue;
9363
9364 QualType QPointeeTy = Context.getCVRQualifiedType(T: PointeeTy, CVR);
9365 MemberPointerTypes.insert(X: Context.getMemberPointerType(
9366 T: QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9367 }
9368
9369 return true;
9370}
9371
9372/// AddTypesConvertedFrom - Add each of the types to which the type @p
9373/// Ty can be implicit converted to the given set of @p Types. We're
9374/// primarily interested in pointer types and enumeration types. We also
9375/// take member pointer types, for the conditional operator.
9376/// AllowUserConversions is true if we should look at the conversion
9377/// functions of a class type, and AllowExplicitConversions if we
9378/// should also include the explicit conversion functions of a class
9379/// type.
9380void
9381BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9382 SourceLocation Loc,
9383 bool AllowUserConversions,
9384 bool AllowExplicitConversions,
9385 const Qualifiers &VisibleQuals) {
9386 // Only deal with canonical types.
9387 Ty = Context.getCanonicalType(T: Ty);
9388
9389 // Look through reference types; they aren't part of the type of an
9390 // expression for the purposes of conversions.
9391 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9392 Ty = RefTy->getPointeeType();
9393
9394 // If we're dealing with an array type, decay to the pointer.
9395 if (Ty->isArrayType())
9396 Ty = SemaRef.Context.getArrayDecayedType(T: Ty);
9397
9398 // Otherwise, we don't care about qualifiers on the type.
9399 Ty = Ty.getLocalUnqualifiedType();
9400
9401 // Flag if we ever add a non-record type.
9402 bool TyIsRec = Ty->isRecordType();
9403 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9404
9405 // Flag if we encounter an arithmetic type.
9406 HasArithmeticOrEnumeralTypes =
9407 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9408
9409 // Flag if the type might convert to a promoted arithmetic or vector type.
9410 // For records, this is set below when visiting their conversion functions.
9411 MayConvertToArithmetic =
9412 MayConvertToArithmetic ||
9413 !(TyIsRec || Ty->isScopedEnumeralType() || Ty->isAnyPointerType() ||
9414 Ty->isMemberPointerType() || Ty->isNullPtrType());
9415
9416 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9417 PointerTypes.insert(X: Ty);
9418 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9419 // Insert our type, and its more-qualified variants, into the set
9420 // of types.
9421 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9422 return;
9423 } else if (Ty->isMemberPointerType()) {
9424 // Member pointers are far easier, since the pointee can't be converted.
9425 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9426 return;
9427 } else if (Ty->isEnumeralType()) {
9428 HasArithmeticOrEnumeralTypes = true;
9429 EnumerationTypes.insert(X: Ty);
9430 } else if (Ty->isBitIntType()) {
9431 HasArithmeticOrEnumeralTypes = true;
9432 BitIntTypes.insert(X: Ty);
9433 } else if (Ty->isVectorType()) {
9434 // We treat vector types as arithmetic types in many contexts as an
9435 // extension.
9436 HasArithmeticOrEnumeralTypes = true;
9437 VectorTypes.insert(X: Ty);
9438 } else if (Ty->isMatrixType()) {
9439 // Similar to vector types, we treat vector types as arithmetic types in
9440 // many contexts as an extension.
9441 HasArithmeticOrEnumeralTypes = true;
9442 MatrixTypes.insert(X: Ty);
9443 } else if (Ty->isNullPtrType()) {
9444 HasNullPtrType = true;
9445 } else if (Ty->isMetaInfoType()) {
9446 HasReflectionType = true;
9447 } else if (AllowUserConversions && TyIsRec) {
9448 // No conversion functions in incomplete types.
9449 if (!SemaRef.isCompleteType(Loc, T: Ty))
9450 return;
9451
9452 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9453 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9454 if (isa<UsingShadowDecl>(Val: D))
9455 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
9456
9457 // Skip conversion function templates; they don't tell us anything
9458 // about which builtin types we can convert to.
9459 if (isa<FunctionTemplateDecl>(Val: D)) {
9460 MayConvertToArithmetic = true;
9461 continue;
9462 }
9463
9464 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
9465 if (AllowExplicitConversions || !Conv->isExplicit()) {
9466 AddTypesConvertedFrom(Ty: Conv->getConversionType(), Loc, AllowUserConversions: false, AllowExplicitConversions: false,
9467 VisibleQuals);
9468 }
9469 }
9470 }
9471}
9472/// Helper function for adjusting address spaces for the pointer or reference
9473/// operands of builtin operators depending on the argument.
9474static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
9475 Expr *Arg) {
9476 return S.Context.getAddrSpaceQualType(T, AddressSpace: Arg->getType().getAddressSpace());
9477}
9478
9479/// Helper function for AddBuiltinOperatorCandidates() that adds
9480/// the volatile- and non-volatile-qualified assignment operators for the
9481/// given type to the candidate set.
9482static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
9483 QualType T,
9484 ArrayRef<Expr *> Args,
9485 OverloadCandidateSet &CandidateSet) {
9486 QualType ParamTypes[2];
9487
9488 // T& operator=(T&, T)
9489 ParamTypes[0] = S.Context.getLValueReferenceType(
9490 T: AdjustAddressSpaceForBuiltinOperandType(S, T, Arg: Args[0]));
9491 ParamTypes[1] = T;
9492 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9493 /*IsAssignmentOperator=*/true);
9494
9495 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
9496 // volatile T& operator=(volatile T&, T)
9497 ParamTypes[0] = S.Context.getLValueReferenceType(
9498 T: AdjustAddressSpaceForBuiltinOperandType(S, T: S.Context.getVolatileType(T),
9499 Arg: Args[0]));
9500 ParamTypes[1] = T;
9501 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9502 /*IsAssignmentOperator=*/true);
9503 }
9504}
9505
9506/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9507/// if any, found in visible type conversion functions found in ArgExpr's type.
9508static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9509 Qualifiers VRQuals;
9510 CXXRecordDecl *ClassDecl;
9511 if (const MemberPointerType *RHSMPType =
9512 ArgExpr->getType()->getAs<MemberPointerType>())
9513 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9514 else
9515 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9516 if (!ClassDecl) {
9517 // Just to be safe, assume the worst case.
9518 VRQuals.addVolatile();
9519 VRQuals.addRestrict();
9520 return VRQuals;
9521 }
9522 if (!ClassDecl->hasDefinition())
9523 return VRQuals;
9524
9525 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9526 if (isa<UsingShadowDecl>(Val: D))
9527 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
9528 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Val: D)) {
9529 QualType CanTy = Context.getCanonicalType(T: Conv->getConversionType());
9530 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9531 CanTy = ResTypeRef->getPointeeType();
9532 // Need to go down the pointer/mempointer chain and add qualifiers
9533 // as see them.
9534 bool done = false;
9535 while (!done) {
9536 if (CanTy.isRestrictQualified())
9537 VRQuals.addRestrict();
9538 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9539 CanTy = ResTypePtr->getPointeeType();
9540 else if (const MemberPointerType *ResTypeMPtr =
9541 CanTy->getAs<MemberPointerType>())
9542 CanTy = ResTypeMPtr->getPointeeType();
9543 else
9544 done = true;
9545 if (CanTy.isVolatileQualified())
9546 VRQuals.addVolatile();
9547 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9548 return VRQuals;
9549 }
9550 }
9551 }
9552 return VRQuals;
9553}
9554
9555// Note: We're currently only handling qualifiers that are meaningful for the
9556// LHS of compound assignment overloading.
9557static void forAllQualifierCombinationsImpl(
9558 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9559 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9560 // _Atomic
9561 if (Available.hasAtomic()) {
9562 Available.removeAtomic();
9563 forAllQualifierCombinationsImpl(Available, Applied: Applied.withAtomic(), Callback);
9564 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9565 return;
9566 }
9567
9568 // volatile
9569 if (Available.hasVolatile()) {
9570 Available.removeVolatile();
9571 assert(!Applied.hasVolatile());
9572 forAllQualifierCombinationsImpl(Available, Applied: Applied.withVolatile(),
9573 Callback);
9574 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9575 return;
9576 }
9577
9578 Callback(Applied);
9579}
9580
9581static void forAllQualifierCombinations(
9582 QualifiersAndAtomic Quals,
9583 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9584 return forAllQualifierCombinationsImpl(Available: Quals, Applied: QualifiersAndAtomic(),
9585 Callback);
9586}
9587
9588static QualType makeQualifiedLValueReferenceType(QualType Base,
9589 QualifiersAndAtomic Quals,
9590 Sema &S) {
9591 if (Quals.hasAtomic())
9592 Base = S.Context.getAtomicType(T: Base);
9593 if (Quals.hasVolatile())
9594 Base = S.Context.getVolatileType(T: Base);
9595 return S.Context.getLValueReferenceType(T: Base);
9596}
9597
9598namespace {
9599
9600/// Helper class to manage the addition of builtin operator overload
9601/// candidates. It provides shared state and utility methods used throughout
9602/// the process, as well as a helper method to add each group of builtin
9603/// operator overloads from the standard to a candidate set.
9604class BuiltinOperatorOverloadBuilder {
9605 // Common instance state available to all overload candidate addition methods.
9606 Sema &S;
9607 ArrayRef<Expr *> Args;
9608 QualifiersAndAtomic VisibleTypeConversionsQuals;
9609 // Whether a candidate whose parameters are all arithmetic, vector or matrix
9610 // types can be viable. It is viable if there is an arithmetic or enumeral
9611 // candidate type, and every argument might convert to such a type.
9612 bool ArithmeticCandidatesMayBeViable;
9613 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9614 OverloadCandidateSet &CandidateSet;
9615
9616 static constexpr int ArithmeticTypesCap = 26;
9617 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9618
9619 // Define some indices used to iterate over the arithmetic types in
9620 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9621 // types are that preserved by promotion (C++ [over.built]p2).
9622 unsigned FirstIntegralType,
9623 LastIntegralType;
9624 unsigned FirstPromotedIntegralType,
9625 LastPromotedIntegralType;
9626 unsigned FirstPromotedArithmeticType,
9627 LastPromotedArithmeticType;
9628 unsigned NumArithmeticTypes;
9629
9630 void InitArithmeticTypes() {
9631 // Start of promoted types.
9632 FirstPromotedArithmeticType = 0;
9633 ArithmeticTypes.push_back(Elt: S.Context.FloatTy);
9634 ArithmeticTypes.push_back(Elt: S.Context.DoubleTy);
9635 ArithmeticTypes.push_back(Elt: S.Context.LongDoubleTy);
9636 if (S.Context.getTargetInfo().hasFloat128Type())
9637 ArithmeticTypes.push_back(Elt: S.Context.Float128Ty);
9638 if (S.Context.getTargetInfo().hasIbm128Type())
9639 ArithmeticTypes.push_back(Elt: S.Context.Ibm128Ty);
9640
9641 // Start of integral types.
9642 FirstIntegralType = ArithmeticTypes.size();
9643 FirstPromotedIntegralType = ArithmeticTypes.size();
9644 ArithmeticTypes.push_back(Elt: S.Context.IntTy);
9645 ArithmeticTypes.push_back(Elt: S.Context.LongTy);
9646 ArithmeticTypes.push_back(Elt: S.Context.LongLongTy);
9647 if (S.Context.getTargetInfo().hasInt128Type() ||
9648 (S.Context.getAuxTargetInfo() &&
9649 S.Context.getAuxTargetInfo()->hasInt128Type()))
9650 ArithmeticTypes.push_back(Elt: S.Context.Int128Ty);
9651 ArithmeticTypes.push_back(Elt: S.Context.UnsignedIntTy);
9652 ArithmeticTypes.push_back(Elt: S.Context.UnsignedLongTy);
9653 ArithmeticTypes.push_back(Elt: S.Context.UnsignedLongLongTy);
9654 if (S.Context.getTargetInfo().hasInt128Type() ||
9655 (S.Context.getAuxTargetInfo() &&
9656 S.Context.getAuxTargetInfo()->hasInt128Type()))
9657 ArithmeticTypes.push_back(Elt: S.Context.UnsignedInt128Ty);
9658
9659 /// We add candidates for the unique, unqualified _BitInt types present in
9660 /// the candidate type set. The candidate set already handled ensuring the
9661 /// type is unqualified and canonical, but because we're adding from N
9662 /// different sets, we need to do some extra work to unique things. Insert
9663 /// the candidates into a unique set, then move from that set into the list
9664 /// of arithmetic types.
9665 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9666 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9667 for (QualType BitTy : Candidate.bitint_types())
9668 BitIntCandidates.insert(X: CanQualType::CreateUnsafe(Other: BitTy));
9669 }
9670 llvm::move(Range&: BitIntCandidates, Out: std::back_inserter(x&: ArithmeticTypes));
9671 LastPromotedIntegralType = ArithmeticTypes.size();
9672 LastPromotedArithmeticType = ArithmeticTypes.size();
9673 // End of promoted types.
9674
9675 ArithmeticTypes.push_back(Elt: S.Context.BoolTy);
9676 ArithmeticTypes.push_back(Elt: S.Context.CharTy);
9677 ArithmeticTypes.push_back(Elt: S.Context.WCharTy);
9678 if (S.Context.getLangOpts().Char8)
9679 ArithmeticTypes.push_back(Elt: S.Context.Char8Ty);
9680 ArithmeticTypes.push_back(Elt: S.Context.Char16Ty);
9681 ArithmeticTypes.push_back(Elt: S.Context.Char32Ty);
9682 ArithmeticTypes.push_back(Elt: S.Context.SignedCharTy);
9683 ArithmeticTypes.push_back(Elt: S.Context.ShortTy);
9684 ArithmeticTypes.push_back(Elt: S.Context.UnsignedCharTy);
9685 ArithmeticTypes.push_back(Elt: S.Context.UnsignedShortTy);
9686 LastIntegralType = ArithmeticTypes.size();
9687 NumArithmeticTypes = ArithmeticTypes.size();
9688 // End of integral types.
9689 // FIXME: What about complex? What about half?
9690
9691 // We don't know for sure how many bit-precise candidates were involved, so
9692 // we subtract those from the total when testing whether we're under the
9693 // cap or not.
9694 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9695 ArithmeticTypesCap &&
9696 "Enough inline storage for all arithmetic types.");
9697 }
9698
9699 /// Helper method to factor out the common pattern of adding overloads
9700 /// for '++' and '--' builtin operators.
9701 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9702 bool HasVolatile,
9703 bool HasRestrict) {
9704 QualType ParamTypes[2] = {
9705 S.Context.getLValueReferenceType(T: CandidateTy),
9706 S.Context.IntTy
9707 };
9708
9709 // Non-volatile version.
9710 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9711
9712 // Use a heuristic to reduce number of builtin candidates in the set:
9713 // add volatile version only if there are conversions to a volatile type.
9714 if (HasVolatile) {
9715 ParamTypes[0] =
9716 S.Context.getLValueReferenceType(
9717 T: S.Context.getVolatileType(T: CandidateTy));
9718 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9719 }
9720
9721 // Add restrict version only if there are conversions to a restrict type
9722 // and our candidate type is a non-restrict-qualified pointer.
9723 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9724 !CandidateTy.isRestrictQualified()) {
9725 ParamTypes[0]
9726 = S.Context.getLValueReferenceType(
9727 T: S.Context.getCVRQualifiedType(T: CandidateTy, CVR: Qualifiers::Restrict));
9728 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9729
9730 if (HasVolatile) {
9731 ParamTypes[0]
9732 = S.Context.getLValueReferenceType(
9733 T: S.Context.getCVRQualifiedType(T: CandidateTy,
9734 CVR: (Qualifiers::Volatile |
9735 Qualifiers::Restrict)));
9736 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9737 }
9738 }
9739
9740 }
9741
9742 /// Helper to add an overload candidate for a binary builtin with types \p L
9743 /// and \p R.
9744 void AddCandidate(QualType L, QualType R) {
9745 QualType LandR[2] = {L, R};
9746 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9747 }
9748
9749public:
9750 BuiltinOperatorOverloadBuilder(
9751 Sema &S, ArrayRef<Expr *> Args,
9752 QualifiersAndAtomic VisibleTypeConversionsQuals,
9753 bool HasArithmeticOrEnumeralCandidateType,
9754 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9755 OverloadCandidateSet &CandidateSet)
9756 : S(S), Args(Args),
9757 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9758 ArithmeticCandidatesMayBeViable(
9759 HasArithmeticOrEnumeralCandidateType &&
9760 llvm::all_of(Range&: CandidateTypes,
9761 P: [](const BuiltinCandidateTypeSet &Types) {
9762 return Types.mayConvertToArithmetic();
9763 })),
9764 CandidateTypes(CandidateTypes), CandidateSet(CandidateSet) {
9765 InitArithmeticTypes();
9766 }
9767
9768 // Increment is deprecated for bool since C++17.
9769 //
9770 // C++ [over.built]p3:
9771 //
9772 // For every pair (T, VQ), where T is an arithmetic type other
9773 // than bool, and VQ is either volatile or empty, there exist
9774 // candidate operator functions of the form
9775 //
9776 // VQ T& operator++(VQ T&);
9777 // T operator++(VQ T&, int);
9778 //
9779 // C++ [over.built]p4:
9780 //
9781 // For every pair (T, VQ), where T is an arithmetic type other
9782 // than bool, and VQ is either volatile or empty, there exist
9783 // candidate operator functions of the form
9784 //
9785 // VQ T& operator--(VQ T&);
9786 // T operator--(VQ T&, int);
9787 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9788 if (!ArithmeticCandidatesMayBeViable)
9789 return;
9790
9791 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9792 const auto TypeOfT = ArithmeticTypes[Arith];
9793 if (TypeOfT == S.Context.BoolTy) {
9794 if (Op == OO_MinusMinus)
9795 continue;
9796 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9797 continue;
9798 }
9799 addPlusPlusMinusMinusStyleOverloads(
9800 CandidateTy: TypeOfT,
9801 HasVolatile: VisibleTypeConversionsQuals.hasVolatile(),
9802 HasRestrict: VisibleTypeConversionsQuals.hasRestrict());
9803 }
9804 }
9805
9806 // C++ [over.built]p5:
9807 //
9808 // For every pair (T, VQ), where T is a cv-qualified or
9809 // cv-unqualified object type, and VQ is either volatile or
9810 // empty, there exist candidate operator functions of the form
9811 //
9812 // T*VQ& operator++(T*VQ&);
9813 // T*VQ& operator--(T*VQ&);
9814 // T* operator++(T*VQ&, int);
9815 // T* operator--(T*VQ&, int);
9816 void addPlusPlusMinusMinusPointerOverloads() {
9817 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9818 // Skip pointer types that aren't pointers to object types.
9819 if (!PtrTy->getPointeeType()->isObjectType())
9820 continue;
9821
9822 addPlusPlusMinusMinusStyleOverloads(
9823 CandidateTy: PtrTy,
9824 HasVolatile: (!PtrTy.isVolatileQualified() &&
9825 VisibleTypeConversionsQuals.hasVolatile()),
9826 HasRestrict: (!PtrTy.isRestrictQualified() &&
9827 VisibleTypeConversionsQuals.hasRestrict()));
9828 }
9829 }
9830
9831 // C++ [over.built]p6:
9832 // For every cv-qualified or cv-unqualified object type T, there
9833 // exist candidate operator functions of the form
9834 //
9835 // T& operator*(T*);
9836 //
9837 // C++ [over.built]p7:
9838 // For every function type T that does not have cv-qualifiers or a
9839 // ref-qualifier, there exist candidate operator functions of the form
9840 // T& operator*(T*);
9841 void addUnaryStarPointerOverloads() {
9842 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9843 QualType PointeeTy = ParamTy->getPointeeType();
9844 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9845 continue;
9846
9847 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9848 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9849 continue;
9850
9851 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet);
9852 }
9853 }
9854
9855 // C++ [over.built]p9:
9856 // For every promoted arithmetic type T, there exist candidate
9857 // operator functions of the form
9858 //
9859 // T operator+(T);
9860 // T operator-(T);
9861 void addUnaryPlusOrMinusArithmeticOverloads() {
9862 if (!ArithmeticCandidatesMayBeViable)
9863 return;
9864
9865 for (unsigned Arith = FirstPromotedArithmeticType;
9866 Arith < LastPromotedArithmeticType; ++Arith) {
9867 QualType ArithTy = ArithmeticTypes[Arith];
9868 S.AddBuiltinCandidate(ParamTys: &ArithTy, Args, CandidateSet);
9869 }
9870
9871 // Extension: We also add these operators for vector types.
9872 for (QualType VecTy : CandidateTypes[0].vector_types())
9873 S.AddBuiltinCandidate(ParamTys: &VecTy, Args, CandidateSet);
9874 }
9875
9876 // C++ [over.built]p8:
9877 // For every type T, there exist candidate operator functions of
9878 // the form
9879 //
9880 // T* operator+(T*);
9881 void addUnaryPlusPointerOverloads() {
9882 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9883 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet);
9884 }
9885
9886 // C++ [over.built]p10:
9887 // For every promoted integral type T, there exist candidate
9888 // operator functions of the form
9889 //
9890 // T operator~(T);
9891 void addUnaryTildePromotedIntegralOverloads() {
9892 if (!ArithmeticCandidatesMayBeViable)
9893 return;
9894
9895 for (unsigned Int = FirstPromotedIntegralType;
9896 Int < LastPromotedIntegralType; ++Int) {
9897 QualType IntTy = ArithmeticTypes[Int];
9898 S.AddBuiltinCandidate(ParamTys: &IntTy, Args, CandidateSet);
9899 }
9900
9901 // Extension: We also add this operator for vector types.
9902 for (QualType VecTy : CandidateTypes[0].vector_types())
9903 S.AddBuiltinCandidate(ParamTys: &VecTy, Args, CandidateSet);
9904 }
9905
9906 // C++ [over.match.oper]p16:
9907 // For every pointer to member type T or type std::nullptr_t, there
9908 // exist candidate operator functions of the form
9909 //
9910 // bool operator==(T,T);
9911 // bool operator!=(T,T);
9912 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9913 /// Set of (canonical) types that we've already handled.
9914 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9915
9916 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9917 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9918 // Don't add the same builtin candidate twice.
9919 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
9920 continue;
9921
9922 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9923 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9924 }
9925
9926 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9927 CanQualType NullPtrTy = S.Context.getCanonicalType(T: S.Context.NullPtrTy);
9928 if (AddedTypes.insert(Ptr: NullPtrTy).second) {
9929 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9930 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9931 }
9932 }
9933
9934 if (CandidateTypes[ArgIdx].hasReflectionType()) {
9935 CanQualType MetaInfoTy = S.Context.MetaInfoTy;
9936 if (AddedTypes.insert(Ptr: MetaInfoTy).second) {
9937 QualType ParamTypes[2] = {MetaInfoTy, MetaInfoTy};
9938 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9939 }
9940 }
9941 }
9942 }
9943
9944 // C++ [over.built]p15:
9945 //
9946 // For every T, where T is an enumeration type or a pointer type,
9947 // there exist candidate operator functions of the form
9948 //
9949 // bool operator<(T, T);
9950 // bool operator>(T, T);
9951 // bool operator<=(T, T);
9952 // bool operator>=(T, T);
9953 // bool operator==(T, T);
9954 // bool operator!=(T, T);
9955 // R operator<=>(T, T)
9956 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9957 // C++ [over.match.oper]p3:
9958 // [...]the built-in candidates include all of the candidate operator
9959 // functions defined in 13.6 that, compared to the given operator, [...]
9960 // do not have the same parameter-type-list as any non-template non-member
9961 // candidate.
9962 //
9963 // Note that in practice, this only affects enumeration types because there
9964 // aren't any built-in candidates of record type, and a user-defined operator
9965 // must have an operand of record or enumeration type. Also, the only other
9966 // overloaded operator with enumeration arguments, operator=,
9967 // cannot be overloaded for enumeration types, so this is the only place
9968 // where we must suppress candidates like this.
9969 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9970 UserDefinedBinaryOperators;
9971
9972 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9973 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9974 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9975 CEnd = CandidateSet.end();
9976 C != CEnd; ++C) {
9977 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9978 continue;
9979
9980 if (C->Function->isFunctionTemplateSpecialization())
9981 continue;
9982
9983 // We interpret "same parameter-type-list" as applying to the
9984 // "synthesized candidate, with the order of the two parameters
9985 // reversed", not to the original function.
9986 bool Reversed = C->isReversed();
9987 QualType FirstParamType = C->Function->getParamDecl(i: Reversed ? 1 : 0)
9988 ->getType()
9989 .getUnqualifiedType();
9990 QualType SecondParamType = C->Function->getParamDecl(i: Reversed ? 0 : 1)
9991 ->getType()
9992 .getUnqualifiedType();
9993
9994 // Skip if either parameter isn't of enumeral type.
9995 if (!FirstParamType->isEnumeralType() ||
9996 !SecondParamType->isEnumeralType())
9997 continue;
9998
9999 // Add this operator to the set of known user-defined operators.
10000 UserDefinedBinaryOperators.insert(
10001 V: std::make_pair(x: S.Context.getCanonicalType(T: FirstParamType),
10002 y: S.Context.getCanonicalType(T: SecondParamType)));
10003 }
10004 }
10005 }
10006
10007 /// Set of (canonical) types that we've already handled.
10008 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10009
10010 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10011 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10012 // Don't add the same builtin candidate twice.
10013 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
10014 continue;
10015 if (IsSpaceship && PtrTy->isFunctionPointerType())
10016 continue;
10017
10018 QualType ParamTypes[2] = {PtrTy, PtrTy};
10019 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10020 }
10021 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10022 CanQualType CanonType = S.Context.getCanonicalType(T: EnumTy);
10023
10024 // Don't add the same builtin candidate twice, or if a user defined
10025 // candidate exists.
10026 if (!AddedTypes.insert(Ptr: CanonType).second ||
10027 UserDefinedBinaryOperators.count(V: std::make_pair(x&: CanonType,
10028 y&: CanonType)))
10029 continue;
10030 QualType ParamTypes[2] = {EnumTy, EnumTy};
10031 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10032 }
10033 }
10034 }
10035
10036 // C++ [over.built]p13:
10037 //
10038 // For every cv-qualified or cv-unqualified object type T
10039 // there exist candidate operator functions of the form
10040 //
10041 // T* operator+(T*, ptrdiff_t);
10042 // T& operator[](T*, ptrdiff_t); [BELOW]
10043 // T* operator-(T*, ptrdiff_t);
10044 // T* operator+(ptrdiff_t, T*);
10045 // T& operator[](ptrdiff_t, T*); [BELOW]
10046 //
10047 // C++ [over.built]p14:
10048 //
10049 // For every T, where T is a pointer to object type, there
10050 // exist candidate operator functions of the form
10051 //
10052 // ptrdiff_t operator-(T, T);
10053 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
10054 /// Set of (canonical) types that we've already handled.
10055 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10056
10057 for (int Arg = 0; Arg < 2; ++Arg) {
10058 QualType AsymmetricParamTypes[2] = {
10059 S.Context.getPointerDiffType(),
10060 S.Context.getPointerDiffType(),
10061 };
10062 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
10063 QualType PointeeTy = PtrTy->getPointeeType();
10064 if (!PointeeTy->isObjectType())
10065 continue;
10066
10067 AsymmetricParamTypes[Arg] = PtrTy;
10068 if (Arg == 0 || Op == OO_Plus) {
10069 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
10070 // T* operator+(ptrdiff_t, T*);
10071 S.AddBuiltinCandidate(ParamTys: AsymmetricParamTypes, Args, CandidateSet);
10072 }
10073 if (Op == OO_Minus) {
10074 // ptrdiff_t operator-(T, T);
10075 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
10076 continue;
10077
10078 QualType ParamTypes[2] = {PtrTy, PtrTy};
10079 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10080 }
10081 }
10082 }
10083 }
10084
10085 // C++ [over.built]p12:
10086 //
10087 // For every pair of promoted arithmetic types L and R, there
10088 // exist candidate operator functions of the form
10089 //
10090 // LR operator*(L, R);
10091 // LR operator/(L, R);
10092 // LR operator+(L, R);
10093 // LR operator-(L, R);
10094 // bool operator<(L, R);
10095 // bool operator>(L, R);
10096 // bool operator<=(L, R);
10097 // bool operator>=(L, R);
10098 // bool operator==(L, R);
10099 // bool operator!=(L, R);
10100 //
10101 // where LR is the result of the usual arithmetic conversions
10102 // between types L and R.
10103 //
10104 // C++ [over.built]p24:
10105 //
10106 // For every pair of promoted arithmetic types L and R, there exist
10107 // candidate operator functions of the form
10108 //
10109 // LR operator?(bool, L, R);
10110 //
10111 // where LR is the result of the usual arithmetic conversions
10112 // between types L and R.
10113 // Our candidates ignore the first parameter.
10114 void addGenericBinaryArithmeticOverloads() {
10115 if (!ArithmeticCandidatesMayBeViable)
10116 return;
10117
10118 for (unsigned Left = FirstPromotedArithmeticType;
10119 Left < LastPromotedArithmeticType; ++Left) {
10120 for (unsigned Right = FirstPromotedArithmeticType;
10121 Right < LastPromotedArithmeticType; ++Right) {
10122 QualType LandR[2] = { ArithmeticTypes[Left],
10123 ArithmeticTypes[Right] };
10124 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
10125 }
10126 }
10127
10128 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
10129 // conditional operator for vector types.
10130 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10131 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
10132 QualType LandR[2] = {Vec1Ty, Vec2Ty};
10133 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
10134 }
10135 }
10136
10137 /// Add binary operator overloads for each candidate matrix type M1, M2:
10138 /// * (M1, M1) -> M1
10139 /// * (M1, M1.getElementType()) -> M1
10140 /// * (M2.getElementType(), M2) -> M2
10141 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
10142 void addMatrixBinaryArithmeticOverloads() {
10143 if (!ArithmeticCandidatesMayBeViable)
10144 return;
10145
10146 for (QualType M1 : CandidateTypes[0].matrix_types()) {
10147 AddCandidate(L: M1, R: cast<MatrixType>(Val&: M1)->getElementType());
10148 AddCandidate(L: M1, R: M1);
10149 }
10150
10151 for (QualType M2 : CandidateTypes[1].matrix_types()) {
10152 AddCandidate(L: cast<MatrixType>(Val&: M2)->getElementType(), R: M2);
10153 if (!CandidateTypes[0].containsMatrixType(Ty: M2))
10154 AddCandidate(L: M2, R: M2);
10155 }
10156 }
10157
10158 // C++2a [over.built]p14:
10159 //
10160 // For every integral type T there exists a candidate operator function
10161 // of the form
10162 //
10163 // std::strong_ordering operator<=>(T, T)
10164 //
10165 // C++2a [over.built]p15:
10166 //
10167 // For every pair of floating-point types L and R, there exists a candidate
10168 // operator function of the form
10169 //
10170 // std::partial_ordering operator<=>(L, R);
10171 //
10172 // FIXME: The current specification for integral types doesn't play nice with
10173 // the direction of p0946r0, which allows mixed integral and unscoped-enum
10174 // comparisons. Under the current spec this can lead to ambiguity during
10175 // overload resolution. For example:
10176 //
10177 // enum A : int {a};
10178 // auto x = (a <=> (long)42);
10179 //
10180 // error: call is ambiguous for arguments 'A' and 'long'.
10181 // note: candidate operator<=>(int, int)
10182 // note: candidate operator<=>(long, long)
10183 //
10184 // To avoid this error, this function deviates from the specification and adds
10185 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
10186 // arithmetic types (the same as the generic relational overloads).
10187 //
10188 // For now this function acts as a placeholder.
10189 void addThreeWayArithmeticOverloads() {
10190 addGenericBinaryArithmeticOverloads();
10191 }
10192
10193 // C++ [over.built]p17:
10194 //
10195 // For every pair of promoted integral types L and R, there
10196 // exist candidate operator functions of the form
10197 //
10198 // LR operator%(L, R);
10199 // LR operator&(L, R);
10200 // LR operator^(L, R);
10201 // LR operator|(L, R);
10202 // L operator<<(L, R);
10203 // L operator>>(L, R);
10204 //
10205 // where LR is the result of the usual arithmetic conversions
10206 // between types L and R.
10207 void addBinaryBitwiseArithmeticOverloads() {
10208 if (!ArithmeticCandidatesMayBeViable)
10209 return;
10210
10211 for (unsigned Left = FirstPromotedIntegralType;
10212 Left < LastPromotedIntegralType; ++Left) {
10213 for (unsigned Right = FirstPromotedIntegralType;
10214 Right < LastPromotedIntegralType; ++Right) {
10215 QualType LandR[2] = { ArithmeticTypes[Left],
10216 ArithmeticTypes[Right] };
10217 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
10218 }
10219 }
10220 }
10221
10222 // C++ [over.built]p20:
10223 //
10224 // For every pair (T, VQ), where T is an enumeration or
10225 // pointer to member type and VQ is either volatile or
10226 // empty, there exist candidate operator functions of the form
10227 //
10228 // VQ T& operator=(VQ T&, T);
10229 void addAssignmentMemberPointerOrEnumeralOverloads() {
10230 /// Set of (canonical) types that we've already handled.
10231 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10232
10233 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10234 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10235 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: EnumTy)).second)
10236 continue;
10237
10238 AddBuiltinAssignmentOperatorCandidates(S, T: EnumTy, Args, CandidateSet);
10239 }
10240
10241 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10242 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
10243 continue;
10244
10245 AddBuiltinAssignmentOperatorCandidates(S, T: MemPtrTy, Args, CandidateSet);
10246 }
10247 }
10248 }
10249
10250 // C++ [over.built]p19:
10251 //
10252 // For every pair (T, VQ), where T is any type and VQ is either
10253 // volatile or empty, there exist candidate operator functions
10254 // of the form
10255 //
10256 // T*VQ& operator=(T*VQ&, T*);
10257 //
10258 // C++ [over.built]p21:
10259 //
10260 // For every pair (T, VQ), where T is a cv-qualified or
10261 // cv-unqualified object type and VQ is either volatile or
10262 // empty, there exist candidate operator functions of the form
10263 //
10264 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
10265 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
10266 void addAssignmentPointerOverloads(bool isEqualOp) {
10267 /// Set of (canonical) types that we've already handled.
10268 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10269
10270 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10271 // If this is operator=, keep track of the builtin candidates we added.
10272 if (isEqualOp)
10273 AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy));
10274 else if (!PtrTy->getPointeeType()->isObjectType())
10275 continue;
10276
10277 // non-volatile version
10278 QualType ParamTypes[2] = {
10279 S.Context.getLValueReferenceType(T: PtrTy),
10280 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
10281 };
10282 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10283 /*IsAssignmentOperator=*/ isEqualOp);
10284
10285 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10286 VisibleTypeConversionsQuals.hasVolatile();
10287 if (NeedVolatile) {
10288 // volatile version
10289 ParamTypes[0] =
10290 S.Context.getLValueReferenceType(T: S.Context.getVolatileType(T: PtrTy));
10291 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10292 /*IsAssignmentOperator=*/isEqualOp);
10293 }
10294
10295 if (!PtrTy.isRestrictQualified() &&
10296 VisibleTypeConversionsQuals.hasRestrict()) {
10297 // restrict version
10298 ParamTypes[0] =
10299 S.Context.getLValueReferenceType(T: S.Context.getRestrictType(T: PtrTy));
10300 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10301 /*IsAssignmentOperator=*/isEqualOp);
10302
10303 if (NeedVolatile) {
10304 // volatile restrict version
10305 ParamTypes[0] =
10306 S.Context.getLValueReferenceType(T: S.Context.getCVRQualifiedType(
10307 T: PtrTy, CVR: (Qualifiers::Volatile | Qualifiers::Restrict)));
10308 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10309 /*IsAssignmentOperator=*/isEqualOp);
10310 }
10311 }
10312 }
10313
10314 if (isEqualOp) {
10315 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10316 // Make sure we don't add the same candidate twice.
10317 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
10318 continue;
10319
10320 QualType ParamTypes[2] = {
10321 S.Context.getLValueReferenceType(T: PtrTy),
10322 PtrTy,
10323 };
10324
10325 // non-volatile version
10326 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10327 /*IsAssignmentOperator=*/true);
10328
10329 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10330 VisibleTypeConversionsQuals.hasVolatile();
10331 if (NeedVolatile) {
10332 // volatile version
10333 ParamTypes[0] = S.Context.getLValueReferenceType(
10334 T: S.Context.getVolatileType(T: PtrTy));
10335 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10336 /*IsAssignmentOperator=*/true);
10337 }
10338
10339 if (!PtrTy.isRestrictQualified() &&
10340 VisibleTypeConversionsQuals.hasRestrict()) {
10341 // restrict version
10342 ParamTypes[0] = S.Context.getLValueReferenceType(
10343 T: S.Context.getRestrictType(T: PtrTy));
10344 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10345 /*IsAssignmentOperator=*/true);
10346
10347 if (NeedVolatile) {
10348 // volatile restrict version
10349 ParamTypes[0] =
10350 S.Context.getLValueReferenceType(T: S.Context.getCVRQualifiedType(
10351 T: PtrTy, CVR: (Qualifiers::Volatile | Qualifiers::Restrict)));
10352 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10353 /*IsAssignmentOperator=*/true);
10354 }
10355 }
10356 }
10357 }
10358 }
10359
10360 // C++ [over.built]p18:
10361 //
10362 // For every triple (L, VQ, R), where L is an arithmetic type,
10363 // VQ is either volatile or empty, and R is a promoted
10364 // arithmetic type, there exist candidate operator functions of
10365 // the form
10366 //
10367 // VQ L& operator=(VQ L&, R);
10368 // VQ L& operator*=(VQ L&, R);
10369 // VQ L& operator/=(VQ L&, R);
10370 // VQ L& operator+=(VQ L&, R);
10371 // VQ L& operator-=(VQ L&, R);
10372 void addAssignmentArithmeticOverloads(bool isEqualOp) {
10373 if (!ArithmeticCandidatesMayBeViable)
10374 return;
10375
10376 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
10377 for (unsigned Right = FirstPromotedArithmeticType;
10378 Right < LastPromotedArithmeticType; ++Right) {
10379 QualType ParamTypes[2];
10380 ParamTypes[1] = ArithmeticTypes[Right];
10381 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
10382 S, T: ArithmeticTypes[Left], Arg: Args[0]);
10383
10384 forAllQualifierCombinations(
10385 Quals: VisibleTypeConversionsQuals, Callback: [&](QualifiersAndAtomic Quals) {
10386 ParamTypes[0] =
10387 makeQualifiedLValueReferenceType(Base: LeftBaseTy, Quals, S);
10388 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10389 /*IsAssignmentOperator=*/isEqualOp);
10390 });
10391 }
10392 }
10393
10394 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10395 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10396 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10397 QualType ParamTypes[2];
10398 ParamTypes[1] = Vec2Ty;
10399 // Add this built-in operator as a candidate (VQ is empty).
10400 ParamTypes[0] = S.Context.getLValueReferenceType(T: Vec1Ty);
10401 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10402 /*IsAssignmentOperator=*/isEqualOp);
10403
10404 // Add this built-in operator as a candidate (VQ is 'volatile').
10405 if (VisibleTypeConversionsQuals.hasVolatile()) {
10406 ParamTypes[0] = S.Context.getVolatileType(T: Vec1Ty);
10407 ParamTypes[0] = S.Context.getLValueReferenceType(T: ParamTypes[0]);
10408 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10409 /*IsAssignmentOperator=*/isEqualOp);
10410 }
10411 }
10412 }
10413
10414 // C++ [over.built]p22:
10415 //
10416 // For every triple (L, VQ, R), where L is an integral type, VQ
10417 // is either volatile or empty, and R is a promoted integral
10418 // type, there exist candidate operator functions of the form
10419 //
10420 // VQ L& operator%=(VQ L&, R);
10421 // VQ L& operator<<=(VQ L&, R);
10422 // VQ L& operator>>=(VQ L&, R);
10423 // VQ L& operator&=(VQ L&, R);
10424 // VQ L& operator^=(VQ L&, R);
10425 // VQ L& operator|=(VQ L&, R);
10426 void addAssignmentIntegralOverloads() {
10427 if (!ArithmeticCandidatesMayBeViable)
10428 return;
10429
10430 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10431 for (unsigned Right = FirstPromotedIntegralType;
10432 Right < LastPromotedIntegralType; ++Right) {
10433 QualType ParamTypes[2];
10434 ParamTypes[1] = ArithmeticTypes[Right];
10435 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
10436 S, T: ArithmeticTypes[Left], Arg: Args[0]);
10437
10438 forAllQualifierCombinations(
10439 Quals: VisibleTypeConversionsQuals, Callback: [&](QualifiersAndAtomic Quals) {
10440 ParamTypes[0] =
10441 makeQualifiedLValueReferenceType(Base: LeftBaseTy, Quals, S);
10442 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10443 });
10444 }
10445 }
10446 }
10447
10448 // C++ [over.operator]p23:
10449 //
10450 // There also exist candidate operator functions of the form
10451 //
10452 // bool operator!(bool);
10453 // bool operator&&(bool, bool);
10454 // bool operator||(bool, bool);
10455 void addExclaimOverload() {
10456 QualType ParamTy = S.Context.BoolTy;
10457 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet,
10458 /*IsAssignmentOperator=*/false,
10459 /*NumContextualBoolArguments=*/1);
10460 }
10461 void addAmpAmpOrPipePipeOverload() {
10462 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10463 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10464 /*IsAssignmentOperator=*/false,
10465 /*NumContextualBoolArguments=*/2);
10466 }
10467
10468 // C++ [over.built]p13:
10469 //
10470 // For every cv-qualified or cv-unqualified object type T there
10471 // exist candidate operator functions of the form
10472 //
10473 // T* operator+(T*, ptrdiff_t); [ABOVE]
10474 // T& operator[](T*, ptrdiff_t);
10475 // T* operator-(T*, ptrdiff_t); [ABOVE]
10476 // T* operator+(ptrdiff_t, T*); [ABOVE]
10477 // T& operator[](ptrdiff_t, T*);
10478 void addSubscriptOverloads() {
10479 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10480 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10481 QualType PointeeType = PtrTy->getPointeeType();
10482 if (!PointeeType->isObjectType())
10483 continue;
10484
10485 // T& operator[](T*, ptrdiff_t)
10486 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10487 }
10488
10489 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10490 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10491 QualType PointeeType = PtrTy->getPointeeType();
10492 if (!PointeeType->isObjectType())
10493 continue;
10494
10495 // T& operator[](ptrdiff_t, T*)
10496 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10497 }
10498 }
10499
10500 // C++ [over.built]p11:
10501 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10502 // C1 is the same type as C2 or is a derived class of C2, T is an object
10503 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10504 // there exist candidate operator functions of the form
10505 //
10506 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10507 //
10508 // where CV12 is the union of CV1 and CV2.
10509 void addArrowStarOverloads() {
10510 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10511 QualType C1Ty = PtrTy;
10512 QualType C1;
10513 QualifierCollector Q1;
10514 C1 = QualType(Q1.strip(type: C1Ty->getPointeeType()), 0);
10515 if (!isa<RecordType>(Val: C1))
10516 continue;
10517 // heuristic to reduce number of builtin candidates in the set.
10518 // Add volatile/restrict version only if there are conversions to a
10519 // volatile/restrict type.
10520 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10521 continue;
10522 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10523 continue;
10524 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10525 const MemberPointerType *mptr = cast<MemberPointerType>(Val&: MemPtrTy);
10526 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),
10527 *D2 = mptr->getMostRecentCXXRecordDecl();
10528 if (!declaresSameEntity(D1, D2) &&
10529 !S.IsDerivedFrom(Loc: CandidateSet.getLocation(), Derived: D1, Base: D2))
10530 break;
10531 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10532 // build CV12 T&
10533 QualType T = mptr->getPointeeType();
10534 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10535 T.isVolatileQualified())
10536 continue;
10537 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10538 T.isRestrictQualified())
10539 continue;
10540 T = Q1.apply(Context: S.Context, QT: T);
10541 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10542 }
10543 }
10544 }
10545
10546 // Note that we don't consider the first argument, since it has been
10547 // contextually converted to bool long ago. The candidates below are
10548 // therefore added as binary.
10549 //
10550 // C++ [over.built]p25:
10551 // For every type T, where T is a pointer, pointer-to-member, or scoped
10552 // enumeration type, there exist candidate operator functions of the form
10553 //
10554 // T operator?(bool, T, T);
10555 //
10556 void addConditionalOperatorOverloads() {
10557 /// Set of (canonical) types that we've already handled.
10558 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10559
10560 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10561 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10562 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
10563 continue;
10564
10565 QualType ParamTypes[2] = {PtrTy, PtrTy};
10566 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10567 }
10568
10569 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10570 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
10571 continue;
10572
10573 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10574 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10575 }
10576
10577 if (S.getLangOpts().CPlusPlus11) {
10578 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10579 if (!EnumTy->castAsCanonical<EnumType>()->getDecl()->isScoped())
10580 continue;
10581
10582 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: EnumTy)).second)
10583 continue;
10584
10585 QualType ParamTypes[2] = {EnumTy, EnumTy};
10586 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10587 }
10588 }
10589 }
10590 }
10591};
10592
10593} // end anonymous namespace
10594
10595void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
10596 SourceLocation OpLoc,
10597 ArrayRef<Expr *> Args,
10598 OverloadCandidateSet &CandidateSet) {
10599 // Find all of the types that the arguments can convert to, but only
10600 // if the operator we're looking at has built-in operator candidates
10601 // that make use of these types. Also record whether we encounter non-record
10602 // candidate types or either arithmetic or enumeral candidate types.
10603 QualifiersAndAtomic VisibleTypeConversionsQuals;
10604 VisibleTypeConversionsQuals.addConst();
10605 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10606 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, ArgExpr: Args[ArgIdx]);
10607 if (Args[ArgIdx]->getType()->isAtomicType())
10608 VisibleTypeConversionsQuals.addAtomic();
10609 }
10610
10611 bool HasNonRecordCandidateType = false;
10612 bool HasArithmeticOrEnumeralCandidateType = false;
10613 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
10614 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10615 CandidateTypes.emplace_back(Args&: *this);
10616 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Ty: Args[ArgIdx]->getType(),
10617 Loc: OpLoc,
10618 AllowUserConversions: true,
10619 AllowExplicitConversions: (Op == OO_Exclaim ||
10620 Op == OO_AmpAmp ||
10621 Op == OO_PipePipe),
10622 VisibleQuals: VisibleTypeConversionsQuals);
10623 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10624 CandidateTypes[ArgIdx].hasNonRecordTypes();
10625 HasArithmeticOrEnumeralCandidateType =
10626 HasArithmeticOrEnumeralCandidateType ||
10627 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10628 }
10629
10630 // Exit early when no non-record types have been added to the candidate set
10631 // for any of the arguments to the operator.
10632 //
10633 // We can't exit early for !, ||, or &&, since there we have always have
10634 // 'bool' overloads.
10635 if (!HasNonRecordCandidateType &&
10636 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10637 return;
10638
10639 // Setup an object to manage the common state for building overloads.
10640 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10641 VisibleTypeConversionsQuals,
10642 HasArithmeticOrEnumeralCandidateType,
10643 CandidateTypes, CandidateSet);
10644
10645 // Dispatch over the operation to add in only those overloads which apply.
10646 switch (Op) {
10647 case OO_None:
10648 case NUM_OVERLOADED_OPERATORS:
10649 llvm_unreachable("Expected an overloaded operator");
10650
10651 case OO_New:
10652 case OO_Delete:
10653 case OO_Array_New:
10654 case OO_Array_Delete:
10655 case OO_Call:
10656 llvm_unreachable(
10657 "Special operators don't use AddBuiltinOperatorCandidates");
10658
10659 case OO_Comma:
10660 case OO_Arrow:
10661 case OO_Coawait:
10662 // C++ [over.match.oper]p3:
10663 // -- For the operator ',', the unary operator '&', the
10664 // operator '->', or the operator 'co_await', the
10665 // built-in candidates set is empty.
10666 break;
10667
10668 case OO_Plus: // '+' is either unary or binary
10669 if (Args.size() == 1)
10670 OpBuilder.addUnaryPlusPointerOverloads();
10671 [[fallthrough]];
10672
10673 case OO_Minus: // '-' is either unary or binary
10674 if (Args.size() == 1) {
10675 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10676 } else {
10677 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10678 OpBuilder.addGenericBinaryArithmeticOverloads();
10679 OpBuilder.addMatrixBinaryArithmeticOverloads();
10680 }
10681 break;
10682
10683 case OO_Star: // '*' is either unary or binary
10684 if (Args.size() == 1)
10685 OpBuilder.addUnaryStarPointerOverloads();
10686 else {
10687 OpBuilder.addGenericBinaryArithmeticOverloads();
10688 OpBuilder.addMatrixBinaryArithmeticOverloads();
10689 }
10690 break;
10691
10692 case OO_Slash:
10693 OpBuilder.addGenericBinaryArithmeticOverloads();
10694 break;
10695
10696 case OO_PlusPlus:
10697 case OO_MinusMinus:
10698 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10699 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10700 break;
10701
10702 case OO_EqualEqual:
10703 case OO_ExclaimEqual:
10704 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10705 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10706 OpBuilder.addGenericBinaryArithmeticOverloads();
10707 break;
10708
10709 case OO_Less:
10710 case OO_Greater:
10711 case OO_LessEqual:
10712 case OO_GreaterEqual:
10713 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10714 OpBuilder.addGenericBinaryArithmeticOverloads();
10715 break;
10716
10717 case OO_Spaceship:
10718 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10719 OpBuilder.addThreeWayArithmeticOverloads();
10720 break;
10721
10722 case OO_Percent:
10723 case OO_Caret:
10724 case OO_Pipe:
10725 case OO_LessLess:
10726 case OO_GreaterGreater:
10727 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10728 break;
10729
10730 case OO_Amp: // '&' is either unary or binary
10731 if (Args.size() == 1)
10732 // C++ [over.match.oper]p3:
10733 // -- For the operator ',', the unary operator '&', or the
10734 // operator '->', the built-in candidates set is empty.
10735 break;
10736
10737 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10738 break;
10739
10740 case OO_Tilde:
10741 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10742 break;
10743
10744 case OO_Equal:
10745 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10746 [[fallthrough]];
10747
10748 case OO_PlusEqual:
10749 case OO_MinusEqual:
10750 OpBuilder.addAssignmentPointerOverloads(isEqualOp: Op == OO_Equal);
10751 [[fallthrough]];
10752
10753 case OO_StarEqual:
10754 case OO_SlashEqual:
10755 OpBuilder.addAssignmentArithmeticOverloads(isEqualOp: Op == OO_Equal);
10756 break;
10757
10758 case OO_PercentEqual:
10759 case OO_LessLessEqual:
10760 case OO_GreaterGreaterEqual:
10761 case OO_AmpEqual:
10762 case OO_CaretEqual:
10763 case OO_PipeEqual:
10764 OpBuilder.addAssignmentIntegralOverloads();
10765 break;
10766
10767 case OO_Exclaim:
10768 OpBuilder.addExclaimOverload();
10769 break;
10770
10771 case OO_AmpAmp:
10772 case OO_PipePipe:
10773 OpBuilder.addAmpAmpOrPipePipeOverload();
10774 break;
10775
10776 case OO_Subscript:
10777 if (Args.size() == 2)
10778 OpBuilder.addSubscriptOverloads();
10779 break;
10780
10781 case OO_ArrowStar:
10782 OpBuilder.addArrowStarOverloads();
10783 break;
10784
10785 case OO_Conditional:
10786 OpBuilder.addConditionalOperatorOverloads();
10787 OpBuilder.addGenericBinaryArithmeticOverloads();
10788 break;
10789 }
10790}
10791
10792void
10793Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
10794 SourceLocation Loc,
10795 ArrayRef<Expr *> Args,
10796 TemplateArgumentListInfo *ExplicitTemplateArgs,
10797 OverloadCandidateSet& CandidateSet,
10798 bool PartialOverloading) {
10799 ADLResult Fns;
10800
10801 // FIXME: This approach for uniquing ADL results (and removing
10802 // redundant candidates from the set) relies on pointer-equality,
10803 // which means we need to key off the canonical decl. However,
10804 // always going back to the canonical decl might not get us the
10805 // right set of default arguments. What default arguments are
10806 // we supposed to consider on ADL candidates, anyway?
10807
10808 // FIXME: Pass in the explicit template arguments?
10809 ArgumentDependentLookup(Name, Loc, Args, Functions&: Fns);
10810
10811 ArrayRef<Expr *> ReversedArgs;
10812
10813 // Erase all of the candidates we already knew about.
10814 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10815 CandEnd = CandidateSet.end();
10816 Cand != CandEnd; ++Cand)
10817 if (Cand->Function) {
10818 FunctionDecl *Fn = Cand->Function;
10819 Fns.erase(D: Fn);
10820 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10821 Fns.erase(D: FunTmpl);
10822 }
10823
10824 // For each of the ADL candidates we found, add it to the overload
10825 // set.
10826 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10827 DeclAccessPair FoundDecl = DeclAccessPair::make(D: *I, AS: AS_none);
10828
10829 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *I)) {
10830 if (ExplicitTemplateArgs)
10831 continue;
10832
10833 AddOverloadCandidate(
10834 Function: FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10835 PartialOverloading, /*AllowExplicit=*/true,
10836 /*AllowExplicitConversion=*/AllowExplicitConversions: false, IsADLCandidate: ADLCallKind::UsesADL);
10837 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD)) {
10838 AddOverloadCandidate(
10839 Function: FD, FoundDecl, Args: {Args[1], Args[0]}, CandidateSet,
10840 /*SuppressUserConversions=*/false, PartialOverloading,
10841 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/AllowExplicitConversions: false,
10842 IsADLCandidate: ADLCallKind::UsesADL, EarlyConversions: {}, PO: OverloadCandidateParamOrder::Reversed);
10843 }
10844 } else {
10845 auto *FTD = cast<FunctionTemplateDecl>(Val: *I);
10846 AddTemplateOverloadCandidate(
10847 FunctionTemplate: FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10848 /*SuppressUserConversions=*/false, PartialOverloading,
10849 /*AllowExplicit=*/true, IsADLCandidate: ADLCallKind::UsesADL);
10850 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10851 S&: *this, OriginalArgs: Args, FD: FTD->getTemplatedDecl())) {
10852
10853 // As template candidates are not deduced immediately,
10854 // persist the array in the overload set.
10855 if (ReversedArgs.empty())
10856 ReversedArgs = CandidateSet.getPersistentArgsArray(Exprs: Args[1], Exprs: Args[0]);
10857
10858 AddTemplateOverloadCandidate(
10859 FunctionTemplate: FTD, FoundDecl, ExplicitTemplateArgs, Args: ReversedArgs, CandidateSet,
10860 /*SuppressUserConversions=*/false, PartialOverloading,
10861 /*AllowExplicit=*/true, IsADLCandidate: ADLCallKind::UsesADL,
10862 PO: OverloadCandidateParamOrder::Reversed);
10863 }
10864 }
10865 }
10866}
10867
10868namespace {
10869enum class Comparison { Equal, Better, Worse };
10870}
10871
10872/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10873/// overload resolution.
10874///
10875/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10876/// Cand1's first N enable_if attributes have precisely the same conditions as
10877/// Cand2's first N enable_if attributes (where N = the number of enable_if
10878/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10879///
10880/// Note that you can have a pair of candidates such that Cand1's enable_if
10881/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10882/// worse than Cand1's.
10883static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10884 const FunctionDecl *Cand2) {
10885 // Common case: One (or both) decls don't have enable_if attrs.
10886 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10887 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10888 if (!Cand1Attr || !Cand2Attr) {
10889 if (Cand1Attr == Cand2Attr)
10890 return Comparison::Equal;
10891 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10892 }
10893
10894 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10895 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10896
10897 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10898 for (auto Pair : zip_longest(t&: Cand1Attrs, u&: Cand2Attrs)) {
10899 std::optional<EnableIfAttr *> Cand1A = std::get<0>(t&: Pair);
10900 std::optional<EnableIfAttr *> Cand2A = std::get<1>(t&: Pair);
10901
10902 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10903 // has fewer enable_if attributes than Cand2, and vice versa.
10904 if (!Cand1A)
10905 return Comparison::Worse;
10906 if (!Cand2A)
10907 return Comparison::Better;
10908
10909 Cand1ID.clear();
10910 Cand2ID.clear();
10911
10912 (*Cand1A)->getCond()->Profile(ID&: Cand1ID, Context: S.getASTContext(), Canonical: true);
10913 (*Cand2A)->getCond()->Profile(ID&: Cand2ID, Context: S.getASTContext(), Canonical: true);
10914 if (Cand1ID != Cand2ID)
10915 return Comparison::Worse;
10916 }
10917
10918 return Comparison::Equal;
10919}
10920
10921static Comparison
10922isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
10923 const OverloadCandidate &Cand2) {
10924 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10925 !Cand2.Function->isMultiVersion())
10926 return Comparison::Equal;
10927
10928 // If both are invalid, they are equal. If one of them is invalid, the other
10929 // is better.
10930 if (Cand1.Function->isInvalidDecl()) {
10931 if (Cand2.Function->isInvalidDecl())
10932 return Comparison::Equal;
10933 return Comparison::Worse;
10934 }
10935 if (Cand2.Function->isInvalidDecl())
10936 return Comparison::Better;
10937
10938 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10939 // cpu_dispatch, else arbitrarily based on the identifiers.
10940 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10941 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10942 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10943 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10944
10945 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10946 return Comparison::Equal;
10947
10948 if (Cand1CPUDisp && !Cand2CPUDisp)
10949 return Comparison::Better;
10950 if (Cand2CPUDisp && !Cand1CPUDisp)
10951 return Comparison::Worse;
10952
10953 if (Cand1CPUSpec && Cand2CPUSpec) {
10954 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10955 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10956 ? Comparison::Better
10957 : Comparison::Worse;
10958
10959 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10960 FirstDiff = std::mismatch(
10961 first1: Cand1CPUSpec->cpus_begin(), last1: Cand1CPUSpec->cpus_end(),
10962 first2: Cand2CPUSpec->cpus_begin(),
10963 binary_pred: [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10964 return LHS->getName() == RHS->getName();
10965 });
10966
10967 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10968 "Two different cpu-specific versions should not have the same "
10969 "identifier list, otherwise they'd be the same decl!");
10970 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10971 ? Comparison::Better
10972 : Comparison::Worse;
10973 }
10974 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10975}
10976
10977/// Compute the type of the implicit object parameter for the given function,
10978/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10979/// null QualType if there is a 'matches anything' implicit object parameter.
10980static std::optional<QualType>
10981getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F) {
10982 if (!isa<CXXMethodDecl>(Val: F) || isa<CXXConstructorDecl>(Val: F))
10983 return std::nullopt;
10984
10985 auto *M = cast<CXXMethodDecl>(Val: F);
10986 // Static member functions' object parameters match all types.
10987 if (M->isStatic())
10988 return QualType();
10989 return M->getFunctionObjectParameterReferenceType();
10990}
10991
10992// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10993// represent the same entity.
10994static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10995 const FunctionDecl *F2) {
10996 if (declaresSameEntity(D1: F1, D2: F2))
10997 return true;
10998 auto PT1 = F1->getPrimaryTemplate();
10999 auto PT2 = F2->getPrimaryTemplate();
11000 if (PT1 && PT2) {
11001 if (declaresSameEntity(D1: PT1, D2: PT2) ||
11002 declaresSameEntity(D1: PT1->getInstantiatedFromMemberTemplate(),
11003 D2: PT2->getInstantiatedFromMemberTemplate()))
11004 return true;
11005 }
11006 // TODO: It is not clear whether comparing parameters is necessary (i.e.
11007 // different functions with same params). Consider removing this (as no test
11008 // fail w/o it).
11009 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
11010 if (First) {
11011 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
11012 return *T;
11013 }
11014 assert(I < F->getNumParams());
11015 return F->getParamDecl(i: I++)->getType();
11016 };
11017
11018 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(Val: F1);
11019 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(Val: F2);
11020
11021 if (F1NumParams != F2NumParams)
11022 return false;
11023
11024 unsigned I1 = 0, I2 = 0;
11025 for (unsigned I = 0; I != F1NumParams; ++I) {
11026 QualType T1 = NextParam(F1, I1, I == 0);
11027 QualType T2 = NextParam(F2, I2, I == 0);
11028 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
11029 if (!Context.hasSameUnqualifiedType(T1, T2))
11030 return false;
11031 }
11032 return true;
11033}
11034
11035/// We're allowed to use constraints partial ordering only if the candidates
11036/// have the same parameter types:
11037/// [over.match.best.general]p2.6
11038/// F1 and F2 are non-template functions with the same
11039/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
11040static bool sameFunctionParameterTypeLists(Sema &S, FunctionDecl *Fn1,
11041 FunctionDecl *Fn2,
11042 bool IsFn1Reversed,
11043 bool IsFn2Reversed) {
11044 assert(Fn1 && Fn2);
11045 if (Fn1->isVariadic() != Fn2->isVariadic())
11046 return false;
11047
11048 if (!S.FunctionNonObjectParamTypesAreEqual(OldFunction: Fn1, NewFunction: Fn2, ArgPos: nullptr,
11049 Reversed: IsFn1Reversed ^ IsFn2Reversed))
11050 return false;
11051
11052 auto *Mem1 = dyn_cast<CXXMethodDecl>(Val: Fn1);
11053 auto *Mem2 = dyn_cast<CXXMethodDecl>(Val: Fn2);
11054 if (Mem1 && Mem2) {
11055 // if they are member functions, both are direct members of the same class,
11056 // and
11057 if (Mem1->getParent() != Mem2->getParent())
11058 return false;
11059 // if both are non-static member functions, they have the same types for
11060 // their object parameters
11061 if (Mem1->isInstance() && Mem2->isInstance() &&
11062 !S.getASTContext().hasSameType(
11063 T1: Mem1->getFunctionObjectParameterReferenceType(),
11064 T2: Mem2->getFunctionObjectParameterReferenceType()))
11065 return false;
11066 }
11067 return true;
11068}
11069
11070static FunctionDecl *
11071getMorePartialOrderingConstrained(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2,
11072 bool IsFn1Reversed, bool IsFn2Reversed) {
11073 if (!Fn1 || !Fn2)
11074 return nullptr;
11075
11076 // C++ [temp.constr.order]:
11077 // A non-template function F1 is more partial-ordering-constrained than a
11078 // non-template function F2 if:
11079 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
11080 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
11081
11082 if (Cand1IsSpecialization || Cand2IsSpecialization)
11083 return nullptr;
11084
11085 // - they have the same non-object-parameter-type-lists, and [...]
11086 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
11087 IsFn2Reversed))
11088 return nullptr;
11089
11090 // - the declaration of F1 is more constrained than the declaration of F2.
11091 return S.getMoreConstrainedFunction(FD1: Fn1, FD2: Fn2);
11092}
11093
11094/// isBetterOverloadCandidate - Determines whether the first overload
11095/// candidate is a better candidate than the second (C++ 13.3.3p1).
11096bool clang::isBetterOverloadCandidate(
11097 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
11098 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind,
11099 bool PartialOverloading) {
11100 // Define viable functions to be better candidates than non-viable
11101 // functions.
11102 if (!Cand2.Viable)
11103 return Cand1.Viable;
11104 else if (!Cand1.Viable)
11105 return false;
11106
11107 // [CUDA] A function with 'never' preference is marked not viable, therefore
11108 // is never shown up here. The worst preference shown up here is 'wrong side',
11109 // e.g. an H function called by a HD function in device compilation. This is
11110 // valid AST as long as the HD function is not emitted, e.g. it is an inline
11111 // function which is called only by an H function. A deferred diagnostic will
11112 // be triggered if it is emitted. However a wrong-sided function is still
11113 // a viable candidate here.
11114 //
11115 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
11116 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
11117 // can be emitted, Cand1 is not better than Cand2. This rule should have
11118 // precedence over other rules.
11119 //
11120 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
11121 // other rules should be used to determine which is better. This is because
11122 // host/device based overloading resolution is mostly for determining
11123 // viability of a function. If two functions are both viable, other factors
11124 // should take precedence in preference, e.g. the standard-defined preferences
11125 // like argument conversion ranks or enable_if partial-ordering. The
11126 // preference for pass-object-size parameters is probably most similar to a
11127 // type-based-overloading decision and so should take priority.
11128 //
11129 // If other rules cannot determine which is better, CUDA preference will be
11130 // used again to determine which is better.
11131 //
11132 // TODO: Currently IdentifyPreference does not return correct values
11133 // for functions called in global variable initializers due to missing
11134 // correct context about device/host. Therefore we can only enforce this
11135 // rule when there is a caller. We should enforce this rule for functions
11136 // in global variable initializers once proper context is added.
11137 //
11138 // TODO: We can only enable the hostness based overloading resolution when
11139 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
11140 // overloading resolution diagnostics.
11141 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
11142 S.getLangOpts().GPUExcludeWrongSideOverloads) {
11143 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
11144 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(D: Caller);
11145 bool IsCand1ImplicitHD =
11146 SemaCUDA::isImplicitHostDeviceFunction(D: Cand1.Function);
11147 bool IsCand2ImplicitHD =
11148 SemaCUDA::isImplicitHostDeviceFunction(D: Cand2.Function);
11149 auto P1 = S.CUDA().IdentifyPreference(Caller, Callee: Cand1.Function);
11150 auto P2 = S.CUDA().IdentifyPreference(Caller, Callee: Cand2.Function);
11151 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
11152 // The implicit HD function may be a function in a system header which
11153 // is forced by pragma. In device compilation, if we prefer HD candidates
11154 // over wrong-sided candidates, overloading resolution may change, which
11155 // may result in non-deferrable diagnostics. As a workaround, we let
11156 // implicit HD candidates take equal preference as wrong-sided candidates.
11157 // This will preserve the overloading resolution.
11158 // TODO: We still need special handling of implicit HD functions since
11159 // they may incur other diagnostics to be deferred. We should make all
11160 // host/device related diagnostics deferrable and remove special handling
11161 // of implicit HD functions.
11162 auto EmitThreshold =
11163 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
11164 (IsCand1ImplicitHD || IsCand2ImplicitHD))
11165 ? SemaCUDA::CFP_Never
11166 : SemaCUDA::CFP_WrongSide;
11167 auto Cand1Emittable = P1 > EmitThreshold;
11168 auto Cand2Emittable = P2 > EmitThreshold;
11169 if (Cand1Emittable && !Cand2Emittable)
11170 return true;
11171 if (!Cand1Emittable && Cand2Emittable)
11172 return false;
11173 }
11174 }
11175
11176 // C++ [over.match.best]p1: (Changed in C++23)
11177 //
11178 // -- if F is a static member function, ICS1(F) is defined such
11179 // that ICS1(F) is neither better nor worse than ICS1(G) for
11180 // any function G, and, symmetrically, ICS1(G) is neither
11181 // better nor worse than ICS1(F).
11182 unsigned StartArg = 0;
11183 if (!Cand1.TookAddressOfOverload &&
11184 (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument))
11185 StartArg = 1;
11186
11187 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
11188 // We don't allow incompatible pointer conversions in C++.
11189 if (!S.getLangOpts().CPlusPlus)
11190 return ICS.isStandard() &&
11191 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
11192
11193 // The only ill-formed conversion we allow in C++ is the string literal to
11194 // char* conversion, which is only considered ill-formed after C++11.
11195 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
11196 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
11197 };
11198
11199 // Define functions that don't require ill-formed conversions for a given
11200 // argument to be better candidates than functions that do.
11201 unsigned NumArgs = Cand1.Conversions.size();
11202 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
11203 bool HasBetterConversion = false;
11204 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11205 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
11206 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
11207 if (Cand1Bad != Cand2Bad) {
11208 if (Cand1Bad)
11209 return false;
11210 HasBetterConversion = true;
11211 }
11212 }
11213
11214 if (HasBetterConversion)
11215 return true;
11216
11217 // C++ [over.match.best]p1:
11218 // A viable function F1 is defined to be a better function than another
11219 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
11220 // conversion sequence than ICSi(F2), and then...
11221 bool HasWorseConversion = false;
11222 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11223 switch (CompareImplicitConversionSequences(S, Loc,
11224 ICS1: Cand1.Conversions[ArgIdx],
11225 ICS2: Cand2.Conversions[ArgIdx])) {
11226 case ImplicitConversionSequence::Better:
11227 // Cand1 has a better conversion sequence.
11228 HasBetterConversion = true;
11229 break;
11230
11231 case ImplicitConversionSequence::Worse:
11232 if (Cand1.Function && Cand2.Function &&
11233 Cand1.isReversed() != Cand2.isReversed() &&
11234 allowAmbiguity(Context&: S.Context, F1: Cand1.Function, F2: Cand2.Function)) {
11235 // Work around large-scale breakage caused by considering reversed
11236 // forms of operator== in C++20:
11237 //
11238 // When comparing a function against a reversed function, if we have a
11239 // better conversion for one argument and a worse conversion for the
11240 // other, the implicit conversion sequences are treated as being equally
11241 // good.
11242 //
11243 // This prevents a comparison function from being considered ambiguous
11244 // with a reversed form that is written in the same way.
11245 //
11246 // We diagnose this as an extension from CreateOverloadedBinOp.
11247 HasWorseConversion = true;
11248 break;
11249 }
11250
11251 // Cand1 can't be better than Cand2.
11252 return false;
11253
11254 case ImplicitConversionSequence::Indistinguishable:
11255 // Do nothing.
11256 break;
11257 }
11258 }
11259
11260 // -- for some argument j, ICSj(F1) is a better conversion sequence than
11261 // ICSj(F2), or, if not that,
11262 if (HasBetterConversion && !HasWorseConversion)
11263 return true;
11264
11265 // -- the context is an initialization by user-defined conversion
11266 // (see 8.5, 13.3.1.5) and the standard conversion sequence
11267 // from the return type of F1 to the destination type (i.e.,
11268 // the type of the entity being initialized) is a better
11269 // conversion sequence than the standard conversion sequence
11270 // from the return type of F2 to the destination type.
11271 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
11272 Cand1.Function && Cand2.Function &&
11273 isa<CXXConversionDecl>(Val: Cand1.Function) &&
11274 isa<CXXConversionDecl>(Val: Cand2.Function)) {
11275
11276 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
11277 // First check whether we prefer one of the conversion functions over the
11278 // other. This only distinguishes the results in non-standard, extension
11279 // cases such as the conversion from a lambda closure type to a function
11280 // pointer or block.
11281 ImplicitConversionSequence::CompareKind Result =
11282 compareConversionFunctions(S, Function1: Cand1.Function, Function2: Cand2.Function);
11283 if (Result == ImplicitConversionSequence::Indistinguishable)
11284 Result = CompareStandardConversionSequences(S, Loc,
11285 SCS1: Cand1.FinalConversion,
11286 SCS2: Cand2.FinalConversion);
11287
11288 if (Result != ImplicitConversionSequence::Indistinguishable)
11289 return Result == ImplicitConversionSequence::Better;
11290
11291 // FIXME: Compare kind of reference binding if conversion functions
11292 // convert to a reference type used in direct reference binding, per
11293 // C++14 [over.match.best]p1 section 2 bullet 3.
11294 }
11295
11296 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
11297 // as combined with the resolution to CWG issue 243.
11298 //
11299 // When the context is initialization by constructor ([over.match.ctor] or
11300 // either phase of [over.match.list]), a constructor is preferred over
11301 // a conversion function.
11302 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
11303 Cand1.Function && Cand2.Function &&
11304 isa<CXXConstructorDecl>(Val: Cand1.Function) !=
11305 isa<CXXConstructorDecl>(Val: Cand2.Function))
11306 return isa<CXXConstructorDecl>(Val: Cand1.Function);
11307
11308 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
11309 return Cand2.StrictPackMatch;
11310
11311 // -- F1 is a non-template function and F2 is a function template
11312 // specialization, or, if not that,
11313 bool Cand1IsSpecialization = Cand1.Function &&
11314 Cand1.Function->getPrimaryTemplate();
11315 bool Cand2IsSpecialization = Cand2.Function &&
11316 Cand2.Function->getPrimaryTemplate();
11317 if (Cand1IsSpecialization != Cand2IsSpecialization)
11318 return Cand2IsSpecialization;
11319
11320 // -- F1 and F2 are function template specializations, and the function
11321 // template for F1 is more specialized than the template for F2
11322 // according to the partial ordering rules described in 14.5.5.2, or,
11323 // if not that,
11324 if (Cand1IsSpecialization && Cand2IsSpecialization) {
11325 const auto *Obj1Context =
11326 dyn_cast<CXXRecordDecl>(Val: Cand1.FoundDecl->getDeclContext());
11327 const auto *Obj2Context =
11328 dyn_cast<CXXRecordDecl>(Val: Cand2.FoundDecl->getDeclContext());
11329 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
11330 FT1: Cand1.Function->getPrimaryTemplate(),
11331 FT2: Cand2.Function->getPrimaryTemplate(), Loc,
11332 TPOC: isa<CXXConversionDecl>(Val: Cand1.Function) ? TPOC_Conversion
11333 : TPOC_Call,
11334 NumCallArguments1: Cand1.ExplicitCallArguments,
11335 RawObj1Ty: Obj1Context ? S.Context.getCanonicalTagType(TD: Obj1Context)
11336 : QualType{},
11337 RawObj2Ty: Obj2Context ? S.Context.getCanonicalTagType(TD: Obj2Context)
11338 : QualType{},
11339 Reversed: Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
11340 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
11341 }
11342 }
11343
11344 // -— F1 and F2 are non-template functions and F1 is more
11345 // partial-ordering-constrained than F2 [...],
11346 if (FunctionDecl *F = getMorePartialOrderingConstrained(
11347 S, Fn1: Cand1.Function, Fn2: Cand2.Function, IsFn1Reversed: Cand1.isReversed(),
11348 IsFn2Reversed: Cand2.isReversed());
11349 F && F == Cand1.Function)
11350 return true;
11351
11352 // -- F1 is a constructor for a class D, F2 is a constructor for a base
11353 // class B of D, and for all arguments the corresponding parameters of
11354 // F1 and F2 have the same type.
11355 // FIXME: Implement the "all parameters have the same type" check.
11356 bool Cand1IsInherited =
11357 isa_and_nonnull<ConstructorUsingShadowDecl>(Val: Cand1.FoundDecl.getDecl());
11358 bool Cand2IsInherited =
11359 isa_and_nonnull<ConstructorUsingShadowDecl>(Val: Cand2.FoundDecl.getDecl());
11360 if (Cand1IsInherited != Cand2IsInherited)
11361 return Cand2IsInherited;
11362 else if (Cand1IsInherited) {
11363 assert(Cand2IsInherited);
11364 auto *Cand1Class = cast<CXXRecordDecl>(Val: Cand1.Function->getDeclContext());
11365 auto *Cand2Class = cast<CXXRecordDecl>(Val: Cand2.Function->getDeclContext());
11366 if (Cand1Class->isDerivedFrom(Base: Cand2Class))
11367 return true;
11368 if (Cand2Class->isDerivedFrom(Base: Cand1Class))
11369 return false;
11370 // Inherited from sibling base classes: still ambiguous.
11371 }
11372
11373 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
11374 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
11375 // with reversed order of parameters and F1 is not
11376 //
11377 // We rank reversed + different operator as worse than just reversed, but
11378 // that comparison can never happen, because we only consider reversing for
11379 // the maximally-rewritten operator (== or <=>).
11380 if (Cand1.RewriteKind != Cand2.RewriteKind)
11381 return Cand1.RewriteKind < Cand2.RewriteKind;
11382
11383 // Check C++17 tie-breakers for deduction guides.
11384 {
11385 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Val: Cand1.Function);
11386 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Val: Cand2.Function);
11387 if (Guide1 && Guide2) {
11388 // -- F1 is generated from a deduction-guide and F2 is not
11389 if (Guide1->isImplicit() != Guide2->isImplicit())
11390 return Guide2->isImplicit();
11391
11392 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11393 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11394 return true;
11395 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11396 return false;
11397
11398 // --F1 is generated from a non-template constructor and F2 is generated
11399 // from a constructor template
11400 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11401 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11402 if (Constructor1 && Constructor2) {
11403 bool isC1Templated = Constructor1->getTemplatedKind() !=
11404 FunctionDecl::TemplatedKind::TK_NonTemplate;
11405 bool isC2Templated = Constructor2->getTemplatedKind() !=
11406 FunctionDecl::TemplatedKind::TK_NonTemplate;
11407 if (isC1Templated != isC2Templated)
11408 return isC2Templated;
11409 }
11410 }
11411 }
11412
11413 // Check for enable_if value-based overload resolution.
11414 if (Cand1.Function && Cand2.Function) {
11415 Comparison Cmp = compareEnableIfAttrs(S, Cand1: Cand1.Function, Cand2: Cand2.Function);
11416 if (Cmp != Comparison::Equal)
11417 return Cmp == Comparison::Better;
11418 }
11419
11420 bool HasPS1 = Cand1.Function != nullptr &&
11421 functionHasPassObjectSizeParams(FD: Cand1.Function);
11422 bool HasPS2 = Cand2.Function != nullptr &&
11423 functionHasPassObjectSizeParams(FD: Cand2.Function);
11424 if (HasPS1 != HasPS2 && HasPS1)
11425 return true;
11426
11427 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11428 if (MV == Comparison::Better)
11429 return true;
11430 if (MV == Comparison::Worse)
11431 return false;
11432
11433 // If other rules cannot determine which is better, CUDA preference is used
11434 // to determine which is better.
11435 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11436 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11437 return S.CUDA().IdentifyPreference(Caller, Callee: Cand1.Function) >
11438 S.CUDA().IdentifyPreference(Caller, Callee: Cand2.Function);
11439 }
11440
11441 // General member function overloading is handled above, so this only handles
11442 // constructors with address spaces.
11443 // This only handles address spaces since C++ has no other
11444 // qualifier that can be used with constructors.
11445 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Val: Cand1.Function);
11446 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Val: Cand2.Function);
11447 if (CD1 && CD2) {
11448 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11449 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11450 if (AS1 != AS2) {
11451 if (Qualifiers::isAddressSpaceSupersetOf(A: AS2, B: AS1, Ctx: S.getASTContext()))
11452 return true;
11453 if (Qualifiers::isAddressSpaceSupersetOf(A: AS1, B: AS2, Ctx: S.getASTContext()))
11454 return false;
11455 }
11456 }
11457
11458 return false;
11459}
11460
11461/// Determine whether two declarations are "equivalent" for the purposes of
11462/// name lookup and overload resolution. This applies when the same internal/no
11463/// linkage entity is defined by two modules (probably by textually including
11464/// the same header). In such a case, we don't consider the declarations to
11465/// declare the same entity, but we also don't want lookups with both
11466/// declarations visible to be ambiguous in some cases (this happens when using
11467/// a modularized libstdc++).
11468bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
11469 const NamedDecl *B) {
11470 auto *VA = dyn_cast_or_null<ValueDecl>(Val: A);
11471 auto *VB = dyn_cast_or_null<ValueDecl>(Val: B);
11472 if (!VA || !VB)
11473 return false;
11474
11475 // The declarations must be declaring the same name as an internal linkage
11476 // entity in different modules.
11477 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11478 DC: VB->getDeclContext()->getRedeclContext()) ||
11479 getOwningModule(Entity: VA) == getOwningModule(Entity: VB) ||
11480 VA->isExternallyVisible() || VB->isExternallyVisible())
11481 return false;
11482
11483 // Check that the declarations appear to be equivalent.
11484 //
11485 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11486 // For constants and functions, we should check the initializer or body is
11487 // the same. For non-constant variables, we shouldn't allow it at all.
11488 if (Context.hasSameType(T1: VA->getType(), T2: VB->getType()))
11489 return true;
11490
11491 // Enum constants within unnamed enumerations will have different types, but
11492 // may still be similar enough to be interchangeable for our purposes.
11493 if (auto *EA = dyn_cast<EnumConstantDecl>(Val: VA)) {
11494 if (auto *EB = dyn_cast<EnumConstantDecl>(Val: VB)) {
11495 // Only handle anonymous enums. If the enumerations were named and
11496 // equivalent, they would have been merged to the same type.
11497 auto *EnumA = cast<EnumDecl>(Val: EA->getDeclContext());
11498 auto *EnumB = cast<EnumDecl>(Val: EB->getDeclContext());
11499 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11500 !Context.hasSameType(T1: EnumA->getIntegerType(),
11501 T2: EnumB->getIntegerType()))
11502 return false;
11503 // Allow this only if the value is the same for both enumerators.
11504 return llvm::APSInt::isSameValue(I1: EA->getInitVal(), I2: EB->getInitVal());
11505 }
11506 }
11507
11508 // Nothing else is sufficiently similar.
11509 return false;
11510}
11511
11512void Sema::diagnoseEquivalentInternalLinkageDeclarations(
11513 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
11514 assert(D && "Unknown declaration");
11515 Diag(Loc, DiagID: diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11516
11517 Module *M = getOwningModule(Entity: D);
11518 Diag(Loc: D->getLocation(), DiagID: diag::note_equivalent_internal_linkage_decl)
11519 << !M << (M ? M->getFullModuleName() : "");
11520
11521 for (auto *E : Equiv) {
11522 Module *M = getOwningModule(Entity: E);
11523 Diag(Loc: E->getLocation(), DiagID: diag::note_equivalent_internal_linkage_decl)
11524 << !M << (M ? M->getFullModuleName() : "");
11525 }
11526}
11527
11528bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const {
11529 return FailureKind == ovl_fail_bad_deduction &&
11530 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11531 TemplateDeductionResult::ConstraintsNotSatisfied &&
11532 static_cast<CNSInfo *>(DeductionFailure.Data)
11533 ->Satisfaction.ContainsErrors;
11534}
11535
11536void OverloadCandidateSet::AddDeferredTemplateCandidate(
11537 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
11538 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11539 bool PartialOverloading, bool AllowExplicit,
11540 CallExpr::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO,
11541 bool AggregateCandidateDeduction) {
11542
11543 auto *C =
11544 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11545
11546 C = new (C) DeferredFunctionTemplateOverloadCandidate{
11547 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Function,
11548 /*AllowObjCConversionOnExplicit=*/false,
11549 /*AllowResultConversion=*/false, .AllowExplicit: AllowExplicit, .SuppressUserConversions: SuppressUserConversions,
11550 .PartialOverloading: PartialOverloading, .AggregateCandidateDeduction: AggregateCandidateDeduction},
11551 .FunctionTemplate: FunctionTemplate,
11552 .FoundDecl: FoundDecl,
11553 .Args: Args,
11554 .IsADLCandidate: IsADLCandidate,
11555 .PO: PO};
11556
11557 HasDeferredTemplateConstructors |=
11558 isa<CXXConstructorDecl>(Val: FunctionTemplate->getTemplatedDecl());
11559}
11560
11561void OverloadCandidateSet::AddDeferredMethodTemplateCandidate(
11562 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11563 CXXRecordDecl *ActingContext, QualType ObjectType,
11564 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11565 bool SuppressUserConversions, bool PartialOverloading,
11566 OverloadCandidateParamOrder PO) {
11567
11568 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11569
11570 auto *C =
11571 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11572
11573 C = new (C) DeferredMethodTemplateOverloadCandidate{
11574 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Method,
11575 /*AllowObjCConversionOnExplicit=*/false,
11576 /*AllowResultConversion=*/false,
11577 /*AllowExplicit=*/false, .SuppressUserConversions: SuppressUserConversions, .PartialOverloading: PartialOverloading,
11578 /*AggregateCandidateDeduction=*/false},
11579 .FunctionTemplate: MethodTmpl,
11580 .FoundDecl: FoundDecl,
11581 .Args: Args,
11582 .ActingContext: ActingContext,
11583 .ObjectClassification: ObjectClassification,
11584 .ObjectType: ObjectType,
11585 .PO: PO};
11586}
11587
11588void OverloadCandidateSet::AddDeferredConversionTemplateCandidate(
11589 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
11590 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11591 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11592 bool AllowResultConversion) {
11593
11594 auto *C =
11595 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11596
11597 C = new (C) DeferredConversionTemplateOverloadCandidate{
11598 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Conversion,
11599 .AllowObjCConversionOnExplicit: AllowObjCConversionOnExplicit, .AllowResultConversion: AllowResultConversion,
11600 /*AllowExplicit=*/false,
11601 /*SuppressUserConversions=*/false,
11602 /*PartialOverloading*/ false,
11603 /*AggregateCandidateDeduction=*/false},
11604 .FunctionTemplate: FunctionTemplate,
11605 .FoundDecl: FoundDecl,
11606 .ActingContext: ActingContext,
11607 .From: From,
11608 .ToType: ToType};
11609}
11610
11611static void
11612AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11613 DeferredMethodTemplateOverloadCandidate &C) {
11614
11615 AddMethodTemplateCandidateImmediately(
11616 S, CandidateSet, MethodTmpl: C.FunctionTemplate, FoundDecl: C.FoundDecl, ActingContext: C.ActingContext,
11617 /*ExplicitTemplateArgs=*/nullptr, ObjectType: C.ObjectType, ObjectClassification: C.ObjectClassification,
11618 Args: C.Args, SuppressUserConversions: C.SuppressUserConversions, PartialOverloading: C.PartialOverloading, PO: C.PO);
11619}
11620
11621static void
11622AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11623 DeferredFunctionTemplateOverloadCandidate &C) {
11624 AddTemplateOverloadCandidateImmediately(
11625 S, CandidateSet, FunctionTemplate: C.FunctionTemplate, FoundDecl: C.FoundDecl,
11626 /*ExplicitTemplateArgs=*/nullptr, Args: C.Args, SuppressUserConversions: C.SuppressUserConversions,
11627 PartialOverloading: C.PartialOverloading, AllowExplicit: C.AllowExplicit, IsADLCandidate: C.IsADLCandidate, PO: C.PO,
11628 AggregateCandidateDeduction: C.AggregateCandidateDeduction);
11629}
11630
11631static void
11632AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11633 DeferredConversionTemplateOverloadCandidate &C) {
11634 return AddTemplateConversionCandidateImmediately(
11635 S, CandidateSet, FunctionTemplate: C.FunctionTemplate, FoundDecl: C.FoundDecl, ActingContext: C.ActingContext, From: C.From,
11636 ToType: C.ToType, AllowObjCConversionOnExplicit: C.AllowObjCConversionOnExplicit, AllowExplicit: C.AllowExplicit,
11637 AllowResultConversion: C.AllowResultConversion);
11638}
11639
11640void OverloadCandidateSet::InjectNonDeducedTemplateCandidates(Sema &S) {
11641 Candidates.reserve(N: Candidates.size() + DeferredCandidatesCount);
11642 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11643 while (Cand) {
11644 switch (Cand->Kind) {
11645 case DeferredTemplateOverloadCandidate::Function:
11646 AddTemplateOverloadCandidate(
11647 S, CandidateSet&: *this,
11648 C&: *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11649 break;
11650 case DeferredTemplateOverloadCandidate::Method:
11651 AddTemplateOverloadCandidate(
11652 S, CandidateSet&: *this,
11653 C&: *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11654 break;
11655 case DeferredTemplateOverloadCandidate::Conversion:
11656 AddTemplateOverloadCandidate(
11657 S, CandidateSet&: *this,
11658 C&: *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11659 break;
11660 }
11661 Cand = Cand->Next;
11662 }
11663 FirstDeferredCandidate = nullptr;
11664 DeferredCandidatesCount = 0;
11665}
11666
11667OverloadingResult
11668OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11669 Best->Best = true;
11670 if (Best->Function && Best->Function->isDeleted())
11671 return OR_Deleted;
11672 return OR_Success;
11673}
11674
11675void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11676 Sema &S, SmallVectorImpl<OverloadCandidate *> &Candidates) {
11677 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11678 // are accepted by both clang and NVCC. However, during a particular
11679 // compilation mode only one call variant is viable. We need to
11680 // exclude non-viable overload candidates from consideration based
11681 // only on their host/device attributes. Specifically, if one
11682 // candidate call is WrongSide and the other is SameSide, we ignore
11683 // the WrongSide candidate.
11684 // We only need to remove wrong-sided candidates here if
11685 // -fgpu-exclude-wrong-side-overloads is off. When
11686 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11687 // uniformly in isBetterOverloadCandidate.
11688 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11689 return;
11690 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11691
11692 bool ContainsSameSideCandidate =
11693 llvm::any_of(Range&: Candidates, P: [&](const OverloadCandidate *Cand) {
11694 // Check viable function only.
11695 return Cand->Viable && Cand->Function &&
11696 S.CUDA().IdentifyPreference(Caller, Callee: Cand->Function) ==
11697 SemaCUDA::CFP_SameSide;
11698 });
11699
11700 if (!ContainsSameSideCandidate)
11701 return;
11702
11703 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11704 // Check viable function only to avoid unnecessary data copying/moving.
11705 return Cand->Viable && Cand->Function &&
11706 S.CUDA().IdentifyPreference(Caller, Callee: Cand->Function) ==
11707 SemaCUDA::CFP_WrongSide;
11708 };
11709 llvm::erase_if(C&: Candidates, P: IsWrongSideCandidate);
11710}
11711
11712/// Computes the best viable function (C++ 13.3.3)
11713/// within an overload candidate set.
11714///
11715/// \param Loc The location of the function name (or operator symbol) for
11716/// which overload resolution occurs.
11717///
11718/// \param Best If overload resolution was successful or found a deleted
11719/// function, \p Best points to the candidate function found.
11720///
11721/// \returns The result of overload resolution.
11722OverloadingResult OverloadCandidateSet::BestViableFunction(Sema &S,
11723 SourceLocation Loc,
11724 iterator &Best) {
11725
11726 assert((shouldDeferTemplateArgumentDeduction(S) ||
11727 DeferredCandidatesCount == 0) &&
11728 "Unexpected deferred template candidates");
11729
11730 bool TwoPhaseResolution =
11731 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11732
11733 if (TwoPhaseResolution) {
11734 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11735 if (Best != end() && Best->isPerfectMatch(Ctx: S.Context)) {
11736 if (!(HasDeferredTemplateConstructors &&
11737 isa_and_nonnull<CXXConversionDecl>(Val: Best->Function)))
11738 return Res;
11739 }
11740 }
11741
11742 InjectNonDeducedTemplateCandidates(S);
11743 return BestViableFunctionImpl(S, Loc, Best);
11744}
11745
11746OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11747 Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best) {
11748
11749 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
11750 Candidates.reserve(N: this->Candidates.size());
11751 std::transform(first: this->Candidates.begin(), last: this->Candidates.end(),
11752 result: std::back_inserter(x&: Candidates),
11753 unary_op: [](OverloadCandidate &Cand) { return &Cand; });
11754
11755 if (S.getLangOpts().CUDA)
11756 CudaExcludeWrongSideCandidates(S, Candidates);
11757
11758 Best = end();
11759 for (auto *Cand : Candidates) {
11760 Cand->Best = false;
11761 if (Cand->Viable) {
11762 if (Best == end() ||
11763 isBetterOverloadCandidate(S, Cand1: *Cand, Cand2: *Best, Loc, Kind))
11764 Best = Cand;
11765 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11766 // This candidate has constraint that we were unable to evaluate because
11767 // it referenced an expression that contained an error. Rather than fall
11768 // back onto a potentially unintended candidate (made worse by
11769 // subsuming constraints), treat this as 'no viable candidate'.
11770 Best = end();
11771 return OR_No_Viable_Function;
11772 }
11773 }
11774
11775 // If we didn't find any viable functions, abort.
11776 if (Best == end())
11777 return OR_No_Viable_Function;
11778
11779 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11780 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11781 PendingBest.push_back(Elt: &*Best);
11782 Best->Best = true;
11783
11784 // Make sure that this function is better than every other viable
11785 // function. If not, we have an ambiguity.
11786 while (!PendingBest.empty()) {
11787 auto *Curr = PendingBest.pop_back_val();
11788 for (auto *Cand : Candidates) {
11789 if (Cand->Viable && !Cand->Best &&
11790 !isBetterOverloadCandidate(S, Cand1: *Curr, Cand2: *Cand, Loc, Kind)) {
11791 PendingBest.push_back(Elt: Cand);
11792 Cand->Best = true;
11793
11794 if (S.isEquivalentInternalLinkageDeclaration(A: Cand->Function,
11795 B: Curr->Function))
11796 EquivalentCands.push_back(Elt: Cand->Function);
11797 else
11798 Best = end();
11799 }
11800 }
11801 }
11802
11803 if (Best == end())
11804 return OR_Ambiguous;
11805
11806 OverloadingResult R = ResultForBestCandidate(Best);
11807
11808 if (!EquivalentCands.empty())
11809 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, D: Best->Function,
11810 Equiv: EquivalentCands);
11811 return R;
11812}
11813
11814namespace {
11815
11816enum OverloadCandidateKind {
11817 oc_function,
11818 oc_method,
11819 oc_reversed_binary_operator,
11820 oc_constructor,
11821 oc_implicit_default_constructor,
11822 oc_implicit_copy_constructor,
11823 oc_implicit_move_constructor,
11824 oc_implicit_copy_assignment,
11825 oc_implicit_move_assignment,
11826 oc_implicit_equality_comparison,
11827 oc_inherited_constructor
11828};
11829
11830enum OverloadCandidateSelect {
11831 ocs_non_template,
11832 ocs_template,
11833 ocs_described_template,
11834};
11835
11836static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11837ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11838 const FunctionDecl *Fn,
11839 OverloadCandidateRewriteKind CRK,
11840 std::string &Description) {
11841
11842 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11843 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11844 isTemplate = true;
11845 Description = S.getTemplateArgumentBindingsText(
11846 Params: FunTmpl->getTemplateParameters(), Args: *Fn->getTemplateSpecializationArgs());
11847 }
11848
11849 OverloadCandidateSelect Select = [&]() {
11850 if (!Description.empty())
11851 return ocs_described_template;
11852 return isTemplate ? ocs_template : ocs_non_template;
11853 }();
11854
11855 OverloadCandidateKind Kind = [&]() {
11856 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11857 return oc_implicit_equality_comparison;
11858
11859 if (CRK & CRK_Reversed)
11860 return oc_reversed_binary_operator;
11861
11862 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: Fn)) {
11863 if (!Ctor->isImplicit()) {
11864 if (isa<ConstructorUsingShadowDecl>(Val: Found))
11865 return oc_inherited_constructor;
11866 else
11867 return oc_constructor;
11868 }
11869
11870 if (Ctor->isDefaultConstructor())
11871 return oc_implicit_default_constructor;
11872
11873 if (Ctor->isMoveConstructor())
11874 return oc_implicit_move_constructor;
11875
11876 assert(Ctor->isCopyConstructor() &&
11877 "unexpected sort of implicit constructor");
11878 return oc_implicit_copy_constructor;
11879 }
11880
11881 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Val: Fn)) {
11882 // This actually gets spelled 'candidate function' for now, but
11883 // it doesn't hurt to split it out.
11884 if (!Meth->isImplicit())
11885 return oc_method;
11886
11887 if (Meth->isMoveAssignmentOperator())
11888 return oc_implicit_move_assignment;
11889
11890 if (Meth->isCopyAssignmentOperator())
11891 return oc_implicit_copy_assignment;
11892
11893 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11894 return oc_method;
11895 }
11896
11897 return oc_function;
11898 }();
11899
11900 return std::make_pair(x&: Kind, y&: Select);
11901}
11902
11903void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11904 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11905 // set.
11906 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl))
11907 S.Diag(Loc: FoundDecl->getLocation(),
11908 DiagID: diag::note_ovl_candidate_inherited_constructor)
11909 << Shadow->getNominatedBaseClass();
11910}
11911
11912} // end anonymous namespace
11913
11914static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
11915 const FunctionDecl *FD) {
11916 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11917 bool AlwaysTrue;
11918 if (EnableIf->getCond()->isValueDependent() ||
11919 !EnableIf->getCond()->EvaluateAsBooleanCondition(Result&: AlwaysTrue, Ctx))
11920 return false;
11921 if (!AlwaysTrue)
11922 return false;
11923 }
11924 return true;
11925}
11926
11927/// Returns true if we can take the address of the function.
11928///
11929/// \param Complain - If true, we'll emit a diagnostic
11930/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11931/// we in overload resolution?
11932/// \param Loc - The location of the statement we're complaining about. Ignored
11933/// if we're not complaining, or if we're in overload resolution.
11934static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
11935 bool Complain,
11936 bool InOverloadResolution,
11937 SourceLocation Loc) {
11938 if (!isFunctionAlwaysEnabled(Ctx: S.Context, FD)) {
11939 if (Complain) {
11940 if (InOverloadResolution)
11941 S.Diag(Loc: FD->getBeginLoc(),
11942 DiagID: diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11943 else
11944 S.Diag(Loc, DiagID: diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11945 }
11946 return false;
11947 }
11948
11949 if (FD->getTrailingRequiresClause()) {
11950 ConstraintSatisfaction Satisfaction;
11951 if (S.CheckFunctionConstraints(FD, Satisfaction, UsageLoc: Loc))
11952 return false;
11953 if (!Satisfaction.IsSatisfied) {
11954 if (Complain) {
11955 if (InOverloadResolution) {
11956 SmallString<128> TemplateArgString;
11957 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11958 TemplateArgString += " ";
11959 TemplateArgString += S.getTemplateArgumentBindingsText(
11960 Params: FunTmpl->getTemplateParameters(),
11961 Args: *FD->getTemplateSpecializationArgs());
11962 }
11963
11964 S.Diag(Loc: FD->getBeginLoc(),
11965 DiagID: diag::note_ovl_candidate_unsatisfied_constraints)
11966 << TemplateArgString;
11967 } else
11968 S.Diag(Loc, DiagID: diag::err_addrof_function_constraints_not_satisfied)
11969 << FD;
11970 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11971 }
11972 return false;
11973 }
11974 }
11975
11976 auto I = llvm::find_if(Range: FD->parameters(), P: [](const ParmVarDecl *P) {
11977 return P->hasAttr<PassObjectSizeAttr>();
11978 });
11979 if (I == FD->param_end())
11980 return true;
11981
11982 if (Complain) {
11983 // Add one to ParamNo because it's user-facing
11984 unsigned ParamNo = std::distance(first: FD->param_begin(), last: I) + 1;
11985 if (InOverloadResolution)
11986 S.Diag(Loc: FD->getLocation(),
11987 DiagID: diag::note_ovl_candidate_has_pass_object_size_params)
11988 << ParamNo;
11989 else
11990 S.Diag(Loc, DiagID: diag::err_address_of_function_with_pass_object_size_params)
11991 << FD << ParamNo;
11992 }
11993 return false;
11994}
11995
11996static bool checkAddressOfCandidateIsAvailable(Sema &S,
11997 const FunctionDecl *FD) {
11998 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11999 /*InOverloadResolution=*/true,
12000 /*Loc=*/SourceLocation());
12001}
12002
12003bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
12004 bool Complain,
12005 SourceLocation Loc) {
12006 return ::checkAddressOfFunctionIsAvailable(S&: *this, FD: Function, Complain,
12007 /*InOverloadResolution=*/false,
12008 Loc);
12009}
12010
12011// Don't print candidates other than the one that matches the calling
12012// convention of the call operator, since that is guaranteed to exist.
12013static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn) {
12014 const auto *ConvD = dyn_cast<CXXConversionDecl>(Val: Fn);
12015
12016 if (!ConvD)
12017 return false;
12018 const auto *RD = cast<CXXRecordDecl>(Val: Fn->getParent());
12019 if (!RD->isLambda())
12020 return false;
12021
12022 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
12023 CallingConv CallOpCC =
12024 CallOp->getType()->castAs<FunctionType>()->getCallConv();
12025 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
12026 CallingConv ConvToCC =
12027 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
12028
12029 return ConvToCC != CallOpCC;
12030}
12031
12032// Notes the location of an overload candidate.
12033void Sema::NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn,
12034 OverloadCandidateRewriteKind RewriteKind,
12035 QualType DestType, bool TakingAddress) {
12036 if (TakingAddress && !checkAddressOfCandidateIsAvailable(S&: *this, FD: Fn))
12037 return;
12038 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
12039 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
12040 return;
12041 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
12042 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
12043 return;
12044 if (shouldSkipNotingLambdaConversionDecl(Fn))
12045 return;
12046
12047 std::string FnDesc;
12048 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
12049 ClassifyOverloadCandidate(S&: *this, Found, Fn, CRK: RewriteKind, Description&: FnDesc);
12050 PartialDiagnostic PD = PDiag(DiagID: diag::note_ovl_candidate)
12051 << (unsigned)KSPair.first << (unsigned)KSPair.second
12052 << Fn << FnDesc;
12053
12054 HandleFunctionTypeMismatch(PDiag&: PD, FromType: Fn->getType(), ToType: DestType);
12055 Diag(Loc: Fn->getLocation(), PD);
12056 MaybeEmitInheritedConstructorNote(S&: *this, FoundDecl: Found);
12057}
12058
12059static void
12060MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
12061 // Perhaps the ambiguity was caused by two atomic constraints that are
12062 // 'identical' but not equivalent:
12063 //
12064 // void foo() requires (sizeof(T) > 4) { } // #1
12065 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
12066 //
12067 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
12068 // #2 to subsume #1, but these constraint are not considered equivalent
12069 // according to the subsumption rules because they are not the same
12070 // source-level construct. This behavior is quite confusing and we should try
12071 // to help the user figure out what happened.
12072
12073 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
12074 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
12075 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
12076 if (!I->Function)
12077 continue;
12078 SmallVector<AssociatedConstraint, 3> AC;
12079 if (auto *Template = I->Function->getPrimaryTemplate())
12080 Template->getAssociatedConstraints(AC);
12081 else
12082 I->Function->getAssociatedConstraints(ACs&: AC);
12083 if (AC.empty())
12084 continue;
12085 if (FirstCand == nullptr) {
12086 FirstCand = I->Function;
12087 FirstAC = AC;
12088 } else if (SecondCand == nullptr) {
12089 SecondCand = I->Function;
12090 SecondAC = AC;
12091 } else {
12092 // We have more than one pair of constrained functions - this check is
12093 // expensive and we'd rather not try to diagnose it.
12094 return;
12095 }
12096 }
12097 if (!SecondCand)
12098 return;
12099 // The diagnostic can only happen if there are associated constraints on
12100 // both sides (there needs to be some identical atomic constraint).
12101 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: FirstCand, AC1: FirstAC,
12102 D2: SecondCand, AC2: SecondAC))
12103 // Just show the user one diagnostic, they'll probably figure it out
12104 // from here.
12105 return;
12106}
12107
12108// Notes the location of all overload candidates designated through
12109// OverloadedExpr
12110void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
12111 bool TakingAddress) {
12112 assert(OverloadedExpr->getType() == Context.OverloadTy);
12113
12114 OverloadExpr::FindResult Ovl = OverloadExpr::find(E: OverloadedExpr);
12115 OverloadExpr *OvlExpr = Ovl.Expression;
12116
12117 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12118 IEnd = OvlExpr->decls_end();
12119 I != IEnd; ++I) {
12120 if (FunctionTemplateDecl *FunTmpl =
12121 dyn_cast<FunctionTemplateDecl>(Val: (*I)->getUnderlyingDecl()) ) {
12122 NoteOverloadCandidate(Found: *I, Fn: FunTmpl->getTemplatedDecl(), RewriteKind: CRK_None, DestType,
12123 TakingAddress);
12124 } else if (FunctionDecl *Fun
12125 = dyn_cast<FunctionDecl>(Val: (*I)->getUnderlyingDecl()) ) {
12126 NoteOverloadCandidate(Found: *I, Fn: Fun, RewriteKind: CRK_None, DestType, TakingAddress);
12127 }
12128 }
12129}
12130
12131/// Diagnoses an ambiguous conversion. The partial diagnostic is the
12132/// "lead" diagnostic; it will be given two arguments, the source and
12133/// target types of the conversion.
12134void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
12135 Sema &S,
12136 SourceLocation CaretLoc,
12137 const PartialDiagnostic &PDiag) const {
12138 S.Diag(Loc: CaretLoc, PD: PDiag)
12139 << Ambiguous.getFromType() << Ambiguous.getToType();
12140 unsigned CandsShown = 0;
12141 AmbiguousConversionSequence::const_iterator I, E;
12142 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
12143 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
12144 break;
12145 ++CandsShown;
12146 S.NoteOverloadCandidate(Found: I->first, Fn: I->second);
12147 }
12148 S.Diags.overloadCandidatesShown(N: CandsShown);
12149 if (I != E)
12150 S.Diag(Loc: SourceLocation(), DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
12151}
12152
12153static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
12154 unsigned I, bool TakingCandidateAddress) {
12155 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
12156 assert(Conv.isBad());
12157 assert(Cand->Function && "for now, candidate must be a function");
12158 FunctionDecl *Fn = Cand->Function;
12159
12160 // There's a conversion slot for the object argument if this is a
12161 // non-constructor method. Note that 'I' corresponds the
12162 // conversion-slot index.
12163 bool isObjectArgument = false;
12164 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Val: Fn) &&
12165 !isa<CXXConstructorDecl>(Val: Fn)) {
12166 if (I == 0)
12167 isObjectArgument = true;
12168 else if (!cast<CXXMethodDecl>(Val: Fn)->isExplicitObjectMemberFunction())
12169 I--;
12170 }
12171
12172 std::string FnDesc;
12173 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12174 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn, CRK: Cand->getRewriteKind(),
12175 Description&: FnDesc);
12176
12177 Expr *FromExpr = Conv.Bad.FromExpr;
12178 QualType FromTy = Conv.Bad.getFromType();
12179 QualType ToTy = Conv.Bad.getToType();
12180 SourceRange ToParamRange;
12181
12182 // FIXME: In presence of parameter packs we can't determine parameter range
12183 // reliably, as we don't have access to instantiation.
12184 bool HasParamPack =
12185 llvm::any_of(Range: Fn->parameters().take_front(N: I), P: [](const ParmVarDecl *Parm) {
12186 return Parm->isParameterPack();
12187 });
12188 if (!isObjectArgument && !HasParamPack && I < Fn->getNumParams())
12189 ToParamRange = Fn->getParamDecl(i: I)->getSourceRange();
12190
12191 if (FromTy == S.Context.OverloadTy) {
12192 assert(FromExpr && "overload set argument came from implicit argument?");
12193 Expr *E = FromExpr->IgnoreParens();
12194 if (isa<UnaryOperator>(Val: E))
12195 E = cast<UnaryOperator>(Val: E)->getSubExpr()->IgnoreParens();
12196 DeclarationName Name = cast<OverloadExpr>(Val: E)->getName();
12197
12198 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_overload)
12199 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12200 << ToParamRange << ToTy << Name << I + 1;
12201 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12202 return;
12203 }
12204
12205 // Do some hand-waving analysis to see if the non-viability is due
12206 // to a qualifier mismatch.
12207 CanQualType CFromTy = S.Context.getCanonicalType(T: FromTy);
12208 CanQualType CToTy = S.Context.getCanonicalType(T: ToTy);
12209 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
12210 CToTy = RT->getPointeeType();
12211 else {
12212 // TODO: detect and diagnose the full richness of const mismatches.
12213 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
12214 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
12215 CFromTy = FromPT->getPointeeType();
12216 CToTy = ToPT->getPointeeType();
12217 }
12218 }
12219
12220 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
12221 !CToTy.isAtLeastAsQualifiedAs(Other: CFromTy, Ctx: S.getASTContext())) {
12222 Qualifiers FromQs = CFromTy.getQualifiers();
12223 Qualifiers ToQs = CToTy.getQualifiers();
12224
12225 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
12226 if (isObjectArgument)
12227 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_addrspace_this)
12228 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12229 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
12230 else
12231 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_addrspace)
12232 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12233 << FnDesc << ToParamRange << FromQs.getAddressSpace()
12234 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
12235 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12236 return;
12237 }
12238
12239 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12240 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_ownership)
12241 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12242 << ToParamRange << FromTy << FromQs.getObjCLifetime()
12243 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
12244 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12245 return;
12246 }
12247
12248 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
12249 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_gc)
12250 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12251 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
12252 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
12253 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12254 return;
12255 }
12256
12257 if (!FromQs.getPointerAuth().isEquivalent(Other: ToQs.getPointerAuth())) {
12258 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_ptrauth)
12259 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12260 << FromTy << !!FromQs.getPointerAuth()
12261 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
12262 << ToQs.getPointerAuth().getAsString() << I + 1
12263 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
12264 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12265 return;
12266 }
12267
12268 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
12269 assert(CVR && "expected qualifiers mismatch");
12270
12271 if (isObjectArgument) {
12272 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_cvr_this)
12273 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12274 << FromTy << (CVR - 1);
12275 } else {
12276 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_cvr)
12277 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12278 << ToParamRange << FromTy << (CVR - 1) << I + 1;
12279 }
12280 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12281 return;
12282 }
12283
12284 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
12285 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
12286 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_value_category)
12287 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12288 << (unsigned)isObjectArgument << I + 1
12289 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
12290 << ToParamRange;
12291 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12292 return;
12293 }
12294
12295 // Special diagnostic for failure to convert an initializer list, since
12296 // telling the user that it has type void is not useful.
12297 if (FromExpr && isa<InitListExpr>(Val: FromExpr)) {
12298 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_list_argument)
12299 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12300 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12301 << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1
12302 : Conv.Bad.Kind == BadConversionSequence::too_many_initializers
12303 ? 2
12304 : 0);
12305 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12306 return;
12307 }
12308
12309 // Diagnose references or pointers to incomplete types differently,
12310 // since it's far from impossible that the incompleteness triggered
12311 // the failure.
12312 QualType TempFromTy = FromTy.getNonReferenceType();
12313 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
12314 TempFromTy = PTy->getPointeeType();
12315 if (TempFromTy->isIncompleteType()) {
12316 // Emit the generic diagnostic and, optionally, add the hints to it.
12317 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_conv_incomplete)
12318 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12319 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12320 << (unsigned)(Cand->Fix.Kind);
12321
12322 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12323 return;
12324 }
12325
12326 // Diagnose base -> derived pointer conversions.
12327 unsigned BaseToDerivedConversion = 0;
12328 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
12329 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
12330 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12331 other: FromPtrTy->getPointeeType(), Ctx: S.getASTContext()) &&
12332 !FromPtrTy->getPointeeType()->isIncompleteType() &&
12333 !ToPtrTy->getPointeeType()->isIncompleteType() &&
12334 S.IsDerivedFrom(Loc: SourceLocation(), Derived: ToPtrTy->getPointeeType(),
12335 Base: FromPtrTy->getPointeeType()))
12336 BaseToDerivedConversion = 1;
12337 }
12338 } else if (const ObjCObjectPointerType *FromPtrTy
12339 = FromTy->getAs<ObjCObjectPointerType>()) {
12340 if (const ObjCObjectPointerType *ToPtrTy
12341 = ToTy->getAs<ObjCObjectPointerType>())
12342 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
12343 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
12344 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12345 other: FromPtrTy->getPointeeType(), Ctx: S.getASTContext()) &&
12346 FromIface->isSuperClassOf(I: ToIface))
12347 BaseToDerivedConversion = 2;
12348 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
12349 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(other: FromTy,
12350 Ctx: S.getASTContext()) &&
12351 !FromTy->isIncompleteType() &&
12352 !ToRefTy->getPointeeType()->isIncompleteType() &&
12353 S.IsDerivedFrom(Loc: SourceLocation(), Derived: ToRefTy->getPointeeType(), Base: FromTy)) {
12354 BaseToDerivedConversion = 3;
12355 }
12356 }
12357
12358 if (BaseToDerivedConversion) {
12359 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_base_to_derived_conv)
12360 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12361 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
12362 << I + 1;
12363 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12364 return;
12365 }
12366
12367 if (isa<ObjCObjectPointerType>(Val: CFromTy) &&
12368 isa<PointerType>(Val: CToTy)) {
12369 Qualifiers FromQs = CFromTy.getQualifiers();
12370 Qualifiers ToQs = CToTy.getQualifiers();
12371 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12372 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_arc_conv)
12373 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12374 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
12375 << I + 1;
12376 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12377 return;
12378 }
12379 }
12380
12381 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, FD: Fn))
12382 return;
12383
12384 // __amdgpu_feature_predicate_t can be explicitly cast to the logical op type,
12385 // although this is almost always an error and we advise against it.
12386 if (FromTy == S.Context.AMDGPUFeaturePredicateTy &&
12387 ToTy == S.Context.getLogicalOperationType()) {
12388 S.Diag(Loc: Conv.Bad.FromExpr->getExprLoc(),
12389 DiagID: diag::err_amdgcn_predicate_type_needs_explicit_bool_cast)
12390 << Conv.Bad.FromExpr << ToTy;
12391 return;
12392 }
12393
12394 // Emit the generic diagnostic and, optionally, add the hints to it.
12395 PartialDiagnostic FDiag = S.PDiag(DiagID: diag::note_ovl_candidate_bad_conv);
12396 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12397 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12398 << (unsigned)(Cand->Fix.Kind);
12399
12400 // Check that location of Fn is not in system header.
12401 if (!S.SourceMgr.isInSystemHeader(Loc: Fn->getLocation())) {
12402 // If we can fix the conversion, suggest the FixIts.
12403 for (const FixItHint &HI : Cand->Fix.Hints)
12404 FDiag << HI;
12405 }
12406
12407 S.Diag(Loc: Fn->getLocation(), PD: FDiag);
12408
12409 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12410}
12411
12412/// Additional arity mismatch diagnosis specific to a function overload
12413/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12414/// over a candidate in any candidate set.
12415static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
12416 unsigned NumArgs, bool IsAddressOf = false) {
12417 assert(Cand->Function && "Candidate is required to be a function.");
12418 FunctionDecl *Fn = Cand->Function;
12419 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12420 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12421
12422 // With invalid overloaded operators, it's possible that we think we
12423 // have an arity mismatch when in fact it looks like we have the
12424 // right number of arguments, because only overloaded operators have
12425 // the weird behavior of overloading member and non-member functions.
12426 // Just don't report anything.
12427 if (Fn->isInvalidDecl() &&
12428 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12429 return true;
12430
12431 if (NumArgs < MinParams) {
12432 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12433 (Cand->FailureKind == ovl_fail_bad_deduction &&
12434 Cand->DeductionFailure.getResult() ==
12435 TemplateDeductionResult::TooFewArguments));
12436 } else {
12437 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12438 (Cand->FailureKind == ovl_fail_bad_deduction &&
12439 Cand->DeductionFailure.getResult() ==
12440 TemplateDeductionResult::TooManyArguments));
12441 }
12442
12443 return false;
12444}
12445
12446/// General arity mismatch diagnosis over a candidate in a candidate set.
12447static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
12448 unsigned NumFormalArgs,
12449 bool IsAddressOf = false) {
12450 assert(isa<FunctionDecl>(D) &&
12451 "The templated declaration should at least be a function"
12452 " when diagnosing bad template argument deduction due to too many"
12453 " or too few arguments");
12454
12455 FunctionDecl *Fn = cast<FunctionDecl>(Val: D);
12456
12457 // TODO: treat calls to a missing default constructor as a special case
12458 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12459 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12460 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12461
12462 // at least / at most / exactly
12463 bool HasExplicitObjectParam =
12464 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12465
12466 unsigned ParamCount =
12467 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12468 unsigned mode, modeCount;
12469
12470 if (NumFormalArgs < MinParams) {
12471 if (MinParams != ParamCount || FnTy->isVariadic() ||
12472 FnTy->isTemplateVariadic())
12473 mode = 0; // "at least"
12474 else
12475 mode = 2; // "exactly"
12476 modeCount = MinParams;
12477 } else {
12478 if (MinParams != ParamCount)
12479 mode = 1; // "at most"
12480 else
12481 mode = 2; // "exactly"
12482 modeCount = ParamCount;
12483 }
12484
12485 std::string Description;
12486 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12487 ClassifyOverloadCandidate(S, Found, Fn, CRK: CRK_None, Description);
12488
12489 unsigned FirstNonObjectParamIdx = HasExplicitObjectParam ? 1 : 0;
12490 if (modeCount == 1 && !IsAddressOf &&
12491 FirstNonObjectParamIdx < Fn->getNumParams() &&
12492 Fn->getParamDecl(i: FirstNonObjectParamIdx)->getDeclName())
12493 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_arity_one)
12494 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12495 << Description << mode << Fn->getParamDecl(i: FirstNonObjectParamIdx)
12496 << NumFormalArgs << HasExplicitObjectParam
12497 << Fn->getParametersSourceRange();
12498 else
12499 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_arity)
12500 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12501 << Description << mode << modeCount << NumFormalArgs
12502 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12503
12504 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12505}
12506
12507/// Arity mismatch diagnosis specific to a function overload candidate.
12508static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
12509 unsigned NumFormalArgs) {
12510 assert(Cand->Function && "Candidate must be a function");
12511 FunctionDecl *Fn = Cand->Function;
12512 if (!CheckArityMismatch(S, Cand, NumArgs: NumFormalArgs, IsAddressOf: Cand->TookAddressOfOverload))
12513 DiagnoseArityMismatch(S, Found: Cand->FoundDecl, D: Fn, NumFormalArgs,
12514 IsAddressOf: Cand->TookAddressOfOverload);
12515}
12516
12517static TemplateDecl *getDescribedTemplate(Decl *Templated) {
12518 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12519 return TD;
12520 llvm_unreachable("Unsupported: Getting the described template declaration"
12521 " for bad deduction diagnosis");
12522}
12523
12524/// Diagnose a failed template-argument deduction.
12525static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12526 DeductionFailureInfo &DeductionFailure,
12527 unsigned NumArgs, bool TakingCandidateAddress,
12528 TemplateSpecCandidateSetKind CandidateSetKind =
12529 TemplateSpecCandidateSetKind::Normal) {
12530 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12531 NamedDecl *ParamD = dyn_cast_if_present<TemplateTypeParmDecl *>(Val&: Param);
12532 if (!ParamD)
12533 ParamD = dyn_cast_if_present<NonTypeTemplateParmDecl *>(Val&: Param);
12534 if (!ParamD)
12535 ParamD = dyn_cast_if_present<TemplateTemplateParmDecl *>(Val&: Param);
12536 switch (DeductionFailure.getResult()) {
12537 case TemplateDeductionResult::Success:
12538 llvm_unreachable(
12539 "TemplateDeductionResult::Success while diagnosing bad deduction");
12540 case TemplateDeductionResult::NonDependentConversionFailure:
12541 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12542 "while diagnosing bad deduction");
12543 case TemplateDeductionResult::Invalid:
12544 case TemplateDeductionResult::AlreadyDiagnosed:
12545 return;
12546
12547 case TemplateDeductionResult::Incomplete: {
12548 assert(ParamD && "no parameter found for incomplete deduction result");
12549 S.Diag(Loc: Templated->getLocation(),
12550 DiagID: diag::note_ovl_candidate_incomplete_deduction)
12551 << ParamD->getDeclName();
12552 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12553 return;
12554 }
12555
12556 case TemplateDeductionResult::IncompletePack: {
12557 assert(ParamD && "no parameter found for incomplete deduction result");
12558 S.Diag(Loc: Templated->getLocation(),
12559 DiagID: diag::note_ovl_candidate_incomplete_deduction_pack)
12560 << ParamD->getDeclName()
12561 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12562 << *DeductionFailure.getFirstArg();
12563 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12564 return;
12565 }
12566
12567 case TemplateDeductionResult::Underqualified: {
12568 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12569 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(Val: ParamD);
12570
12571 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12572
12573 // Param will have been canonicalized, but it should just be a
12574 // qualified version of ParamD, so move the qualifiers to that.
12575 QualifierCollector Qs;
12576 Qs.strip(type: Param);
12577 QualType NonCanonParam = Qs.apply(Context: S.Context, T: TParam->getTypeForDecl());
12578 assert(S.Context.hasSameType(Param, NonCanonParam));
12579
12580 // Arg has also been canonicalized, but there's nothing we can do
12581 // about that. It also doesn't matter as much, because it won't
12582 // have any template parameters in it (because deduction isn't
12583 // done on dependent types).
12584 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12585
12586 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_underqualified)
12587 << ParamD->getDeclName() << Arg << NonCanonParam;
12588 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12589 return;
12590 }
12591
12592 case TemplateDeductionResult::Inconsistent: {
12593 assert(ParamD && "no parameter found for inconsistent deduction result");
12594 int which = 0;
12595 if (isa<TemplateTypeParmDecl>(Val: ParamD))
12596 which = 0;
12597 else if (isa<NonTypeTemplateParmDecl>(Val: ParamD)) {
12598 // Deduction might have failed because we deduced arguments of two
12599 // different types for a non-type template parameter.
12600 // FIXME: Use a different TDK value for this.
12601 QualType T1 =
12602 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12603 QualType T2 =
12604 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12605 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12606 S.Diag(Loc: Templated->getLocation(),
12607 DiagID: diag::note_ovl_candidate_inconsistent_deduction_types)
12608 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12609 << *DeductionFailure.getSecondArg() << T2;
12610 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12611 return;
12612 }
12613
12614 which = 1;
12615 } else {
12616 which = 2;
12617 }
12618
12619 // Tweak the diagnostic if the problem is that we deduced packs of
12620 // different arities. We'll print the actual packs anyway in case that
12621 // includes additional useful information.
12622 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12623 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12624 DeductionFailure.getFirstArg()->pack_size() !=
12625 DeductionFailure.getSecondArg()->pack_size()) {
12626 which = 3;
12627 }
12628
12629 S.Diag(Loc: Templated->getLocation(),
12630 DiagID: diag::note_ovl_candidate_inconsistent_deduction)
12631 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12632 << *DeductionFailure.getSecondArg();
12633 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12634 return;
12635 }
12636
12637 case TemplateDeductionResult::InvalidExplicitArguments: {
12638 assert(ParamD && "no parameter found for invalid explicit arguments");
12639
12640 auto Diag = S.Diag(Loc: Templated->getLocation(),
12641 DiagID: diag::note_ovl_candidate_explicit_arg_mismatch);
12642 if (ParamD->getDeclName())
12643 Diag << diag::ExplicitArgMismatchNameKind::Named << ParamD->getDeclName();
12644 else
12645 Diag << diag::ExplicitArgMismatchNameKind::Unnamed
12646 << (getDepthAndIndex(ND: ParamD).second + 1);
12647 if (PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic()) {
12648 SmallString<128> DiagContent;
12649 PDiag->second.EmitToString(Diags&: S.getDiagnostics(), Buf&: DiagContent);
12650 Diag << diag::ExplicitArgMismatchReasonKind::Detailed << DiagContent;
12651 } else {
12652 Diag << diag::ExplicitArgMismatchReasonKind::Vague;
12653 }
12654
12655 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12656 return;
12657 }
12658 case TemplateDeductionResult::ConstraintsNotSatisfied: {
12659 // Format the template argument list into the argument string.
12660 SmallString<128> TemplateArgString;
12661 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12662 TemplateArgString = " ";
12663 TemplateArgString += S.getTemplateArgumentBindingsText(
12664 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12665 if (TemplateArgString.size() == 1)
12666 TemplateArgString.clear();
12667 S.Diag(Loc: Templated->getLocation(),
12668 DiagID: diag::note_ovl_candidate_unsatisfied_constraints)
12669 << TemplateArgString;
12670
12671 S.DiagnoseUnsatisfiedConstraint(
12672 Satisfaction: static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12673 return;
12674 }
12675 case TemplateDeductionResult::TooManyArguments:
12676 case TemplateDeductionResult::TooFewArguments:
12677 DiagnoseArityMismatch(S, Found, D: Templated, NumFormalArgs: NumArgs, IsAddressOf: TakingCandidateAddress);
12678 return;
12679
12680 case TemplateDeductionResult::InstantiationDepth:
12681 S.Diag(Loc: Templated->getLocation(),
12682 DiagID: diag::note_ovl_candidate_instantiation_depth);
12683 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12684 return;
12685
12686 case TemplateDeductionResult::SubstitutionFailure: {
12687 // Format the template argument list into the argument string.
12688 SmallString<128> TemplateArgString;
12689 if (TemplateArgumentList *Args =
12690 DeductionFailure.getTemplateArgumentList()) {
12691 TemplateArgString = " ";
12692 TemplateArgString += S.getTemplateArgumentBindingsText(
12693 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12694 if (TemplateArgString.size() == 1)
12695 TemplateArgString.clear();
12696 }
12697
12698 // If this candidate was disabled by enable_if, say so.
12699 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12700 if (PDiag && PDiag->second.getDiagID() ==
12701 diag::err_typename_nested_not_found_enable_if) {
12702 // FIXME: Use the source range of the condition, and the fully-qualified
12703 // name of the enable_if template. These are both present in PDiag.
12704 S.Diag(Loc: PDiag->first, DiagID: diag::note_ovl_candidate_disabled_by_enable_if)
12705 << "'enable_if'" << TemplateArgString;
12706 return;
12707 }
12708
12709 // We found a specific requirement that disabled the enable_if.
12710 if (PDiag && PDiag->second.getDiagID() ==
12711 diag::err_typename_nested_not_found_requirement) {
12712 S.Diag(Loc: Templated->getLocation(),
12713 DiagID: diag::note_ovl_candidate_disabled_by_requirement)
12714 << PDiag->second.getStringArg(I: 0) << TemplateArgString;
12715 return;
12716 }
12717
12718 // Format the SFINAE diagnostic into the argument string.
12719 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12720 // formatted message in another diagnostic.
12721 SmallString<128> SFINAEArgString;
12722 SourceRange R;
12723 if (PDiag) {
12724 SFINAEArgString = ": ";
12725 R = SourceRange(PDiag->first, PDiag->first);
12726 PDiag->second.EmitToString(Diags&: S.getDiagnostics(), Buf&: SFINAEArgString);
12727 }
12728
12729 S.Diag(Loc: Templated->getLocation(),
12730 DiagID: diag::note_ovl_candidate_substitution_failure)
12731 << TemplateArgString << SFINAEArgString << R;
12732 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12733 return;
12734 }
12735
12736 case TemplateDeductionResult::DeducedMismatch:
12737 case TemplateDeductionResult::DeducedMismatchNested: {
12738 // Format the template argument list into the argument string.
12739 SmallString<128> TemplateArgString;
12740 if (TemplateArgumentList *Args =
12741 DeductionFailure.getTemplateArgumentList()) {
12742 TemplateArgString = " ";
12743 TemplateArgString += S.getTemplateArgumentBindingsText(
12744 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12745 if (TemplateArgString.size() == 1)
12746 TemplateArgString.clear();
12747 }
12748
12749 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_deduced_mismatch)
12750 << (*DeductionFailure.getCallArgIndex() + 1)
12751 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12752 << TemplateArgString
12753 << (DeductionFailure.getResult() ==
12754 TemplateDeductionResult::DeducedMismatchNested);
12755 break;
12756 }
12757
12758 case TemplateDeductionResult::NonDeducedMismatch: {
12759 // FIXME: Provide a source location to indicate what we couldn't match.
12760 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12761 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12762 if (FirstTA.getKind() == TemplateArgument::Template &&
12763 SecondTA.getKind() == TemplateArgument::Template) {
12764 TemplateName FirstTN = FirstTA.getAsTemplate();
12765 TemplateName SecondTN = SecondTA.getAsTemplate();
12766 if (FirstTN.getKind() == TemplateName::Template &&
12767 SecondTN.getKind() == TemplateName::Template) {
12768 if (FirstTN.getAsTemplateDecl()->getName() ==
12769 SecondTN.getAsTemplateDecl()->getName()) {
12770 // FIXME: This fixes a bad diagnostic where both templates are named
12771 // the same. This particular case is a bit difficult since:
12772 // 1) It is passed as a string to the diagnostic printer.
12773 // 2) The diagnostic printer only attempts to find a better
12774 // name for types, not decls.
12775 // Ideally, this should folded into the diagnostic printer.
12776 S.Diag(Loc: Templated->getLocation(),
12777 DiagID: CandidateSetKind ==
12778 TemplateSpecCandidateSetKind::FriendTemplate
12779 ? diag::note_friend_template_non_deduced_mismatch_qualified
12780 : diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12781 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12782 return;
12783 }
12784 }
12785 }
12786
12787 if (TakingCandidateAddress && isa<FunctionDecl>(Val: Templated) &&
12788 !checkAddressOfCandidateIsAvailable(S, FD: cast<FunctionDecl>(Val: Templated)))
12789 return;
12790
12791 // FIXME: For generic lambda parameters, check if the function is a lambda
12792 // call operator, and if so, emit a prettier and more informative
12793 // diagnostic that mentions 'auto' and lambda in addition to
12794 // (or instead of?) the canonical template type parameters.
12795 S.Diag(Loc: Templated->getLocation(),
12796 DiagID: CandidateSetKind == TemplateSpecCandidateSetKind::FriendTemplate
12797 ? diag::note_friend_template_non_deduced_mismatch
12798 : diag::note_ovl_candidate_non_deduced_mismatch)
12799 << FirstTA << SecondTA;
12800 return;
12801 }
12802 // TODO: diagnose these individually, then kill off
12803 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12804 case TemplateDeductionResult::MiscellaneousDeductionFailure:
12805 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_bad_deduction);
12806 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12807 return;
12808 case TemplateDeductionResult::CUDATargetMismatch:
12809 S.Diag(Loc: Templated->getLocation(),
12810 DiagID: diag::note_cuda_ovl_candidate_target_mismatch);
12811 return;
12812 }
12813}
12814
12815/// Diagnose a failed template-argument deduction, for function calls.
12816static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
12817 unsigned NumArgs,
12818 bool TakingCandidateAddress) {
12819 assert(Cand->Function && "Candidate must be a function");
12820 FunctionDecl *Fn = Cand->Function;
12821 TemplateDeductionResult TDK = Cand->DeductionFailure.getResult();
12822 if (TDK == TemplateDeductionResult::TooFewArguments ||
12823 TDK == TemplateDeductionResult::TooManyArguments) {
12824 if (CheckArityMismatch(S, Cand, NumArgs))
12825 return;
12826 }
12827 DiagnoseBadDeduction(S, Found: Cand->FoundDecl, Templated: Fn, // pattern
12828 DeductionFailure&: Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12829}
12830
12831/// CUDA: diagnose an invalid call across targets.
12832static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
12833 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12834 assert(Cand->Function && "Candidate must be a Function.");
12835 FunctionDecl *Callee = Cand->Function;
12836
12837 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(D: Caller),
12838 CalleeTarget = S.CUDA().IdentifyTarget(D: Callee);
12839
12840 std::string FnDesc;
12841 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12842 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn: Callee,
12843 CRK: Cand->getRewriteKind(), Description&: FnDesc);
12844
12845 S.Diag(Loc: Callee->getLocation(), DiagID: diag::note_ovl_candidate_bad_target)
12846 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12847 << FnDesc /* Ignored */
12848 << CalleeTarget << CallerTarget;
12849
12850 // This could be an implicit constructor for which we could not infer the
12851 // target due to a collsion. Diagnose that case.
12852 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Val: Callee);
12853 if (Meth != nullptr && Meth->isImplicit()) {
12854 CXXRecordDecl *ParentClass = Meth->getParent();
12855 CXXSpecialMemberKind CSM;
12856
12857 switch (FnKindPair.first) {
12858 default:
12859 return;
12860 case oc_implicit_default_constructor:
12861 CSM = CXXSpecialMemberKind::DefaultConstructor;
12862 break;
12863 case oc_implicit_copy_constructor:
12864 CSM = CXXSpecialMemberKind::CopyConstructor;
12865 break;
12866 case oc_implicit_move_constructor:
12867 CSM = CXXSpecialMemberKind::MoveConstructor;
12868 break;
12869 case oc_implicit_copy_assignment:
12870 CSM = CXXSpecialMemberKind::CopyAssignment;
12871 break;
12872 case oc_implicit_move_assignment:
12873 CSM = CXXSpecialMemberKind::MoveAssignment;
12874 break;
12875 };
12876
12877 bool ConstRHS = false;
12878 if (Meth->getNumParams()) {
12879 if (const ReferenceType *RT =
12880 Meth->getParamDecl(i: 0)->getType()->getAs<ReferenceType>()) {
12881 ConstRHS = RT->getPointeeType().isConstQualified();
12882 }
12883 }
12884
12885 S.CUDA().inferTargetForImplicitSpecialMember(ClassDecl: ParentClass, CSM, MemberDecl: Meth,
12886 /* ConstRHS */ ConstRHS,
12887 /* Diagnose */ true);
12888 }
12889}
12890
12891static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
12892 assert(Cand->Function && "Candidate must be a function");
12893 FunctionDecl *Callee = Cand->Function;
12894 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12895
12896 S.Diag(Loc: Callee->getLocation(),
12897 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
12898 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12899}
12900
12901static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
12902 assert(Cand->Function && "Candidate must be a function");
12903 FunctionDecl *Fn = Cand->Function;
12904 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function: Fn);
12905 assert(ES.isExplicit() && "not an explicit candidate");
12906
12907 unsigned Kind;
12908 switch (Fn->getDeclKind()) {
12909 case Decl::Kind::CXXConstructor:
12910 Kind = 0;
12911 break;
12912 case Decl::Kind::CXXConversion:
12913 Kind = 1;
12914 break;
12915 case Decl::Kind::CXXDeductionGuide:
12916 Kind = Fn->isImplicit() ? 0 : 2;
12917 break;
12918 default:
12919 llvm_unreachable("invalid Decl");
12920 }
12921
12922 // Note the location of the first (in-class) declaration; a redeclaration
12923 // (particularly an out-of-class definition) will typically lack the
12924 // 'explicit' specifier.
12925 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12926 FunctionDecl *First = Fn->getFirstDecl();
12927 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12928 First = Pattern->getFirstDecl();
12929
12930 S.Diag(Loc: First->getLocation(),
12931 DiagID: diag::note_ovl_candidate_explicit)
12932 << Kind << (ES.getExpr() ? 1 : 0)
12933 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12934}
12935
12936static void NoteImplicitDeductionGuide(Sema &S, FunctionDecl *Fn) {
12937 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Val: Fn);
12938 if (!DG)
12939 return;
12940 TemplateDecl *OriginTemplate =
12941 DG->getDeclName().getCXXDeductionGuideTemplate();
12942 // We want to always print synthesized deduction guides for type aliases.
12943 // They would retain the explicit bit of the corresponding constructor.
12944 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12945 return;
12946 std::string FunctionProto;
12947 llvm::raw_string_ostream OS(FunctionProto);
12948 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12949 if (!Template) {
12950 // This also could be an instantiation. Find out the primary template.
12951 FunctionDecl *Pattern =
12952 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12953 if (!Pattern) {
12954 // The implicit deduction guide is built on an explicit non-template
12955 // deduction guide. Currently, this might be the case only for type
12956 // aliases.
12957 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12958 // gets merged.
12959 assert(OriginTemplate->isTypeAlias() &&
12960 "Non-template implicit deduction guides are only possible for "
12961 "type aliases");
12962 DG->print(Out&: OS);
12963 S.Diag(Loc: DG->getLocation(), DiagID: diag::note_implicit_deduction_guide)
12964 << FunctionProto;
12965 return;
12966 }
12967 Template = Pattern->getDescribedFunctionTemplate();
12968 assert(Template && "Cannot find the associated function template of "
12969 "CXXDeductionGuideDecl?");
12970 }
12971 Template->print(Out&: OS);
12972 S.Diag(Loc: DG->getLocation(), DiagID: diag::note_implicit_deduction_guide)
12973 << FunctionProto;
12974}
12975
12976/// Generates a 'note' diagnostic for an overload candidate. We've
12977/// already generated a primary error at the call site.
12978///
12979/// It really does need to be a single diagnostic with its caret
12980/// pointed at the candidate declaration. Yes, this creates some
12981/// major challenges of technical writing. Yes, this makes pointing
12982/// out problems with specific arguments quite awkward. It's still
12983/// better than generating twenty screens of text for every failed
12984/// overload.
12985///
12986/// It would be great to be able to express per-candidate problems
12987/// more richly for those diagnostic clients that cared, but we'd
12988/// still have to be just as careful with the default diagnostics.
12989/// \param CtorDestAS Addr space of object being constructed (for ctor
12990/// candidates only).
12991static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
12992 unsigned NumArgs,
12993 bool TakingCandidateAddress,
12994 LangAS CtorDestAS = LangAS::Default) {
12995 assert(Cand->Function && "Candidate must be a function");
12996 FunctionDecl *Fn = Cand->Function;
12997 if (shouldSkipNotingLambdaConversionDecl(Fn))
12998 return;
12999
13000 // There is no physical candidate declaration to point to for OpenCL builtins.
13001 // Except for failed conversions, the notes are identical for each candidate,
13002 // so do not generate such notes.
13003 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
13004 Cand->FailureKind != ovl_fail_bad_conversion)
13005 return;
13006
13007 // Skip implicit member functions when trying to resolve
13008 // the address of a an overload set for a function pointer.
13009 if (Cand->TookAddressOfOverload &&
13010 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
13011 return;
13012
13013 // Note deleted candidates, but only if they're viable.
13014 if (Cand->Viable) {
13015 if (Fn->isDeleted()) {
13016 std::string FnDesc;
13017 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
13018 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn,
13019 CRK: Cand->getRewriteKind(), Description&: FnDesc);
13020
13021 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_deleted)
13022 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
13023 << (Fn->isDeleted()
13024 ? (Fn->getCanonicalDecl()->isDeletedAsWritten() ? 1 : 2)
13025 : 0);
13026 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
13027 return;
13028 }
13029
13030 // We don't really have anything else to say about viable candidates.
13031 S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
13032 return;
13033 }
13034
13035 // If this is a synthesized deduction guide we're deducing against, add a note
13036 // for it. These deduction guides are not explicitly spelled in the source
13037 // code, so simply printing a deduction failure note mentioning synthesized
13038 // template parameters or pointing to the header of the surrounding RecordDecl
13039 // would be confusing.
13040 //
13041 // We prefer adding such notes at the end of the deduction failure because
13042 // duplicate code snippets appearing in the diagnostic would likely become
13043 // noisy.
13044 llvm::scope_exit _([&] { NoteImplicitDeductionGuide(S, Fn); });
13045
13046 switch (Cand->FailureKind) {
13047 case ovl_fail_too_many_arguments:
13048 case ovl_fail_too_few_arguments:
13049 return DiagnoseArityMismatch(S, Cand, NumFormalArgs: NumArgs);
13050
13051 case ovl_fail_bad_deduction:
13052 return DiagnoseBadDeduction(S, Cand, NumArgs,
13053 TakingCandidateAddress);
13054
13055 case ovl_fail_illegal_constructor: {
13056 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_illegal_constructor)
13057 << (Fn->getPrimaryTemplate() ? 1 : 0);
13058 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
13059 return;
13060 }
13061
13062 case ovl_fail_object_addrspace_mismatch: {
13063 Qualifiers QualsForPrinting;
13064 QualsForPrinting.setAddressSpace(CtorDestAS);
13065 S.Diag(Loc: Fn->getLocation(),
13066 DiagID: diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
13067 << QualsForPrinting;
13068 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
13069 return;
13070 }
13071
13072 case ovl_fail_trivial_conversion:
13073 case ovl_fail_bad_final_conversion:
13074 case ovl_fail_final_conversion_not_exact:
13075 return S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
13076
13077 case ovl_fail_bad_conversion: {
13078 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
13079 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
13080 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
13081 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
13082
13083 // FIXME: this currently happens when we're called from SemaInit
13084 // when user-conversion overload fails. Figure out how to handle
13085 // those conditions and diagnose them well.
13086 return S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
13087 }
13088
13089 case ovl_fail_bad_target:
13090 return DiagnoseBadTarget(S, Cand);
13091
13092 case ovl_fail_enable_if:
13093 return DiagnoseFailedEnableIfAttr(S, Cand);
13094
13095 case ovl_fail_explicit:
13096 return DiagnoseFailedExplicitSpec(S, Cand);
13097
13098 case ovl_fail_inhctor_slice:
13099 // It's generally not interesting to note copy/move constructors here.
13100 if (cast<CXXConstructorDecl>(Val: Fn)->isCopyOrMoveConstructor())
13101 return;
13102 S.Diag(Loc: Fn->getLocation(),
13103 DiagID: diag::note_ovl_candidate_inherited_constructor_slice)
13104 << (Fn->getPrimaryTemplate() ? 1 : 0)
13105 << Fn->getParamDecl(i: 0)->getType()->isRValueReferenceType();
13106 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
13107 return;
13108
13109 case ovl_fail_addr_not_available: {
13110 bool Available = checkAddressOfCandidateIsAvailable(S, FD: Fn);
13111 (void)Available;
13112 assert(!Available);
13113 break;
13114 }
13115 case ovl_non_default_multiversion_function:
13116 // Do nothing, these should simply be ignored.
13117 break;
13118
13119 case ovl_fail_constraints_not_satisfied: {
13120 std::string FnDesc;
13121 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
13122 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn,
13123 CRK: Cand->getRewriteKind(), Description&: FnDesc);
13124
13125 S.Diag(Loc: Fn->getLocation(),
13126 DiagID: diag::note_ovl_candidate_constraints_not_satisfied)
13127 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
13128 << FnDesc /* Ignored */;
13129 ConstraintSatisfaction Satisfaction;
13130 if (S.CheckFunctionConstraints(FD: Fn, Satisfaction, UsageLoc: SourceLocation(),
13131 /*ForOverloadResolution=*/true))
13132 break;
13133 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
13134 }
13135 }
13136}
13137
13138static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
13139 if (shouldSkipNotingLambdaConversionDecl(Fn: Cand->Surrogate))
13140 return;
13141
13142 // Desugar the type of the surrogate down to a function type,
13143 // retaining as many typedefs as possible while still showing
13144 // the function type (and, therefore, its parameter types).
13145 QualType FnType = Cand->Surrogate->getConversionType();
13146 bool isLValueReference = false;
13147 bool isRValueReference = false;
13148 bool isPointer = false;
13149 if (const LValueReferenceType *FnTypeRef =
13150 FnType->getAs<LValueReferenceType>()) {
13151 FnType = FnTypeRef->getPointeeType();
13152 isLValueReference = true;
13153 } else if (const RValueReferenceType *FnTypeRef =
13154 FnType->getAs<RValueReferenceType>()) {
13155 FnType = FnTypeRef->getPointeeType();
13156 isRValueReference = true;
13157 }
13158 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
13159 FnType = FnTypePtr->getPointeeType();
13160 isPointer = true;
13161 }
13162 // Desugar down to a function type.
13163 FnType = QualType(FnType->getAs<FunctionType>(), 0);
13164 // Reconstruct the pointer/reference as appropriate.
13165 if (isPointer) FnType = S.Context.getPointerType(T: FnType);
13166 if (isRValueReference) FnType = S.Context.getRValueReferenceType(T: FnType);
13167 if (isLValueReference) FnType = S.Context.getLValueReferenceType(T: FnType);
13168
13169 if (!Cand->Viable &&
13170 Cand->FailureKind == ovl_fail_constraints_not_satisfied) {
13171 S.Diag(Loc: Cand->Surrogate->getLocation(),
13172 DiagID: diag::note_ovl_surrogate_constraints_not_satisfied)
13173 << Cand->Surrogate;
13174 ConstraintSatisfaction Satisfaction;
13175 if (S.CheckFunctionConstraints(FD: Cand->Surrogate, Satisfaction))
13176 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
13177 } else {
13178 S.Diag(Loc: Cand->Surrogate->getLocation(), DiagID: diag::note_ovl_surrogate_cand)
13179 << FnType;
13180 }
13181}
13182
13183static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
13184 SourceLocation OpLoc,
13185 OverloadCandidate *Cand) {
13186 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
13187 std::string TypeStr("operator");
13188 TypeStr += Opc;
13189 TypeStr += "(";
13190 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
13191 if (Cand->Conversions.size() == 1) {
13192 TypeStr += ")";
13193 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_builtin_candidate) << TypeStr;
13194 } else {
13195 TypeStr += ", ";
13196 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
13197 TypeStr += ")";
13198 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_builtin_candidate) << TypeStr;
13199 }
13200}
13201
13202static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
13203 OverloadCandidate *Cand) {
13204 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
13205 if (ICS.isBad()) break; // all meaningless after first invalid
13206 if (!ICS.isAmbiguous()) continue;
13207
13208 ICS.DiagnoseAmbiguousConversion(
13209 S, CaretLoc: OpLoc, PDiag: S.PDiag(DiagID: diag::note_ambiguous_type_conversion));
13210 }
13211}
13212
13213static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
13214 if (Cand->Function)
13215 return Cand->Function->getLocation();
13216 if (Cand->IsSurrogate)
13217 return Cand->Surrogate->getLocation();
13218 return SourceLocation();
13219}
13220
13221static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
13222 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
13223 case TemplateDeductionResult::Success:
13224 case TemplateDeductionResult::NonDependentConversionFailure:
13225 case TemplateDeductionResult::AlreadyDiagnosed:
13226 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
13227
13228 case TemplateDeductionResult::Invalid:
13229 case TemplateDeductionResult::Incomplete:
13230 case TemplateDeductionResult::IncompletePack:
13231 return 1;
13232
13233 case TemplateDeductionResult::Underqualified:
13234 case TemplateDeductionResult::Inconsistent:
13235 return 2;
13236
13237 case TemplateDeductionResult::SubstitutionFailure:
13238 case TemplateDeductionResult::DeducedMismatch:
13239 case TemplateDeductionResult::ConstraintsNotSatisfied:
13240 case TemplateDeductionResult::DeducedMismatchNested:
13241 case TemplateDeductionResult::NonDeducedMismatch:
13242 case TemplateDeductionResult::MiscellaneousDeductionFailure:
13243 case TemplateDeductionResult::CUDATargetMismatch:
13244 return 3;
13245
13246 case TemplateDeductionResult::InstantiationDepth:
13247 return 4;
13248
13249 case TemplateDeductionResult::InvalidExplicitArguments:
13250 return 5;
13251
13252 case TemplateDeductionResult::TooManyArguments:
13253 case TemplateDeductionResult::TooFewArguments:
13254 return 6;
13255 }
13256 llvm_unreachable("Unhandled deduction result");
13257}
13258
13259namespace {
13260
13261struct CompareOverloadCandidatesForDisplay {
13262 Sema &S;
13263 SourceLocation Loc;
13264 size_t NumArgs;
13265 OverloadCandidateSet::CandidateSetKind CSK;
13266
13267 CompareOverloadCandidatesForDisplay(
13268 Sema &S, SourceLocation Loc, size_t NArgs,
13269 OverloadCandidateSet::CandidateSetKind CSK)
13270 : S(S), NumArgs(NArgs), CSK(CSK) {}
13271
13272 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
13273 // If there are too many or too few arguments, that's the high-order bit we
13274 // want to sort by, even if the immediate failure kind was something else.
13275 if (C->FailureKind == ovl_fail_too_many_arguments ||
13276 C->FailureKind == ovl_fail_too_few_arguments)
13277 return static_cast<OverloadFailureKind>(C->FailureKind);
13278
13279 if (C->Function) {
13280 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
13281 return ovl_fail_too_many_arguments;
13282 if (NumArgs < C->Function->getMinRequiredArguments())
13283 return ovl_fail_too_few_arguments;
13284 }
13285
13286 return static_cast<OverloadFailureKind>(C->FailureKind);
13287 }
13288
13289 bool operator()(const OverloadCandidate *L,
13290 const OverloadCandidate *R) {
13291 // Fast-path this check.
13292 if (L == R) return false;
13293
13294 // Order first by viability.
13295 if (L->Viable) {
13296 if (!R->Viable) return true;
13297
13298 if (int Ord = CompareConversions(L: *L, R: *R))
13299 return Ord < 0;
13300 // Use other tie breakers.
13301 } else if (R->Viable)
13302 return false;
13303
13304 assert(L->Viable == R->Viable);
13305
13306 // Criteria by which we can sort non-viable candidates:
13307 if (!L->Viable) {
13308 OverloadFailureKind LFailureKind = EffectiveFailureKind(C: L);
13309 OverloadFailureKind RFailureKind = EffectiveFailureKind(C: R);
13310
13311 // 1. Arity mismatches come after other candidates.
13312 if (LFailureKind == ovl_fail_too_many_arguments ||
13313 LFailureKind == ovl_fail_too_few_arguments) {
13314 if (RFailureKind == ovl_fail_too_many_arguments ||
13315 RFailureKind == ovl_fail_too_few_arguments) {
13316 int LDist = std::abs(x: (int)L->getNumParams() - (int)NumArgs);
13317 int RDist = std::abs(x: (int)R->getNumParams() - (int)NumArgs);
13318 if (LDist == RDist) {
13319 if (LFailureKind == RFailureKind)
13320 // Sort non-surrogates before surrogates.
13321 return !L->IsSurrogate && R->IsSurrogate;
13322 // Sort candidates requiring fewer parameters than there were
13323 // arguments given after candidates requiring more parameters
13324 // than there were arguments given.
13325 return LFailureKind == ovl_fail_too_many_arguments;
13326 }
13327 return LDist < RDist;
13328 }
13329 return false;
13330 }
13331 if (RFailureKind == ovl_fail_too_many_arguments ||
13332 RFailureKind == ovl_fail_too_few_arguments)
13333 return true;
13334
13335 // 2. Bad conversions come first and are ordered by the number
13336 // of bad conversions and quality of good conversions.
13337 if (LFailureKind == ovl_fail_bad_conversion) {
13338 if (RFailureKind != ovl_fail_bad_conversion)
13339 return true;
13340
13341 // The conversion that can be fixed with a smaller number of changes,
13342 // comes first.
13343 unsigned numLFixes = L->Fix.NumConversionsFixed;
13344 unsigned numRFixes = R->Fix.NumConversionsFixed;
13345 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
13346 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
13347 if (numLFixes != numRFixes) {
13348 return numLFixes < numRFixes;
13349 }
13350
13351 // If there's any ordering between the defined conversions...
13352 if (int Ord = CompareConversions(L: *L, R: *R))
13353 return Ord < 0;
13354 } else if (RFailureKind == ovl_fail_bad_conversion)
13355 return false;
13356
13357 if (LFailureKind == ovl_fail_bad_deduction) {
13358 if (RFailureKind != ovl_fail_bad_deduction)
13359 return true;
13360
13361 if (L->DeductionFailure.Result != R->DeductionFailure.Result) {
13362 unsigned LRank = RankDeductionFailure(DFI: L->DeductionFailure);
13363 unsigned RRank = RankDeductionFailure(DFI: R->DeductionFailure);
13364 if (LRank != RRank)
13365 return LRank < RRank;
13366 }
13367 } else if (RFailureKind == ovl_fail_bad_deduction)
13368 return false;
13369
13370 // TODO: others?
13371 }
13372
13373 // Sort everything else by location.
13374 SourceLocation LLoc = GetLocationForCandidate(Cand: L);
13375 SourceLocation RLoc = GetLocationForCandidate(Cand: R);
13376
13377 // Put candidates without locations (e.g. builtins) at the end.
13378 if (LLoc.isValid() && RLoc.isValid())
13379 return S.SourceMgr.isBeforeInTranslationUnit(LHS: LLoc, RHS: RLoc);
13380 if (LLoc.isValid() && !RLoc.isValid())
13381 return true;
13382 if (RLoc.isValid() && !LLoc.isValid())
13383 return false;
13384 assert(!LLoc.isValid() && !RLoc.isValid());
13385 // For builtins and other functions without locations, fallback to the order
13386 // in which they were added into the candidate set.
13387 return L < R;
13388 }
13389
13390private:
13391 struct ConversionSignals {
13392 unsigned KindRank = 0;
13393 ImplicitConversionRank Rank = ICR_Exact_Match;
13394
13395 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
13396 ConversionSignals Sig;
13397 Sig.KindRank = Seq.getKindRank();
13398 if (Seq.isStandard())
13399 Sig.Rank = Seq.Standard.getRank();
13400 else if (Seq.isUserDefined())
13401 Sig.Rank = Seq.UserDefined.After.getRank();
13402 // We intend StaticObjectArgumentConversion to compare the same as
13403 // StandardConversion with ICR_ExactMatch rank.
13404 return Sig;
13405 }
13406
13407 static ConversionSignals ForObjectArgument() {
13408 // We intend StaticObjectArgumentConversion to compare the same as
13409 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13410 return {};
13411 }
13412 };
13413
13414 // Returns -1 if conversions in L are considered better.
13415 // 0 if they are considered indistinguishable.
13416 // 1 if conversions in R are better.
13417 int CompareConversions(const OverloadCandidate &L,
13418 const OverloadCandidate &R) {
13419 // We cannot use `isBetterOverloadCandidate` because it is defined
13420 // according to the C++ standard and provides a partial order, but we need
13421 // a total order as this function is used in sort.
13422 assert(L.Conversions.size() == R.Conversions.size());
13423 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13424 auto LS = L.IgnoreObjectArgument && I == 0
13425 ? ConversionSignals::ForObjectArgument()
13426 : ConversionSignals::ForSequence(Seq&: L.Conversions[I]);
13427 auto RS = R.IgnoreObjectArgument
13428 ? ConversionSignals::ForObjectArgument()
13429 : ConversionSignals::ForSequence(Seq&: R.Conversions[I]);
13430 if (std::tie(args&: LS.KindRank, args&: LS.Rank) != std::tie(args&: RS.KindRank, args&: RS.Rank))
13431 return std::tie(args&: LS.KindRank, args&: LS.Rank) < std::tie(args&: RS.KindRank, args&: RS.Rank)
13432 ? -1
13433 : 1;
13434 }
13435 // FIXME: find a way to compare templates for being more or less
13436 // specialized that provides a strict weak ordering.
13437 return 0;
13438 }
13439};
13440}
13441
13442/// CompleteNonViableCandidate - Normally, overload resolution only
13443/// computes up to the first bad conversion. Produces the FixIt set if
13444/// possible.
13445static void
13446CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
13447 ArrayRef<Expr *> Args,
13448 OverloadCandidateSet::CandidateSetKind CSK) {
13449 assert(!Cand->Viable);
13450
13451 // Don't do anything on failures other than bad conversion.
13452 if (Cand->FailureKind != ovl_fail_bad_conversion)
13453 return;
13454
13455 // We only want the FixIts if all the arguments can be corrected.
13456 bool Unfixable = false;
13457 // Use a implicit copy initialization to check conversion fixes.
13458 Cand->Fix.setConversionChecker(TryCopyInitialization);
13459
13460 // Attempt to fix the bad conversion.
13461 unsigned ConvCount = Cand->Conversions.size();
13462 for (unsigned ConvIdx =
13463 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13464 : 0);
13465 /**/; ++ConvIdx) {
13466 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13467 if (Cand->Conversions[ConvIdx].isInitialized() &&
13468 Cand->Conversions[ConvIdx].isBad()) {
13469 Unfixable = !Cand->TryToFixBadConversion(Idx: ConvIdx, S);
13470 break;
13471 }
13472 }
13473
13474 // FIXME: this should probably be preserved from the overload
13475 // operation somehow.
13476 bool SuppressUserConversions = false;
13477
13478 unsigned ConvIdx = 0;
13479 unsigned ArgIdx = 0;
13480 ArrayRef<QualType> ParamTypes;
13481 bool Reversed = Cand->isReversed();
13482
13483 if (Cand->IsSurrogate) {
13484 QualType ConvType
13485 = Cand->Surrogate->getConversionType().getNonReferenceType();
13486 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13487 ConvType = ConvPtrType->getPointeeType();
13488 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13489 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13490 ConvIdx = 1;
13491 } else if (Cand->Function) {
13492 ParamTypes =
13493 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13494 if (isa<CXXMethodDecl>(Val: Cand->Function) &&
13495 !isa<CXXConstructorDecl>(Val: Cand->Function) && !Reversed &&
13496 !Cand->Function->hasCXXExplicitFunctionObjectParameter()) {
13497 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13498 ConvIdx = 1;
13499 if (CSK == OverloadCandidateSet::CSK_Operator &&
13500 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13501 Cand->Function->getDeclName().getCXXOverloadedOperator() !=
13502 OO_Subscript)
13503 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13504 ArgIdx = 1;
13505 }
13506 } else {
13507 // Builtin operator.
13508 assert(ConvCount <= 3);
13509 ParamTypes = Cand->BuiltinParamTypes;
13510 }
13511
13512 // Fill in the rest of the conversions.
13513 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13514 ConvIdx != ConvCount && ArgIdx < Args.size();
13515 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13516 if (Cand->Conversions[ConvIdx].isInitialized()) {
13517 // We've already checked this conversion.
13518 } else if (ParamIdx < ParamTypes.size()) {
13519 if (ParamTypes[ParamIdx]->isDependentType())
13520 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13521 Args[ArgIdx]->getType());
13522 else {
13523 Cand->Conversions[ConvIdx] =
13524 TryCopyInitialization(S, From: Args[ArgIdx], ToType: ParamTypes[ParamIdx],
13525 SuppressUserConversions,
13526 /*InOverloadResolution=*/true,
13527 /*AllowObjCWritebackConversion=*/
13528 S.getLangOpts().ObjCAutoRefCount);
13529 // Store the FixIt in the candidate if it exists.
13530 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13531 Unfixable = !Cand->TryToFixBadConversion(Idx: ConvIdx, S);
13532 }
13533 } else
13534 Cand->Conversions[ConvIdx].setEllipsis();
13535 }
13536}
13537
13538SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
13539 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
13540 SourceLocation OpLoc,
13541 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13542
13543 InjectNonDeducedTemplateCandidates(S);
13544
13545 // Sort the candidates by viability and position. Sorting directly would
13546 // be prohibitive, so we make a set of pointers and sort those.
13547 SmallVector<OverloadCandidate*, 32> Cands;
13548 if (OCD == OCD_AllCandidates) Cands.reserve(N: size());
13549 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13550 Cand != LastCand; ++Cand) {
13551 if (!Filter(*Cand))
13552 continue;
13553 switch (OCD) {
13554 case OCD_AllCandidates:
13555 if (!Cand->Viable) {
13556 if (!Cand->Function && !Cand->IsSurrogate) {
13557 // This a non-viable builtin candidate. We do not, in general,
13558 // want to list every possible builtin candidate.
13559 continue;
13560 }
13561 CompleteNonViableCandidate(S, Cand, Args, CSK: Kind);
13562 }
13563 break;
13564
13565 case OCD_ViableCandidates:
13566 if (!Cand->Viable)
13567 continue;
13568 break;
13569
13570 case OCD_AmbiguousCandidates:
13571 if (!Cand->Best)
13572 continue;
13573 break;
13574 }
13575
13576 Cands.push_back(Elt: Cand);
13577 }
13578
13579 llvm::stable_sort(
13580 Range&: Cands, C: CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13581
13582 return Cands;
13583}
13584
13585bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
13586 SourceLocation OpLoc) {
13587 bool DeferHint = false;
13588 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13589 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13590 // host device candidates.
13591 auto WrongSidedCands =
13592 CompleteCandidates(S, OCD: OCD_AllCandidates, Args, OpLoc, Filter: [](auto &Cand) {
13593 return (Cand.Viable == false &&
13594 Cand.FailureKind == ovl_fail_bad_target) ||
13595 (Cand.Function &&
13596 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13597 Cand.Function->template hasAttr<CUDADeviceAttr>());
13598 });
13599 DeferHint = !WrongSidedCands.empty();
13600 }
13601 return DeferHint;
13602}
13603
13604/// When overload resolution fails, prints diagnostic messages containing the
13605/// candidates in the candidate set.
13606void OverloadCandidateSet::NoteCandidates(
13607 PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
13608 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13609 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13610
13611 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13612
13613 {
13614 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13615 S.Diag(Loc: PD.first, PD: PD.second);
13616 }
13617
13618 // In WebAssembly we don't want to emit further diagnostics if a table is
13619 // passed as an argument to a function.
13620 bool NoteCands = true;
13621 for (const Expr *Arg : Args) {
13622 if (Arg->getType()->isWebAssemblyTableType())
13623 NoteCands = false;
13624 }
13625
13626 if (NoteCands)
13627 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13628
13629 if (OCD == OCD_AmbiguousCandidates)
13630 MaybeDiagnoseAmbiguousConstraints(S,
13631 Cands: {Candidates.begin(), Candidates.end()});
13632}
13633
13634void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
13635 ArrayRef<OverloadCandidate *> Cands,
13636 StringRef Opc, SourceLocation OpLoc) {
13637 bool ReportedAmbiguousConversions = false;
13638
13639 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13640 unsigned CandsShown = 0;
13641 auto I = Cands.begin(), E = Cands.end();
13642 for (; I != E; ++I) {
13643 OverloadCandidate *Cand = *I;
13644
13645 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13646 ShowOverloads == Ovl_Best) {
13647 break;
13648 }
13649 ++CandsShown;
13650
13651 if (Cand->Function)
13652 NoteFunctionCandidate(S, Cand, NumArgs: Args.size(),
13653 TakingCandidateAddress: Kind == CSK_AddressOfOverloadSet, CtorDestAS: DestAS);
13654 else if (Cand->IsSurrogate)
13655 NoteSurrogateCandidate(S, Cand);
13656 else {
13657 assert(Cand->Viable &&
13658 "Non-viable built-in candidates are not added to Cands.");
13659 // Generally we only see ambiguities including viable builtin
13660 // operators if overload resolution got screwed up by an
13661 // ambiguous user-defined conversion.
13662 //
13663 // FIXME: It's quite possible for different conversions to see
13664 // different ambiguities, though.
13665 if (!ReportedAmbiguousConversions) {
13666 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13667 ReportedAmbiguousConversions = true;
13668 }
13669
13670 // If this is a viable builtin, print it.
13671 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13672 }
13673 }
13674
13675 // Inform S.Diags that we've shown an overload set with N elements. This may
13676 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13677 S.Diags.overloadCandidatesShown(N: CandsShown);
13678
13679 if (I != E) {
13680 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13681 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
13682 }
13683}
13684
13685bool OverloadCandidateSet::shouldDeferTemplateArgumentDeduction(
13686 const Sema &S) const {
13687 if (S.getLangOpts().CUDA) {
13688 auto *Caller = S.getCurFunctionDecl(AllowLambda: true);
13689 // Overloading based on __host__ and __device__ attributes takes
13690 // higher priority, HD functions may favor template candidates even when a
13691 // non-template candidate would be a perfect match.
13692 if (Caller && Caller->hasAttr<CUDAHostAttr>() &&
13693 Caller->hasAttr<CUDADeviceAttr>())
13694 return false;
13695 }
13696
13697 return
13698 // For user defined conversion we need to check against different
13699 // combination of CV qualifiers and look at any explicit specifier, so
13700 // always deduce template candidates.
13701 Kind != CSK_InitByUserDefinedConversion
13702 // When doing code completion, we want to see all the
13703 // viable candidates.
13704 && Kind != CSK_CodeCompletion;
13705}
13706
13707static SourceLocation
13708GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
13709 return Cand->Specialization ? Cand->Specialization->getLocation()
13710 : SourceLocation();
13711}
13712
13713namespace {
13714struct CompareTemplateSpecCandidatesForDisplay {
13715 Sema &S;
13716 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13717
13718 bool operator()(const TemplateSpecCandidate *L,
13719 const TemplateSpecCandidate *R) {
13720 // Fast-path this check.
13721 if (L == R)
13722 return false;
13723
13724 // Assuming that both candidates are not matches...
13725
13726 // Sort by the ranking of deduction failures.
13727 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
13728 return RankDeductionFailure(DFI: L->DeductionFailure) <
13729 RankDeductionFailure(DFI: R->DeductionFailure);
13730
13731 // Sort everything else by location.
13732 SourceLocation LLoc = GetLocationForCandidate(Cand: L);
13733 SourceLocation RLoc = GetLocationForCandidate(Cand: R);
13734
13735 // Put candidates without locations (e.g. builtins) at the end.
13736 if (LLoc.isInvalid())
13737 return false;
13738 if (RLoc.isInvalid())
13739 return true;
13740
13741 return S.SourceMgr.isBeforeInTranslationUnit(LHS: LLoc, RHS: RLoc);
13742 }
13743};
13744}
13745
13746/// Diagnose a template argument deduction failure.
13747/// We are treating these failures as overload failures due to bad
13748/// deductions.
13749void TemplateSpecCandidate::NoteDeductionFailure(
13750 Sema &S, bool ForTakingAddress,
13751 TemplateSpecCandidateSetKind CandidateSetKind) {
13752 DiagnoseBadDeduction(S, Found: FoundDecl, Templated: Specialization, // pattern
13753 DeductionFailure, /*NumArgs=*/0, TakingCandidateAddress: ForTakingAddress,
13754 CandidateSetKind);
13755}
13756
13757void TemplateSpecCandidateSet::destroyCandidates() {
13758 for (iterator i = begin(), e = end(); i != e; ++i) {
13759 i->DeductionFailure.Destroy();
13760 }
13761}
13762
13763void TemplateSpecCandidateSet::clear() {
13764 destroyCandidates();
13765 Candidates.clear();
13766}
13767
13768/// NoteCandidates - When no template specialization match is found, prints
13769/// diagnostic messages containing the non-matching specializations that form
13770/// the candidate set.
13771/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13772/// OCD == OCD_AllCandidates and Cand->Viable == false.
13773void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
13774 // Sort the candidates by position (assuming no candidate is a match).
13775 // Sorting directly would be prohibitive, so we make a set of pointers
13776 // and sort those.
13777 SmallVector<TemplateSpecCandidate *, 32> Cands;
13778 Cands.reserve(N: size());
13779 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13780 if (Cand->Specialization)
13781 Cands.push_back(Elt: Cand);
13782 // Otherwise, this is a non-matching builtin candidate. We do not,
13783 // in general, want to list every possible builtin candidate.
13784 }
13785
13786 llvm::sort(C&: Cands, Comp: CompareTemplateSpecCandidatesForDisplay(S));
13787
13788 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13789 // for generalization purposes (?).
13790 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13791
13792 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
13793 unsigned CandsShown = 0;
13794 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13795 TemplateSpecCandidate *Cand = *I;
13796
13797 // Set an arbitrary limit on the number of candidates we'll spam
13798 // the user with. FIXME: This limit should depend on details of the
13799 // candidate list.
13800 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13801 break;
13802 ++CandsShown;
13803
13804 assert(Cand->Specialization &&
13805 "Non-matching built-in candidates are not added to Cands.");
13806 Cand->NoteDeductionFailure(S, ForTakingAddress, CandidateSetKind);
13807 }
13808
13809 if (I != E)
13810 S.Diag(Loc, DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
13811}
13812
13813// [PossiblyAFunctionType] --> [Return]
13814// NonFunctionType --> NonFunctionType
13815// R (A) --> R(A)
13816// R (*)(A) --> R (A)
13817// R (&)(A) --> R (A)
13818// R (S::*)(A) --> R (A)
13819QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
13820 QualType Ret = PossiblyAFunctionType;
13821 if (const PointerType *ToTypePtr =
13822 PossiblyAFunctionType->getAs<PointerType>())
13823 Ret = ToTypePtr->getPointeeType();
13824 else if (const ReferenceType *ToTypeRef =
13825 PossiblyAFunctionType->getAs<ReferenceType>())
13826 Ret = ToTypeRef->getPointeeType();
13827 else if (const MemberPointerType *MemTypePtr =
13828 PossiblyAFunctionType->getAs<MemberPointerType>())
13829 Ret = MemTypePtr->getPointeeType();
13830 Ret =
13831 Context.getCanonicalType(T: Ret).getUnqualifiedType();
13832 return Ret;
13833}
13834
13835static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
13836 bool Complain = true) {
13837 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13838 S.DeduceReturnType(FD, Loc, Diagnose: Complain))
13839 return true;
13840
13841 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13842 if (S.getLangOpts().CPlusPlus17 &&
13843 isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType()) &&
13844 !S.ResolveExceptionSpec(Loc, FPT))
13845 return true;
13846
13847 return false;
13848}
13849
13850namespace {
13851// A helper class to help with address of function resolution
13852// - allows us to avoid passing around all those ugly parameters
13853class AddressOfFunctionResolver {
13854 Sema& S;
13855 Expr* SourceExpr;
13856 const QualType& TargetType;
13857 QualType TargetFunctionType; // Extracted function type from target type
13858
13859 bool Complain;
13860 //DeclAccessPair& ResultFunctionAccessPair;
13861 ASTContext& Context;
13862
13863 bool TargetTypeIsNonStaticMemberFunction;
13864 bool FoundNonTemplateFunction;
13865 bool StaticMemberFunctionFromBoundPointer;
13866 bool HasComplained;
13867
13868 OverloadExpr::FindResult OvlExprInfo;
13869 OverloadExpr *OvlExpr;
13870 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13871 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13872 TemplateSpecCandidateSet FailedCandidates;
13873
13874public:
13875 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13876 const QualType &TargetType, bool Complain)
13877 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13878 Complain(Complain), Context(S.getASTContext()),
13879 TargetTypeIsNonStaticMemberFunction(
13880 !!TargetType->getAs<MemberPointerType>()),
13881 FoundNonTemplateFunction(false),
13882 StaticMemberFunctionFromBoundPointer(false),
13883 HasComplained(false),
13884 OvlExprInfo(OverloadExpr::find(E: SourceExpr)),
13885 OvlExpr(OvlExprInfo.Expression),
13886 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13887 ExtractUnqualifiedFunctionTypeFromTargetType();
13888
13889 if (TargetFunctionType->isFunctionType()) {
13890 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(Val: OvlExpr))
13891 if (!UME->isImplicitAccess() &&
13892 !S.ResolveSingleFunctionTemplateSpecialization(ovl: UME))
13893 StaticMemberFunctionFromBoundPointer = true;
13894 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13895 DeclAccessPair dap;
13896 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13897 ovl: OvlExpr, Complain: false, Found: &dap)) {
13898 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn))
13899 if (!Method->isStatic()) {
13900 // If the target type is a non-function type and the function found
13901 // is a non-static member function, pretend as if that was the
13902 // target, it's the only possible type to end up with.
13903 TargetTypeIsNonStaticMemberFunction = true;
13904
13905 // And skip adding the function if its not in the proper form.
13906 // We'll diagnose this due to an empty set of functions.
13907 if (!OvlExprInfo.HasFormOfMemberPointer)
13908 return;
13909 }
13910
13911 Matches.push_back(Elt: std::make_pair(x&: dap, y&: Fn));
13912 }
13913 return;
13914 }
13915
13916 if (OvlExpr->hasExplicitTemplateArgs())
13917 OvlExpr->copyTemplateArgumentsInto(List&: OvlExplicitTemplateArgs);
13918
13919 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13920 if (Matches.size() > 1 && S.getLangOpts().CUDA)
13921 EliminateSuboptimalCudaMatches();
13922
13923 // C++ [over.over]p4:
13924 // If more than one function is selected, [...]
13925 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13926 if (FoundNonTemplateFunction) {
13927 EliminateAllTemplateMatches();
13928 EliminateLessPartialOrderingConstrainedMatches();
13929 } else
13930 EliminateAllExceptMostSpecializedTemplate();
13931 }
13932 }
13933 }
13934
13935 bool hasComplained() const { return HasComplained; }
13936
13937private:
13938 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13939 return Context.hasSameUnqualifiedType(T1: TargetFunctionType, T2: FD->getType()) ||
13940 S.IsFunctionConversion(FromType: FD->getType(), ToType: TargetFunctionType);
13941 }
13942
13943 /// \return true if A is considered a better overload candidate for the
13944 /// desired type than B.
13945 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13946 // If A doesn't have exactly the correct type, we don't want to classify it
13947 // as "better" than anything else. This way, the user is required to
13948 // disambiguate for us if there are multiple candidates and no exact match.
13949 return candidateHasExactlyCorrectType(FD: A) &&
13950 (!candidateHasExactlyCorrectType(FD: B) ||
13951 compareEnableIfAttrs(S, Cand1: A, Cand2: B) == Comparison::Better);
13952 }
13953
13954 /// \return true if we were able to eliminate all but one overload candidate,
13955 /// false otherwise.
13956 bool eliminiateSuboptimalOverloadCandidates() {
13957 // Same algorithm as overload resolution -- one pass to pick the "best",
13958 // another pass to be sure that nothing is better than the best.
13959 auto Best = Matches.begin();
13960 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13961 if (isBetterCandidate(A: I->second, B: Best->second))
13962 Best = I;
13963
13964 const FunctionDecl *BestFn = Best->second;
13965 auto IsBestOrInferiorToBest = [this, BestFn](
13966 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13967 return BestFn == Pair.second || isBetterCandidate(A: BestFn, B: Pair.second);
13968 };
13969
13970 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13971 // option, so we can potentially give the user a better error
13972 if (!llvm::all_of(Range&: Matches, P: IsBestOrInferiorToBest))
13973 return false;
13974 Matches[0] = *Best;
13975 Matches.resize(N: 1);
13976 return true;
13977 }
13978
13979 bool isTargetTypeAFunction() const {
13980 return TargetFunctionType->isFunctionType();
13981 }
13982
13983 // [ToType] [Return]
13984
13985 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13986 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13987 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13988 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13989 TargetFunctionType = S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: TargetType);
13990 }
13991
13992 // return true if any matching specializations were found
13993 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13994 const DeclAccessPair& CurAccessFunPair) {
13995 if (CXXMethodDecl *Method
13996 = dyn_cast<CXXMethodDecl>(Val: FunctionTemplate->getTemplatedDecl())) {
13997 // Skip non-static function templates when converting to pointer, and
13998 // static when converting to member pointer.
13999 bool CanConvertToFunctionPointer =
14000 Method->isStatic() || Method->isExplicitObjectMemberFunction();
14001 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
14002 return false;
14003 }
14004 else if (TargetTypeIsNonStaticMemberFunction)
14005 return false;
14006
14007 // C++ [over.over]p2:
14008 // If the name is a function template, template argument deduction is
14009 // done (14.8.2.2), and if the argument deduction succeeds, the
14010 // resulting template argument list is used to generate a single
14011 // function template specialization, which is added to the set of
14012 // overloaded functions considered.
14013 FunctionDecl *Specialization = nullptr;
14014 TemplateDeductionInfo Info(FailedCandidates.getLocation());
14015 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
14016 FunctionTemplate, ExplicitTemplateArgs: &OvlExplicitTemplateArgs, ArgFunctionType: TargetFunctionType,
14017 Specialization, Info, /*IsAddressOfFunction*/ true);
14018 Result != TemplateDeductionResult::Success) {
14019 // Make a note of the failed deduction for diagnostics.
14020 FailedCandidates.addCandidate()
14021 .set(Found: CurAccessFunPair, Spec: FunctionTemplate->getTemplatedDecl(),
14022 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
14023 return false;
14024 }
14025
14026 // Template argument deduction ensures that we have an exact match or
14027 // compatible pointer-to-function arguments that would be adjusted by ICS.
14028 // This function template specicalization works.
14029 assert(S.isSameOrCompatibleFunctionType(
14030 Context.getCanonicalType(Specialization->getType()),
14031 Context.getCanonicalType(TargetFunctionType)));
14032
14033 if (!S.checkAddressOfFunctionIsAvailable(Function: Specialization))
14034 return false;
14035
14036 Matches.push_back(Elt: std::make_pair(x: CurAccessFunPair, y&: Specialization));
14037 return true;
14038 }
14039
14040 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
14041 const DeclAccessPair& CurAccessFunPair) {
14042 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn)) {
14043 // Skip non-static functions when converting to pointer, and static
14044 // when converting to member pointer.
14045 bool CanConvertToFunctionPointer =
14046 Method->isStatic() || Method->isExplicitObjectMemberFunction();
14047 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
14048 return false;
14049 }
14050 else if (TargetTypeIsNonStaticMemberFunction)
14051 return false;
14052
14053 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Val: Fn)) {
14054 if (S.getLangOpts().CUDA) {
14055 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
14056 if (!(Caller && Caller->isImplicit()) &&
14057 !S.CUDA().IsAllowedCall(Caller, Callee: FunDecl))
14058 return false;
14059 }
14060 if (FunDecl->isMultiVersion()) {
14061 const auto *TA = FunDecl->getAttr<TargetAttr>();
14062 if (TA && !TA->isDefaultVersion())
14063 return false;
14064 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
14065 if (TVA && !TVA->isDefaultVersion())
14066 return false;
14067 }
14068
14069 // If any candidate has a placeholder return type, trigger its deduction
14070 // now.
14071 if (completeFunctionType(S, FD: FunDecl, Loc: SourceExpr->getBeginLoc(),
14072 Complain)) {
14073 HasComplained |= Complain;
14074 return false;
14075 }
14076
14077 if (!S.checkAddressOfFunctionIsAvailable(Function: FunDecl))
14078 return false;
14079
14080 // If we're in C, we need to support types that aren't exactly identical.
14081 if (!S.getLangOpts().CPlusPlus ||
14082 candidateHasExactlyCorrectType(FD: FunDecl)) {
14083 Matches.push_back(Elt: std::make_pair(
14084 x: CurAccessFunPair, y: cast<FunctionDecl>(Val: FunDecl->getCanonicalDecl())));
14085 FoundNonTemplateFunction = true;
14086 return true;
14087 }
14088 }
14089
14090 return false;
14091 }
14092
14093 bool FindAllFunctionsThatMatchTargetTypeExactly() {
14094 bool Ret = false;
14095
14096 // If the overload expression doesn't have the form of a pointer to
14097 // member, don't try to convert it to a pointer-to-member type.
14098 if (IsInvalidFormOfPointerToMemberFunction())
14099 return false;
14100
14101 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
14102 E = OvlExpr->decls_end();
14103 I != E; ++I) {
14104 // Look through any using declarations to find the underlying function.
14105 NamedDecl *Fn = (*I)->getUnderlyingDecl();
14106
14107 // C++ [over.over]p3:
14108 // Non-member functions and static member functions match
14109 // targets of type "pointer-to-function" or "reference-to-function."
14110 // Nonstatic member functions match targets of
14111 // type "pointer-to-member-function."
14112 // Note that according to DR 247, the containing class does not matter.
14113 if (FunctionTemplateDecl *FunctionTemplate
14114 = dyn_cast<FunctionTemplateDecl>(Val: Fn)) {
14115 if (AddMatchingTemplateFunction(FunctionTemplate, CurAccessFunPair: I.getPair()))
14116 Ret = true;
14117 }
14118 // If we have explicit template arguments supplied, skip non-templates.
14119 else if (!OvlExpr->hasExplicitTemplateArgs() &&
14120 AddMatchingNonTemplateFunction(Fn, CurAccessFunPair: I.getPair()))
14121 Ret = true;
14122 }
14123 assert(Ret || Matches.empty());
14124 return Ret;
14125 }
14126
14127 void EliminateAllExceptMostSpecializedTemplate() {
14128 // [...] and any given function template specialization F1 is
14129 // eliminated if the set contains a second function template
14130 // specialization whose function template is more specialized
14131 // than the function template of F1 according to the partial
14132 // ordering rules of 14.5.5.2.
14133
14134 // The algorithm specified above is quadratic. We instead use a
14135 // two-pass algorithm (similar to the one used to identify the
14136 // best viable function in an overload set) that identifies the
14137 // best function template (if it exists).
14138
14139 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
14140 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
14141 MatchesCopy.addDecl(D: Matches[I].second, AS: Matches[I].first.getAccess());
14142
14143 // TODO: It looks like FailedCandidates does not serve much purpose
14144 // here, since the no_viable diagnostic has index 0.
14145 UnresolvedSetIterator Result = S.getMostSpecialized(
14146 SBegin: MatchesCopy.begin(), SEnd: MatchesCopy.end(), FailedCandidates,
14147 Loc: SourceExpr->getBeginLoc(), NoneDiag: S.PDiag(),
14148 AmbigDiag: S.PDiag(DiagID: diag::err_addr_ovl_ambiguous)
14149 << Matches[0].second->getDeclName(),
14150 CandidateDiag: S.PDiag(DiagID: diag::note_ovl_candidate)
14151 << (unsigned)oc_function << (unsigned)ocs_described_template,
14152 Complain, TargetType: TargetFunctionType);
14153
14154 if (Result != MatchesCopy.end()) {
14155 // Make it the first and only element
14156 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
14157 Matches[0].second = cast<FunctionDecl>(Val: *Result);
14158 Matches.resize(N: 1);
14159 } else
14160 HasComplained |= Complain;
14161 }
14162
14163 void EliminateAllTemplateMatches() {
14164 // [...] any function template specializations in the set are
14165 // eliminated if the set also contains a non-template function, [...]
14166 for (unsigned I = 0, N = Matches.size(); I != N; ) {
14167 if (Matches[I].second->getPrimaryTemplate() == nullptr)
14168 ++I;
14169 else {
14170 Matches[I] = Matches[--N];
14171 Matches.resize(N);
14172 }
14173 }
14174 }
14175
14176 void EliminateLessPartialOrderingConstrainedMatches() {
14177 // C++ [over.over]p5:
14178 // [...] Any given non-template function F0 is eliminated if the set
14179 // contains a second non-template function that is more
14180 // partial-ordering-constrained than F0. [...]
14181 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
14182 "Call EliminateAllTemplateMatches() first");
14183 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
14184 Results.push_back(Elt: Matches[0]);
14185 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
14186 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
14187 FunctionDecl *F = getMorePartialOrderingConstrained(
14188 S, Fn1: Matches[I].second, Fn2: Results[0].second,
14189 /*IsFn1Reversed=*/false,
14190 /*IsFn2Reversed=*/false);
14191 if (!F) {
14192 Results.push_back(Elt: Matches[I]);
14193 continue;
14194 }
14195 if (F == Matches[I].second) {
14196 Results.clear();
14197 Results.push_back(Elt: Matches[I]);
14198 }
14199 }
14200 std::swap(LHS&: Matches, RHS&: Results);
14201 }
14202
14203 void EliminateSuboptimalCudaMatches() {
14204 S.CUDA().EraseUnwantedMatches(Caller: S.getCurFunctionDecl(/*AllowLambda=*/true),
14205 Matches);
14206 }
14207
14208public:
14209 void ComplainNoMatchesFound() const {
14210 assert(Matches.empty());
14211 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_no_viable)
14212 << OvlExpr->getName() << TargetFunctionType
14213 << OvlExpr->getSourceRange();
14214 if (FailedCandidates.empty())
14215 S.NoteAllOverloadCandidates(OverloadedExpr: OvlExpr, DestType: TargetFunctionType,
14216 /*TakingAddress=*/true);
14217 else {
14218 // We have some deduction failure messages. Use them to diagnose
14219 // the function templates, and diagnose the non-template candidates
14220 // normally.
14221 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
14222 IEnd = OvlExpr->decls_end();
14223 I != IEnd; ++I)
14224 if (FunctionDecl *Fun =
14225 dyn_cast<FunctionDecl>(Val: (*I)->getUnderlyingDecl()))
14226 if (!functionHasPassObjectSizeParams(FD: Fun))
14227 S.NoteOverloadCandidate(Found: *I, Fn: Fun, RewriteKind: CRK_None, DestType: TargetFunctionType,
14228 /*TakingAddress=*/true);
14229 FailedCandidates.NoteCandidates(S, Loc: OvlExpr->getBeginLoc());
14230 }
14231 }
14232
14233 bool IsInvalidFormOfPointerToMemberFunction() const {
14234 return TargetTypeIsNonStaticMemberFunction &&
14235 !OvlExprInfo.HasFormOfMemberPointer;
14236 }
14237
14238 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
14239 // TODO: Should we condition this on whether any functions might
14240 // have matched, or is it more appropriate to do that in callers?
14241 // TODO: a fixit wouldn't hurt.
14242 S.Diag(Loc: OvlExpr->getNameLoc(), DiagID: diag::err_addr_ovl_no_qualifier)
14243 << TargetType << OvlExpr->getSourceRange();
14244 }
14245
14246 bool IsStaticMemberFunctionFromBoundPointer() const {
14247 return StaticMemberFunctionFromBoundPointer;
14248 }
14249
14250 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
14251 S.Diag(Loc: OvlExpr->getBeginLoc(),
14252 DiagID: diag::err_invalid_form_pointer_member_function)
14253 << OvlExpr->getSourceRange();
14254 }
14255
14256 void ComplainOfInvalidConversion() const {
14257 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_not_func_ptrref)
14258 << OvlExpr->getName() << TargetType;
14259 }
14260
14261 void ComplainMultipleMatchesFound() const {
14262 assert(Matches.size() > 1);
14263 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_ambiguous)
14264 << OvlExpr->getName() << OvlExpr->getSourceRange();
14265 S.NoteAllOverloadCandidates(OverloadedExpr: OvlExpr, DestType: TargetFunctionType,
14266 /*TakingAddress=*/true);
14267 }
14268
14269 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
14270
14271 int getNumMatches() const { return Matches.size(); }
14272
14273 FunctionDecl* getMatchingFunctionDecl() const {
14274 if (Matches.size() != 1) return nullptr;
14275 return Matches[0].second;
14276 }
14277
14278 const DeclAccessPair* getMatchingFunctionAccessPair() const {
14279 if (Matches.size() != 1) return nullptr;
14280 return &Matches[0].first;
14281 }
14282};
14283}
14284
14285FunctionDecl *
14286Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
14287 QualType TargetType,
14288 bool Complain,
14289 DeclAccessPair &FoundResult,
14290 bool *pHadMultipleCandidates) {
14291 assert(AddressOfExpr->getType() == Context.OverloadTy);
14292
14293 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
14294 Complain);
14295 int NumMatches = Resolver.getNumMatches();
14296 FunctionDecl *Fn = nullptr;
14297 bool ShouldComplain = Complain && !Resolver.hasComplained();
14298 if (NumMatches == 0 && ShouldComplain) {
14299 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
14300 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
14301 else
14302 Resolver.ComplainNoMatchesFound();
14303 }
14304 else if (NumMatches > 1 && ShouldComplain)
14305 Resolver.ComplainMultipleMatchesFound();
14306 else if (NumMatches == 1) {
14307 Fn = Resolver.getMatchingFunctionDecl();
14308 assert(Fn);
14309 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
14310 ResolveExceptionSpec(Loc: AddressOfExpr->getExprLoc(), FPT);
14311 FoundResult = *Resolver.getMatchingFunctionAccessPair();
14312 if (Complain) {
14313 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
14314 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
14315 else
14316 CheckAddressOfMemberAccess(OvlExpr: AddressOfExpr, FoundDecl: FoundResult);
14317 }
14318 }
14319
14320 if (pHadMultipleCandidates)
14321 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
14322 return Fn;
14323}
14324
14325FunctionDecl *
14326Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
14327 OverloadExpr::FindResult R = OverloadExpr::find(E);
14328 OverloadExpr *Ovl = R.Expression;
14329 bool IsResultAmbiguous = false;
14330 FunctionDecl *Result = nullptr;
14331 DeclAccessPair DAP;
14332 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
14333
14334 // Return positive for better, negative for worse, 0 for equal preference.
14335 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
14336 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
14337 return static_cast<int>(CUDA().IdentifyPreference(Caller, Callee: FD1)) -
14338 static_cast<int>(CUDA().IdentifyPreference(Caller, Callee: FD2));
14339 };
14340
14341 // Don't use the AddressOfResolver because we're specifically looking for
14342 // cases where we have one overload candidate that lacks
14343 // enable_if/pass_object_size/...
14344 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
14345 auto *FD = dyn_cast<FunctionDecl>(Val: I->getUnderlyingDecl());
14346 if (!FD)
14347 return nullptr;
14348
14349 if (!checkAddressOfFunctionIsAvailable(Function: FD))
14350 continue;
14351
14352 // If we found a better result, update Result.
14353 auto FoundBetter = [&]() {
14354 IsResultAmbiguous = false;
14355 DAP = I.getPair();
14356 Result = FD;
14357 };
14358
14359 // We have more than one result - see if it is more
14360 // partial-ordering-constrained than the previous one.
14361 if (Result) {
14362 // Check CUDA preference first. If the candidates have differennt CUDA
14363 // preference, choose the one with higher CUDA preference. Otherwise,
14364 // choose the one with more constraints.
14365 if (getLangOpts().CUDA) {
14366 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
14367 // FD has different preference than Result.
14368 if (PreferenceByCUDA != 0) {
14369 // FD is more preferable than Result.
14370 if (PreferenceByCUDA > 0)
14371 FoundBetter();
14372 continue;
14373 }
14374 }
14375 // FD has the same CUDA preference than Result. Continue to check
14376 // constraints.
14377
14378 // C++ [over.over]p5:
14379 // [...] Any given non-template function F0 is eliminated if the set
14380 // contains a second non-template function that is more
14381 // partial-ordering-constrained than F0 [...]
14382 FunctionDecl *MoreConstrained =
14383 getMorePartialOrderingConstrained(S&: *this, Fn1: FD, Fn2: Result,
14384 /*IsFn1Reversed=*/false,
14385 /*IsFn2Reversed=*/false);
14386 if (MoreConstrained != FD) {
14387 if (!MoreConstrained) {
14388 IsResultAmbiguous = true;
14389 AmbiguousDecls.push_back(Elt: FD);
14390 }
14391 continue;
14392 }
14393 // FD is more constrained - replace Result with it.
14394 }
14395 FoundBetter();
14396 }
14397
14398 if (IsResultAmbiguous)
14399 return nullptr;
14400
14401 if (Result) {
14402 // We skipped over some ambiguous declarations which might be ambiguous with
14403 // the selected result.
14404 for (FunctionDecl *Skipped : AmbiguousDecls) {
14405 // If skipped candidate has different CUDA preference than the result,
14406 // there is no ambiguity. Otherwise check whether they have different
14407 // constraints.
14408 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
14409 continue;
14410 if (!getMoreConstrainedFunction(FD1: Skipped, FD2: Result))
14411 return nullptr;
14412 }
14413 Pair = DAP;
14414 }
14415 return Result;
14416}
14417
14418bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
14419 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
14420 Expr *E = SrcExpr.get();
14421 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
14422
14423 DeclAccessPair DAP;
14424 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, Pair&: DAP);
14425 if (!Found || Found->isCPUDispatchMultiVersion() ||
14426 Found->isCPUSpecificMultiVersion())
14427 return false;
14428
14429 // Emitting multiple diagnostics for a function that is both inaccessible and
14430 // unavailable is consistent with our behavior elsewhere. So, always check
14431 // for both.
14432 DiagnoseUseOfDecl(D: Found, Locs: E->getExprLoc());
14433 CheckAddressOfMemberAccess(OvlExpr: E, FoundDecl: DAP);
14434 ExprResult Res = FixOverloadedFunctionReference(E, FoundDecl: DAP, Fn: Found);
14435 if (Res.isInvalid())
14436 return false;
14437 Expr *Fixed = Res.get();
14438 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14439 SrcExpr = DefaultFunctionArrayConversion(E: Fixed, /*Diagnose=*/false);
14440 else
14441 SrcExpr = Fixed;
14442 return true;
14443}
14444
14445FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(
14446 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14447 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14448 // C++ [over.over]p1:
14449 // [...] [Note: any redundant set of parentheses surrounding the
14450 // overloaded function name is ignored (5.1). ]
14451 // C++ [over.over]p1:
14452 // [...] The overloaded function name can be preceded by the &
14453 // operator.
14454
14455 // If we didn't actually find any template-ids, we're done.
14456 if (!ovl->hasExplicitTemplateArgs())
14457 return nullptr;
14458
14459 TemplateArgumentListInfo ExplicitTemplateArgs;
14460 ovl->copyTemplateArgumentsInto(List&: ExplicitTemplateArgs);
14461
14462 // Look through all of the overloaded functions, searching for one
14463 // whose type matches exactly.
14464 FunctionDecl *Matched = nullptr;
14465 for (UnresolvedSetIterator I = ovl->decls_begin(),
14466 E = ovl->decls_end(); I != E; ++I) {
14467 // C++0x [temp.arg.explicit]p3:
14468 // [...] In contexts where deduction is done and fails, or in contexts
14469 // where deduction is not done, if a template argument list is
14470 // specified and it, along with any default template arguments,
14471 // identifies a single function template specialization, then the
14472 // template-id is an lvalue for the function template specialization.
14473 FunctionTemplateDecl *FunctionTemplate =
14474 dyn_cast<FunctionTemplateDecl>(Val: (*I)->getUnderlyingDecl());
14475 if (!FunctionTemplate)
14476 continue;
14477
14478 // C++ [over.over]p2:
14479 // If the name is a function template, template argument deduction is
14480 // done (14.8.2.2), and if the argument deduction succeeds, the
14481 // resulting template argument list is used to generate a single
14482 // function template specialization, which is added to the set of
14483 // overloaded functions considered.
14484 FunctionDecl *Specialization = nullptr;
14485 TemplateDeductionInfo Info(ovl->getNameLoc());
14486 if (TemplateDeductionResult Result = DeduceTemplateArguments(
14487 FunctionTemplate, ExplicitTemplateArgs: &ExplicitTemplateArgs, Specialization, Info,
14488 /*IsAddressOfFunction*/ true);
14489 Result != TemplateDeductionResult::Success) {
14490 // Make a note of the failed deduction for diagnostics.
14491 if (FailedTSC)
14492 FailedTSC->addCandidate().set(
14493 Found: I.getPair(), Spec: FunctionTemplate->getTemplatedDecl(),
14494 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
14495 continue;
14496 }
14497
14498 assert(Specialization && "no specialization and no error?");
14499
14500 // C++ [temp.deduct.call]p6:
14501 // [...] If all successful deductions yield the same deduced A, that
14502 // deduced A is the result of deduction; otherwise, the parameter is
14503 // treated as a non-deduced context.
14504 if (Matched) {
14505 if (ForTypeDeduction &&
14506 isSameOrCompatibleFunctionType(Param: Matched->getType(),
14507 Arg: Specialization->getType()))
14508 continue;
14509 // Multiple matches; we can't resolve to a single declaration.
14510 if (Complain) {
14511 Diag(Loc: ovl->getExprLoc(), DiagID: diag::err_addr_ovl_ambiguous)
14512 << ovl->getName();
14513 NoteAllOverloadCandidates(OverloadedExpr: ovl);
14514 }
14515 return nullptr;
14516 }
14517
14518 Matched = Specialization;
14519 if (FoundResult) *FoundResult = I.getPair();
14520 }
14521
14522 if (Matched &&
14523 completeFunctionType(S&: *this, FD: Matched, Loc: ovl->getExprLoc(), Complain))
14524 return nullptr;
14525
14526 return Matched;
14527}
14528
14529bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
14530 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14531 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14532 unsigned DiagIDForComplaining) {
14533 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14534
14535 OverloadExpr::FindResult ovl = OverloadExpr::find(E: SrcExpr.get());
14536
14537 DeclAccessPair found;
14538 ExprResult SingleFunctionExpression;
14539 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
14540 ovl: ovl.Expression, /*complain*/ Complain: false, FoundResult: &found)) {
14541 if (DiagnoseUseOfDecl(D: fn, Locs: SrcExpr.get()->getBeginLoc())) {
14542 SrcExpr = ExprError();
14543 return true;
14544 }
14545
14546 // It is only correct to resolve to an instance method if we're
14547 // resolving a form that's permitted to be a pointer to member.
14548 // Otherwise we'll end up making a bound member expression, which
14549 // is illegal in all the contexts we resolve like this.
14550 if (!ovl.HasFormOfMemberPointer &&
14551 isa<CXXMethodDecl>(Val: fn) &&
14552 cast<CXXMethodDecl>(Val: fn)->isInstance()) {
14553 if (!complain) return false;
14554
14555 Diag(Loc: ovl.Expression->getExprLoc(),
14556 DiagID: diag::err_bound_member_function)
14557 << 0 << ovl.Expression->getSourceRange();
14558
14559 // TODO: I believe we only end up here if there's a mix of
14560 // static and non-static candidates (otherwise the expression
14561 // would have 'bound member' type, not 'overload' type).
14562 // Ideally we would note which candidate was chosen and why
14563 // the static candidates were rejected.
14564 SrcExpr = ExprError();
14565 return true;
14566 }
14567
14568 // Fix the expression to refer to 'fn'.
14569 SingleFunctionExpression =
14570 FixOverloadedFunctionReference(E: SrcExpr.get(), FoundDecl: found, Fn: fn);
14571
14572 // If desired, do function-to-pointer decay.
14573 if (doFunctionPointerConversion) {
14574 SingleFunctionExpression =
14575 DefaultFunctionArrayLvalueConversion(E: SingleFunctionExpression.get());
14576 if (SingleFunctionExpression.isInvalid()) {
14577 SrcExpr = ExprError();
14578 return true;
14579 }
14580 }
14581 }
14582
14583 if (!SingleFunctionExpression.isUsable()) {
14584 if (complain) {
14585 Diag(Loc: OpRangeForComplaining.getBegin(), DiagID: DiagIDForComplaining)
14586 << ovl.Expression->getName()
14587 << DestTypeForComplaining
14588 << OpRangeForComplaining
14589 << ovl.Expression->getQualifierLoc().getSourceRange();
14590 NoteAllOverloadCandidates(OverloadedExpr: SrcExpr.get());
14591
14592 SrcExpr = ExprError();
14593 return true;
14594 }
14595
14596 return false;
14597 }
14598
14599 SrcExpr = SingleFunctionExpression;
14600 return true;
14601}
14602
14603/// Add a single candidate to the overload set.
14604static void AddOverloadedCallCandidate(Sema &S,
14605 DeclAccessPair FoundDecl,
14606 TemplateArgumentListInfo *ExplicitTemplateArgs,
14607 ArrayRef<Expr *> Args,
14608 OverloadCandidateSet &CandidateSet,
14609 bool PartialOverloading,
14610 bool KnownValid) {
14611 NamedDecl *Callee = FoundDecl.getDecl();
14612 if (isa<UsingShadowDecl>(Val: Callee))
14613 Callee = cast<UsingShadowDecl>(Val: Callee)->getTargetDecl();
14614
14615 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: Callee)) {
14616 if (ExplicitTemplateArgs) {
14617 assert(!KnownValid && "Explicit template arguments?");
14618 return;
14619 }
14620 // Prevent ill-formed function decls to be added as overload candidates.
14621 if (!isa<FunctionProtoType>(Val: Func->getType()->getAs<FunctionType>()))
14622 return;
14623
14624 S.AddOverloadCandidate(Function: Func, FoundDecl, Args, CandidateSet,
14625 /*SuppressUserConversions=*/false,
14626 PartialOverloading);
14627 return;
14628 }
14629
14630 if (FunctionTemplateDecl *FuncTemplate
14631 = dyn_cast<FunctionTemplateDecl>(Val: Callee)) {
14632 S.AddTemplateOverloadCandidate(FunctionTemplate: FuncTemplate, FoundDecl,
14633 ExplicitTemplateArgs, Args, CandidateSet,
14634 /*SuppressUserConversions=*/false,
14635 PartialOverloading);
14636 return;
14637 }
14638
14639 assert(!KnownValid && "unhandled case in overloaded call candidate");
14640}
14641
14642void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
14643 ArrayRef<Expr *> Args,
14644 OverloadCandidateSet &CandidateSet,
14645 bool PartialOverloading) {
14646
14647#ifndef NDEBUG
14648 // Verify that ArgumentDependentLookup is consistent with the rules
14649 // in C++0x [basic.lookup.argdep]p3:
14650 //
14651 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14652 // and let Y be the lookup set produced by argument dependent
14653 // lookup (defined as follows). If X contains
14654 //
14655 // -- a declaration of a class member, or
14656 //
14657 // -- a block-scope function declaration that is not a
14658 // using-declaration, or
14659 //
14660 // -- a declaration that is neither a function or a function
14661 // template
14662 //
14663 // then Y is empty.
14664
14665 if (ULE->requiresADL()) {
14666 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
14667 E = ULE->decls_end(); I != E; ++I) {
14668 assert(!(*I)->getDeclContext()->isRecord());
14669 assert(isa<UsingShadowDecl>(*I) ||
14670 !(*I)->getDeclContext()->isFunctionOrMethod());
14671 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14672 }
14673 }
14674#endif
14675
14676 // It would be nice to avoid this copy.
14677 TemplateArgumentListInfo TABuffer;
14678 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14679 if (ULE->hasExplicitTemplateArgs()) {
14680 ULE->copyTemplateArgumentsInto(List&: TABuffer);
14681 ExplicitTemplateArgs = &TABuffer;
14682 }
14683
14684 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
14685 E = ULE->decls_end(); I != E; ++I)
14686 AddOverloadedCallCandidate(S&: *this, FoundDecl: I.getPair(), ExplicitTemplateArgs, Args,
14687 CandidateSet, PartialOverloading,
14688 /*KnownValid*/ true);
14689
14690 if (ULE->requiresADL())
14691 AddArgumentDependentLookupCandidates(Name: ULE->getName(), Loc: ULE->getExprLoc(),
14692 Args, ExplicitTemplateArgs,
14693 CandidateSet, PartialOverloading);
14694}
14695
14696void Sema::AddOverloadedCallCandidates(
14697 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14698 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14699 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14700 AddOverloadedCallCandidate(S&: *this, FoundDecl: I.getPair(), ExplicitTemplateArgs, Args,
14701 CandidateSet, PartialOverloading: false, /*KnownValid*/ false);
14702}
14703
14704/// Determine whether a declaration with the specified name could be moved into
14705/// a different namespace.
14706static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
14707 switch (Name.getCXXOverloadedOperator()) {
14708 case OO_New: case OO_Array_New:
14709 case OO_Delete: case OO_Array_Delete:
14710 return false;
14711
14712 default:
14713 return true;
14714 }
14715}
14716
14717/// Attempt to recover from an ill-formed use of a non-dependent name in a
14718/// template, where the non-dependent name was declared after the template
14719/// was defined. This is common in code written for compilers which do not
14720/// correctly implement two-stage name lookup.
14721///
14722/// Returns true if a viable candidate was found and a diagnostic was issued.
14723static bool DiagnoseTwoPhaseLookup(
14724 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14725 LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
14726 const OverloadCandidateSet &ResolvedCandidates,
14727 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14728 CXXRecordDecl **FoundInClass = nullptr) {
14729 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14730 return false;
14731
14732 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14733 if (DC->isTransparentContext())
14734 continue;
14735
14736 SemaRef.LookupQualifiedName(R, LookupCtx: DC);
14737
14738 if (!R.empty()) {
14739 R.suppressDiagnostics();
14740
14741 OverloadCandidateSet Candidates(FnLoc, CSK);
14742 // We have performed a BestViableFunction over these candidates, so
14743 // exclude them.
14744 for (auto &Cand : ResolvedCandidates) {
14745 if (Cand.Function)
14746 Candidates.exclude(F: Cand.Function);
14747 else if (Cand.IsSurrogate)
14748 Candidates.exclude(F: Cand.Surrogate);
14749 }
14750 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14751 CandidateSet&: Candidates);
14752
14753 OverloadCandidateSet::iterator Best;
14754 OverloadingResult OR =
14755 Candidates.BestViableFunction(S&: SemaRef, Loc: FnLoc, Best);
14756
14757 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC)) {
14758 // We either found non-function declarations or a best viable function
14759 // at class scope. A class-scope lookup result disables ADL. Don't
14760 // look past this, but let the caller know that we found something that
14761 // either is, or might be, usable in this class.
14762 if (FoundInClass) {
14763 *FoundInClass = RD;
14764 if (OR == OR_Success) {
14765 R.clear();
14766 R.addDecl(D: Best->FoundDecl.getDecl(), AS: Best->FoundDecl.getAccess());
14767 R.resolveKind();
14768 }
14769 }
14770 return false;
14771 }
14772
14773 if (OR != OR_Success) {
14774 // There wasn't a unique best function or function template.
14775 return false;
14776 }
14777
14778 // Find the namespaces where ADL would have looked, and suggest
14779 // declaring the function there instead.
14780 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14781 Sema::AssociatedClassSet AssociatedClasses;
14782 SemaRef.FindAssociatedClassesAndNamespaces(InstantiationLoc: FnLoc, Args,
14783 AssociatedNamespaces,
14784 AssociatedClasses);
14785 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14786 if (canBeDeclaredInNamespace(Name: R.getLookupName())) {
14787 DeclContext *Std = SemaRef.getStdNamespace();
14788 for (Sema::AssociatedNamespaceSet::iterator
14789 it = AssociatedNamespaces.begin(),
14790 end = AssociatedNamespaces.end(); it != end; ++it) {
14791 // Never suggest declaring a function within namespace 'std'.
14792 if (Std && Std->Encloses(DC: *it))
14793 continue;
14794
14795 // Never suggest declaring a function within a namespace with a
14796 // reserved name, like __gnu_cxx.
14797 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: *it);
14798 if (NS &&
14799 NS->getQualifiedNameAsString().find(s: "__") != std::string::npos)
14800 continue;
14801
14802 SuggestedNamespaces.insert(X: *it);
14803 }
14804 }
14805
14806 SemaRef.Diag(Loc: R.getNameLoc(), DiagID: diag::err_not_found_by_two_phase_lookup)
14807 << R.getLookupName();
14808 if (SuggestedNamespaces.empty()) {
14809 SemaRef.Diag(Loc: Best->Function->getLocation(),
14810 DiagID: diag::note_not_found_by_two_phase_lookup)
14811 << R.getLookupName() << 0;
14812 } else if (SuggestedNamespaces.size() == 1) {
14813 SemaRef.Diag(Loc: Best->Function->getLocation(),
14814 DiagID: diag::note_not_found_by_two_phase_lookup)
14815 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14816 } else {
14817 // FIXME: It would be useful to list the associated namespaces here,
14818 // but the diagnostics infrastructure doesn't provide a way to produce
14819 // a localized representation of a list of items.
14820 SemaRef.Diag(Loc: Best->Function->getLocation(),
14821 DiagID: diag::note_not_found_by_two_phase_lookup)
14822 << R.getLookupName() << 2;
14823 }
14824
14825 // Try to recover by calling this function.
14826 return true;
14827 }
14828
14829 R.clear();
14830 }
14831
14832 return false;
14833}
14834
14835/// Attempt to recover from ill-formed use of a non-dependent operator in a
14836/// template, where the non-dependent operator was declared after the template
14837/// was defined.
14838///
14839/// Returns true if a viable candidate was found and a diagnostic was issued.
14840static bool DiagnoseTwoPhaseOperatorLookup(
14841 Sema &SemaRef, OverloadedOperatorKind Op, SourceLocation OpLoc,
14842 ArrayRef<Expr *> Args, const OverloadCandidateSet &ResolvedCandidateSet) {
14843 DeclarationName OpName =
14844 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
14845 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14846 return DiagnoseTwoPhaseLookup(
14847 SemaRef, FnLoc: OpLoc, SS: CXXScopeSpec(), R, CSK: OverloadCandidateSet::CSK_Operator,
14848 ResolvedCandidates: ResolvedCandidateSet,
14849 /*ExplicitTemplateArgs=*/nullptr, Args, /*FoundInClass=*/nullptr);
14850}
14851
14852namespace {
14853class BuildRecoveryCallExprRAII {
14854 Sema &SemaRef;
14855 Sema::SatisfactionStackResetRAII SatStack;
14856
14857public:
14858 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14859 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14860 SemaRef.IsBuildingRecoveryCallExpr = true;
14861 }
14862
14863 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14864};
14865}
14866
14867/// Attempts to recover from a call where no functions were found.
14868///
14869/// This function will do one of three things:
14870/// * Diagnose, recover, and return a recovery expression.
14871/// * Diagnose, fail to recover, and return ExprError().
14872/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14873/// expected to diagnose as appropriate.
14874static ExprResult
14875BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
14876 UnresolvedLookupExpr *ULE, SourceLocation LParenLoc,
14877 MutableArrayRef<Expr *> Args, SourceLocation RParenLoc,
14878 const OverloadCandidateSet &ResolvedCandidateSet,
14879 bool AllowTypoCorrection) {
14880 // Do not try to recover if it is already building a recovery call.
14881 // This stops infinite loops for template instantiations like
14882 //
14883 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14884 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14885 if (SemaRef.IsBuildingRecoveryCallExpr)
14886 return ExprResult();
14887 BuildRecoveryCallExprRAII RCE(SemaRef);
14888
14889 CXXScopeSpec SS;
14890 SS.Adopt(Other: ULE->getQualifierLoc());
14891 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14892
14893 TemplateArgumentListInfo TABuffer;
14894 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14895 if (ULE->hasExplicitTemplateArgs()) {
14896 ULE->copyTemplateArgumentsInto(List&: TABuffer);
14897 ExplicitTemplateArgs = &TABuffer;
14898 }
14899
14900 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14901 Sema::LookupOrdinaryName);
14902 CXXRecordDecl *FoundInClass = nullptr;
14903 if (DiagnoseTwoPhaseLookup(
14904 SemaRef, FnLoc: Fn->getExprLoc(), SS, R, CSK: OverloadCandidateSet::CSK_Normal,
14905 ResolvedCandidates: ResolvedCandidateSet, ExplicitTemplateArgs, Args, FoundInClass: &FoundInClass)) {
14906 // OK, diagnosed a two-phase lookup issue.
14907 } else if (ResolvedCandidateSet.empty()) {
14908 // Try to recover from an empty lookup with typo correction.
14909 R.clear();
14910 NoTypoCorrectionCCC NoTypoValidator{};
14911 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14912 ExplicitTemplateArgs != nullptr,
14913 dyn_cast<MemberExpr>(Val: Fn));
14914 CorrectionCandidateCallback &Validator =
14915 AllowTypoCorrection
14916 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14917 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14918 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, CCC&: Validator, ExplicitTemplateArgs,
14919 Args))
14920 return ExprError();
14921 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14922 // We found a usable declaration of the name in a dependent base of some
14923 // enclosing class.
14924 // FIXME: We should also explain why the candidates found by name lookup
14925 // were not viable.
14926 if (SemaRef.DiagnoseDependentMemberLookup(R))
14927 return ExprError();
14928 } else {
14929 // We had viable candidates and couldn't recover; let the caller diagnose
14930 // this.
14931 return ExprResult();
14932 }
14933
14934 // If we get here, we should have issued a diagnostic and formed a recovery
14935 // lookup result.
14936 assert(!R.empty() && "lookup results empty despite recovery");
14937
14938 // If recovery created an ambiguity, just bail out.
14939 if (R.isAmbiguous()) {
14940 R.suppressDiagnostics();
14941 return ExprError();
14942 }
14943
14944 // Build an implicit member call if appropriate. Just drop the
14945 // casts and such from the call, we don't really care.
14946 ExprResult NewFn = ExprError();
14947 if ((*R.begin())->isCXXClassMember())
14948 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14949 TemplateArgs: ExplicitTemplateArgs, S);
14950 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14951 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL: false,
14952 TemplateArgs: ExplicitTemplateArgs);
14953 else
14954 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, NeedsADL: false);
14955
14956 if (NewFn.isInvalid())
14957 return ExprError();
14958
14959 // This shouldn't cause an infinite loop because we're giving it
14960 // an expression with viable lookup results, which should never
14961 // end up here.
14962 return SemaRef.BuildCallExpr(/*Scope*/ S: nullptr, Fn: NewFn.get(), LParenLoc,
14963 ArgExprs: MultiExprArg(Args.data(), Args.size()),
14964 RParenLoc);
14965}
14966
14967bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
14968 UnresolvedLookupExpr *ULE,
14969 MultiExprArg Args,
14970 SourceLocation RParenLoc,
14971 OverloadCandidateSet *CandidateSet,
14972 ExprResult *Result) {
14973#ifndef NDEBUG
14974 if (ULE->requiresADL()) {
14975 // To do ADL, we must have found an unqualified name.
14976 assert(!ULE->getQualifier() && "qualified name with ADL");
14977
14978 // We don't perform ADL for implicit declarations of builtins.
14979 // Verify that this was correctly set up.
14980 FunctionDecl *F;
14981 if (ULE->decls_begin() != ULE->decls_end() &&
14982 ULE->decls_begin() + 1 == ULE->decls_end() &&
14983 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14984 F->getBuiltinID() && F->isImplicit())
14985 llvm_unreachable("performing ADL for builtin");
14986
14987 // We don't perform ADL in C.
14988 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14989 }
14990#endif
14991
14992 UnbridgedCastsSet UnbridgedCasts;
14993 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts)) {
14994 *Result = ExprError();
14995 return true;
14996 }
14997
14998 // Add the functions denoted by the callee to the set of candidate
14999 // functions, including those from argument-dependent lookup.
15000 AddOverloadedCallCandidates(ULE, Args, CandidateSet&: *CandidateSet);
15001
15002 if (getLangOpts().MSVCCompat &&
15003 CurContext->isDependentContext() && !isSFINAEContext() &&
15004 (isa<FunctionDecl>(Val: CurContext) || isa<CXXRecordDecl>(Val: CurContext))) {
15005
15006 OverloadCandidateSet::iterator Best;
15007 if (CandidateSet->empty() ||
15008 CandidateSet->BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best) ==
15009 OR_No_Viable_Function) {
15010 // In Microsoft mode, if we are inside a template class member function
15011 // then create a type dependent CallExpr. The goal is to postpone name
15012 // lookup to instantiation time to be able to search into type dependent
15013 // base classes.
15014 CallExpr *CE =
15015 CallExpr::Create(Ctx: Context, Fn, Args, Ty: Context.DependentTy, VK: VK_PRValue,
15016 RParenLoc, FPFeatures: CurFPFeatureOverrides());
15017 CE->markDependentForPostponedNameLookup();
15018 *Result = CE;
15019 return true;
15020 }
15021 }
15022
15023 if (CandidateSet->empty())
15024 return false;
15025
15026 UnbridgedCasts.restore();
15027 return false;
15028}
15029
15030// Guess at what the return type for an unresolvable overload should be.
15031static QualType chooseRecoveryType(OverloadCandidateSet &CS,
15032 OverloadCandidateSet::iterator *Best) {
15033 std::optional<QualType> Result;
15034 // Adjust Type after seeing a candidate.
15035 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
15036 if (!Candidate.Function)
15037 return;
15038 if (Candidate.Function->isInvalidDecl())
15039 return;
15040 QualType T = Candidate.Function->getReturnType();
15041 if (T.isNull())
15042 return;
15043 if (!Result)
15044 Result = T;
15045 else if (Result != T)
15046 Result = QualType();
15047 };
15048
15049 // Look for an unambiguous type from a progressively larger subset.
15050 // e.g. if types disagree, but all *viable* overloads return int, choose int.
15051 //
15052 // First, consider only the best candidate.
15053 if (Best && *Best != CS.end())
15054 ConsiderCandidate(**Best);
15055 // Next, consider only viable candidates.
15056 if (!Result)
15057 for (const auto &C : CS)
15058 if (C.Viable)
15059 ConsiderCandidate(C);
15060 // Finally, consider all candidates.
15061 if (!Result)
15062 for (const auto &C : CS)
15063 ConsiderCandidate(C);
15064
15065 if (!Result)
15066 return QualType();
15067 auto Value = *Result;
15068 if (Value.isNull() || Value->isUndeducedType())
15069 return QualType();
15070 return Value;
15071}
15072
15073/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
15074/// the completed call expression. If overload resolution fails, emits
15075/// diagnostics and returns ExprError()
15076static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
15077 UnresolvedLookupExpr *ULE,
15078 SourceLocation LParenLoc,
15079 MultiExprArg Args,
15080 SourceLocation RParenLoc,
15081 Expr *ExecConfig,
15082 OverloadCandidateSet *CandidateSet,
15083 OverloadCandidateSet::iterator *Best,
15084 OverloadingResult OverloadResult,
15085 bool AllowTypoCorrection) {
15086 switch (OverloadResult) {
15087 case OR_Success: {
15088 FunctionDecl *FDecl = (*Best)->Function;
15089 SemaRef.CheckUnresolvedLookupAccess(E: ULE, FoundDecl: (*Best)->FoundDecl);
15090 if (SemaRef.DiagnoseUseOfDecl(D: FDecl, Locs: ULE->getNameLoc()))
15091 return ExprError();
15092 ExprResult Res =
15093 SemaRef.FixOverloadedFunctionReference(E: Fn, FoundDecl: (*Best)->FoundDecl, Fn: FDecl);
15094 if (Res.isInvalid())
15095 return ExprError();
15096 return SemaRef.BuildResolvedCallExpr(
15097 Fn: Res.get(), NDecl: FDecl, LParenLoc, Arg: Args, RParenLoc, Config: ExecConfig,
15098 /*IsExecConfig=*/false,
15099 UsesADL: static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
15100 }
15101
15102 case OR_No_Viable_Function: {
15103 if (*Best != CandidateSet->end() &&
15104 CandidateSet->getKind() ==
15105 clang::OverloadCandidateSet::CSK_AddressOfOverloadSet) {
15106 if (CXXMethodDecl *M =
15107 dyn_cast_if_present<CXXMethodDecl>(Val: (*Best)->Function);
15108 M && M->isImplicitObjectMemberFunction()) {
15109 CandidateSet->NoteCandidates(
15110 PD: PartialDiagnosticAt(
15111 Fn->getBeginLoc(),
15112 SemaRef.PDiag(DiagID: diag::err_member_call_without_object) << 0 << M),
15113 S&: SemaRef, OCD: OCD_AmbiguousCandidates, Args);
15114 return ExprError();
15115 }
15116 }
15117
15118 // Try to recover by looking for viable functions which the user might
15119 // have meant to call.
15120 ExprResult Recovery =
15121 BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, RParenLoc,
15122 ResolvedCandidateSet: *CandidateSet, AllowTypoCorrection);
15123 if (Recovery.isInvalid() || Recovery.isUsable())
15124 return Recovery;
15125
15126 // If the user passes in a function that we can't take the address of, we
15127 // generally end up emitting really bad error messages. Here, we attempt to
15128 // emit better ones.
15129 for (const Expr *Arg : Args) {
15130 if (!Arg->getType()->isFunctionType())
15131 continue;
15132 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: Arg->IgnoreParenImpCasts())) {
15133 auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl());
15134 if (FD &&
15135 !SemaRef.checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
15136 Loc: Arg->getExprLoc()))
15137 return ExprError();
15138 }
15139 }
15140
15141 CandidateSet->NoteCandidates(
15142 PD: PartialDiagnosticAt(
15143 Fn->getBeginLoc(),
15144 SemaRef.PDiag(DiagID: diag::err_ovl_no_viable_function_in_call)
15145 << ULE->getName() << Fn->getSourceRange()),
15146 S&: SemaRef, OCD: OCD_AllCandidates, Args);
15147 break;
15148 }
15149
15150 case OR_Ambiguous:
15151 CandidateSet->NoteCandidates(
15152 PD: PartialDiagnosticAt(Fn->getBeginLoc(),
15153 SemaRef.PDiag(DiagID: diag::err_ovl_ambiguous_call)
15154 << ULE->getName() << Fn->getSourceRange()),
15155 S&: SemaRef, OCD: OCD_AmbiguousCandidates, Args);
15156 break;
15157
15158 case OR_Deleted: {
15159 FunctionDecl *FDecl = (*Best)->Function;
15160 SemaRef.DiagnoseUseOfDeletedFunction(Loc: Fn->getBeginLoc(),
15161 Range: Fn->getSourceRange(), Name: ULE->getName(),
15162 CandidateSet&: *CandidateSet, Fn: FDecl, Args);
15163
15164 // We emitted an error for the unavailable/deleted function call but keep
15165 // the call in the AST.
15166 ExprResult Res =
15167 SemaRef.FixOverloadedFunctionReference(E: Fn, FoundDecl: (*Best)->FoundDecl, Fn: FDecl);
15168 if (Res.isInvalid())
15169 return ExprError();
15170 return SemaRef.BuildResolvedCallExpr(
15171 Fn: Res.get(), NDecl: FDecl, LParenLoc, Arg: Args, RParenLoc, Config: ExecConfig,
15172 /*IsExecConfig=*/false,
15173 UsesADL: static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
15174 }
15175 }
15176
15177 // Overload resolution failed, try to recover.
15178 SmallVector<Expr *, 8> SubExprs = {Fn};
15179 SubExprs.append(in_start: Args.begin(), in_end: Args.end());
15180 return SemaRef.CreateRecoveryExpr(Begin: Fn->getBeginLoc(), End: RParenLoc, SubExprs,
15181 T: chooseRecoveryType(CS&: *CandidateSet, Best));
15182}
15183
15184static void markUnaddressableCandidatesUnviable(Sema &S,
15185 OverloadCandidateSet &CS) {
15186 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
15187 if (I->Viable &&
15188 !S.checkAddressOfFunctionIsAvailable(Function: I->Function, /*Complain=*/false)) {
15189 I->Viable = false;
15190 I->FailureKind = ovl_fail_addr_not_available;
15191 }
15192 }
15193}
15194
15195ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
15196 UnresolvedLookupExpr *ULE,
15197 SourceLocation LParenLoc,
15198 MultiExprArg Args,
15199 SourceLocation RParenLoc,
15200 Expr *ExecConfig,
15201 bool AllowTypoCorrection,
15202 bool CalleesAddressIsTaken) {
15203
15204 OverloadCandidateSet::CandidateSetKind CSK =
15205 CalleesAddressIsTaken ? OverloadCandidateSet::CSK_AddressOfOverloadSet
15206 : OverloadCandidateSet::CSK_Normal;
15207
15208 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
15209 ExprResult result;
15210
15211 if (buildOverloadedCallSet(S, Fn, ULE, Args, RParenLoc: LParenLoc, CandidateSet: &CandidateSet,
15212 Result: &result))
15213 return result;
15214
15215 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
15216 // functions that aren't addressible are considered unviable.
15217 if (CalleesAddressIsTaken)
15218 markUnaddressableCandidatesUnviable(S&: *this, CS&: CandidateSet);
15219
15220 OverloadCandidateSet::iterator Best;
15221 OverloadingResult OverloadResult =
15222 CandidateSet.BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best);
15223
15224 // [C++23][over.call.func]
15225 // if overload resolution selects a non-static member function,
15226 // the call is ill-formed;
15227 if (CSK == OverloadCandidateSet::CSK_AddressOfOverloadSet &&
15228 Best != CandidateSet.end()) {
15229 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Val: Best->Function);
15230 M && M->isImplicitObjectMemberFunction()) {
15231 OverloadResult = OR_No_Viable_Function;
15232 }
15233 }
15234
15235 // Model the case with a call to a templated function whose definition
15236 // encloses the call and whose return type contains a placeholder type as if
15237 // the UnresolvedLookupExpr was type-dependent.
15238 if (OverloadResult == OR_Success) {
15239 const FunctionDecl *FDecl = Best->Function;
15240 if (LangOpts.CUDA)
15241 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
15242 if (FDecl && FDecl->isTemplateInstantiation() &&
15243 FDecl->getReturnType()->isUndeducedType()) {
15244
15245 // Creating dependent CallExpr is not okay if the enclosing context itself
15246 // is not dependent. This situation notably arises if a non-dependent
15247 // member function calls the later-defined overloaded static function.
15248 //
15249 // For example, in
15250 // class A {
15251 // void c() { callee(1); }
15252 // static auto callee(auto x) { }
15253 // };
15254 //
15255 // Here callee(1) is unresolved at the call site, but is not inside a
15256 // dependent context. There will be no further attempt to resolve this
15257 // call if it is made dependent.
15258
15259 if (const auto *TP =
15260 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
15261 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
15262 return CallExpr::Create(Ctx: Context, Fn, Args, Ty: Context.DependentTy,
15263 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
15264 }
15265 }
15266 }
15267
15268 return FinishOverloadedCallExpr(SemaRef&: *this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
15269 ExecConfig, CandidateSet: &CandidateSet, Best: &Best,
15270 OverloadResult, AllowTypoCorrection);
15271}
15272
15273ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
15274 NestedNameSpecifierLoc NNSLoc,
15275 DeclarationNameInfo DNI,
15276 const UnresolvedSetImpl &Fns,
15277 bool PerformADL) {
15278 return UnresolvedLookupExpr::Create(
15279 Context, NamingClass, QualifierLoc: NNSLoc, NameInfo: DNI, RequiresADL: PerformADL, Begin: Fns.begin(), End: Fns.end(),
15280 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
15281}
15282
15283ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
15284 CXXConversionDecl *Method,
15285 bool HadMultipleCandidates) {
15286 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
15287 // the FoundDecl as it impedes TransformMemberExpr.
15288 // We go a bit further here: if there's no difference in UnderlyingDecl,
15289 // then using FoundDecl vs Method shouldn't make a difference either.
15290 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
15291 FoundDecl = Method;
15292 // Convert the expression to match the conversion function's implicit object
15293 // parameter.
15294 ExprResult Exp;
15295 if (Method->isExplicitObjectMemberFunction())
15296 Exp = InitializeExplicitObjectArgument(S&: *this, Obj: E, Fun: Method);
15297 else
15298 Exp = PerformImplicitObjectArgumentInitialization(
15299 From: E, /*Qualifier=*/std::nullopt, FoundDecl, Method);
15300 if (Exp.isInvalid())
15301 return true;
15302
15303 if (Method->getParent()->isLambda() &&
15304 Method->getConversionType()->isBlockPointerType()) {
15305 // This is a lambda conversion to block pointer; check if the argument
15306 // was a LambdaExpr.
15307 Expr *SubE = E;
15308 auto *CE = dyn_cast<CastExpr>(Val: SubE);
15309 if (CE && CE->getCastKind() == CK_NoOp)
15310 SubE = CE->getSubExpr();
15311 SubE = SubE->IgnoreParens();
15312 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(Val: SubE))
15313 SubE = BE->getSubExpr();
15314 if (isa<LambdaExpr>(Val: SubE)) {
15315 // For the conversion to block pointer on a lambda expression, we
15316 // construct a special BlockLiteral instead; this doesn't really make
15317 // a difference in ARC, but outside of ARC the resulting block literal
15318 // follows the normal lifetime rules for block literals instead of being
15319 // autoreleased.
15320 PushExpressionEvaluationContext(
15321 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated);
15322 ExprResult BlockExp = BuildBlockForLambdaConversion(
15323 CurrentLocation: Exp.get()->getExprLoc(), ConvLocation: Exp.get()->getExprLoc(), Conv: Method, Src: Exp.get());
15324 PopExpressionEvaluationContext();
15325
15326 // FIXME: This note should be produced by a CodeSynthesisContext.
15327 if (BlockExp.isInvalid())
15328 Diag(Loc: Exp.get()->getExprLoc(), DiagID: diag::note_lambda_to_block_conv);
15329 return BlockExp;
15330 }
15331 }
15332 CallExpr *CE;
15333 QualType ResultType = Method->getReturnType();
15334 ExprValueKind VK = Expr::getValueKindForType(T: ResultType);
15335 ResultType = ResultType.getNonLValueExprType(Context);
15336 if (Method->isExplicitObjectMemberFunction()) {
15337 ExprResult FnExpr =
15338 CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl, Base: Exp.get(),
15339 HadMultipleCandidates, Loc: E->getBeginLoc());
15340 if (FnExpr.isInvalid())
15341 return ExprError();
15342 Expr *ObjectParam = Exp.get();
15343 CE = CallExpr::Create(Ctx: Context, Fn: FnExpr.get(), Args: MultiExprArg(&ObjectParam, 1),
15344 Ty: ResultType, VK, RParenLoc: Exp.get()->getEndLoc(),
15345 FPFeatures: CurFPFeatureOverrides());
15346 CE->setUsesMemberSyntax(true);
15347 } else {
15348 MemberExpr *ME =
15349 BuildMemberExpr(Base: Exp.get(), /*IsArrow=*/false, OpLoc: SourceLocation(),
15350 NNS: NestedNameSpecifierLoc(), TemplateKWLoc: SourceLocation(), Member: Method,
15351 FoundDecl: DeclAccessPair::make(D: FoundDecl, AS: FoundDecl->getAccess()),
15352 HadMultipleCandidates, MemberNameInfo: DeclarationNameInfo(),
15353 Ty: Context.BoundMemberTy, VK: VK_PRValue, OK: OK_Ordinary);
15354
15355 CE = CXXMemberCallExpr::Create(Ctx: Context, Fn: ME, /*Args=*/{}, Ty: ResultType, VK,
15356 RP: Exp.get()->getEndLoc(),
15357 FPFeatures: CurFPFeatureOverrides());
15358 }
15359
15360 if (CheckFunctionCall(FDecl: Method, TheCall: CE,
15361 Proto: Method->getType()->castAs<FunctionProtoType>()))
15362 return ExprError();
15363
15364 return CheckForImmediateInvocation(E: CE, Decl: CE->getDirectCallee());
15365}
15366
15367void Sema::LookupOverloadedUnaryOp(OverloadCandidateSet &CandidateSet,
15368 OverloadedOperatorKind Op,
15369 const UnresolvedSetImpl &Fns,
15370 ArrayRef<Expr *> Args, bool PerformADL) {
15371 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15372
15373 SourceLocation OpLoc = CandidateSet.getLocation();
15374 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15375
15376 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15377 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15378 if (PerformADL)
15379 AddArgumentDependentLookupCandidates(Name: OpName, Loc: OpLoc, Args,
15380 /*ExplicitTemplateArgs*/ nullptr,
15381 CandidateSet);
15382 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15383}
15384
15385ExprResult
15386Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
15387 const UnresolvedSetImpl &Fns,
15388 Expr *Input, bool PerformADL) {
15389 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
15390 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15391 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15392 // TODO: provide better source location info.
15393 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15394
15395 if (checkPlaceholderForOverload(S&: *this, E&: Input))
15396 return ExprError();
15397
15398 Expr *Args[2] = { Input, nullptr };
15399 unsigned NumArgs = 1;
15400
15401 // For post-increment and post-decrement, add the implicit '0' as
15402 // the second argument, so that we know this is a post-increment or
15403 // post-decrement.
15404 if (Opc == UO_PostInc || Opc == UO_PostDec) {
15405 llvm::APSInt Zero(Context.getTypeSize(T: Context.IntTy), false);
15406 Args[1] = IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy,
15407 l: SourceLocation());
15408 NumArgs = 2;
15409 }
15410
15411 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
15412
15413 if (Input->isTypeDependent()) {
15414 ExprValueKind VK = ExprValueKind::VK_PRValue;
15415 // [C++26][expr.unary.op][expr.pre.incr]
15416 // The * operator yields an lvalue of type
15417 // The pre/post increment operators yied an lvalue.
15418 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
15419 VK = VK_LValue;
15420
15421 if (Fns.empty())
15422 return UnaryOperator::Create(C: Context, input: Input, opc: Opc, type: Context.DependentTy, VK,
15423 OK: OK_Ordinary, l: OpLoc, CanOverflow: false,
15424 FPFeatures: CurFPFeatureOverrides());
15425
15426 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15427 ExprResult Fn = CreateUnresolvedLookupExpr(
15428 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns);
15429 if (Fn.isInvalid())
15430 return ExprError();
15431 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: Op, Fn: Fn.get(), Args: ArgsArray,
15432 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: OpLoc,
15433 FPFeatures: CurFPFeatureOverrides());
15434 }
15435
15436 // Build an empty overload set.
15437 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
15438 LookupOverloadedUnaryOp(CandidateSet, Op, Fns, Args: ArgsArray, PerformADL);
15439
15440 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15441
15442 // Perform overload resolution.
15443 OverloadCandidateSet::iterator Best;
15444 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
15445 case OR_Success: {
15446 // We found a built-in operator or an overloaded operator.
15447 FunctionDecl *FnDecl = Best->Function;
15448
15449 if (FnDecl) {
15450 Expr *Base = nullptr;
15451 // We matched an overloaded operator. Build a call to that
15452 // operator.
15453
15454 // Convert the arguments.
15455 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
15456 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Input, ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
15457
15458 ExprResult InputInit;
15459 if (Method->isExplicitObjectMemberFunction())
15460 InputInit = InitializeExplicitObjectArgument(S&: *this, Obj: Input, Fun: Method);
15461 else
15462 InputInit = PerformImplicitObjectArgumentInitialization(
15463 From: Input, /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
15464 if (InputInit.isInvalid())
15465 return ExprError();
15466 Base = Input = InputInit.get();
15467 } else {
15468 // Convert the arguments.
15469 ExprResult InputInit
15470 = PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
15471 Context,
15472 Parm: FnDecl->getParamDecl(i: 0)),
15473 EqualLoc: SourceLocation(),
15474 Init: Input);
15475 if (InputInit.isInvalid())
15476 return ExprError();
15477 Input = InputInit.get();
15478 }
15479
15480 // Build the actual expression node.
15481 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: FnDecl, FoundDecl: Best->FoundDecl,
15482 Base, HadMultipleCandidates,
15483 Loc: OpLoc);
15484 if (FnExpr.isInvalid())
15485 return ExprError();
15486
15487 // Determine the result type.
15488 QualType ResultTy = FnDecl->getReturnType();
15489 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
15490 ResultTy = ResultTy.getNonLValueExprType(Context);
15491
15492 Args[0] = Input;
15493 CallExpr *TheCall = CXXOperatorCallExpr::Create(
15494 Ctx: Context, OpKind: Op, Fn: FnExpr.get(), Args: ArgsArray, Ty: ResultTy, VK, OperatorLoc: OpLoc,
15495 FPFeatures: CurFPFeatureOverrides(),
15496 UsesADL: static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15497
15498 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: OpLoc, CE: TheCall, FD: FnDecl))
15499 return ExprError();
15500
15501 if (CheckFunctionCall(FDecl: FnDecl, TheCall,
15502 Proto: FnDecl->getType()->castAs<FunctionProtoType>()))
15503 return ExprError();
15504 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: FnDecl);
15505 } else {
15506 // We matched a built-in operator. Convert the arguments, then
15507 // break out so that we will build the appropriate built-in
15508 // operator node.
15509 ExprResult InputRes = PerformImplicitConversion(
15510 From: Input, ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
15511 Action: AssignmentAction::Passing,
15512 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15513 if (InputRes.isInvalid())
15514 return ExprError();
15515 Input = InputRes.get();
15516 break;
15517 }
15518 }
15519
15520 case OR_No_Viable_Function:
15521 // This is an erroneous use of an operator which can be overloaded by
15522 // a non-member function. Check for non-member operators which were
15523 // defined too late to be candidates.
15524 if (DiagnoseTwoPhaseOperatorLookup(SemaRef&: *this, Op, OpLoc, Args: ArgsArray,
15525 ResolvedCandidateSet: CandidateSet))
15526 // FIXME: Recover by calling the found function.
15527 return ExprError();
15528
15529 // No viable function; fall through to handling this as a
15530 // built-in operator, which will produce an error message for us.
15531 break;
15532
15533 case OR_Ambiguous:
15534 CandidateSet.NoteCandidates(
15535 PD: PartialDiagnosticAt(OpLoc,
15536 PDiag(DiagID: diag::err_ovl_ambiguous_oper_unary)
15537 << UnaryOperator::getOpcodeStr(Op: Opc)
15538 << Input->getType() << Input->getSourceRange()),
15539 S&: *this, OCD: OCD_AmbiguousCandidates, Args: ArgsArray,
15540 Opc: UnaryOperator::getOpcodeStr(Op: Opc), OpLoc);
15541 return ExprError();
15542
15543 case OR_Deleted: {
15544 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15545 // object whose method was called. Later in NoteCandidates size of ArgsArray
15546 // is passed further and it eventually ends up compared to number of
15547 // function candidate parameters which never includes the object parameter,
15548 // so slice ArgsArray to make sure apples are compared to apples.
15549 StringLiteral *Msg = Best->Function->getDeletedMessage();
15550 CandidateSet.NoteCandidates(
15551 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_deleted_oper)
15552 << UnaryOperator::getOpcodeStr(Op: Opc)
15553 << (Msg != nullptr)
15554 << (Msg ? Msg->getString() : StringRef())
15555 << Input->getSourceRange()),
15556 S&: *this, OCD: OCD_AllCandidates, Args: ArgsArray.drop_front(),
15557 Opc: UnaryOperator::getOpcodeStr(Op: Opc), OpLoc);
15558 return ExprError();
15559 }
15560 }
15561
15562 // Either we found no viable overloaded operator or we matched a
15563 // built-in operator. In either case, fall through to trying to
15564 // build a built-in operation.
15565 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
15566}
15567
15568void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
15569 OverloadedOperatorKind Op,
15570 const UnresolvedSetImpl &Fns,
15571 ArrayRef<Expr *> Args, bool PerformADL) {
15572 SourceLocation OpLoc = CandidateSet.getLocation();
15573
15574 OverloadedOperatorKind ExtraOp =
15575 CandidateSet.getRewriteInfo().AllowRewrittenCandidates
15576 ? getRewrittenOverloadedOperator(Kind: Op)
15577 : OO_None;
15578
15579 // Add the candidates from the given function set. This also adds the
15580 // rewritten candidates using these functions if necessary.
15581 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15582
15583 // As template candidates are not deduced immediately,
15584 // persist the array in the overload set.
15585 ArrayRef<Expr *> ReversedArgs;
15586 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15587 CandidateSet.getRewriteInfo().allowsReversed(Op: ExtraOp))
15588 ReversedArgs = CandidateSet.getPersistentArgsArray(Exprs: Args[1], Exprs: Args[0]);
15589
15590 // Add operator candidates that are member functions.
15591 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15592 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15593 AddMemberOperatorCandidates(Op, OpLoc, Args: ReversedArgs, CandidateSet,
15594 PO: OverloadCandidateParamOrder::Reversed);
15595
15596 // In C++20, also add any rewritten member candidates.
15597 if (ExtraOp) {
15598 AddMemberOperatorCandidates(Op: ExtraOp, OpLoc, Args, CandidateSet);
15599 if (CandidateSet.getRewriteInfo().allowsReversed(Op: ExtraOp))
15600 AddMemberOperatorCandidates(Op: ExtraOp, OpLoc, Args: ReversedArgs, CandidateSet,
15601 PO: OverloadCandidateParamOrder::Reversed);
15602 }
15603
15604 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15605 // performed for an assignment operator (nor for operator[] nor operator->,
15606 // which don't get here).
15607 if (Op != OO_Equal && PerformADL) {
15608 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15609 AddArgumentDependentLookupCandidates(Name: OpName, Loc: OpLoc, Args,
15610 /*ExplicitTemplateArgs*/ nullptr,
15611 CandidateSet);
15612 if (ExtraOp) {
15613 DeclarationName ExtraOpName =
15614 Context.DeclarationNames.getCXXOperatorName(Op: ExtraOp);
15615 AddArgumentDependentLookupCandidates(Name: ExtraOpName, Loc: OpLoc, Args,
15616 /*ExplicitTemplateArgs*/ nullptr,
15617 CandidateSet);
15618 }
15619 }
15620
15621 // Add builtin operator candidates.
15622 //
15623 // FIXME: We don't add any rewritten candidates here. This is strictly
15624 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15625 // resulting in our selecting a rewritten builtin candidate. For example:
15626 //
15627 // enum class E { e };
15628 // bool operator!=(E, E) requires false;
15629 // bool k = E::e != E::e;
15630 //
15631 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15632 // it seems unreasonable to consider rewritten builtin candidates. A core
15633 // issue has been filed proposing to removed this requirement.
15634 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15635}
15636
15637ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
15638 BinaryOperatorKind Opc,
15639 const UnresolvedSetImpl &Fns, Expr *LHS,
15640 Expr *RHS, bool PerformADL,
15641 bool AllowRewrittenCandidates,
15642 FunctionDecl *DefaultedFn) {
15643 Expr *Args[2] = { LHS, RHS };
15644 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15645
15646 if (!getLangOpts().CPlusPlus20)
15647 AllowRewrittenCandidates = false;
15648
15649 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
15650
15651 // If either side is type-dependent, create an appropriate dependent
15652 // expression.
15653 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15654 if (Fns.empty()) {
15655 // If there are no functions to store, just build a dependent
15656 // BinaryOperator or CompoundAssignment.
15657 if (BinaryOperator::isCompoundAssignmentOp(Opc))
15658 return CompoundAssignOperator::Create(
15659 C: Context, lhs: Args[0], rhs: Args[1], opc: Opc, ResTy: Context.DependentTy, VK: VK_LValue,
15660 OK: OK_Ordinary, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides(), CompLHSType: Context.DependentTy,
15661 CompResultType: Context.DependentTy);
15662 return BinaryOperator::Create(
15663 C: Context, lhs: Args[0], rhs: Args[1], opc: Opc, ResTy: Context.DependentTy, VK: VK_PRValue,
15664 OK: OK_Ordinary, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
15665 }
15666
15667 // FIXME: save results of ADL from here?
15668 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15669 // TODO: provide better source location info in DNLoc component.
15670 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15671 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15672 ExprResult Fn = CreateUnresolvedLookupExpr(
15673 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns, PerformADL);
15674 if (Fn.isInvalid())
15675 return ExprError();
15676 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: Op, Fn: Fn.get(), Args,
15677 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: OpLoc,
15678 FPFeatures: CurFPFeatureOverrides());
15679 }
15680
15681 // If this is the .* operator, which is not overloadable, just
15682 // create a built-in binary operator.
15683 if (Opc == BO_PtrMemD) {
15684 auto CheckPlaceholder = [&](Expr *&Arg) {
15685 ExprResult Res = CheckPlaceholderExpr(E: Arg);
15686 if (Res.isUsable())
15687 Arg = Res.get();
15688 return !Res.isUsable();
15689 };
15690
15691 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15692 // expression that contains placeholders (in either the LHS or RHS).
15693 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15694 return ExprError();
15695 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15696 }
15697
15698 // Always do placeholder-like conversions on the RHS.
15699 if (checkPlaceholderForOverload(S&: *this, E&: Args[1]))
15700 return ExprError();
15701
15702 // Do placeholder-like conversion on the LHS; note that we should
15703 // not get here with a PseudoObject LHS.
15704 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15705 if (checkPlaceholderForOverload(S&: *this, E&: Args[0]))
15706 return ExprError();
15707
15708 // If this is the assignment operator, we only perform overload resolution
15709 // if the left-hand side is a class or enumeration type. This is actually
15710 // a hack. The standard requires that we do overload resolution between the
15711 // various built-in candidates, but as DR507 points out, this can lead to
15712 // problems. So we do it this way, which pretty much follows what GCC does.
15713 // Note that we go the traditional code path for compound assignment forms.
15714 // In HLSL, user-defined structs/classes do not have constructors or
15715 // overloadable assignment operators, so we can take this shortcut too.
15716 const Type *LHSTy = Args[0]->getType().getTypePtr();
15717 if (Opc == BO_Assign &&
15718 (!LHSTy->isOverloadableType() ||
15719 (getLangOpts().HLSL && LHSTy->isRecordType() &&
15720 !LHSTy->getAsCXXRecordDecl()->isHLSLBuiltinRecord())))
15721 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15722
15723 // Build the overload set.
15724 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator,
15725 OverloadCandidateSet::OperatorRewriteInfo(
15726 Op, OpLoc, AllowRewrittenCandidates));
15727 if (DefaultedFn)
15728 CandidateSet.exclude(F: DefaultedFn);
15729 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15730
15731 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15732
15733 // Perform overload resolution.
15734 OverloadCandidateSet::iterator Best;
15735 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
15736 case OR_Success: {
15737 // We found a built-in operator or an overloaded operator.
15738 FunctionDecl *FnDecl = Best->Function;
15739
15740 bool IsReversed = Best->isReversed();
15741 if (IsReversed)
15742 std::swap(a&: Args[0], b&: Args[1]);
15743
15744 if (FnDecl) {
15745
15746 if (FnDecl->isInvalidDecl())
15747 return ExprError();
15748
15749 Expr *Base = nullptr;
15750 // We matched an overloaded operator. Build a call to that
15751 // operator.
15752
15753 OverloadedOperatorKind ChosenOp =
15754 FnDecl->getDeclName().getCXXOverloadedOperator();
15755
15756 // C++2a [over.match.oper]p9:
15757 // If a rewritten operator== candidate is selected by overload
15758 // resolution for an operator@, its return type shall be cv bool
15759 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15760 !FnDecl->getReturnType()->isBooleanType()) {
15761 bool IsExtension =
15762 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
15763 Diag(Loc: OpLoc, DiagID: IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15764 : diag::err_ovl_rewrite_equalequal_not_bool)
15765 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Op: Opc)
15766 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15767 Diag(Loc: FnDecl->getLocation(), DiagID: diag::note_declared_at);
15768 if (!IsExtension)
15769 return ExprError();
15770 }
15771
15772 if (AllowRewrittenCandidates && !IsReversed &&
15773 CandidateSet.getRewriteInfo().isReversible()) {
15774 // We could have reversed this operator, but didn't. Check if some
15775 // reversed form was a viable candidate, and if so, if it had a
15776 // better conversion for either parameter. If so, this call is
15777 // formally ambiguous, and allowing it is an extension.
15778 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
15779 for (OverloadCandidate &Cand : CandidateSet) {
15780 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15781 allowAmbiguity(Context, F1: Cand.Function, F2: FnDecl)) {
15782 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15783 if (CompareImplicitConversionSequences(
15784 S&: *this, Loc: OpLoc, ICS1: Cand.Conversions[ArgIdx],
15785 ICS2: Best->Conversions[ArgIdx]) ==
15786 ImplicitConversionSequence::Better) {
15787 AmbiguousWith.push_back(Elt: Cand.Function);
15788 break;
15789 }
15790 }
15791 }
15792 }
15793
15794 if (!AmbiguousWith.empty()) {
15795 bool AmbiguousWithSelf =
15796 AmbiguousWith.size() == 1 &&
15797 declaresSameEntity(D1: AmbiguousWith.front(), D2: FnDecl);
15798 Diag(Loc: OpLoc, DiagID: diag::ext_ovl_ambiguous_oper_binary_reversed)
15799 << BinaryOperator::getOpcodeStr(Op: Opc)
15800 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15801 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15802 if (AmbiguousWithSelf) {
15803 Diag(Loc: FnDecl->getLocation(),
15804 DiagID: diag::note_ovl_ambiguous_oper_binary_reversed_self);
15805 // Mark member== const or provide matching != to disallow reversed
15806 // args. Eg.
15807 // struct S { bool operator==(const S&); };
15808 // S()==S();
15809 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FnDecl))
15810 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15811 !MD->isConst() &&
15812 !MD->hasCXXExplicitFunctionObjectParameter() &&
15813 Context.hasSameUnqualifiedType(
15814 T1: MD->getFunctionObjectParameterType(),
15815 T2: MD->getParamDecl(i: 0)->getType().getNonReferenceType()) &&
15816 Context.hasSameUnqualifiedType(
15817 T1: MD->getFunctionObjectParameterType(),
15818 T2: Args[0]->getType()) &&
15819 Context.hasSameUnqualifiedType(
15820 T1: MD->getFunctionObjectParameterType(),
15821 T2: Args[1]->getType()))
15822 Diag(Loc: FnDecl->getLocation(),
15823 DiagID: diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15824 } else {
15825 Diag(Loc: FnDecl->getLocation(),
15826 DiagID: diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15827 for (auto *F : AmbiguousWith)
15828 Diag(Loc: F->getLocation(),
15829 DiagID: diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15830 }
15831 }
15832 }
15833
15834 // Check for nonnull = nullable.
15835 // This won't be caught in the arg's initialization: the parameter to
15836 // the assignment operator is not marked nonnull.
15837 if (Op == OO_Equal)
15838 diagnoseNullableToNonnullConversion(DstType: Args[0]->getType(),
15839 SrcType: Args[1]->getType(), Loc: OpLoc);
15840
15841 // Convert the arguments.
15842 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
15843 // Best->Access is only meaningful for class members.
15844 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Args[0], ArgExpr: Args[1], FoundDecl: Best->FoundDecl);
15845
15846 ExprResult Arg0, Arg1;
15847 unsigned ParamIdx = 0;
15848 if (Method->isExplicitObjectMemberFunction()) {
15849 Arg0 = InitializeExplicitObjectArgument(S&: *this, Obj: Args[0], Fun: FnDecl);
15850 ParamIdx = 1;
15851 } else {
15852 Arg0 = PerformImplicitObjectArgumentInitialization(
15853 From: Args[0], /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
15854 }
15855 Arg1 = PerformCopyInitialization(
15856 Entity: InitializedEntity::InitializeParameter(
15857 Context, Parm: FnDecl->getParamDecl(i: ParamIdx)),
15858 EqualLoc: SourceLocation(), Init: Args[1]);
15859 if (Arg0.isInvalid() || Arg1.isInvalid())
15860 return ExprError();
15861
15862 Base = Args[0] = Arg0.getAs<Expr>();
15863 Args[1] = RHS = Arg1.getAs<Expr>();
15864 } else {
15865 // Convert the arguments.
15866 ExprResult Arg0 = PerformCopyInitialization(
15867 Entity: InitializedEntity::InitializeParameter(Context,
15868 Parm: FnDecl->getParamDecl(i: 0)),
15869 EqualLoc: SourceLocation(), Init: Args[0]);
15870 if (Arg0.isInvalid())
15871 return ExprError();
15872
15873 ExprResult Arg1 =
15874 PerformCopyInitialization(
15875 Entity: InitializedEntity::InitializeParameter(Context,
15876 Parm: FnDecl->getParamDecl(i: 1)),
15877 EqualLoc: SourceLocation(), Init: Args[1]);
15878 if (Arg1.isInvalid())
15879 return ExprError();
15880 Args[0] = LHS = Arg0.getAs<Expr>();
15881 Args[1] = RHS = Arg1.getAs<Expr>();
15882 }
15883
15884 // Build the actual expression node.
15885 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: FnDecl,
15886 FoundDecl: Best->FoundDecl, Base,
15887 HadMultipleCandidates, Loc: OpLoc);
15888 if (FnExpr.isInvalid())
15889 return ExprError();
15890
15891 if (auto *Pattern = FnDecl->getInstantiatedFromMemberFunction();
15892 Pattern && Pattern->getOverloadedOperator() == OO_Spaceship)
15893 Pattern->setIsUsed();
15894
15895 // Determine the result type.
15896 QualType ResultTy = FnDecl->getReturnType();
15897 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
15898 ResultTy = ResultTy.getNonLValueExprType(Context);
15899
15900 CallExpr *TheCall;
15901 ArrayRef<const Expr *> ArgsArray(Args, 2);
15902 const Expr *ImplicitThis = nullptr;
15903
15904 // We always create a CXXOperatorCallExpr, even for explicit object
15905 // members; CodeGen should take care not to emit the this pointer.
15906 TheCall = CXXOperatorCallExpr::Create(
15907 Ctx: Context, OpKind: ChosenOp, Fn: FnExpr.get(), Args, Ty: ResultTy, VK, OperatorLoc: OpLoc,
15908 FPFeatures: CurFPFeatureOverrides(),
15909 UsesADL: static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate),
15910 IsReversed);
15911
15912 if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl);
15913 Method && Method->isImplicitObjectMemberFunction()) {
15914 // Cut off the implicit 'this'.
15915 ImplicitThis = ArgsArray[0];
15916 ArgsArray = ArgsArray.slice(N: 1);
15917 }
15918
15919 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: OpLoc, CE: TheCall,
15920 FD: FnDecl))
15921 return ExprError();
15922
15923 if (Op == OO_Equal) {
15924 // Check for a self move.
15925 DiagnoseSelfMove(LHSExpr: Args[0], RHSExpr: Args[1], OpLoc);
15926 // lifetime check.
15927 checkAssignmentLifetime(
15928 SemaRef&: *this, Entity: AssignedEntity{.LHS: Args[0], .AssignmentOperator: dyn_cast<CXXMethodDecl>(Val: FnDecl)},
15929 Init: Args[1]);
15930 }
15931 if (ImplicitThis) {
15932 QualType ThisType = Context.getPointerType(T: ImplicitThis->getType());
15933 QualType ThisTypeFromDecl = Context.getPointerType(
15934 T: cast<CXXMethodDecl>(Val: FnDecl)->getFunctionObjectParameterType());
15935
15936 CheckArgAlignment(Loc: OpLoc, FDecl: FnDecl, ParamName: "'this'", ArgTy: ThisType,
15937 ParamTy: ThisTypeFromDecl);
15938 }
15939
15940 checkCall(FDecl: FnDecl, Proto: nullptr, ThisArg: ImplicitThis, Args: ArgsArray,
15941 IsMemberFunction: isa<CXXMethodDecl>(Val: FnDecl), Loc: OpLoc, Range: TheCall->getSourceRange(),
15942 CallType: VariadicCallType::DoesNotApply);
15943
15944 ExprResult R = MaybeBindToTemporary(E: TheCall);
15945 if (R.isInvalid())
15946 return ExprError();
15947
15948 R = CheckForImmediateInvocation(E: R, Decl: FnDecl);
15949 if (R.isInvalid())
15950 return ExprError();
15951
15952 // For a rewritten candidate, we've already reversed the arguments
15953 // if needed. Perform the rest of the rewrite now.
15954 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15955 (Op == OO_Spaceship && IsReversed)) {
15956 if (Op == OO_ExclaimEqual) {
15957 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15958 R = CreateBuiltinUnaryOp(OpLoc, Opc: UO_LNot, InputExpr: R.get());
15959 } else {
15960 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15961 llvm::APSInt Zero(Context.getTypeSize(T: Context.IntTy), false);
15962 Expr *ZeroLiteral =
15963 IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy, l: OpLoc);
15964
15965 Sema::CodeSynthesisContext Ctx;
15966 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
15967 Ctx.Entity = FnDecl;
15968 pushCodeSynthesisContext(Ctx);
15969
15970 R = CreateOverloadedBinOp(
15971 OpLoc, Opc, Fns, LHS: IsReversed ? ZeroLiteral : R.get(),
15972 RHS: IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15973 /*AllowRewrittenCandidates=*/false);
15974
15975 popCodeSynthesisContext();
15976 }
15977 if (R.isInvalid())
15978 return ExprError();
15979 } else {
15980 assert(ChosenOp == Op && "unexpected operator name");
15981 }
15982
15983 // Make a note in the AST if we did any rewriting.
15984 if (Best->RewriteKind != CRK_None)
15985 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
15986
15987 return R;
15988 } else {
15989 // We matched a built-in operator. Convert the arguments, then
15990 // break out so that we will build the appropriate built-in
15991 // operator node.
15992 ExprResult ArgsRes0 = PerformImplicitConversion(
15993 From: Args[0], ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
15994 Action: AssignmentAction::Passing,
15995 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15996 if (ArgsRes0.isInvalid())
15997 return ExprError();
15998 Args[0] = ArgsRes0.get();
15999
16000 ExprResult ArgsRes1 = PerformImplicitConversion(
16001 From: Args[1], ToType: Best->BuiltinParamTypes[1], ICS: Best->Conversions[1],
16002 Action: AssignmentAction::Passing,
16003 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
16004 if (ArgsRes1.isInvalid())
16005 return ExprError();
16006 Args[1] = ArgsRes1.get();
16007 break;
16008 }
16009 }
16010
16011 case OR_No_Viable_Function: {
16012 // C++ [over.match.oper]p9:
16013 // If the operator is the operator , [...] and there are no
16014 // viable functions, then the operator is assumed to be the
16015 // built-in operator and interpreted according to clause 5.
16016 if (Opc == BO_Comma)
16017 break;
16018
16019 // When defaulting an 'operator<=>', we can try to synthesize a three-way
16020 // compare result using '==' and '<'.
16021 if (DefaultedFn && Opc == BO_Cmp) {
16022 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, LHS: Args[0],
16023 RHS: Args[1], DefaultedFn);
16024 if (E.isInvalid() || E.isUsable())
16025 return E;
16026 }
16027
16028 // For class as left operand for assignment or compound assignment
16029 // operator do not fall through to handling in built-in, but report that
16030 // no overloaded assignment operator found
16031 ExprResult Result = ExprError();
16032 StringRef OpcStr = BinaryOperator::getOpcodeStr(Op: Opc);
16033 auto Cands = CandidateSet.CompleteCandidates(S&: *this, OCD: OCD_AllCandidates,
16034 Args, OpLoc);
16035 DeferDiagsRAII DDR(*this,
16036 CandidateSet.shouldDeferDiags(S&: *this, Args, OpLoc));
16037 if (Args[0]->getType()->isRecordType() &&
16038 Opc >= BO_Assign && Opc <= BO_OrAssign) {
16039 Diag(Loc: OpLoc, DiagID: diag::err_ovl_no_viable_oper)
16040 << BinaryOperator::getOpcodeStr(Op: Opc)
16041 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
16042 if (Args[0]->getType()->isIncompleteType()) {
16043 Diag(Loc: OpLoc, DiagID: diag::note_assign_lhs_incomplete)
16044 << Args[0]->getType()
16045 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
16046 }
16047 } else {
16048 // This is an erroneous use of an operator which can be overloaded by
16049 // a non-member function. Check for non-member operators which were
16050 // defined too late to be candidates.
16051 if (DiagnoseTwoPhaseOperatorLookup(SemaRef&: *this, Op, OpLoc, Args,
16052 ResolvedCandidateSet: CandidateSet))
16053 // FIXME: Recover by calling the found function.
16054 return ExprError();
16055
16056 // No viable function; try to create a built-in operation, which will
16057 // produce an error. Then, show the non-viable candidates.
16058 Result = CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
16059 }
16060 assert(Result.isInvalid() &&
16061 "C++ binary operator overloading is missing candidates!");
16062 CandidateSet.NoteCandidates(S&: *this, Args, Cands, Opc: OpcStr, OpLoc);
16063 return Result;
16064 }
16065
16066 case OR_Ambiguous:
16067 CandidateSet.NoteCandidates(
16068 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_binary)
16069 << BinaryOperator::getOpcodeStr(Op: Opc)
16070 << Args[0]->getType()
16071 << Args[1]->getType()
16072 << Args[0]->getSourceRange()
16073 << Args[1]->getSourceRange()),
16074 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: BinaryOperator::getOpcodeStr(Op: Opc),
16075 OpLoc);
16076 return ExprError();
16077
16078 case OR_Deleted: {
16079 if (isImplicitlyDeleted(FD: Best->Function)) {
16080 FunctionDecl *DeletedFD = Best->Function;
16081 FunctionDecl::DefaultedFunctionKind DFK =
16082 DeletedFD->getDefaultedFunctionKind();
16083 if (DFK.isSpecialMember()) {
16084 Diag(Loc: OpLoc, DiagID: diag::err_ovl_deleted_special_oper)
16085 << Args[0]->getType() << DFK.asSpecialMember();
16086 } else {
16087 assert(DFK.isComparison());
16088 Diag(Loc: OpLoc, DiagID: diag::err_ovl_deleted_comparison)
16089 << Args[0]->getType() << DeletedFD;
16090 }
16091
16092 // The user probably meant to call this special member. Just
16093 // explain why it's deleted.
16094 NoteDeletedFunction(FD: DeletedFD);
16095 return ExprError();
16096 }
16097
16098 StringLiteral *Msg = Best->Function->getDeletedMessage();
16099 CandidateSet.NoteCandidates(
16100 PD: PartialDiagnosticAt(
16101 OpLoc,
16102 PDiag(DiagID: diag::err_ovl_deleted_oper)
16103 << getOperatorSpelling(Operator: Best->Function->getDeclName()
16104 .getCXXOverloadedOperator())
16105 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
16106 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
16107 S&: *this, OCD: OCD_AllCandidates, Args, Opc: BinaryOperator::getOpcodeStr(Op: Opc),
16108 OpLoc);
16109 return ExprError();
16110 }
16111 }
16112
16113 // We matched a built-in operator; build it.
16114 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
16115}
16116
16117ExprResult Sema::BuildSynthesizedThreeWayComparison(
16118 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
16119 FunctionDecl *DefaultedFn) {
16120 const ComparisonCategoryInfo *Info =
16121 Context.CompCategories.lookupInfoForType(Ty: DefaultedFn->getReturnType());
16122 // If we're not producing a known comparison category type, we can't
16123 // synthesize a three-way comparison. Let the caller diagnose this.
16124 if (!Info)
16125 return ExprResult((Expr*)nullptr);
16126
16127 // If we ever want to perform this synthesis more generally, we will need to
16128 // apply the temporary materialization conversion to the operands.
16129 assert(LHS->isGLValue() && RHS->isGLValue() &&
16130 "cannot use prvalue expressions more than once");
16131 Expr *OrigLHS = LHS;
16132 Expr *OrigRHS = RHS;
16133
16134 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
16135 // each of them multiple times below.
16136 LHS = new (Context)
16137 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
16138 LHS->getObjectKind(), LHS);
16139 RHS = new (Context)
16140 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
16141 RHS->getObjectKind(), RHS);
16142
16143 ExprResult Eq = CreateOverloadedBinOp(OpLoc, Opc: BO_EQ, Fns, LHS, RHS, PerformADL: true, AllowRewrittenCandidates: true,
16144 DefaultedFn);
16145 if (Eq.isInvalid())
16146 return ExprError();
16147
16148 ExprResult Less = CreateOverloadedBinOp(OpLoc, Opc: BO_LT, Fns, LHS, RHS, PerformADL: true,
16149 AllowRewrittenCandidates: true, DefaultedFn);
16150 if (Less.isInvalid())
16151 return ExprError();
16152
16153 ExprResult Greater;
16154 if (Info->isPartial()) {
16155 Greater = CreateOverloadedBinOp(OpLoc, Opc: BO_LT, Fns, LHS: RHS, RHS: LHS, PerformADL: true, AllowRewrittenCandidates: true,
16156 DefaultedFn);
16157 if (Greater.isInvalid())
16158 return ExprError();
16159 }
16160
16161 // Form the list of comparisons we're going to perform.
16162 struct Comparison {
16163 ExprResult Cmp;
16164 ComparisonCategoryResult Result;
16165 } Comparisons[4] =
16166 { {.Cmp: Eq, .Result: Info->isStrong() ? ComparisonCategoryResult::Equal
16167 : ComparisonCategoryResult::Equivalent},
16168 {.Cmp: Less, .Result: ComparisonCategoryResult::Less},
16169 {.Cmp: Greater, .Result: ComparisonCategoryResult::Greater},
16170 {.Cmp: ExprResult(), .Result: ComparisonCategoryResult::Unordered},
16171 };
16172
16173 int I = Info->isPartial() ? 3 : 2;
16174
16175 // Combine the comparisons with suitable conditional expressions.
16176 ExprResult Result;
16177 for (; I >= 0; --I) {
16178 // Build a reference to the comparison category constant.
16179 auto *VI = Info->lookupValueInfo(ValueKind: Comparisons[I].Result);
16180 // FIXME: Missing a constant for a comparison category. Diagnose this?
16181 if (!VI)
16182 return ExprResult((Expr*)nullptr);
16183 ExprResult ThisResult =
16184 BuildDeclarationNameExpr(SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(), D: VI->VD);
16185 if (ThisResult.isInvalid())
16186 return ExprError();
16187
16188 // Build a conditional unless this is the final case.
16189 if (Result.get()) {
16190 Result = ActOnConditionalOp(QuestionLoc: OpLoc, ColonLoc: OpLoc, CondExpr: Comparisons[I].Cmp.get(),
16191 LHSExpr: ThisResult.get(), RHSExpr: Result.get());
16192 if (Result.isInvalid())
16193 return ExprError();
16194 } else {
16195 Result = ThisResult;
16196 }
16197 }
16198
16199 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
16200 // bind the OpaqueValueExprs before they're (repeatedly) used.
16201 Expr *SyntacticForm = BinaryOperator::Create(
16202 C: Context, lhs: OrigLHS, rhs: OrigRHS, opc: BO_Cmp, ResTy: Result.get()->getType(),
16203 VK: Result.get()->getValueKind(), OK: Result.get()->getObjectKind(), opLoc: OpLoc,
16204 FPFeatures: CurFPFeatureOverrides());
16205 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
16206 return PseudoObjectExpr::Create(Context, syntactic: SyntacticForm, semantic: SemanticForm, resultIndex: 2);
16207}
16208
16209static bool PrepareArgumentsForCallToObjectOfClassType(
16210 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
16211 MultiExprArg Args, SourceLocation LParenLoc) {
16212
16213 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16214 unsigned NumParams = Proto->getNumParams();
16215 unsigned NumArgsSlots =
16216 MethodArgs.size() + std::max<unsigned>(a: Args.size(), b: NumParams);
16217 // Build the full argument list for the method call (the implicit object
16218 // parameter is placed at the beginning of the list).
16219 MethodArgs.reserve(N: MethodArgs.size() + NumArgsSlots);
16220 bool IsError = false;
16221 // Initialize the implicit object parameter.
16222 // Check the argument types.
16223 for (unsigned i = 0; i != NumParams; i++) {
16224 Expr *Arg;
16225 if (i < Args.size()) {
16226 Arg = Args[i];
16227 ExprResult InputInit =
16228 S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
16229 Context&: S.Context, Parm: Method->getParamDecl(i)),
16230 EqualLoc: SourceLocation(), Init: Arg);
16231 IsError |= InputInit.isInvalid();
16232 Arg = InputInit.getAs<Expr>();
16233 } else {
16234 ExprResult DefArg =
16235 S.BuildCXXDefaultArgExpr(CallLoc: LParenLoc, FD: Method, Param: Method->getParamDecl(i));
16236 if (DefArg.isInvalid()) {
16237 IsError = true;
16238 break;
16239 }
16240 Arg = DefArg.getAs<Expr>();
16241 }
16242
16243 MethodArgs.push_back(Elt: Arg);
16244 }
16245 return IsError;
16246}
16247
16248ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
16249 SourceLocation RLoc,
16250 Expr *Base,
16251 MultiExprArg ArgExpr) {
16252 SmallVector<Expr *, 2> Args;
16253 Args.push_back(Elt: Base);
16254 for (auto *e : ArgExpr) {
16255 Args.push_back(Elt: e);
16256 }
16257 DeclarationName OpName =
16258 Context.DeclarationNames.getCXXOperatorName(Op: OO_Subscript);
16259
16260 SourceRange Range = ArgExpr.empty()
16261 ? SourceRange{}
16262 : SourceRange(ArgExpr.front()->getBeginLoc(),
16263 ArgExpr.back()->getEndLoc());
16264
16265 // If either side is type-dependent, create an appropriate dependent
16266 // expression.
16267 if (Expr::hasAnyTypeDependentArguments(Exprs: Args)) {
16268
16269 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
16270 // CHECKME: no 'operator' keyword?
16271 DeclarationNameInfo OpNameInfo(OpName, LLoc);
16272 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16273 ExprResult Fn = CreateUnresolvedLookupExpr(
16274 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns: UnresolvedSet<0>());
16275 if (Fn.isInvalid())
16276 return ExprError();
16277 // Can't add any actual overloads yet
16278
16279 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: OO_Subscript, Fn: Fn.get(), Args,
16280 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: RLoc,
16281 FPFeatures: CurFPFeatureOverrides());
16282 }
16283
16284 // Handle placeholders
16285 UnbridgedCastsSet UnbridgedCasts;
16286 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts)) {
16287 return ExprError();
16288 }
16289 // Build an empty overload set.
16290 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
16291
16292 // Subscript can only be overloaded as a member function.
16293
16294 // Add operator candidates that are member functions.
16295 AddMemberOperatorCandidates(Op: OO_Subscript, OpLoc: LLoc, Args, CandidateSet);
16296
16297 // Add builtin operator candidates.
16298 if (Args.size() == 2)
16299 AddBuiltinOperatorCandidates(Op: OO_Subscript, OpLoc: LLoc, Args, CandidateSet);
16300
16301 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16302
16303 // Perform overload resolution.
16304 OverloadCandidateSet::iterator Best;
16305 switch (CandidateSet.BestViableFunction(S&: *this, Loc: LLoc, Best)) {
16306 case OR_Success: {
16307 // We found a built-in operator or an overloaded operator.
16308 FunctionDecl *FnDecl = Best->Function;
16309
16310 if (FnDecl) {
16311 // We matched an overloaded operator. Build a call to that
16312 // operator.
16313
16314 CheckMemberOperatorAccess(Loc: LLoc, ObjectExpr: Args[0], ArgExprs: ArgExpr, FoundDecl: Best->FoundDecl);
16315
16316 // Convert the arguments.
16317 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: FnDecl);
16318 SmallVector<Expr *, 2> MethodArgs;
16319
16320 // Initialize the object parameter.
16321 if (Method->isExplicitObjectMemberFunction()) {
16322 ExprResult Res =
16323 InitializeExplicitObjectArgument(S&: *this, Obj: Args[0], Fun: Method);
16324 if (Res.isInvalid())
16325 return ExprError();
16326 Args[0] = Res.get();
16327 ArgExpr = Args;
16328 } else {
16329 ExprResult Arg0 = PerformImplicitObjectArgumentInitialization(
16330 From: Args[0], /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
16331 if (Arg0.isInvalid())
16332 return ExprError();
16333
16334 MethodArgs.push_back(Elt: Arg0.get());
16335 }
16336
16337 bool IsError = PrepareArgumentsForCallToObjectOfClassType(
16338 S&: *this, MethodArgs, Method, Args: ArgExpr, LParenLoc: LLoc);
16339 if (IsError)
16340 return ExprError();
16341
16342 // Build the actual expression node.
16343 DeclarationNameInfo OpLocInfo(OpName, LLoc);
16344 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16345 ExprResult FnExpr =
16346 CreateFunctionRefExpr(S&: *this, Fn: FnDecl, FoundDecl: Best->FoundDecl, Base,
16347 HadMultipleCandidates, NameInfo: OpLocInfo);
16348 if (FnExpr.isInvalid())
16349 return ExprError();
16350
16351 // Determine the result type
16352 QualType ResultTy = FnDecl->getReturnType();
16353 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16354 ResultTy = ResultTy.getNonLValueExprType(Context);
16355
16356 CallExpr *TheCall = CXXOperatorCallExpr::Create(
16357 Ctx: Context, OpKind: OO_Subscript, Fn: FnExpr.get(), Args: MethodArgs, Ty: ResultTy, VK, OperatorLoc: RLoc,
16358 FPFeatures: CurFPFeatureOverrides());
16359
16360 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: LLoc, CE: TheCall, FD: FnDecl))
16361 return ExprError();
16362
16363 if (CheckFunctionCall(FDecl: Method, TheCall,
16364 Proto: Method->getType()->castAs<FunctionProtoType>()))
16365 return ExprError();
16366
16367 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall),
16368 Decl: FnDecl);
16369 } else {
16370 // We matched a built-in operator. Convert the arguments, then
16371 // break out so that we will build the appropriate built-in
16372 // operator node.
16373 ExprResult ArgsRes0 = PerformImplicitConversion(
16374 From: Args[0], ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
16375 Action: AssignmentAction::Passing,
16376 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
16377 if (ArgsRes0.isInvalid())
16378 return ExprError();
16379 Args[0] = ArgsRes0.get();
16380
16381 ExprResult ArgsRes1 = PerformImplicitConversion(
16382 From: Args[1], ToType: Best->BuiltinParamTypes[1], ICS: Best->Conversions[1],
16383 Action: AssignmentAction::Passing,
16384 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
16385 if (ArgsRes1.isInvalid())
16386 return ExprError();
16387 Args[1] = ArgsRes1.get();
16388
16389 break;
16390 }
16391 }
16392
16393 case OR_No_Viable_Function: {
16394 PartialDiagnostic PD =
16395 CandidateSet.empty()
16396 ? (PDiag(DiagID: diag::err_ovl_no_oper)
16397 << Args[0]->getType() << /*subscript*/ 0
16398 << Args[0]->getSourceRange() << Range)
16399 : (PDiag(DiagID: diag::err_ovl_no_viable_subscript)
16400 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
16401 CandidateSet.NoteCandidates(PD: PartialDiagnosticAt(LLoc, PD), S&: *this,
16402 OCD: OCD_AllCandidates, Args: ArgExpr, Opc: "[]", OpLoc: LLoc);
16403 return ExprError();
16404 }
16405
16406 case OR_Ambiguous:
16407 if (Args.size() == 2) {
16408 CandidateSet.NoteCandidates(
16409 PD: PartialDiagnosticAt(
16410 LLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_binary)
16411 << "[]" << Args[0]->getType() << Args[1]->getType()
16412 << Args[0]->getSourceRange() << Range),
16413 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: "[]", OpLoc: LLoc);
16414 } else {
16415 CandidateSet.NoteCandidates(
16416 PD: PartialDiagnosticAt(LLoc,
16417 PDiag(DiagID: diag::err_ovl_ambiguous_subscript_call)
16418 << Args[0]->getType()
16419 << Args[0]->getSourceRange() << Range),
16420 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: "[]", OpLoc: LLoc);
16421 }
16422 return ExprError();
16423
16424 case OR_Deleted: {
16425 StringLiteral *Msg = Best->Function->getDeletedMessage();
16426 CandidateSet.NoteCandidates(
16427 PD: PartialDiagnosticAt(LLoc,
16428 PDiag(DiagID: diag::err_ovl_deleted_oper)
16429 << "[]" << (Msg != nullptr)
16430 << (Msg ? Msg->getString() : StringRef())
16431 << Args[0]->getSourceRange() << Range),
16432 S&: *this, OCD: OCD_AllCandidates, Args, Opc: "[]", OpLoc: LLoc);
16433 return ExprError();
16434 }
16435 }
16436
16437 // We matched a built-in operator; build it.
16438 return CreateBuiltinArraySubscriptExpr(Base: Args[0], LLoc, Idx: Args[1], RLoc);
16439}
16440
16441ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
16442 SourceLocation LParenLoc,
16443 MultiExprArg Args,
16444 SourceLocation RParenLoc,
16445 Expr *ExecConfig, bool IsExecConfig,
16446 bool AllowRecovery) {
16447 assert(MemExprE->getType() == Context.BoundMemberTy ||
16448 MemExprE->getType() == Context.OverloadTy);
16449
16450 // Dig out the member expression. This holds both the object
16451 // argument and the member function we're referring to.
16452 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16453
16454 // Determine whether this is a call to a pointer-to-member function.
16455 if (BinaryOperator *op = dyn_cast<BinaryOperator>(Val: NakedMemExpr)) {
16456 assert(op->getType() == Context.BoundMemberTy);
16457 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16458
16459 QualType fnType =
16460 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16461
16462 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16463 QualType resultType = proto->getCallResultType(Context);
16464 ExprValueKind valueKind = Expr::getValueKindForType(T: proto->getReturnType());
16465
16466 // Check that the object type isn't more qualified than the
16467 // member function we're calling.
16468 Qualifiers funcQuals = proto->getMethodQuals();
16469
16470 QualType objectType = op->getLHS()->getType();
16471 if (op->getOpcode() == BO_PtrMemI)
16472 objectType = objectType->castAs<PointerType>()->getPointeeType();
16473 Qualifiers objectQuals = objectType.getQualifiers();
16474
16475 Qualifiers difference = objectQuals - funcQuals;
16476 difference.removeObjCGCAttr();
16477 difference.removeAddressSpace();
16478 if (difference) {
16479 std::string qualsString = difference.getAsString();
16480 Diag(Loc: LParenLoc, DiagID: diag::err_pointer_to_member_call_drops_quals)
16481 << fnType.getUnqualifiedType()
16482 << qualsString
16483 << (qualsString.find(c: ' ') == std::string::npos ? 1 : 2);
16484 }
16485
16486 CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
16487 Ctx: Context, Fn: MemExprE, Args, Ty: resultType, VK: valueKind, RP: RParenLoc,
16488 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: proto->getNumParams());
16489
16490 if (CheckCallReturnType(ReturnType: proto->getReturnType(), Loc: op->getRHS()->getBeginLoc(),
16491 CE: call, FD: nullptr))
16492 return ExprError();
16493
16494 if (ConvertArgumentsForCall(Call: call, Fn: op, FDecl: nullptr, Proto: proto, Args, RParenLoc))
16495 return ExprError();
16496
16497 if (CheckOtherCall(TheCall: call, Proto: proto))
16498 return ExprError();
16499
16500 return MaybeBindToTemporary(E: call);
16501 }
16502
16503 // We only try to build a recovery expr at this level if we can preserve
16504 // the return type, otherwise we return ExprError() and let the caller
16505 // recover.
16506 auto BuildRecoveryExpr = [&](QualType Type) {
16507 if (!AllowRecovery)
16508 return ExprError();
16509 std::vector<Expr *> SubExprs = {MemExprE};
16510 llvm::append_range(C&: SubExprs, R&: Args);
16511 return CreateRecoveryExpr(Begin: MemExprE->getBeginLoc(), End: RParenLoc, SubExprs,
16512 T: Type);
16513 };
16514 if (isa<CXXPseudoDestructorExpr>(Val: NakedMemExpr))
16515 return CallExpr::Create(Ctx: Context, Fn: MemExprE, Args, Ty: Context.VoidTy, VK: VK_PRValue,
16516 RParenLoc, FPFeatures: CurFPFeatureOverrides());
16517
16518 UnbridgedCastsSet UnbridgedCasts;
16519 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts))
16520 return ExprError();
16521
16522 MemberExpr *MemExpr;
16523 CXXMethodDecl *Method = nullptr;
16524 bool HadMultipleCandidates = false;
16525 DeclAccessPair FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_public);
16526 NestedNameSpecifier Qualifier = std::nullopt;
16527 if (isa<MemberExpr>(Val: NakedMemExpr)) {
16528 MemExpr = cast<MemberExpr>(Val: NakedMemExpr);
16529 Method = cast<CXXMethodDecl>(Val: MemExpr->getMemberDecl());
16530 FoundDecl = MemExpr->getFoundDecl();
16531 Qualifier = MemExpr->getQualifier();
16532 UnbridgedCasts.restore();
16533 } else {
16534 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(Val: NakedMemExpr);
16535 Qualifier = UnresExpr->getQualifier();
16536
16537 QualType ObjectType = UnresExpr->getBaseType();
16538 Expr::Classification ObjectClassification
16539 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
16540 : UnresExpr->getBase()->Classify(Ctx&: Context);
16541
16542 // Add overload candidates
16543 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16544 OverloadCandidateSet::CSK_Normal);
16545
16546 // FIXME: avoid copy.
16547 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16548 if (UnresExpr->hasExplicitTemplateArgs()) {
16549 UnresExpr->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
16550 TemplateArgs = &TemplateArgsBuffer;
16551 }
16552
16553 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
16554 E = UnresExpr->decls_end(); I != E; ++I) {
16555
16556 QualType ExplicitObjectType = ObjectType;
16557
16558 NamedDecl *Func = *I;
16559 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: Func->getDeclContext());
16560 if (isa<UsingShadowDecl>(Val: Func))
16561 Func = cast<UsingShadowDecl>(Val: Func)->getTargetDecl();
16562
16563 bool HasExplicitParameter = false;
16564 if (const auto *M = dyn_cast<FunctionDecl>(Val: Func);
16565 M && M->hasCXXExplicitFunctionObjectParameter())
16566 HasExplicitParameter = true;
16567 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Val: Func);
16568 M &&
16569 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16570 HasExplicitParameter = true;
16571
16572 if (HasExplicitParameter)
16573 ExplicitObjectType = GetExplicitObjectType(S&: *this, MemExprE: UnresExpr);
16574
16575 // Microsoft supports direct constructor calls.
16576 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Val: Func)) {
16577 AddOverloadCandidate(Function: cast<CXXConstructorDecl>(Val: Func), FoundDecl: I.getPair(), Args,
16578 CandidateSet,
16579 /*SuppressUserConversions*/ false);
16580 } else if ((Method = dyn_cast<CXXMethodDecl>(Val: Func))) {
16581 // If explicit template arguments were provided, we can't call a
16582 // non-template member function.
16583 if (TemplateArgs)
16584 continue;
16585
16586 AddMethodCandidate(Method, FoundDecl: I.getPair(), ActingContext: ActingDC, ObjectType: ExplicitObjectType,
16587 ObjectClassification, Args, CandidateSet,
16588 /*SuppressUserConversions=*/false);
16589 } else {
16590 AddMethodTemplateCandidate(MethodTmpl: cast<FunctionTemplateDecl>(Val: Func),
16591 FoundDecl: I.getPair(), ActingContext: ActingDC, ExplicitTemplateArgs: TemplateArgs,
16592 ObjectType: ExplicitObjectType, ObjectClassification,
16593 Args, CandidateSet,
16594 /*SuppressUserConversions=*/false);
16595 }
16596 }
16597
16598 HadMultipleCandidates = (CandidateSet.size() > 1);
16599
16600 DeclarationName DeclName = UnresExpr->getMemberName();
16601
16602 UnbridgedCasts.restore();
16603
16604 OverloadCandidateSet::iterator Best;
16605 bool Succeeded = false;
16606 switch (CandidateSet.BestViableFunction(S&: *this, Loc: UnresExpr->getBeginLoc(),
16607 Best)) {
16608 case OR_Success:
16609 Method = cast<CXXMethodDecl>(Val: Best->Function);
16610 FoundDecl = Best->FoundDecl;
16611 CheckUnresolvedMemberAccess(E: UnresExpr, FoundDecl: Best->FoundDecl);
16612 if (DiagnoseUseOfOverloadedDecl(D: Best->FoundDecl, Loc: UnresExpr->getNameLoc()))
16613 break;
16614 // If FoundDecl is different from Method (such as if one is a template
16615 // and the other a specialization), make sure DiagnoseUseOfDecl is
16616 // called on both.
16617 // FIXME: This would be more comprehensively addressed by modifying
16618 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16619 // being used.
16620 if (Method != FoundDecl.getDecl() &&
16621 DiagnoseUseOfOverloadedDecl(D: Method, Loc: UnresExpr->getNameLoc()))
16622 break;
16623 Succeeded = true;
16624 break;
16625
16626 case OR_No_Viable_Function:
16627 CandidateSet.NoteCandidates(
16628 PD: PartialDiagnosticAt(
16629 UnresExpr->getMemberLoc(),
16630 PDiag(DiagID: diag::err_ovl_no_viable_member_function_in_call)
16631 << DeclName << MemExprE->getSourceRange()),
16632 S&: *this, OCD: OCD_AllCandidates, Args);
16633 break;
16634 case OR_Ambiguous:
16635 CandidateSet.NoteCandidates(
16636 PD: PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16637 PDiag(DiagID: diag::err_ovl_ambiguous_member_call)
16638 << DeclName << MemExprE->getSourceRange()),
16639 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
16640 break;
16641 case OR_Deleted:
16642 DiagnoseUseOfDeletedFunction(
16643 Loc: UnresExpr->getMemberLoc(), Range: MemExprE->getSourceRange(), Name: DeclName,
16644 CandidateSet, Fn: Best->Function, Args, /*IsMember=*/true);
16645 break;
16646 }
16647 // Overload resolution fails, try to recover.
16648 if (!Succeeded)
16649 return BuildRecoveryExpr(chooseRecoveryType(CS&: CandidateSet, Best: &Best));
16650
16651 ExprResult Res =
16652 FixOverloadedFunctionReference(E: MemExprE, FoundDecl, Fn: Method);
16653 if (Res.isInvalid())
16654 return ExprError();
16655 MemExprE = Res.get();
16656
16657 // If overload resolution picked a static member
16658 // build a non-member call based on that function.
16659 if (Method->isStatic()) {
16660 return BuildResolvedCallExpr(Fn: MemExprE, NDecl: Method, LParenLoc, Arg: Args, RParenLoc,
16661 Config: ExecConfig, IsExecConfig);
16662 }
16663
16664 MemExpr = cast<MemberExpr>(Val: MemExprE->IgnoreParens());
16665 }
16666
16667 QualType ResultType = Method->getReturnType();
16668 ExprValueKind VK = Expr::getValueKindForType(T: ResultType);
16669 ResultType = ResultType.getNonLValueExprType(Context);
16670
16671 assert(Method && "Member call to something that isn't a method?");
16672 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16673
16674 CallExpr *TheCall = nullptr;
16675 llvm::SmallVector<Expr *, 8> NewArgs;
16676 if (Method->isExplicitObjectMemberFunction()) {
16677 if (PrepareExplicitObjectArgument(S&: *this, Method, Object: MemExpr->getBase(), Args,
16678 NewArgs))
16679 return ExprError();
16680
16681 // FIXME: avoid copy.
16682 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16683 if (MemExpr->hasExplicitTemplateArgs()) {
16684 MemExpr->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
16685 TemplateArgs = &TemplateArgsBuffer;
16686 }
16687
16688 // Build the actual expression node.
16689 ExprResult FnExpr = CreateFunctionRefExpr(
16690 S&: *this, QualifierLoc: MemExpr->getQualifierLoc(), TemplateKWLoc: MemExpr->getTemplateKeywordLoc(),
16691 Fn: Method, FoundDecl, Base: MemExpr, HadMultipleCandidates,
16692 NameInfo: MemExpr->getMemberNameInfo(), TemplateArgs);
16693 if (FnExpr.isInvalid())
16694 return ExprError();
16695
16696 TheCall =
16697 CallExpr::Create(Ctx: Context, Fn: FnExpr.get(), Args, Ty: ResultType, VK, RParenLoc,
16698 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: Proto->getNumParams());
16699 TheCall->setUsesMemberSyntax(true);
16700 } else {
16701 // Convert the object argument (for a non-static member function call).
16702 ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization(
16703 From: MemExpr->getBase(), Qualifier, FoundDecl, Method);
16704 if (ObjectArg.isInvalid())
16705 return ExprError();
16706 MemExpr->setBase(ObjectArg.get());
16707 TheCall = CXXMemberCallExpr::Create(Ctx: Context, Fn: MemExprE, Args, Ty: ResultType, VK,
16708 RP: RParenLoc, FPFeatures: CurFPFeatureOverrides(),
16709 MinNumArgs: Proto->getNumParams());
16710 }
16711
16712 // Check for a valid return type.
16713 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: MemExpr->getMemberLoc(),
16714 CE: TheCall, FD: Method))
16715 return BuildRecoveryExpr(ResultType);
16716
16717 // Convert the rest of the arguments
16718 if (ConvertArgumentsForCall(Call: TheCall, Fn: MemExpr, FDecl: Method, Proto, Args,
16719 RParenLoc))
16720 return BuildRecoveryExpr(ResultType);
16721
16722 DiagnoseSentinelCalls(D: Method, Loc: LParenLoc, Args);
16723
16724 if (CheckFunctionCall(FDecl: Method, TheCall, Proto))
16725 return ExprError();
16726
16727 // In the case the method to call was not selected by the overloading
16728 // resolution process, we still need to handle the enable_if attribute. Do
16729 // that here, so it will not hide previous -- and more relevant -- errors.
16730 if (auto *MemE = dyn_cast<MemberExpr>(Val: NakedMemExpr)) {
16731 if (const EnableIfAttr *Attr =
16732 CheckEnableIf(Function: Method, CallLoc: LParenLoc, Args, MissingImplicitThis: true)) {
16733 Diag(Loc: MemE->getMemberLoc(),
16734 DiagID: diag::err_ovl_no_viable_member_function_in_call)
16735 << Method << Method->getSourceRange();
16736 Diag(Loc: Method->getLocation(),
16737 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
16738 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16739 return ExprError();
16740 }
16741 }
16742
16743 if (isa<CXXConstructorDecl, CXXDestructorDecl>(Val: CurContext) &&
16744 TheCall->getDirectCallee()->isPureVirtual()) {
16745 const FunctionDecl *MD = TheCall->getDirectCallee();
16746
16747 if (isa<CXXThisExpr>(Val: MemExpr->getBase()->IgnoreParenCasts()) &&
16748 MemExpr->performsVirtualDispatch(LO: getLangOpts())) {
16749 Diag(Loc: MemExpr->getBeginLoc(),
16750 DiagID: diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16751 << MD->getDeclName() << isa<CXXDestructorDecl>(Val: CurContext)
16752 << MD->getParent();
16753
16754 Diag(Loc: MD->getBeginLoc(), DiagID: diag::note_previous_decl) << MD->getDeclName();
16755 if (getLangOpts().AppleKext)
16756 Diag(Loc: MemExpr->getBeginLoc(), DiagID: diag::note_pure_qualified_call_kext)
16757 << MD->getParent() << MD->getDeclName();
16758 }
16759 }
16760
16761 if (auto *DD = dyn_cast<CXXDestructorDecl>(Val: TheCall->getDirectCallee())) {
16762 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16763 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16764 CheckVirtualDtorCall(dtor: DD, Loc: MemExpr->getBeginLoc(), /*IsDelete=*/false,
16765 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16766 DtorLoc: MemExpr->getMemberLoc());
16767 }
16768
16769 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall),
16770 Decl: TheCall->getDirectCallee());
16771}
16772
16773ExprResult
16774Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
16775 SourceLocation LParenLoc,
16776 MultiExprArg Args,
16777 SourceLocation RParenLoc) {
16778 if (checkPlaceholderForOverload(S&: *this, E&: Obj))
16779 return ExprError();
16780 ExprResult Object = Obj;
16781
16782 UnbridgedCastsSet UnbridgedCasts;
16783 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts))
16784 return ExprError();
16785
16786 assert(Object.get()->getType()->isRecordType() &&
16787 "Requires object type argument");
16788
16789 // C++ [over.call.object]p1:
16790 // If the primary-expression E in the function call syntax
16791 // evaluates to a class object of type "cv T", then the set of
16792 // candidate functions includes at least the function call
16793 // operators of T. The function call operators of T are obtained by
16794 // ordinary lookup of the name operator() in the context of
16795 // (E).operator().
16796 OverloadCandidateSet CandidateSet(LParenLoc,
16797 OverloadCandidateSet::CSK_Operator);
16798 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op: OO_Call);
16799
16800 if (RequireCompleteType(Loc: LParenLoc, T: Object.get()->getType(),
16801 DiagID: diag::err_incomplete_object_call, Args: Object.get()))
16802 return true;
16803
16804 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();
16805 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16806 LookupQualifiedName(R, LookupCtx: Record);
16807 R.suppressAccessDiagnostics();
16808
16809 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16810 Oper != OperEnd; ++Oper) {
16811 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Object.get()->getType(),
16812 ObjectClassification: Object.get()->Classify(Ctx&: Context), Args, CandidateSet,
16813 /*SuppressUserConversion=*/SuppressUserConversions: false);
16814 }
16815
16816 // When calling a lambda, both the call operator, and
16817 // the conversion operator to function pointer
16818 // are considered. But when constraint checking
16819 // on the call operator fails, it will also fail on the
16820 // conversion operator as the constraints are always the same.
16821 // As the user probably does not intend to perform a surrogate call,
16822 // we filter them out to produce better error diagnostics, ie to avoid
16823 // showing 2 failed overloads instead of one.
16824 bool IgnoreSurrogateFunctions = false;
16825 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {
16826 const OverloadCandidate &Candidate = *CandidateSet.begin();
16827 if (!Candidate.Viable &&
16828 Candidate.FailureKind == ovl_fail_constraints_not_satisfied)
16829 IgnoreSurrogateFunctions = true;
16830 }
16831
16832 // C++ [over.call.object]p2:
16833 // In addition, for each (non-explicit in C++0x) conversion function
16834 // declared in T of the form
16835 //
16836 // operator conversion-type-id () cv-qualifier;
16837 //
16838 // where cv-qualifier is the same cv-qualification as, or a
16839 // greater cv-qualification than, cv, and where conversion-type-id
16840 // denotes the type "pointer to function of (P1,...,Pn) returning
16841 // R", or the type "reference to pointer to function of
16842 // (P1,...,Pn) returning R", or the type "reference to function
16843 // of (P1,...,Pn) returning R", a surrogate call function [...]
16844 // is also considered as a candidate function. Similarly,
16845 // surrogate call functions are added to the set of candidate
16846 // functions for each conversion function declared in an
16847 // accessible base class provided the function is not hidden
16848 // within T by another intervening declaration.
16849 const auto &Conversions = Record->getVisibleConversionFunctions();
16850 for (auto I = Conversions.begin(), E = Conversions.end();
16851 !IgnoreSurrogateFunctions && I != E; ++I) {
16852 NamedDecl *D = *I;
16853 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
16854 if (isa<UsingShadowDecl>(Val: D))
16855 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
16856
16857 // Skip over templated conversion functions; they aren't
16858 // surrogates.
16859 if (isa<FunctionTemplateDecl>(Val: D))
16860 continue;
16861
16862 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
16863 if (!Conv->isExplicit()) {
16864 // Strip the reference type (if any) and then the pointer type (if
16865 // any) to get down to what might be a function type.
16866 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16867 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16868 ConvType = ConvPtrType->getPointeeType();
16869
16870 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16871 {
16872 AddSurrogateCandidate(Conversion: Conv, FoundDecl: I.getPair(), ActingContext, Proto,
16873 Object: Object.get(), Args, CandidateSet);
16874 }
16875 }
16876 }
16877
16878 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16879
16880 // Perform overload resolution.
16881 OverloadCandidateSet::iterator Best;
16882 switch (CandidateSet.BestViableFunction(S&: *this, Loc: Object.get()->getBeginLoc(),
16883 Best)) {
16884 case OR_Success:
16885 // Overload resolution succeeded; we'll build the appropriate call
16886 // below.
16887 break;
16888
16889 case OR_No_Viable_Function: {
16890 PartialDiagnostic PD =
16891 CandidateSet.empty()
16892 ? (PDiag(DiagID: diag::err_ovl_no_oper)
16893 << Object.get()->getType() << /*call*/ 1
16894 << Object.get()->getSourceRange())
16895 : (PDiag(DiagID: diag::err_ovl_no_viable_object_call)
16896 << Object.get()->getType() << Object.get()->getSourceRange());
16897 CandidateSet.NoteCandidates(
16898 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), S&: *this,
16899 OCD: OCD_AllCandidates, Args);
16900 break;
16901 }
16902 case OR_Ambiguous:
16903 if (!R.isAmbiguous())
16904 CandidateSet.NoteCandidates(
16905 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(),
16906 PDiag(DiagID: diag::err_ovl_ambiguous_object_call)
16907 << Object.get()->getType()
16908 << Object.get()->getSourceRange()),
16909 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
16910 break;
16911
16912 case OR_Deleted: {
16913 // FIXME: Is this diagnostic here really necessary? It seems that
16914 // 1. we don't have any tests for this diagnostic, and
16915 // 2. we already issue err_deleted_function_use for this later on anyway.
16916 StringLiteral *Msg = Best->Function->getDeletedMessage();
16917 CandidateSet.NoteCandidates(
16918 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(),
16919 PDiag(DiagID: diag::err_ovl_deleted_object_call)
16920 << Object.get()->getType() << (Msg != nullptr)
16921 << (Msg ? Msg->getString() : StringRef())
16922 << Object.get()->getSourceRange()),
16923 S&: *this, OCD: OCD_AllCandidates, Args);
16924 break;
16925 }
16926 }
16927
16928 if (Best == CandidateSet.end())
16929 return true;
16930
16931 UnbridgedCasts.restore();
16932
16933 if (Best->Function == nullptr) {
16934 // Since there is no function declaration, this is one of the
16935 // surrogate candidates. Dig out the conversion function.
16936 CXXConversionDecl *Conv
16937 = cast<CXXConversionDecl>(
16938 Val: Best->Conversions[0].UserDefined.ConversionFunction);
16939
16940 // FoundDecl may be a UsingShadowDecl naming the conversion function.
16941 assert(Conv == Best->FoundDecl.getDecl()->getUnderlyingDecl() &&
16942 "Found Decl & conversion-to-functionptr should be same, right?!");
16943 CheckMemberOperatorAccess(Loc: LParenLoc, ObjectExpr: Object.get(), ArgExpr: nullptr,
16944 FoundDecl: Best->FoundDecl);
16945 if (DiagnoseUseOfDecl(D: Conv, Locs: LParenLoc))
16946 return ExprError();
16947 // We selected one of the surrogate functions that converts the
16948 // object parameter to a function pointer. Perform the conversion
16949 // on the object argument, then let BuildCallExpr finish the job.
16950
16951 // Create an implicit member expr to refer to the conversion operator.
16952 // and then call it.
16953 ExprResult Call = BuildCXXMemberCallExpr(E: Object.get(), FoundDecl: Best->FoundDecl,
16954 Method: Conv, HadMultipleCandidates);
16955 if (Call.isInvalid())
16956 return ExprError();
16957 // Record usage of conversion in an implicit cast.
16958 Call = ImplicitCastExpr::Create(
16959 Context, T: Call.get()->getType(), Kind: CK_UserDefinedConversion, Operand: Call.get(),
16960 BasePath: nullptr, Cat: VK_PRValue, FPO: CurFPFeatureOverrides());
16961
16962 return BuildCallExpr(S, Fn: Call.get(), LParenLoc, ArgExprs: Args, RParenLoc);
16963 }
16964
16965 CheckMemberOperatorAccess(Loc: LParenLoc, ObjectExpr: Object.get(), ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
16966
16967 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16968 // that calls this method, using Object for the implicit object
16969 // parameter and passing along the remaining arguments.
16970 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Best->Function);
16971
16972 // An error diagnostic has already been printed when parsing the declaration.
16973 if (Method->isInvalidDecl())
16974 return ExprError();
16975
16976 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16977 unsigned NumParams = Proto->getNumParams();
16978
16979 DeclarationNameInfo OpLocInfo(
16980 Context.DeclarationNames.getCXXOperatorName(Op: OO_Call), LParenLoc);
16981 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16982 ExprResult NewFn = CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl: Best->FoundDecl, Base: Obj,
16983 HadMultipleCandidates, NameInfo: OpLocInfo);
16984 if (NewFn.isInvalid())
16985 return true;
16986
16987 SmallVector<Expr *, 8> MethodArgs;
16988 MethodArgs.reserve(N: NumParams + 1);
16989
16990 bool IsError = false;
16991
16992 // Initialize the object parameter.
16993 llvm::SmallVector<Expr *, 8> NewArgs;
16994 if (Method->isExplicitObjectMemberFunction()) {
16995 IsError |= PrepareExplicitObjectArgument(S&: *this, Method, Object: Obj, Args, NewArgs);
16996 } else {
16997 ExprResult ObjRes = PerformImplicitObjectArgumentInitialization(
16998 From: Object.get(), /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
16999 if (ObjRes.isInvalid())
17000 IsError = true;
17001 else
17002 Object = ObjRes;
17003 MethodArgs.push_back(Elt: Object.get());
17004 }
17005
17006 IsError |= PrepareArgumentsForCallToObjectOfClassType(
17007 S&: *this, MethodArgs, Method, Args, LParenLoc);
17008
17009 // If this is a variadic call, handle args passed through "...".
17010 if (Proto->isVariadic()) {
17011 // Promote the arguments (C99 6.5.2.2p7).
17012 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
17013 ExprResult Arg = DefaultVariadicArgumentPromotion(
17014 E: Args[i], CT: VariadicCallType::Method, FDecl: nullptr);
17015 IsError |= Arg.isInvalid();
17016 MethodArgs.push_back(Elt: Arg.get());
17017 }
17018 }
17019
17020 if (IsError)
17021 return true;
17022
17023 DiagnoseSentinelCalls(D: Method, Loc: LParenLoc, Args);
17024
17025 // Once we've built TheCall, all of the expressions are properly owned.
17026 QualType ResultTy = Method->getReturnType();
17027 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
17028 ResultTy = ResultTy.getNonLValueExprType(Context);
17029
17030 CallExpr *TheCall = CXXOperatorCallExpr::Create(
17031 Ctx: Context, OpKind: OO_Call, Fn: NewFn.get(), Args: MethodArgs, Ty: ResultTy, VK, OperatorLoc: RParenLoc,
17032 FPFeatures: CurFPFeatureOverrides());
17033
17034 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: LParenLoc, CE: TheCall, FD: Method))
17035 return true;
17036
17037 if (CheckFunctionCall(FDecl: Method, TheCall, Proto))
17038 return true;
17039
17040 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: Method);
17041}
17042
17043ExprResult Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base,
17044 SourceLocation OpLoc,
17045 bool *NoArrowOperatorFound) {
17046 assert(Base->getType()->isRecordType() &&
17047 "left-hand side must have class type");
17048
17049 if (checkPlaceholderForOverload(S&: *this, E&: Base))
17050 return ExprError();
17051
17052 SourceLocation Loc = Base->getExprLoc();
17053
17054 // C++ [over.ref]p1:
17055 //
17056 // [...] An expression x->m is interpreted as (x.operator->())->m
17057 // for a class object x of type T if T::operator->() exists and if
17058 // the operator is selected as the best match function by the
17059 // overload resolution mechanism (13.3).
17060 DeclarationName OpName =
17061 Context.DeclarationNames.getCXXOperatorName(Op: OO_Arrow);
17062 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
17063
17064 if (RequireCompleteType(Loc, T: Base->getType(),
17065 DiagID: diag::err_typecheck_incomplete_tag, Args: Base))
17066 return ExprError();
17067
17068 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
17069 LookupQualifiedName(R, LookupCtx: Base->getType()->castAsRecordDecl());
17070 R.suppressAccessDiagnostics();
17071
17072 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
17073 Oper != OperEnd; ++Oper) {
17074 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Base->getType(), ObjectClassification: Base->Classify(Ctx&: Context),
17075 Args: {}, CandidateSet,
17076 /*SuppressUserConversion=*/SuppressUserConversions: false);
17077 }
17078
17079 bool HadMultipleCandidates = (CandidateSet.size() > 1);
17080
17081 // Perform overload resolution.
17082 OverloadCandidateSet::iterator Best;
17083 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
17084 case OR_Success:
17085 // Overload resolution succeeded; we'll build the call below.
17086 break;
17087
17088 case OR_No_Viable_Function: {
17089 auto Cands = CandidateSet.CompleteCandidates(S&: *this, OCD: OCD_AllCandidates, Args: Base);
17090 if (CandidateSet.empty()) {
17091 QualType BaseType = Base->getType();
17092 if (NoArrowOperatorFound) {
17093 // Report this specific error to the caller instead of emitting a
17094 // diagnostic, as requested.
17095 *NoArrowOperatorFound = true;
17096 return ExprError();
17097 }
17098 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_member_reference_arrow)
17099 << BaseType << Base->getSourceRange();
17100 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
17101 Diag(Loc: OpLoc, DiagID: diag::note_typecheck_member_reference_suggestion)
17102 << FixItHint::CreateReplacement(RemoveRange: OpLoc, Code: ".");
17103 }
17104 } else
17105 Diag(Loc: OpLoc, DiagID: diag::err_ovl_no_viable_oper)
17106 << "operator->" << Base->getSourceRange();
17107 CandidateSet.NoteCandidates(S&: *this, Args: Base, Cands);
17108 return ExprError();
17109 }
17110 case OR_Ambiguous:
17111 if (!R.isAmbiguous())
17112 CandidateSet.NoteCandidates(
17113 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_unary)
17114 << "->" << Base->getType()
17115 << Base->getSourceRange()),
17116 S&: *this, OCD: OCD_AmbiguousCandidates, Args: Base);
17117 return ExprError();
17118
17119 case OR_Deleted: {
17120 StringLiteral *Msg = Best->Function->getDeletedMessage();
17121 CandidateSet.NoteCandidates(
17122 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_deleted_oper)
17123 << "->" << (Msg != nullptr)
17124 << (Msg ? Msg->getString() : StringRef())
17125 << Base->getSourceRange()),
17126 S&: *this, OCD: OCD_AllCandidates, Args: Base);
17127 return ExprError();
17128 }
17129 }
17130
17131 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Base, ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
17132
17133 // Convert the object parameter.
17134 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Best->Function);
17135
17136 if (Method->isExplicitObjectMemberFunction()) {
17137 ExprResult R = InitializeExplicitObjectArgument(S&: *this, Obj: Base, Fun: Method);
17138 if (R.isInvalid())
17139 return ExprError();
17140 Base = R.get();
17141 } else {
17142 ExprResult BaseResult = PerformImplicitObjectArgumentInitialization(
17143 From: Base, /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
17144 if (BaseResult.isInvalid())
17145 return ExprError();
17146 Base = BaseResult.get();
17147 }
17148
17149 // Build the operator call.
17150 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl: Best->FoundDecl,
17151 Base, HadMultipleCandidates, Loc: OpLoc);
17152 if (FnExpr.isInvalid())
17153 return ExprError();
17154
17155 QualType ResultTy = Method->getReturnType();
17156 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
17157 ResultTy = ResultTy.getNonLValueExprType(Context);
17158
17159 CallExpr *TheCall =
17160 CXXOperatorCallExpr::Create(Ctx: Context, OpKind: OO_Arrow, Fn: FnExpr.get(), Args: Base,
17161 Ty: ResultTy, VK, OperatorLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
17162
17163 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: OpLoc, CE: TheCall, FD: Method))
17164 return ExprError();
17165
17166 if (CheckFunctionCall(FDecl: Method, TheCall,
17167 Proto: Method->getType()->castAs<FunctionProtoType>()))
17168 return ExprError();
17169
17170 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: Method);
17171}
17172
17173ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
17174 DeclarationNameInfo &SuffixInfo,
17175 ArrayRef<Expr*> Args,
17176 SourceLocation LitEndLoc,
17177 TemplateArgumentListInfo *TemplateArgs) {
17178 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
17179
17180 OverloadCandidateSet CandidateSet(UDSuffixLoc,
17181 OverloadCandidateSet::CSK_Normal);
17182 AddNonMemberOperatorCandidates(Fns: R.asUnresolvedSet(), Args, CandidateSet,
17183 ExplicitTemplateArgs: TemplateArgs);
17184
17185 bool HadMultipleCandidates = (CandidateSet.size() > 1);
17186
17187 // Perform overload resolution. This will usually be trivial, but might need
17188 // to perform substitutions for a literal operator template.
17189 OverloadCandidateSet::iterator Best;
17190 switch (CandidateSet.BestViableFunction(S&: *this, Loc: UDSuffixLoc, Best)) {
17191 case OR_Success:
17192 case OR_Deleted:
17193 break;
17194
17195 case OR_No_Viable_Function:
17196 CandidateSet.NoteCandidates(
17197 PD: PartialDiagnosticAt(UDSuffixLoc,
17198 PDiag(DiagID: diag::err_ovl_no_viable_function_in_call)
17199 << R.getLookupName()),
17200 S&: *this, OCD: OCD_AllCandidates, Args);
17201 return ExprError();
17202
17203 case OR_Ambiguous:
17204 CandidateSet.NoteCandidates(
17205 PD: PartialDiagnosticAt(R.getNameLoc(), PDiag(DiagID: diag::err_ovl_ambiguous_call)
17206 << R.getLookupName()),
17207 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
17208 return ExprError();
17209 }
17210
17211 FunctionDecl *FD = Best->Function;
17212 ExprResult Fn = CreateFunctionRefExpr(S&: *this, Fn: FD, FoundDecl: Best->FoundDecl, Base: nullptr,
17213 HadMultipleCandidates, NameInfo: SuffixInfo);
17214 if (Fn.isInvalid())
17215 return true;
17216
17217 // Check the argument types. This should almost always be a no-op, except
17218 // that array-to-pointer decay is applied to string literals.
17219 Expr *ConvArgs[2];
17220 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
17221 ExprResult InputInit = PerformCopyInitialization(
17222 Entity: InitializedEntity::InitializeParameter(Context, Parm: FD->getParamDecl(i: ArgIdx)),
17223 EqualLoc: SourceLocation(), Init: Args[ArgIdx]);
17224 if (InputInit.isInvalid())
17225 return true;
17226 ConvArgs[ArgIdx] = InputInit.get();
17227 }
17228
17229 QualType ResultTy = FD->getReturnType();
17230 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
17231 ResultTy = ResultTy.getNonLValueExprType(Context);
17232
17233 UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
17234 Ctx: Context, Fn: Fn.get(), Args: llvm::ArrayRef(ConvArgs, Args.size()), Ty: ResultTy, VK,
17235 LitEndLoc, SuffixLoc: UDSuffixLoc, FPFeatures: CurFPFeatureOverrides());
17236
17237 if (CheckCallReturnType(ReturnType: FD->getReturnType(), Loc: UDSuffixLoc, CE: UDL, FD))
17238 return ExprError();
17239
17240 if (CheckFunctionCall(FDecl: FD, TheCall: UDL, Proto: nullptr))
17241 return ExprError();
17242
17243 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: UDL), Decl: FD);
17244}
17245
17246Sema::ForRangeStatus
17247Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
17248 SourceLocation RangeLoc,
17249 const DeclarationNameInfo &NameInfo,
17250 LookupResult &MemberLookup,
17251 OverloadCandidateSet *CandidateSet,
17252 Expr *Range, ExprResult *CallExpr) {
17253 Scope *S = nullptr;
17254
17255 CandidateSet->clear(CSK: OverloadCandidateSet::CSK_Normal);
17256 if (!MemberLookup.empty()) {
17257 ExprResult MemberRef =
17258 BuildMemberReferenceExpr(Base: Range, BaseType: Range->getType(), OpLoc: Loc,
17259 /*IsPtr=*/IsArrow: false, SS: CXXScopeSpec(),
17260 /*TemplateKWLoc=*/SourceLocation(),
17261 /*FirstQualifierInScope=*/nullptr,
17262 R&: MemberLookup,
17263 /*TemplateArgs=*/nullptr, S);
17264 if (MemberRef.isInvalid()) {
17265 *CallExpr = ExprError();
17266 return FRS_DiagnosticIssued;
17267 }
17268 *CallExpr = BuildCallExpr(S, Fn: MemberRef.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc, ExecConfig: nullptr);
17269 if (CallExpr->isInvalid()) {
17270 *CallExpr = ExprError();
17271 return FRS_DiagnosticIssued;
17272 }
17273 } else {
17274 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
17275 NNSLoc: NestedNameSpecifierLoc(),
17276 DNI: NameInfo, Fns: UnresolvedSet<0>());
17277 if (FnR.isInvalid())
17278 return FRS_DiagnosticIssued;
17279 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(Val: FnR.get());
17280
17281 bool CandidateSetError = buildOverloadedCallSet(S, Fn, ULE: Fn, Args: Range, RParenLoc: Loc,
17282 CandidateSet, Result: CallExpr);
17283 if (CandidateSet->empty() || CandidateSetError) {
17284 *CallExpr = ExprError();
17285 return FRS_NoViableFunction;
17286 }
17287 OverloadCandidateSet::iterator Best;
17288 OverloadingResult OverloadResult =
17289 CandidateSet->BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best);
17290
17291 if (OverloadResult == OR_No_Viable_Function) {
17292 *CallExpr = ExprError();
17293 return FRS_NoViableFunction;
17294 }
17295 *CallExpr = FinishOverloadedCallExpr(SemaRef&: *this, S, Fn, ULE: Fn, LParenLoc: Loc, Args: Range,
17296 RParenLoc: Loc, ExecConfig: nullptr, CandidateSet, Best: &Best,
17297 OverloadResult,
17298 /*AllowTypoCorrection=*/false);
17299 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
17300 *CallExpr = ExprError();
17301 return FRS_DiagnosticIssued;
17302 }
17303 }
17304 return FRS_Success;
17305}
17306
17307ExprResult Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
17308 FunctionDecl *Fn) {
17309 if (ParenExpr *PE = dyn_cast<ParenExpr>(Val: E)) {
17310 ExprResult SubExpr =
17311 FixOverloadedFunctionReference(E: PE->getSubExpr(), Found, Fn);
17312 if (SubExpr.isInvalid())
17313 return ExprError();
17314 if (SubExpr.get() == PE->getSubExpr())
17315 return PE;
17316
17317 return new (Context)
17318 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
17319 }
17320
17321 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
17322 ExprResult SubExpr =
17323 FixOverloadedFunctionReference(E: ICE->getSubExpr(), Found, Fn);
17324 if (SubExpr.isInvalid())
17325 return ExprError();
17326 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
17327 SubExpr.get()->getType()) &&
17328 "Implicit cast type cannot be determined from overload");
17329 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
17330 if (SubExpr.get() == ICE->getSubExpr())
17331 return ICE;
17332
17333 return ImplicitCastExpr::Create(Context, T: ICE->getType(), Kind: ICE->getCastKind(),
17334 Operand: SubExpr.get(), BasePath: nullptr, Cat: ICE->getValueKind(),
17335 FPO: CurFPFeatureOverrides());
17336 }
17337
17338 if (auto *GSE = dyn_cast<GenericSelectionExpr>(Val: E)) {
17339 if (!GSE->isResultDependent()) {
17340 ExprResult SubExpr =
17341 FixOverloadedFunctionReference(E: GSE->getResultExpr(), Found, Fn);
17342 if (SubExpr.isInvalid())
17343 return ExprError();
17344 if (SubExpr.get() == GSE->getResultExpr())
17345 return GSE;
17346
17347 // Replace the resulting type information before rebuilding the generic
17348 // selection expression.
17349 ArrayRef<Expr *> A = GSE->getAssocExprs();
17350 SmallVector<Expr *, 4> AssocExprs(A);
17351 unsigned ResultIdx = GSE->getResultIndex();
17352 AssocExprs[ResultIdx] = SubExpr.get();
17353
17354 if (GSE->isExprPredicate())
17355 return GenericSelectionExpr::Create(
17356 Context, GenericLoc: GSE->getGenericLoc(), ControllingExpr: GSE->getControllingExpr(),
17357 AssocTypes: GSE->getAssocTypeSourceInfos(), AssocExprs, DefaultLoc: GSE->getDefaultLoc(),
17358 RParenLoc: GSE->getRParenLoc(), ContainsUnexpandedParameterPack: GSE->containsUnexpandedParameterPack(),
17359 ResultIndex: ResultIdx);
17360 return GenericSelectionExpr::Create(
17361 Context, GenericLoc: GSE->getGenericLoc(), ControllingType: GSE->getControllingType(),
17362 AssocTypes: GSE->getAssocTypeSourceInfos(), AssocExprs, DefaultLoc: GSE->getDefaultLoc(),
17363 RParenLoc: GSE->getRParenLoc(), ContainsUnexpandedParameterPack: GSE->containsUnexpandedParameterPack(),
17364 ResultIndex: ResultIdx);
17365 }
17366 // Rather than fall through to the unreachable, return the original generic
17367 // selection expression.
17368 return GSE;
17369 }
17370
17371 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: E)) {
17372 assert(UnOp->getOpcode() == UO_AddrOf &&
17373 "Can only take the address of an overloaded function");
17374 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn)) {
17375 if (!Method->isImplicitObjectMemberFunction()) {
17376 // Do nothing: the address of static and
17377 // explicit object member functions is a (non-member) function pointer.
17378 } else {
17379 // Fix the subexpression, which really has to be an
17380 // UnresolvedLookupExpr holding an overloaded member function
17381 // or template.
17382 ExprResult SubExpr =
17383 FixOverloadedFunctionReference(E: UnOp->getSubExpr(), Found, Fn);
17384 if (SubExpr.isInvalid())
17385 return ExprError();
17386 if (SubExpr.get() == UnOp->getSubExpr())
17387 return UnOp;
17388
17389 if (CheckUseOfCXXMethodAsAddressOfOperand(OpLoc: UnOp->getBeginLoc(),
17390 Op: SubExpr.get(), MD: Method))
17391 return ExprError();
17392
17393 assert(isa<DeclRefExpr>(SubExpr.get()) &&
17394 "fixed to something other than a decl ref");
17395 NestedNameSpecifier Qualifier =
17396 cast<DeclRefExpr>(Val: SubExpr.get())->getQualifier();
17397 assert(Qualifier &&
17398 "fixed to a member ref with no nested name qualifier");
17399
17400 // We have taken the address of a pointer to member
17401 // function. Perform the computation here so that we get the
17402 // appropriate pointer to member type.
17403 QualType MemPtrType = Context.getMemberPointerType(
17404 T: Fn->getType(), Qualifier,
17405 Cls: cast<CXXRecordDecl>(Val: Method->getDeclContext()));
17406 // Under the MS ABI, lock down the inheritance model now.
17407 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
17408 (void)isCompleteType(Loc: UnOp->getOperatorLoc(), T: MemPtrType);
17409
17410 return UnaryOperator::Create(C: Context, input: SubExpr.get(), opc: UO_AddrOf,
17411 type: MemPtrType, VK: VK_PRValue, OK: OK_Ordinary,
17412 l: UnOp->getOperatorLoc(), CanOverflow: false,
17413 FPFeatures: CurFPFeatureOverrides());
17414 }
17415 }
17416 ExprResult SubExpr =
17417 FixOverloadedFunctionReference(E: UnOp->getSubExpr(), Found, Fn);
17418 if (SubExpr.isInvalid())
17419 return ExprError();
17420 if (SubExpr.get() == UnOp->getSubExpr())
17421 return UnOp;
17422
17423 return CreateBuiltinUnaryOp(OpLoc: UnOp->getOperatorLoc(), Opc: UO_AddrOf,
17424 InputExpr: SubExpr.get());
17425 }
17426
17427 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) {
17428 if (Found.getAccess() == AS_none) {
17429 CheckUnresolvedLookupAccess(E: ULE, FoundDecl: Found);
17430 }
17431 // FIXME: avoid copy.
17432 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17433 if (ULE->hasExplicitTemplateArgs()) {
17434 ULE->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
17435 TemplateArgs = &TemplateArgsBuffer;
17436 }
17437
17438 QualType Type = Fn->getType();
17439 ExprValueKind ValueKind =
17440 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
17441 ? VK_LValue
17442 : VK_PRValue;
17443
17444 // FIXME: Duplicated from BuildDeclarationNameExpr.
17445 if (unsigned BID = Fn->getBuiltinID()) {
17446 if (!Context.BuiltinInfo.isDirectlyAddressable(ID: BID)) {
17447 Type = Context.BuiltinFnTy;
17448 ValueKind = VK_PRValue;
17449 }
17450 }
17451
17452 DeclRefExpr *DRE = BuildDeclRefExpr(
17453 D: Fn, Ty: Type, VK: ValueKind, NameInfo: ULE->getNameInfo(), NNS: ULE->getQualifierLoc(),
17454 FoundD: Found.getDecl(), TemplateKWLoc: ULE->getTemplateKeywordLoc(), TemplateArgs);
17455 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17456 return DRE;
17457 }
17458
17459 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(Val: E)) {
17460 // FIXME: avoid copy.
17461 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17462 if (MemExpr->hasExplicitTemplateArgs()) {
17463 MemExpr->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
17464 TemplateArgs = &TemplateArgsBuffer;
17465 }
17466
17467 Expr *Base;
17468
17469 // If we're filling in a static method where we used to have an
17470 // implicit member access, rewrite to a simple decl ref.
17471 if (MemExpr->isImplicitAccess()) {
17472 if (cast<CXXMethodDecl>(Val: Fn)->isStatic()) {
17473 DeclRefExpr *DRE = BuildDeclRefExpr(
17474 D: Fn, Ty: Fn->getType(), VK: VK_LValue, NameInfo: MemExpr->getNameInfo(),
17475 NNS: MemExpr->getQualifierLoc(), FoundD: Found.getDecl(),
17476 TemplateKWLoc: MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17477 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17478 return DRE;
17479 } else {
17480 SourceLocation Loc = MemExpr->getMemberLoc();
17481 if (MemExpr->getQualifier())
17482 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17483 Base =
17484 BuildCXXThisExpr(Loc, Type: MemExpr->getBaseType(), /*IsImplicit=*/true);
17485 }
17486 } else
17487 Base = MemExpr->getBase();
17488
17489 ExprValueKind valueKind;
17490 QualType type;
17491 if (cast<CXXMethodDecl>(Val: Fn)->isStatic()) {
17492 valueKind = VK_LValue;
17493 type = Fn->getType();
17494 } else {
17495 valueKind = VK_PRValue;
17496 type = Context.BoundMemberTy;
17497 }
17498
17499 return BuildMemberExpr(
17500 Base, IsArrow: MemExpr->isArrow(), OpLoc: MemExpr->getOperatorLoc(),
17501 NNS: MemExpr->getQualifierLoc(), TemplateKWLoc: MemExpr->getTemplateKeywordLoc(), Member: Fn, FoundDecl: Found,
17502 /*HadMultipleCandidates=*/true, MemberNameInfo: MemExpr->getMemberNameInfo(),
17503 Ty: type, VK: valueKind, OK: OK_Ordinary, TemplateArgs);
17504 }
17505
17506 llvm_unreachable("Invalid reference to overloaded function");
17507}
17508
17509ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
17510 DeclAccessPair Found,
17511 FunctionDecl *Fn) {
17512 return FixOverloadedFunctionReference(E: E.get(), Found, Fn);
17513}
17514
17515bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17516 FunctionDecl *Function) {
17517 if (!PartialOverloading || !Function)
17518 return true;
17519 if (Function->isVariadic())
17520 return false;
17521 if (const auto *Proto =
17522 dyn_cast<FunctionProtoType>(Val: Function->getFunctionType()))
17523 if (Proto->isTemplateVariadic())
17524 return false;
17525 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17526 if (const auto *Proto =
17527 dyn_cast<FunctionProtoType>(Val: Pattern->getFunctionType()))
17528 if (Proto->isTemplateVariadic())
17529 return false;
17530 return true;
17531}
17532
17533void Sema::DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range,
17534 DeclarationName Name,
17535 OverloadCandidateSet &CandidateSet,
17536 FunctionDecl *Fn, MultiExprArg Args,
17537 bool IsMember) {
17538 StringLiteral *Msg = Fn->getDeletedMessage();
17539 CandidateSet.NoteCandidates(
17540 PD: PartialDiagnosticAt(Loc, PDiag(DiagID: diag::err_ovl_deleted_call)
17541 << IsMember << Name << (Msg != nullptr)
17542 << (Msg ? Msg->getString() : StringRef())
17543 << Range),
17544 S&: *this, OCD: OCD_AllCandidates, Args);
17545}
17546