xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaOverload.cpp (revision 1db9f3b21e39176dd5b67cf8ac378633b172463e)
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 "clang/AST/ASTContext.h"
14 #include "clang/AST/ASTLambda.h"
15 #include "clang/AST/CXXInheritance.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/DependenceFlags.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/Type.h"
23 #include "clang/AST/TypeOrdering.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/SemaInternal.h"
35 #include "clang/Sema/Template.h"
36 #include "clang/Sema/TemplateDeduction.h"
37 #include "llvm/ADT/DenseSet.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/SmallString.h"
41 #include "llvm/ADT/SmallVector.h"
42 #include "llvm/Support/Casting.h"
43 #include <algorithm>
44 #include <cstddef>
45 #include <cstdlib>
46 #include <optional>
47 
48 using namespace clang;
49 using namespace sema;
50 
51 using AllowedExplicit = Sema::AllowedExplicit;
52 
53 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
54   return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
55     return P->hasAttr<PassObjectSizeAttr>();
56   });
57 }
58 
59 /// A convenience routine for creating a decayed reference to a function.
60 static ExprResult CreateFunctionRefExpr(
61     Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
62     bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
63     const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
64   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
65     return ExprError();
66   // If FoundDecl is different from Fn (such as if one is a template
67   // and the other a specialization), make sure DiagnoseUseOfDecl is
68   // called on both.
69   // FIXME: This would be more comprehensively addressed by modifying
70   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
71   // being used.
72   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
73     return ExprError();
74   DeclRefExpr *DRE = new (S.Context)
75       DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
76   if (HadMultipleCandidates)
77     DRE->setHadMultipleCandidates(true);
78 
79   S.MarkDeclRefReferenced(DRE, Base);
80   if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
81     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
82       S.ResolveExceptionSpec(Loc, FPT);
83       DRE->setType(Fn->getType());
84     }
85   }
86   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
87                              CK_FunctionToPointerDecay);
88 }
89 
90 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
91                                  bool InOverloadResolution,
92                                  StandardConversionSequence &SCS,
93                                  bool CStyle,
94                                  bool AllowObjCWritebackConversion);
95 
96 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
97                                                  QualType &ToType,
98                                                  bool InOverloadResolution,
99                                                  StandardConversionSequence &SCS,
100                                                  bool CStyle);
101 static OverloadingResult
102 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
103                         UserDefinedConversionSequence& User,
104                         OverloadCandidateSet& Conversions,
105                         AllowedExplicit AllowExplicit,
106                         bool AllowObjCConversionOnExplicit);
107 
108 static ImplicitConversionSequence::CompareKind
109 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
110                                    const StandardConversionSequence& SCS1,
111                                    const StandardConversionSequence& SCS2);
112 
113 static ImplicitConversionSequence::CompareKind
114 CompareQualificationConversions(Sema &S,
115                                 const StandardConversionSequence& SCS1,
116                                 const StandardConversionSequence& SCS2);
117 
118 static ImplicitConversionSequence::CompareKind
119 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
120                                 const StandardConversionSequence& SCS1,
121                                 const StandardConversionSequence& SCS2);
122 
123 /// GetConversionRank - Retrieve the implicit conversion rank
124 /// corresponding to the given implicit conversion kind.
125 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
126   static const ImplicitConversionRank
127     Rank[] = {
128     ICR_Exact_Match,
129     ICR_Exact_Match,
130     ICR_Exact_Match,
131     ICR_Exact_Match,
132     ICR_Exact_Match,
133     ICR_Exact_Match,
134     ICR_Promotion,
135     ICR_Promotion,
136     ICR_Promotion,
137     ICR_Conversion,
138     ICR_Conversion,
139     ICR_Conversion,
140     ICR_Conversion,
141     ICR_Conversion,
142     ICR_Conversion,
143     ICR_Conversion,
144     ICR_Conversion,
145     ICR_Conversion,
146     ICR_Conversion,
147     ICR_Conversion,
148     ICR_Conversion,
149     ICR_OCL_Scalar_Widening,
150     ICR_Complex_Real_Conversion,
151     ICR_Conversion,
152     ICR_Conversion,
153     ICR_Writeback_Conversion,
154     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
155                      // it was omitted by the patch that added
156                      // ICK_Zero_Event_Conversion
157     ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
158                      // it was omitted by the patch that added
159                      // ICK_Zero_Queue_Conversion
160     ICR_C_Conversion,
161     ICR_C_Conversion_Extension,
162     ICR_Conversion,
163   };
164   static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
165   return Rank[(int)Kind];
166 }
167 
168 /// GetImplicitConversionName - Return the name of this kind of
169 /// implicit conversion.
170 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
171   static const char* const Name[] = {
172     "No conversion",
173     "Lvalue-to-rvalue",
174     "Array-to-pointer",
175     "Function-to-pointer",
176     "Function pointer conversion",
177     "Qualification",
178     "Integral promotion",
179     "Floating point promotion",
180     "Complex promotion",
181     "Integral conversion",
182     "Floating conversion",
183     "Complex conversion",
184     "Floating-integral conversion",
185     "Pointer conversion",
186     "Pointer-to-member conversion",
187     "Boolean conversion",
188     "Compatible-types conversion",
189     "Derived-to-base conversion",
190     "Vector conversion",
191     "SVE Vector conversion",
192     "RVV Vector conversion",
193     "Vector splat",
194     "Complex-real conversion",
195     "Block Pointer conversion",
196     "Transparent Union Conversion",
197     "Writeback conversion",
198     "OpenCL Zero Event Conversion",
199     "OpenCL Zero Queue Conversion",
200     "C specific type conversion",
201     "Incompatible pointer conversion",
202     "Fixed point conversion",
203   };
204   static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
205   return Name[Kind];
206 }
207 
208 /// StandardConversionSequence - Set the standard conversion
209 /// sequence to the identity conversion.
210 void StandardConversionSequence::setAsIdentityConversion() {
211   First = ICK_Identity;
212   Second = ICK_Identity;
213   Third = ICK_Identity;
214   DeprecatedStringLiteralToCharPtr = false;
215   QualificationIncludesObjCLifetime = false;
216   ReferenceBinding = false;
217   DirectBinding = false;
218   IsLvalueReference = true;
219   BindsToFunctionLvalue = false;
220   BindsToRvalue = false;
221   BindsImplicitObjectArgumentWithoutRefQualifier = false;
222   ObjCLifetimeConversionBinding = false;
223   CopyConstructor = nullptr;
224 }
225 
226 /// getRank - Retrieve the rank of this standard conversion sequence
227 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
228 /// implicit conversions.
229 ImplicitConversionRank StandardConversionSequence::getRank() const {
230   ImplicitConversionRank Rank = ICR_Exact_Match;
231   if  (GetConversionRank(First) > Rank)
232     Rank = GetConversionRank(First);
233   if  (GetConversionRank(Second) > Rank)
234     Rank = GetConversionRank(Second);
235   if  (GetConversionRank(Third) > Rank)
236     Rank = GetConversionRank(Third);
237   return Rank;
238 }
239 
240 /// isPointerConversionToBool - Determines whether this conversion is
241 /// a conversion of a pointer or pointer-to-member to bool. This is
242 /// used as part of the ranking of standard conversion sequences
243 /// (C++ 13.3.3.2p4).
244 bool StandardConversionSequence::isPointerConversionToBool() const {
245   // Note that FromType has not necessarily been transformed by the
246   // array-to-pointer or function-to-pointer implicit conversions, so
247   // check for their presence as well as checking whether FromType is
248   // a pointer.
249   if (getToType(1)->isBooleanType() &&
250       (getFromType()->isPointerType() ||
251        getFromType()->isMemberPointerType() ||
252        getFromType()->isObjCObjectPointerType() ||
253        getFromType()->isBlockPointerType() ||
254        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
255     return true;
256 
257   return false;
258 }
259 
260 /// isPointerConversionToVoidPointer - Determines whether this
261 /// conversion is a conversion of a pointer to a void pointer. This is
262 /// used as part of the ranking of standard conversion sequences (C++
263 /// 13.3.3.2p4).
264 bool
265 StandardConversionSequence::
266 isPointerConversionToVoidPointer(ASTContext& Context) const {
267   QualType FromType = getFromType();
268   QualType ToType = getToType(1);
269 
270   // Note that FromType has not necessarily been transformed by the
271   // array-to-pointer implicit conversion, so check for its presence
272   // and redo the conversion to get a pointer.
273   if (First == ICK_Array_To_Pointer)
274     FromType = Context.getArrayDecayedType(FromType);
275 
276   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
277     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
278       return ToPtrType->getPointeeType()->isVoidType();
279 
280   return false;
281 }
282 
283 /// Skip any implicit casts which could be either part of a narrowing conversion
284 /// or after one in an implicit conversion.
285 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
286                                              const Expr *Converted) {
287   // We can have cleanups wrapping the converted expression; these need to be
288   // preserved so that destructors run if necessary.
289   if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
290     Expr *Inner =
291         const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
292     return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
293                                     EWC->getObjects());
294   }
295 
296   while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
297     switch (ICE->getCastKind()) {
298     case CK_NoOp:
299     case CK_IntegralCast:
300     case CK_IntegralToBoolean:
301     case CK_IntegralToFloating:
302     case CK_BooleanToSignedIntegral:
303     case CK_FloatingToIntegral:
304     case CK_FloatingToBoolean:
305     case CK_FloatingCast:
306       Converted = ICE->getSubExpr();
307       continue;
308 
309     default:
310       return Converted;
311     }
312   }
313 
314   return Converted;
315 }
316 
317 /// Check if this standard conversion sequence represents a narrowing
318 /// conversion, according to C++11 [dcl.init.list]p7.
319 ///
320 /// \param Ctx  The AST context.
321 /// \param Converted  The result of applying this standard conversion sequence.
322 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
323 ///        value of the expression prior to the narrowing conversion.
324 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
325 ///        type of the expression prior to the narrowing conversion.
326 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
327 ///        from floating point types to integral types should be ignored.
328 NarrowingKind StandardConversionSequence::getNarrowingKind(
329     ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
330     QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
331   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
332 
333   // C++11 [dcl.init.list]p7:
334   //   A narrowing conversion is an implicit conversion ...
335   QualType FromType = getToType(0);
336   QualType ToType = getToType(1);
337 
338   // A conversion to an enumeration type is narrowing if the conversion to
339   // the underlying type is narrowing. This only arises for expressions of
340   // the form 'Enum{init}'.
341   if (auto *ET = ToType->getAs<EnumType>())
342     ToType = ET->getDecl()->getIntegerType();
343 
344   switch (Second) {
345   // 'bool' is an integral type; dispatch to the right place to handle it.
346   case ICK_Boolean_Conversion:
347     if (FromType->isRealFloatingType())
348       goto FloatingIntegralConversion;
349     if (FromType->isIntegralOrUnscopedEnumerationType())
350       goto IntegralConversion;
351     // -- from a pointer type or pointer-to-member type to bool, or
352     return NK_Type_Narrowing;
353 
354   // -- from a floating-point type to an integer type, or
355   //
356   // -- from an integer type or unscoped enumeration type to a floating-point
357   //    type, except where the source is a constant expression and the actual
358   //    value after conversion will fit into the target type and will produce
359   //    the original value when converted back to the original type, or
360   case ICK_Floating_Integral:
361   FloatingIntegralConversion:
362     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
363       return NK_Type_Narrowing;
364     } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
365                ToType->isRealFloatingType()) {
366       if (IgnoreFloatToIntegralConversion)
367         return NK_Not_Narrowing;
368       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
369       assert(Initializer && "Unknown conversion expression");
370 
371       // If it's value-dependent, we can't tell whether it's narrowing.
372       if (Initializer->isValueDependent())
373         return NK_Dependent_Narrowing;
374 
375       if (std::optional<llvm::APSInt> IntConstantValue =
376               Initializer->getIntegerConstantExpr(Ctx)) {
377         // Convert the integer to the floating type.
378         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
379         Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
380                                 llvm::APFloat::rmNearestTiesToEven);
381         // And back.
382         llvm::APSInt ConvertedValue = *IntConstantValue;
383         bool ignored;
384         Result.convertToInteger(ConvertedValue,
385                                 llvm::APFloat::rmTowardZero, &ignored);
386         // If the resulting value is different, this was a narrowing conversion.
387         if (*IntConstantValue != ConvertedValue) {
388           ConstantValue = APValue(*IntConstantValue);
389           ConstantType = Initializer->getType();
390           return NK_Constant_Narrowing;
391         }
392       } else {
393         // Variables are always narrowings.
394         return NK_Variable_Narrowing;
395       }
396     }
397     return NK_Not_Narrowing;
398 
399   // -- from long double to double or float, or from double to float, except
400   //    where the source is a constant expression and the actual value after
401   //    conversion is within the range of values that can be represented (even
402   //    if it cannot be represented exactly), or
403   case ICK_Floating_Conversion:
404     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
405         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
406       // FromType is larger than ToType.
407       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
408 
409       // If it's value-dependent, we can't tell whether it's narrowing.
410       if (Initializer->isValueDependent())
411         return NK_Dependent_Narrowing;
412 
413       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
414         // Constant!
415         assert(ConstantValue.isFloat());
416         llvm::APFloat FloatVal = ConstantValue.getFloat();
417         // Convert the source value into the target type.
418         bool ignored;
419         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
420           Ctx.getFloatTypeSemantics(ToType),
421           llvm::APFloat::rmNearestTiesToEven, &ignored);
422         // If there was no overflow, the source value is within the range of
423         // values that can be represented.
424         if (ConvertStatus & llvm::APFloat::opOverflow) {
425           ConstantType = Initializer->getType();
426           return NK_Constant_Narrowing;
427         }
428       } else {
429         return NK_Variable_Narrowing;
430       }
431     }
432     return NK_Not_Narrowing;
433 
434   // -- from an integer type or unscoped enumeration type to an integer type
435   //    that cannot represent all the values of the original type, except where
436   //    the source is a constant expression and the actual value after
437   //    conversion will fit into the target type and will produce the original
438   //    value when converted back to the original type.
439   case ICK_Integral_Conversion:
440   IntegralConversion: {
441     assert(FromType->isIntegralOrUnscopedEnumerationType());
442     assert(ToType->isIntegralOrUnscopedEnumerationType());
443     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
444     const unsigned FromWidth = Ctx.getIntWidth(FromType);
445     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
446     const unsigned ToWidth = Ctx.getIntWidth(ToType);
447 
448     if (FromWidth > ToWidth ||
449         (FromWidth == ToWidth && FromSigned != ToSigned) ||
450         (FromSigned && !ToSigned)) {
451       // Not all values of FromType can be represented in ToType.
452       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
453 
454       // If it's value-dependent, we can't tell whether it's narrowing.
455       if (Initializer->isValueDependent())
456         return NK_Dependent_Narrowing;
457 
458       std::optional<llvm::APSInt> OptInitializerValue;
459       if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) {
460         // Such conversions on variables are always narrowing.
461         return NK_Variable_Narrowing;
462       }
463       llvm::APSInt &InitializerValue = *OptInitializerValue;
464       bool Narrowing = false;
465       if (FromWidth < ToWidth) {
466         // Negative -> unsigned is narrowing. Otherwise, more bits is never
467         // narrowing.
468         if (InitializerValue.isSigned() && InitializerValue.isNegative())
469           Narrowing = true;
470       } else {
471         // Add a bit to the InitializerValue so we don't have to worry about
472         // signed vs. unsigned comparisons.
473         InitializerValue = InitializerValue.extend(
474           InitializerValue.getBitWidth() + 1);
475         // Convert the initializer to and from the target width and signed-ness.
476         llvm::APSInt ConvertedValue = InitializerValue;
477         ConvertedValue = ConvertedValue.trunc(ToWidth);
478         ConvertedValue.setIsSigned(ToSigned);
479         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
480         ConvertedValue.setIsSigned(InitializerValue.isSigned());
481         // If the result is different, this was a narrowing conversion.
482         if (ConvertedValue != InitializerValue)
483           Narrowing = true;
484       }
485       if (Narrowing) {
486         ConstantType = Initializer->getType();
487         ConstantValue = APValue(InitializerValue);
488         return NK_Constant_Narrowing;
489       }
490     }
491     return NK_Not_Narrowing;
492   }
493 
494   default:
495     // Other kinds of conversions are not narrowings.
496     return NK_Not_Narrowing;
497   }
498 }
499 
500 /// dump - Print this standard conversion sequence to standard
501 /// error. Useful for debugging overloading issues.
502 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
503   raw_ostream &OS = llvm::errs();
504   bool PrintedSomething = false;
505   if (First != ICK_Identity) {
506     OS << GetImplicitConversionName(First);
507     PrintedSomething = true;
508   }
509 
510   if (Second != ICK_Identity) {
511     if (PrintedSomething) {
512       OS << " -> ";
513     }
514     OS << GetImplicitConversionName(Second);
515 
516     if (CopyConstructor) {
517       OS << " (by copy constructor)";
518     } else if (DirectBinding) {
519       OS << " (direct reference binding)";
520     } else if (ReferenceBinding) {
521       OS << " (reference binding)";
522     }
523     PrintedSomething = true;
524   }
525 
526   if (Third != ICK_Identity) {
527     if (PrintedSomething) {
528       OS << " -> ";
529     }
530     OS << GetImplicitConversionName(Third);
531     PrintedSomething = true;
532   }
533 
534   if (!PrintedSomething) {
535     OS << "No conversions required";
536   }
537 }
538 
539 /// dump - Print this user-defined conversion sequence to standard
540 /// error. Useful for debugging overloading issues.
541 void UserDefinedConversionSequence::dump() const {
542   raw_ostream &OS = llvm::errs();
543   if (Before.First || Before.Second || Before.Third) {
544     Before.dump();
545     OS << " -> ";
546   }
547   if (ConversionFunction)
548     OS << '\'' << *ConversionFunction << '\'';
549   else
550     OS << "aggregate initialization";
551   if (After.First || After.Second || After.Third) {
552     OS << " -> ";
553     After.dump();
554   }
555 }
556 
557 /// dump - Print this implicit conversion sequence to standard
558 /// error. Useful for debugging overloading issues.
559 void ImplicitConversionSequence::dump() const {
560   raw_ostream &OS = llvm::errs();
561   if (hasInitializerListContainerType())
562     OS << "Worst list element conversion: ";
563   switch (ConversionKind) {
564   case StandardConversion:
565     OS << "Standard conversion: ";
566     Standard.dump();
567     break;
568   case UserDefinedConversion:
569     OS << "User-defined conversion: ";
570     UserDefined.dump();
571     break;
572   case EllipsisConversion:
573     OS << "Ellipsis conversion";
574     break;
575   case AmbiguousConversion:
576     OS << "Ambiguous conversion";
577     break;
578   case BadConversion:
579     OS << "Bad conversion";
580     break;
581   }
582 
583   OS << "\n";
584 }
585 
586 void AmbiguousConversionSequence::construct() {
587   new (&conversions()) ConversionSet();
588 }
589 
590 void AmbiguousConversionSequence::destruct() {
591   conversions().~ConversionSet();
592 }
593 
594 void
595 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
596   FromTypePtr = O.FromTypePtr;
597   ToTypePtr = O.ToTypePtr;
598   new (&conversions()) ConversionSet(O.conversions());
599 }
600 
601 namespace {
602   // Structure used by DeductionFailureInfo to store
603   // template argument information.
604   struct DFIArguments {
605     TemplateArgument FirstArg;
606     TemplateArgument SecondArg;
607   };
608   // Structure used by DeductionFailureInfo to store
609   // template parameter and template argument information.
610   struct DFIParamWithArguments : DFIArguments {
611     TemplateParameter Param;
612   };
613   // Structure used by DeductionFailureInfo to store template argument
614   // information and the index of the problematic call argument.
615   struct DFIDeducedMismatchArgs : DFIArguments {
616     TemplateArgumentList *TemplateArgs;
617     unsigned CallArgIndex;
618   };
619   // Structure used by DeductionFailureInfo to store information about
620   // unsatisfied constraints.
621   struct CNSInfo {
622     TemplateArgumentList *TemplateArgs;
623     ConstraintSatisfaction Satisfaction;
624   };
625 }
626 
627 /// Convert from Sema's representation of template deduction information
628 /// to the form used in overload-candidate information.
629 DeductionFailureInfo
630 clang::MakeDeductionFailureInfo(ASTContext &Context,
631                                 Sema::TemplateDeductionResult TDK,
632                                 TemplateDeductionInfo &Info) {
633   DeductionFailureInfo Result;
634   Result.Result = static_cast<unsigned>(TDK);
635   Result.HasDiagnostic = false;
636   switch (TDK) {
637   case Sema::TDK_Invalid:
638   case Sema::TDK_InstantiationDepth:
639   case Sema::TDK_TooManyArguments:
640   case Sema::TDK_TooFewArguments:
641   case Sema::TDK_MiscellaneousDeductionFailure:
642   case Sema::TDK_CUDATargetMismatch:
643     Result.Data = nullptr;
644     break;
645 
646   case Sema::TDK_Incomplete:
647   case Sema::TDK_InvalidExplicitArguments:
648     Result.Data = Info.Param.getOpaqueValue();
649     break;
650 
651   case Sema::TDK_DeducedMismatch:
652   case Sema::TDK_DeducedMismatchNested: {
653     // FIXME: Should allocate from normal heap so that we can free this later.
654     auto *Saved = new (Context) DFIDeducedMismatchArgs;
655     Saved->FirstArg = Info.FirstArg;
656     Saved->SecondArg = Info.SecondArg;
657     Saved->TemplateArgs = Info.takeSugared();
658     Saved->CallArgIndex = Info.CallArgIndex;
659     Result.Data = Saved;
660     break;
661   }
662 
663   case Sema::TDK_NonDeducedMismatch: {
664     // FIXME: Should allocate from normal heap so that we can free this later.
665     DFIArguments *Saved = new (Context) DFIArguments;
666     Saved->FirstArg = Info.FirstArg;
667     Saved->SecondArg = Info.SecondArg;
668     Result.Data = Saved;
669     break;
670   }
671 
672   case Sema::TDK_IncompletePack:
673     // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
674   case Sema::TDK_Inconsistent:
675   case Sema::TDK_Underqualified: {
676     // FIXME: Should allocate from normal heap so that we can free this later.
677     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
678     Saved->Param = Info.Param;
679     Saved->FirstArg = Info.FirstArg;
680     Saved->SecondArg = Info.SecondArg;
681     Result.Data = Saved;
682     break;
683   }
684 
685   case Sema::TDK_SubstitutionFailure:
686     Result.Data = Info.takeSugared();
687     if (Info.hasSFINAEDiagnostic()) {
688       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
689           SourceLocation(), PartialDiagnostic::NullDiagnostic());
690       Info.takeSFINAEDiagnostic(*Diag);
691       Result.HasDiagnostic = true;
692     }
693     break;
694 
695   case Sema::TDK_ConstraintsNotSatisfied: {
696     CNSInfo *Saved = new (Context) CNSInfo;
697     Saved->TemplateArgs = Info.takeSugared();
698     Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
699     Result.Data = Saved;
700     break;
701   }
702 
703   case Sema::TDK_Success:
704   case Sema::TDK_NonDependentConversionFailure:
705   case Sema::TDK_AlreadyDiagnosed:
706     llvm_unreachable("not a deduction failure");
707   }
708 
709   return Result;
710 }
711 
712 void DeductionFailureInfo::Destroy() {
713   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
714   case Sema::TDK_Success:
715   case Sema::TDK_Invalid:
716   case Sema::TDK_InstantiationDepth:
717   case Sema::TDK_Incomplete:
718   case Sema::TDK_TooManyArguments:
719   case Sema::TDK_TooFewArguments:
720   case Sema::TDK_InvalidExplicitArguments:
721   case Sema::TDK_CUDATargetMismatch:
722   case Sema::TDK_NonDependentConversionFailure:
723     break;
724 
725   case Sema::TDK_IncompletePack:
726   case Sema::TDK_Inconsistent:
727   case Sema::TDK_Underqualified:
728   case Sema::TDK_DeducedMismatch:
729   case Sema::TDK_DeducedMismatchNested:
730   case Sema::TDK_NonDeducedMismatch:
731     // FIXME: Destroy the data?
732     Data = nullptr;
733     break;
734 
735   case Sema::TDK_SubstitutionFailure:
736     // FIXME: Destroy the template argument list?
737     Data = nullptr;
738     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
739       Diag->~PartialDiagnosticAt();
740       HasDiagnostic = false;
741     }
742     break;
743 
744   case Sema::TDK_ConstraintsNotSatisfied:
745     // FIXME: Destroy the template argument list?
746     Data = nullptr;
747     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
748       Diag->~PartialDiagnosticAt();
749       HasDiagnostic = false;
750     }
751     break;
752 
753   // Unhandled
754   case Sema::TDK_MiscellaneousDeductionFailure:
755   case Sema::TDK_AlreadyDiagnosed:
756     break;
757   }
758 }
759 
760 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
761   if (HasDiagnostic)
762     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
763   return nullptr;
764 }
765 
766 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
767   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
768   case Sema::TDK_Success:
769   case Sema::TDK_Invalid:
770   case Sema::TDK_InstantiationDepth:
771   case Sema::TDK_TooManyArguments:
772   case Sema::TDK_TooFewArguments:
773   case Sema::TDK_SubstitutionFailure:
774   case Sema::TDK_DeducedMismatch:
775   case Sema::TDK_DeducedMismatchNested:
776   case Sema::TDK_NonDeducedMismatch:
777   case Sema::TDK_CUDATargetMismatch:
778   case Sema::TDK_NonDependentConversionFailure:
779   case Sema::TDK_ConstraintsNotSatisfied:
780     return TemplateParameter();
781 
782   case Sema::TDK_Incomplete:
783   case Sema::TDK_InvalidExplicitArguments:
784     return TemplateParameter::getFromOpaqueValue(Data);
785 
786   case Sema::TDK_IncompletePack:
787   case Sema::TDK_Inconsistent:
788   case Sema::TDK_Underqualified:
789     return static_cast<DFIParamWithArguments*>(Data)->Param;
790 
791   // Unhandled
792   case Sema::TDK_MiscellaneousDeductionFailure:
793   case Sema::TDK_AlreadyDiagnosed:
794     break;
795   }
796 
797   return TemplateParameter();
798 }
799 
800 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
801   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
802   case Sema::TDK_Success:
803   case Sema::TDK_Invalid:
804   case Sema::TDK_InstantiationDepth:
805   case Sema::TDK_TooManyArguments:
806   case Sema::TDK_TooFewArguments:
807   case Sema::TDK_Incomplete:
808   case Sema::TDK_IncompletePack:
809   case Sema::TDK_InvalidExplicitArguments:
810   case Sema::TDK_Inconsistent:
811   case Sema::TDK_Underqualified:
812   case Sema::TDK_NonDeducedMismatch:
813   case Sema::TDK_CUDATargetMismatch:
814   case Sema::TDK_NonDependentConversionFailure:
815     return nullptr;
816 
817   case Sema::TDK_DeducedMismatch:
818   case Sema::TDK_DeducedMismatchNested:
819     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
820 
821   case Sema::TDK_SubstitutionFailure:
822     return static_cast<TemplateArgumentList*>(Data);
823 
824   case Sema::TDK_ConstraintsNotSatisfied:
825     return static_cast<CNSInfo*>(Data)->TemplateArgs;
826 
827   // Unhandled
828   case Sema::TDK_MiscellaneousDeductionFailure:
829   case Sema::TDK_AlreadyDiagnosed:
830     break;
831   }
832 
833   return nullptr;
834 }
835 
836 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
837   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
838   case Sema::TDK_Success:
839   case Sema::TDK_Invalid:
840   case Sema::TDK_InstantiationDepth:
841   case Sema::TDK_Incomplete:
842   case Sema::TDK_TooManyArguments:
843   case Sema::TDK_TooFewArguments:
844   case Sema::TDK_InvalidExplicitArguments:
845   case Sema::TDK_SubstitutionFailure:
846   case Sema::TDK_CUDATargetMismatch:
847   case Sema::TDK_NonDependentConversionFailure:
848   case Sema::TDK_ConstraintsNotSatisfied:
849     return nullptr;
850 
851   case Sema::TDK_IncompletePack:
852   case Sema::TDK_Inconsistent:
853   case Sema::TDK_Underqualified:
854   case Sema::TDK_DeducedMismatch:
855   case Sema::TDK_DeducedMismatchNested:
856   case Sema::TDK_NonDeducedMismatch:
857     return &static_cast<DFIArguments*>(Data)->FirstArg;
858 
859   // Unhandled
860   case Sema::TDK_MiscellaneousDeductionFailure:
861   case Sema::TDK_AlreadyDiagnosed:
862     break;
863   }
864 
865   return nullptr;
866 }
867 
868 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
869   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
870   case Sema::TDK_Success:
871   case Sema::TDK_Invalid:
872   case Sema::TDK_InstantiationDepth:
873   case Sema::TDK_Incomplete:
874   case Sema::TDK_IncompletePack:
875   case Sema::TDK_TooManyArguments:
876   case Sema::TDK_TooFewArguments:
877   case Sema::TDK_InvalidExplicitArguments:
878   case Sema::TDK_SubstitutionFailure:
879   case Sema::TDK_CUDATargetMismatch:
880   case Sema::TDK_NonDependentConversionFailure:
881   case Sema::TDK_ConstraintsNotSatisfied:
882     return nullptr;
883 
884   case Sema::TDK_Inconsistent:
885   case Sema::TDK_Underqualified:
886   case Sema::TDK_DeducedMismatch:
887   case Sema::TDK_DeducedMismatchNested:
888   case Sema::TDK_NonDeducedMismatch:
889     return &static_cast<DFIArguments*>(Data)->SecondArg;
890 
891   // Unhandled
892   case Sema::TDK_MiscellaneousDeductionFailure:
893   case Sema::TDK_AlreadyDiagnosed:
894     break;
895   }
896 
897   return nullptr;
898 }
899 
900 std::optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
901   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
902   case Sema::TDK_DeducedMismatch:
903   case Sema::TDK_DeducedMismatchNested:
904     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
905 
906   default:
907     return std::nullopt;
908   }
909 }
910 
911 static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X,
912                                 const FunctionDecl *Y) {
913   if (!X || !Y)
914     return false;
915   if (X->getNumParams() != Y->getNumParams())
916     return false;
917   // FIXME: when do rewritten comparison operators
918   // with explicit object parameters correspond?
919   // https://cplusplus.github.io/CWG/issues/2797.html
920   for (unsigned I = 0; I < X->getNumParams(); ++I)
921     if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
922                                     Y->getParamDecl(I)->getType()))
923       return false;
924   if (auto *FTX = X->getDescribedFunctionTemplate()) {
925     auto *FTY = Y->getDescribedFunctionTemplate();
926     if (!FTY)
927       return false;
928     if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
929                                          FTY->getTemplateParameters()))
930       return false;
931   }
932   return true;
933 }
934 
935 static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc,
936                                   Expr *FirstOperand, FunctionDecl *EqFD) {
937   assert(EqFD->getOverloadedOperator() ==
938          OverloadedOperatorKind::OO_EqualEqual);
939   // C++2a [over.match.oper]p4:
940   // A non-template function or function template F named operator== is a
941   // rewrite target with first operand o unless a search for the name operator!=
942   // in the scope S from the instantiation context of the operator expression
943   // finds a function or function template that would correspond
944   // ([basic.scope.scope]) to F if its name were operator==, where S is the
945   // scope of the class type of o if F is a class member, and the namespace
946   // scope of which F is a member otherwise. A function template specialization
947   // named operator== is a rewrite target if its function template is a rewrite
948   // target.
949   DeclarationName NotEqOp = S.Context.DeclarationNames.getCXXOperatorName(
950       OverloadedOperatorKind::OO_ExclaimEqual);
951   if (isa<CXXMethodDecl>(EqFD)) {
952     // If F is a class member, search scope is class type of first operand.
953     QualType RHS = FirstOperand->getType();
954     auto *RHSRec = RHS->getAs<RecordType>();
955     if (!RHSRec)
956       return true;
957     LookupResult Members(S, NotEqOp, OpLoc,
958                          Sema::LookupNameKind::LookupMemberName);
959     S.LookupQualifiedName(Members, RHSRec->getDecl());
960     Members.suppressAccessDiagnostics();
961     for (NamedDecl *Op : Members)
962       if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
963         return false;
964     return true;
965   }
966   // Otherwise the search scope is the namespace scope of which F is a member.
967   for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
968     auto *NotEqFD = Op->getAsFunction();
969     if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
970       NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
971     if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
972         declaresSameEntity(cast<Decl>(EqFD->getEnclosingNamespaceContext()),
973                            cast<Decl>(Op->getLexicalDeclContext())))
974       return false;
975   }
976   return true;
977 }
978 
979 bool OverloadCandidateSet::OperatorRewriteInfo::allowsReversed(
980     OverloadedOperatorKind Op) {
981   if (!AllowRewrittenCandidates)
982     return false;
983   return Op == OO_EqualEqual || Op == OO_Spaceship;
984 }
985 
986 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
987     Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) {
988   auto Op = FD->getOverloadedOperator();
989   if (!allowsReversed(Op))
990     return false;
991   if (Op == OverloadedOperatorKind::OO_EqualEqual) {
992     assert(OriginalArgs.size() == 2);
993     if (!shouldAddReversedEqEq(
994             S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
995       return false;
996   }
997   // Don't bother adding a reversed candidate that can never be a better
998   // match than the non-reversed version.
999   return FD->getNumNonObjectParams() != 2 ||
1000          !S.Context.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
1001                                            FD->getParamDecl(1)->getType()) ||
1002          FD->hasAttr<EnableIfAttr>();
1003 }
1004 
1005 void OverloadCandidateSet::destroyCandidates() {
1006   for (iterator i = begin(), e = end(); i != e; ++i) {
1007     for (auto &C : i->Conversions)
1008       C.~ImplicitConversionSequence();
1009     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1010       i->DeductionFailure.Destroy();
1011   }
1012 }
1013 
1014 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
1015   destroyCandidates();
1016   SlabAllocator.Reset();
1017   NumInlineBytesUsed = 0;
1018   Candidates.clear();
1019   Functions.clear();
1020   Kind = CSK;
1021 }
1022 
1023 namespace {
1024   class UnbridgedCastsSet {
1025     struct Entry {
1026       Expr **Addr;
1027       Expr *Saved;
1028     };
1029     SmallVector<Entry, 2> Entries;
1030 
1031   public:
1032     void save(Sema &S, Expr *&E) {
1033       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1034       Entry entry = { &E, E };
1035       Entries.push_back(entry);
1036       E = S.stripARCUnbridgedCast(E);
1037     }
1038 
1039     void restore() {
1040       for (SmallVectorImpl<Entry>::iterator
1041              i = Entries.begin(), e = Entries.end(); i != e; ++i)
1042         *i->Addr = i->Saved;
1043     }
1044   };
1045 }
1046 
1047 /// checkPlaceholderForOverload - Do any interesting placeholder-like
1048 /// preprocessing on the given expression.
1049 ///
1050 /// \param unbridgedCasts a collection to which to add unbridged casts;
1051 ///   without this, they will be immediately diagnosed as errors
1052 ///
1053 /// Return true on unrecoverable error.
1054 static bool
1055 checkPlaceholderForOverload(Sema &S, Expr *&E,
1056                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
1057   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
1058     // We can't handle overloaded expressions here because overload
1059     // resolution might reasonably tweak them.
1060     if (placeholder->getKind() == BuiltinType::Overload) return false;
1061 
1062     // If the context potentially accepts unbridged ARC casts, strip
1063     // the unbridged cast and add it to the collection for later restoration.
1064     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1065         unbridgedCasts) {
1066       unbridgedCasts->save(S, E);
1067       return false;
1068     }
1069 
1070     // Go ahead and check everything else.
1071     ExprResult result = S.CheckPlaceholderExpr(E);
1072     if (result.isInvalid())
1073       return true;
1074 
1075     E = result.get();
1076     return false;
1077   }
1078 
1079   // Nothing to do.
1080   return false;
1081 }
1082 
1083 /// checkArgPlaceholdersForOverload - Check a set of call operands for
1084 /// placeholders.
1085 static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args,
1086                                             UnbridgedCastsSet &unbridged) {
1087   for (unsigned i = 0, e = Args.size(); i != e; ++i)
1088     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1089       return true;
1090 
1091   return false;
1092 }
1093 
1094 /// Determine whether the given New declaration is an overload of the
1095 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
1096 /// New and Old cannot be overloaded, e.g., if New has the same signature as
1097 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
1098 /// functions (or function templates) at all. When it does return Ovl_Match or
1099 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1100 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1101 /// declaration.
1102 ///
1103 /// Example: Given the following input:
1104 ///
1105 ///   void f(int, float); // #1
1106 ///   void f(int, int); // #2
1107 ///   int f(int, int); // #3
1108 ///
1109 /// When we process #1, there is no previous declaration of "f", so IsOverload
1110 /// will not be used.
1111 ///
1112 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1113 /// the parameter types, we see that #1 and #2 are overloaded (since they have
1114 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1115 /// unchanged.
1116 ///
1117 /// When we process #3, Old is an overload set containing #1 and #2. We compare
1118 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1119 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1120 /// functions are not part of the signature), IsOverload returns Ovl_Match and
1121 /// MatchedDecl will be set to point to the FunctionDecl for #2.
1122 ///
1123 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1124 /// by a using declaration. The rules for whether to hide shadow declarations
1125 /// ignore some properties which otherwise figure into a function template's
1126 /// signature.
1127 Sema::OverloadKind
1128 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1129                     NamedDecl *&Match, bool NewIsUsingDecl) {
1130   for (LookupResult::iterator I = Old.begin(), E = Old.end();
1131          I != E; ++I) {
1132     NamedDecl *OldD = *I;
1133 
1134     bool OldIsUsingDecl = false;
1135     if (isa<UsingShadowDecl>(OldD)) {
1136       OldIsUsingDecl = true;
1137 
1138       // We can always introduce two using declarations into the same
1139       // context, even if they have identical signatures.
1140       if (NewIsUsingDecl) continue;
1141 
1142       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1143     }
1144 
1145     // A using-declaration does not conflict with another declaration
1146     // if one of them is hidden.
1147     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1148       continue;
1149 
1150     // If either declaration was introduced by a using declaration,
1151     // we'll need to use slightly different rules for matching.
1152     // Essentially, these rules are the normal rules, except that
1153     // function templates hide function templates with different
1154     // return types or template parameter lists.
1155     bool UseMemberUsingDeclRules =
1156       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1157       !New->getFriendObjectKind();
1158 
1159     if (FunctionDecl *OldF = OldD->getAsFunction()) {
1160       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1161         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1162           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1163           continue;
1164         }
1165 
1166         if (!isa<FunctionTemplateDecl>(OldD) &&
1167             !shouldLinkPossiblyHiddenDecl(*I, New))
1168           continue;
1169 
1170         Match = *I;
1171         return Ovl_Match;
1172       }
1173 
1174       // Builtins that have custom typechecking or have a reference should
1175       // not be overloadable or redeclarable.
1176       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1177         Match = *I;
1178         return Ovl_NonFunction;
1179       }
1180     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1181       // We can overload with these, which can show up when doing
1182       // redeclaration checks for UsingDecls.
1183       assert(Old.getLookupKind() == LookupUsingDeclName);
1184     } else if (isa<TagDecl>(OldD)) {
1185       // We can always overload with tags by hiding them.
1186     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1187       // Optimistically assume that an unresolved using decl will
1188       // overload; if it doesn't, we'll have to diagnose during
1189       // template instantiation.
1190       //
1191       // Exception: if the scope is dependent and this is not a class
1192       // member, the using declaration can only introduce an enumerator.
1193       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1194         Match = *I;
1195         return Ovl_NonFunction;
1196       }
1197     } else {
1198       // (C++ 13p1):
1199       //   Only function declarations can be overloaded; object and type
1200       //   declarations cannot be overloaded.
1201       Match = *I;
1202       return Ovl_NonFunction;
1203     }
1204   }
1205 
1206   // C++ [temp.friend]p1:
1207   //   For a friend function declaration that is not a template declaration:
1208   //    -- if the name of the friend is a qualified or unqualified template-id,
1209   //       [...], otherwise
1210   //    -- if the name of the friend is a qualified-id and a matching
1211   //       non-template function is found in the specified class or namespace,
1212   //       the friend declaration refers to that function, otherwise,
1213   //    -- if the name of the friend is a qualified-id and a matching function
1214   //       template is found in the specified class or namespace, the friend
1215   //       declaration refers to the deduced specialization of that function
1216   //       template, otherwise
1217   //    -- the name shall be an unqualified-id [...]
1218   // If we get here for a qualified friend declaration, we've just reached the
1219   // third bullet. If the type of the friend is dependent, skip this lookup
1220   // until instantiation.
1221   if (New->getFriendObjectKind() && New->getQualifier() &&
1222       !New->getDescribedFunctionTemplate() &&
1223       !New->getDependentSpecializationInfo() &&
1224       !New->getType()->isDependentType()) {
1225     LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1226     TemplateSpecResult.addAllDecls(Old);
1227     if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1228                                             /*QualifiedFriend*/true)) {
1229       New->setInvalidDecl();
1230       return Ovl_Overload;
1231     }
1232 
1233     Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1234     return Ovl_Match;
1235   }
1236 
1237   return Ovl_Overload;
1238 }
1239 
1240 static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New,
1241                                      FunctionDecl *Old,
1242                                      bool UseMemberUsingDeclRules,
1243                                      bool ConsiderCudaAttrs,
1244                                      bool UseOverrideRules = false) {
1245   // C++ [basic.start.main]p2: This function shall not be overloaded.
1246   if (New->isMain())
1247     return false;
1248 
1249   // MSVCRT user defined entry points cannot be overloaded.
1250   if (New->isMSVCRTEntryPoint())
1251     return false;
1252 
1253   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1254   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1255 
1256   // C++ [temp.fct]p2:
1257   //   A function template can be overloaded with other function templates
1258   //   and with normal (non-template) functions.
1259   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1260     return true;
1261 
1262   if (NewTemplate) {
1263     // C++ [temp.over.link]p4:
1264     //   The signature of a function template consists of its function
1265     //   signature, its return type and its template parameter list. The names
1266     //   of the template parameters are significant only for establishing the
1267     //   relationship between the template parameters and the rest of the
1268     //   signature.
1269     //
1270     // We check the return type and template parameter lists for function
1271     // templates first; the remaining checks follow.
1272     bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1273         NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1274         OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1275     bool SameReturnType = SemaRef.Context.hasSameType(
1276         Old->getDeclaredReturnType(), New->getDeclaredReturnType());
1277     // FIXME(GH58571): Match template parameter list even for non-constrained
1278     // template heads. This currently ensures that the code prior to C++20 is
1279     // not newly broken.
1280     bool ConstraintsInTemplateHead =
1281         NewTemplate->getTemplateParameters()->hasAssociatedConstraints() ||
1282         OldTemplate->getTemplateParameters()->hasAssociatedConstraints();
1283     // C++ [namespace.udecl]p11:
1284     //   The set of declarations named by a using-declarator that inhabits a
1285     //   class C does not include member functions and member function
1286     //   templates of a base class that "correspond" to (and thus would
1287     //   conflict with) a declaration of a function or function template in
1288     //   C.
1289     // Comparing return types is not required for the "correspond" check to
1290     // decide whether a member introduced by a shadow declaration is hidden.
1291     if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1292         !SameTemplateParameterList)
1293       return true;
1294     if (!UseMemberUsingDeclRules &&
1295         (!SameTemplateParameterList || !SameReturnType))
1296       return true;
1297   }
1298 
1299   // Is the function New an overload of the function Old?
1300   QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1301   QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1302 
1303   // Compare the signatures (C++ 1.3.10) of the two functions to
1304   // determine whether they are overloads. If we find any mismatch
1305   // in the signature, they are overloads.
1306 
1307   // If either of these functions is a K&R-style function (no
1308   // prototype), then we consider them to have matching signatures.
1309   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1310       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1311     return false;
1312 
1313   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1314   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1315 
1316   // The signature of a function includes the types of its
1317   // parameters (C++ 1.3.10), which includes the presence or absence
1318   // of the ellipsis; see C++ DR 357).
1319   if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1320     return true;
1321 
1322   // For member-like friends, the enclosing class is part of the signature.
1323   if ((New->isMemberLikeConstrainedFriend() ||
1324        Old->isMemberLikeConstrainedFriend()) &&
1325       !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext()))
1326     return true;
1327   const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1328   const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1329 
1330   int OldParamsOffset = 0;
1331   int NewParamsOffset = 0;
1332 
1333   // When determining if a method is an overload from a base class, act as if
1334   // the implicit object parameter are of the same type.
1335 
1336   auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1337     if (M->isExplicitObjectMemberFunction())
1338       return Q;
1339 
1340     // We do not allow overloading based off of '__restrict'.
1341     Q.removeRestrict();
1342 
1343     // We may not have applied the implicit const for a constexpr member
1344     // function yet (because we haven't yet resolved whether this is a static
1345     // or non-static member function). Add it now, on the assumption that this
1346     // is a redeclaration of OldMethod.
1347     if (!SemaRef.getLangOpts().CPlusPlus14 &&
1348         (M->isConstexpr() || M->isConsteval()) &&
1349         !isa<CXXConstructorDecl>(NewMethod))
1350       Q.addConst();
1351     return Q;
1352   };
1353 
1354   auto CompareType = [&](QualType Base, QualType D) {
1355     auto BS = Base.getNonReferenceType().getCanonicalType().split();
1356     BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1357 
1358     auto DS = D.getNonReferenceType().getCanonicalType().split();
1359     DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1360 
1361     if (BS.Quals != DS.Quals)
1362       return false;
1363 
1364     if (OldMethod->isImplicitObjectMemberFunction() &&
1365         OldMethod->getParent() != NewMethod->getParent()) {
1366       QualType ParentType =
1367           SemaRef.Context.getTypeDeclType(OldMethod->getParent())
1368               .getCanonicalType();
1369       if (ParentType.getTypePtr() != BS.Ty)
1370         return false;
1371       BS.Ty = DS.Ty;
1372     }
1373 
1374     // FIXME: should we ignore some type attributes here?
1375     if (BS.Ty != DS.Ty)
1376       return false;
1377 
1378     if (Base->isLValueReferenceType())
1379       return D->isLValueReferenceType();
1380     return Base->isRValueReferenceType() == D->isRValueReferenceType();
1381   };
1382 
1383   // If the function is a class member, its signature includes the
1384   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1385   auto DiagnoseInconsistentRefQualifiers = [&]() {
1386     if (SemaRef.LangOpts.CPlusPlus23)
1387       return false;
1388     if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1389       return false;
1390     if (OldMethod->isExplicitObjectMemberFunction() ||
1391         NewMethod->isExplicitObjectMemberFunction())
1392       return false;
1393     if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1394                                      NewMethod->getRefQualifier() == RQ_None)) {
1395       SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1396           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1397       SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1398       return true;
1399     }
1400     return false;
1401   };
1402 
1403   if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1404     OldParamsOffset++;
1405   if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1406     NewParamsOffset++;
1407 
1408   if (OldType->getNumParams() - OldParamsOffset !=
1409           NewType->getNumParams() - NewParamsOffset ||
1410       !SemaRef.FunctionParamTypesAreEqual(
1411           {OldType->param_type_begin() + OldParamsOffset,
1412            OldType->param_type_end()},
1413           {NewType->param_type_begin() + NewParamsOffset,
1414            NewType->param_type_end()},
1415           nullptr)) {
1416     return true;
1417   }
1418 
1419   if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1420       !OldMethod->isStatic()) {
1421     bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1422                                                  const CXXMethodDecl *New) {
1423       auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1424       auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1425 
1426       auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1427         return F->getRefQualifier() == RQ_None &&
1428                !F->isExplicitObjectMemberFunction();
1429       };
1430 
1431       if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1432           CompareType(OldObjectType.getNonReferenceType(),
1433                       NewObjectType.getNonReferenceType()))
1434         return true;
1435       return CompareType(OldObjectType, NewObjectType);
1436     }(OldMethod, NewMethod);
1437 
1438     if (!HaveCorrespondingObjectParameters) {
1439       if (DiagnoseInconsistentRefQualifiers())
1440         return true;
1441       // CWG2554
1442       // and, if at least one is an explicit object member function, ignoring
1443       // object parameters
1444       if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1445                                 !OldMethod->isExplicitObjectMemberFunction()))
1446         return true;
1447     }
1448   }
1449 
1450   if (!UseOverrideRules) {
1451     Expr *NewRC = New->getTrailingRequiresClause(),
1452          *OldRC = Old->getTrailingRequiresClause();
1453     if ((NewRC != nullptr) != (OldRC != nullptr))
1454       return true;
1455 
1456     if (NewRC && !SemaRef.AreConstraintExpressionsEqual(Old, OldRC, New, NewRC))
1457       return true;
1458   }
1459 
1460   if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1461       NewMethod->isImplicitObjectMemberFunction()) {
1462     if (DiagnoseInconsistentRefQualifiers())
1463       return true;
1464   }
1465 
1466   // Though pass_object_size is placed on parameters and takes an argument, we
1467   // consider it to be a function-level modifier for the sake of function
1468   // identity. Either the function has one or more parameters with
1469   // pass_object_size or it doesn't.
1470   if (functionHasPassObjectSizeParams(New) !=
1471       functionHasPassObjectSizeParams(Old))
1472     return true;
1473 
1474   // enable_if attributes are an order-sensitive part of the signature.
1475   for (specific_attr_iterator<EnableIfAttr>
1476          NewI = New->specific_attr_begin<EnableIfAttr>(),
1477          NewE = New->specific_attr_end<EnableIfAttr>(),
1478          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1479          OldE = Old->specific_attr_end<EnableIfAttr>();
1480        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1481     if (NewI == NewE || OldI == OldE)
1482       return true;
1483     llvm::FoldingSetNodeID NewID, OldID;
1484     NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1485     OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1486     if (NewID != OldID)
1487       return true;
1488   }
1489 
1490   if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1491     // Don't allow overloading of destructors.  (In theory we could, but it
1492     // would be a giant change to clang.)
1493     if (!isa<CXXDestructorDecl>(New)) {
1494       Sema::CUDAFunctionTarget NewTarget = SemaRef.IdentifyCUDATarget(New),
1495                                OldTarget = SemaRef.IdentifyCUDATarget(Old);
1496       if (NewTarget != Sema::CFT_InvalidTarget) {
1497         assert((OldTarget != Sema::CFT_InvalidTarget) &&
1498                "Unexpected invalid target.");
1499 
1500         // Allow overloading of functions with same signature and different CUDA
1501         // target attributes.
1502         if (NewTarget != OldTarget)
1503           return true;
1504       }
1505     }
1506   }
1507 
1508   // The signatures match; this is not an overload.
1509   return false;
1510 }
1511 
1512 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1513                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1514   return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1515                                   ConsiderCudaAttrs);
1516 }
1517 
1518 bool Sema::IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
1519                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1520   return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1521                                   /*UseMemberUsingDeclRules=*/false,
1522                                   /*ConsiderCudaAttrs=*/true,
1523                                   /*UseOverrideRules=*/true);
1524 }
1525 
1526 /// Tries a user-defined conversion from From to ToType.
1527 ///
1528 /// Produces an implicit conversion sequence for when a standard conversion
1529 /// is not an option. See TryImplicitConversion for more information.
1530 static ImplicitConversionSequence
1531 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1532                          bool SuppressUserConversions,
1533                          AllowedExplicit AllowExplicit,
1534                          bool InOverloadResolution,
1535                          bool CStyle,
1536                          bool AllowObjCWritebackConversion,
1537                          bool AllowObjCConversionOnExplicit) {
1538   ImplicitConversionSequence ICS;
1539 
1540   if (SuppressUserConversions) {
1541     // We're not in the case above, so there is no conversion that
1542     // we can perform.
1543     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1544     return ICS;
1545   }
1546 
1547   // Attempt user-defined conversion.
1548   OverloadCandidateSet Conversions(From->getExprLoc(),
1549                                    OverloadCandidateSet::CSK_Normal);
1550   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1551                                   Conversions, AllowExplicit,
1552                                   AllowObjCConversionOnExplicit)) {
1553   case OR_Success:
1554   case OR_Deleted:
1555     ICS.setUserDefined();
1556     // C++ [over.ics.user]p4:
1557     //   A conversion of an expression of class type to the same class
1558     //   type is given Exact Match rank, and a conversion of an
1559     //   expression of class type to a base class of that type is
1560     //   given Conversion rank, in spite of the fact that a copy
1561     //   constructor (i.e., a user-defined conversion function) is
1562     //   called for those cases.
1563     if (CXXConstructorDecl *Constructor
1564           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1565       QualType FromCanon
1566         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1567       QualType ToCanon
1568         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1569       if (Constructor->isCopyConstructor() &&
1570           (FromCanon == ToCanon ||
1571            S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1572         // Turn this into a "standard" conversion sequence, so that it
1573         // gets ranked with standard conversion sequences.
1574         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1575         ICS.setStandard();
1576         ICS.Standard.setAsIdentityConversion();
1577         ICS.Standard.setFromType(From->getType());
1578         ICS.Standard.setAllToTypes(ToType);
1579         ICS.Standard.CopyConstructor = Constructor;
1580         ICS.Standard.FoundCopyConstructor = Found;
1581         if (ToCanon != FromCanon)
1582           ICS.Standard.Second = ICK_Derived_To_Base;
1583       }
1584     }
1585     break;
1586 
1587   case OR_Ambiguous:
1588     ICS.setAmbiguous();
1589     ICS.Ambiguous.setFromType(From->getType());
1590     ICS.Ambiguous.setToType(ToType);
1591     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1592          Cand != Conversions.end(); ++Cand)
1593       if (Cand->Best)
1594         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1595     break;
1596 
1597     // Fall through.
1598   case OR_No_Viable_Function:
1599     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1600     break;
1601   }
1602 
1603   return ICS;
1604 }
1605 
1606 /// TryImplicitConversion - Attempt to perform an implicit conversion
1607 /// from the given expression (Expr) to the given type (ToType). This
1608 /// function returns an implicit conversion sequence that can be used
1609 /// to perform the initialization. Given
1610 ///
1611 ///   void f(float f);
1612 ///   void g(int i) { f(i); }
1613 ///
1614 /// this routine would produce an implicit conversion sequence to
1615 /// describe the initialization of f from i, which will be a standard
1616 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1617 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1618 //
1619 /// Note that this routine only determines how the conversion can be
1620 /// performed; it does not actually perform the conversion. As such,
1621 /// it will not produce any diagnostics if no conversion is available,
1622 /// but will instead return an implicit conversion sequence of kind
1623 /// "BadConversion".
1624 ///
1625 /// If @p SuppressUserConversions, then user-defined conversions are
1626 /// not permitted.
1627 /// If @p AllowExplicit, then explicit user-defined conversions are
1628 /// permitted.
1629 ///
1630 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1631 /// writeback conversion, which allows __autoreleasing id* parameters to
1632 /// be initialized with __strong id* or __weak id* arguments.
1633 static ImplicitConversionSequence
1634 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1635                       bool SuppressUserConversions,
1636                       AllowedExplicit AllowExplicit,
1637                       bool InOverloadResolution,
1638                       bool CStyle,
1639                       bool AllowObjCWritebackConversion,
1640                       bool AllowObjCConversionOnExplicit) {
1641   ImplicitConversionSequence ICS;
1642   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1643                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1644     ICS.setStandard();
1645     return ICS;
1646   }
1647 
1648   if (!S.getLangOpts().CPlusPlus) {
1649     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1650     return ICS;
1651   }
1652 
1653   // C++ [over.ics.user]p4:
1654   //   A conversion of an expression of class type to the same class
1655   //   type is given Exact Match rank, and a conversion of an
1656   //   expression of class type to a base class of that type is
1657   //   given Conversion rank, in spite of the fact that a copy/move
1658   //   constructor (i.e., a user-defined conversion function) is
1659   //   called for those cases.
1660   QualType FromType = From->getType();
1661   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1662       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1663        S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1664     ICS.setStandard();
1665     ICS.Standard.setAsIdentityConversion();
1666     ICS.Standard.setFromType(FromType);
1667     ICS.Standard.setAllToTypes(ToType);
1668 
1669     // We don't actually check at this point whether there is a valid
1670     // copy/move constructor, since overloading just assumes that it
1671     // exists. When we actually perform initialization, we'll find the
1672     // appropriate constructor to copy the returned object, if needed.
1673     ICS.Standard.CopyConstructor = nullptr;
1674 
1675     // Determine whether this is considered a derived-to-base conversion.
1676     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1677       ICS.Standard.Second = ICK_Derived_To_Base;
1678 
1679     return ICS;
1680   }
1681 
1682   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1683                                   AllowExplicit, InOverloadResolution, CStyle,
1684                                   AllowObjCWritebackConversion,
1685                                   AllowObjCConversionOnExplicit);
1686 }
1687 
1688 ImplicitConversionSequence
1689 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1690                             bool SuppressUserConversions,
1691                             AllowedExplicit AllowExplicit,
1692                             bool InOverloadResolution,
1693                             bool CStyle,
1694                             bool AllowObjCWritebackConversion) {
1695   return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1696                                  AllowExplicit, InOverloadResolution, CStyle,
1697                                  AllowObjCWritebackConversion,
1698                                  /*AllowObjCConversionOnExplicit=*/false);
1699 }
1700 
1701 /// PerformImplicitConversion - Perform an implicit conversion of the
1702 /// expression From to the type ToType. Returns the
1703 /// converted expression. Flavor is the kind of conversion we're
1704 /// performing, used in the error message. If @p AllowExplicit,
1705 /// explicit user-defined conversions are permitted.
1706 ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1707                                            AssignmentAction Action,
1708                                            bool AllowExplicit) {
1709   if (checkPlaceholderForOverload(*this, From))
1710     return ExprError();
1711 
1712   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1713   bool AllowObjCWritebackConversion
1714     = getLangOpts().ObjCAutoRefCount &&
1715       (Action == AA_Passing || Action == AA_Sending);
1716   if (getLangOpts().ObjC)
1717     CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1718                                       From->getType(), From);
1719   ImplicitConversionSequence ICS = ::TryImplicitConversion(
1720       *this, From, ToType,
1721       /*SuppressUserConversions=*/false,
1722       AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1723       /*InOverloadResolution=*/false,
1724       /*CStyle=*/false, AllowObjCWritebackConversion,
1725       /*AllowObjCConversionOnExplicit=*/false);
1726   return PerformImplicitConversion(From, ToType, ICS, Action);
1727 }
1728 
1729 /// Determine whether the conversion from FromType to ToType is a valid
1730 /// conversion that strips "noexcept" or "noreturn" off the nested function
1731 /// type.
1732 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1733                                 QualType &ResultTy) {
1734   if (Context.hasSameUnqualifiedType(FromType, ToType))
1735     return false;
1736 
1737   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1738   //                    or F(t noexcept) -> F(t)
1739   // where F adds one of the following at most once:
1740   //   - a pointer
1741   //   - a member pointer
1742   //   - a block pointer
1743   // Changes here need matching changes in FindCompositePointerType.
1744   CanQualType CanTo = Context.getCanonicalType(ToType);
1745   CanQualType CanFrom = Context.getCanonicalType(FromType);
1746   Type::TypeClass TyClass = CanTo->getTypeClass();
1747   if (TyClass != CanFrom->getTypeClass()) return false;
1748   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1749     if (TyClass == Type::Pointer) {
1750       CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1751       CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1752     } else if (TyClass == Type::BlockPointer) {
1753       CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1754       CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1755     } else if (TyClass == Type::MemberPointer) {
1756       auto ToMPT = CanTo.castAs<MemberPointerType>();
1757       auto FromMPT = CanFrom.castAs<MemberPointerType>();
1758       // A function pointer conversion cannot change the class of the function.
1759       if (ToMPT->getClass() != FromMPT->getClass())
1760         return false;
1761       CanTo = ToMPT->getPointeeType();
1762       CanFrom = FromMPT->getPointeeType();
1763     } else {
1764       return false;
1765     }
1766 
1767     TyClass = CanTo->getTypeClass();
1768     if (TyClass != CanFrom->getTypeClass()) return false;
1769     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1770       return false;
1771   }
1772 
1773   const auto *FromFn = cast<FunctionType>(CanFrom);
1774   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1775 
1776   const auto *ToFn = cast<FunctionType>(CanTo);
1777   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1778 
1779   bool Changed = false;
1780 
1781   // Drop 'noreturn' if not present in target type.
1782   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1783     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1784     Changed = true;
1785   }
1786 
1787   // Drop the 'arm_preserves_za' if not present in the target type (we can do
1788   // that because it is merely a hint).
1789   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1790     FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1791     if (ExtInfo.AArch64SMEAttributes &
1792         FunctionType::SME_PStateZAPreservedMask) {
1793       unsigned ToFlags = 0;
1794       if (const auto *ToFPT = dyn_cast<FunctionProtoType>(ToFn))
1795         ToFlags = ToFPT->getExtProtoInfo().AArch64SMEAttributes;
1796       if (!(ToFlags & FunctionType::SME_PStateZAPreservedMask)) {
1797         ExtInfo.setArmSMEAttribute(FunctionType::SME_PStateZAPreservedMask,
1798                                    false);
1799         QualType QT = Context.getFunctionType(
1800             FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);
1801         FromFn = QT->getAs<FunctionType>();
1802         Changed = true;
1803       }
1804     }
1805   }
1806 
1807   // Drop 'noexcept' if not present in target type.
1808   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1809     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1810     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1811       FromFn = cast<FunctionType>(
1812           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1813                                                    EST_None)
1814                  .getTypePtr());
1815       Changed = true;
1816     }
1817 
1818     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1819     // only if the ExtParameterInfo lists of the two function prototypes can be
1820     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1821     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1822     bool CanUseToFPT, CanUseFromFPT;
1823     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1824                                       CanUseFromFPT, NewParamInfos) &&
1825         CanUseToFPT && !CanUseFromFPT) {
1826       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1827       ExtInfo.ExtParameterInfos =
1828           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1829       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1830                                             FromFPT->getParamTypes(), ExtInfo);
1831       FromFn = QT->getAs<FunctionType>();
1832       Changed = true;
1833     }
1834   }
1835 
1836   if (!Changed)
1837     return false;
1838 
1839   assert(QualType(FromFn, 0).isCanonical());
1840   if (QualType(FromFn, 0) != CanTo) return false;
1841 
1842   ResultTy = ToType;
1843   return true;
1844 }
1845 
1846 /// Determine whether the conversion from FromType to ToType is a valid
1847 /// vector conversion.
1848 ///
1849 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1850 /// conversion.
1851 static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
1852                                ImplicitConversionKind &ICK, Expr *From,
1853                                bool InOverloadResolution, bool CStyle) {
1854   // We need at least one of these types to be a vector type to have a vector
1855   // conversion.
1856   if (!ToType->isVectorType() && !FromType->isVectorType())
1857     return false;
1858 
1859   // Identical types require no conversions.
1860   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1861     return false;
1862 
1863   // There are no conversions between extended vector types, only identity.
1864   if (ToType->isExtVectorType()) {
1865     // There are no conversions between extended vector types other than the
1866     // identity conversion.
1867     if (FromType->isExtVectorType())
1868       return false;
1869 
1870     // Vector splat from any arithmetic type to a vector.
1871     if (FromType->isArithmeticType()) {
1872       ICK = ICK_Vector_Splat;
1873       return true;
1874     }
1875   }
1876 
1877   if (ToType->isSVESizelessBuiltinType() ||
1878       FromType->isSVESizelessBuiltinType())
1879     if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
1880         S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
1881       ICK = ICK_SVE_Vector_Conversion;
1882       return true;
1883     }
1884 
1885   if (ToType->isRVVSizelessBuiltinType() ||
1886       FromType->isRVVSizelessBuiltinType())
1887     if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
1888         S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
1889       ICK = ICK_RVV_Vector_Conversion;
1890       return true;
1891     }
1892 
1893   // We can perform the conversion between vector types in the following cases:
1894   // 1)vector types are equivalent AltiVec and GCC vector types
1895   // 2)lax vector conversions are permitted and the vector types are of the
1896   //   same size
1897   // 3)the destination type does not have the ARM MVE strict-polymorphism
1898   //   attribute, which inhibits lax vector conversion for overload resolution
1899   //   only
1900   if (ToType->isVectorType() && FromType->isVectorType()) {
1901     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1902         (S.isLaxVectorConversion(FromType, ToType) &&
1903          !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
1904       if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
1905           S.isLaxVectorConversion(FromType, ToType) &&
1906           S.anyAltivecTypes(FromType, ToType) &&
1907           !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
1908           !InOverloadResolution && !CStyle) {
1909         S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
1910             << FromType << ToType;
1911       }
1912       ICK = ICK_Vector_Conversion;
1913       return true;
1914     }
1915   }
1916 
1917   return false;
1918 }
1919 
1920 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1921                                 bool InOverloadResolution,
1922                                 StandardConversionSequence &SCS,
1923                                 bool CStyle);
1924 
1925 /// IsStandardConversion - Determines whether there is a standard
1926 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1927 /// expression From to the type ToType. Standard conversion sequences
1928 /// only consider non-class types; for conversions that involve class
1929 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1930 /// contain the standard conversion sequence required to perform this
1931 /// conversion and this routine will return true. Otherwise, this
1932 /// routine will return false and the value of SCS is unspecified.
1933 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1934                                  bool InOverloadResolution,
1935                                  StandardConversionSequence &SCS,
1936                                  bool CStyle,
1937                                  bool AllowObjCWritebackConversion) {
1938   QualType FromType = From->getType();
1939 
1940   // Standard conversions (C++ [conv])
1941   SCS.setAsIdentityConversion();
1942   SCS.IncompatibleObjC = false;
1943   SCS.setFromType(FromType);
1944   SCS.CopyConstructor = nullptr;
1945 
1946   // There are no standard conversions for class types in C++, so
1947   // abort early. When overloading in C, however, we do permit them.
1948   if (S.getLangOpts().CPlusPlus &&
1949       (FromType->isRecordType() || ToType->isRecordType()))
1950     return false;
1951 
1952   // The first conversion can be an lvalue-to-rvalue conversion,
1953   // array-to-pointer conversion, or function-to-pointer conversion
1954   // (C++ 4p1).
1955 
1956   if (FromType == S.Context.OverloadTy) {
1957     DeclAccessPair AccessPair;
1958     if (FunctionDecl *Fn
1959           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1960                                                  AccessPair)) {
1961       // We were able to resolve the address of the overloaded function,
1962       // so we can convert to the type of that function.
1963       FromType = Fn->getType();
1964       SCS.setFromType(FromType);
1965 
1966       // we can sometimes resolve &foo<int> regardless of ToType, so check
1967       // if the type matches (identity) or we are converting to bool
1968       if (!S.Context.hasSameUnqualifiedType(
1969                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1970         QualType resultTy;
1971         // if the function type matches except for [[noreturn]], it's ok
1972         if (!S.IsFunctionConversion(FromType,
1973               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1974           // otherwise, only a boolean conversion is standard
1975           if (!ToType->isBooleanType())
1976             return false;
1977       }
1978 
1979       // Check if the "from" expression is taking the address of an overloaded
1980       // function and recompute the FromType accordingly. Take advantage of the
1981       // fact that non-static member functions *must* have such an address-of
1982       // expression.
1983       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1984       if (Method && !Method->isStatic() &&
1985           !Method->isExplicitObjectMemberFunction()) {
1986         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1987                "Non-unary operator on non-static member address");
1988         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1989                == UO_AddrOf &&
1990                "Non-address-of operator on non-static member address");
1991         const Type *ClassType
1992           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1993         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1994       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1995         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1996                UO_AddrOf &&
1997                "Non-address-of operator for overloaded function expression");
1998         FromType = S.Context.getPointerType(FromType);
1999       }
2000     } else {
2001       return false;
2002     }
2003   }
2004   // Lvalue-to-rvalue conversion (C++11 4.1):
2005   //   A glvalue (3.10) of a non-function, non-array type T can
2006   //   be converted to a prvalue.
2007   bool argIsLValue = From->isGLValue();
2008   if (argIsLValue &&
2009       !FromType->isFunctionType() && !FromType->isArrayType() &&
2010       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2011     SCS.First = ICK_Lvalue_To_Rvalue;
2012 
2013     // C11 6.3.2.1p2:
2014     //   ... if the lvalue has atomic type, the value has the non-atomic version
2015     //   of the type of the lvalue ...
2016     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2017       FromType = Atomic->getValueType();
2018 
2019     // If T is a non-class type, the type of the rvalue is the
2020     // cv-unqualified version of T. Otherwise, the type of the rvalue
2021     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2022     // just strip the qualifiers because they don't matter.
2023     FromType = FromType.getUnqualifiedType();
2024   } else if (FromType->isArrayType()) {
2025     // Array-to-pointer conversion (C++ 4.2)
2026     SCS.First = ICK_Array_To_Pointer;
2027 
2028     // An lvalue or rvalue of type "array of N T" or "array of unknown
2029     // bound of T" can be converted to an rvalue of type "pointer to
2030     // T" (C++ 4.2p1).
2031     FromType = S.Context.getArrayDecayedType(FromType);
2032 
2033     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2034       // This conversion is deprecated in C++03 (D.4)
2035       SCS.DeprecatedStringLiteralToCharPtr = true;
2036 
2037       // For the purpose of ranking in overload resolution
2038       // (13.3.3.1.1), this conversion is considered an
2039       // array-to-pointer conversion followed by a qualification
2040       // conversion (4.4). (C++ 4.2p2)
2041       SCS.Second = ICK_Identity;
2042       SCS.Third = ICK_Qualification;
2043       SCS.QualificationIncludesObjCLifetime = false;
2044       SCS.setAllToTypes(FromType);
2045       return true;
2046     }
2047   } else if (FromType->isFunctionType() && argIsLValue) {
2048     // Function-to-pointer conversion (C++ 4.3).
2049     SCS.First = ICK_Function_To_Pointer;
2050 
2051     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2052       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2053         if (!S.checkAddressOfFunctionIsAvailable(FD))
2054           return false;
2055 
2056     // An lvalue of function type T can be converted to an rvalue of
2057     // type "pointer to T." The result is a pointer to the
2058     // function. (C++ 4.3p1).
2059     FromType = S.Context.getPointerType(FromType);
2060   } else {
2061     // We don't require any conversions for the first step.
2062     SCS.First = ICK_Identity;
2063   }
2064   SCS.setToType(0, FromType);
2065 
2066   // The second conversion can be an integral promotion, floating
2067   // point promotion, integral conversion, floating point conversion,
2068   // floating-integral conversion, pointer conversion,
2069   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2070   // For overloading in C, this can also be a "compatible-type"
2071   // conversion.
2072   bool IncompatibleObjC = false;
2073   ImplicitConversionKind SecondICK = ICK_Identity;
2074   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2075     // The unqualified versions of the types are the same: there's no
2076     // conversion to do.
2077     SCS.Second = ICK_Identity;
2078   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2079     // Integral promotion (C++ 4.5).
2080     SCS.Second = ICK_Integral_Promotion;
2081     FromType = ToType.getUnqualifiedType();
2082   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2083     // Floating point promotion (C++ 4.6).
2084     SCS.Second = ICK_Floating_Promotion;
2085     FromType = ToType.getUnqualifiedType();
2086   } else if (S.IsComplexPromotion(FromType, ToType)) {
2087     // Complex promotion (Clang extension)
2088     SCS.Second = ICK_Complex_Promotion;
2089     FromType = ToType.getUnqualifiedType();
2090   } else if (ToType->isBooleanType() &&
2091              (FromType->isArithmeticType() ||
2092               FromType->isAnyPointerType() ||
2093               FromType->isBlockPointerType() ||
2094               FromType->isMemberPointerType())) {
2095     // Boolean conversions (C++ 4.12).
2096     SCS.Second = ICK_Boolean_Conversion;
2097     FromType = S.Context.BoolTy;
2098   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2099              ToType->isIntegralType(S.Context)) {
2100     // Integral conversions (C++ 4.7).
2101     SCS.Second = ICK_Integral_Conversion;
2102     FromType = ToType.getUnqualifiedType();
2103   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2104     // Complex conversions (C99 6.3.1.6)
2105     SCS.Second = ICK_Complex_Conversion;
2106     FromType = ToType.getUnqualifiedType();
2107   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2108              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2109     // Complex-real conversions (C99 6.3.1.7)
2110     SCS.Second = ICK_Complex_Real;
2111     FromType = ToType.getUnqualifiedType();
2112   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
2113     // FIXME: disable conversions between long double, __ibm128 and __float128
2114     // if their representation is different until there is back end support
2115     // We of course allow this conversion if long double is really double.
2116 
2117     // Conversions between bfloat16 and float16 are currently not supported.
2118     if ((FromType->isBFloat16Type() &&
2119          (ToType->isFloat16Type() || ToType->isHalfType())) ||
2120         (ToType->isBFloat16Type() &&
2121          (FromType->isFloat16Type() || FromType->isHalfType())))
2122       return false;
2123 
2124     // Conversions between IEEE-quad and IBM-extended semantics are not
2125     // permitted.
2126     const llvm::fltSemantics &FromSem =
2127         S.Context.getFloatTypeSemantics(FromType);
2128     const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
2129     if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2130          &ToSem == &llvm::APFloat::IEEEquad()) ||
2131         (&FromSem == &llvm::APFloat::IEEEquad() &&
2132          &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2133       return false;
2134 
2135     // Floating point conversions (C++ 4.8).
2136     SCS.Second = ICK_Floating_Conversion;
2137     FromType = ToType.getUnqualifiedType();
2138   } else if ((FromType->isRealFloatingType() &&
2139               ToType->isIntegralType(S.Context)) ||
2140              (FromType->isIntegralOrUnscopedEnumerationType() &&
2141               ToType->isRealFloatingType())) {
2142 
2143     // Floating-integral conversions (C++ 4.9).
2144     SCS.Second = ICK_Floating_Integral;
2145     FromType = ToType.getUnqualifiedType();
2146   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2147     SCS.Second = ICK_Block_Pointer_Conversion;
2148   } else if (AllowObjCWritebackConversion &&
2149              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
2150     SCS.Second = ICK_Writeback_Conversion;
2151   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2152                                    FromType, IncompatibleObjC)) {
2153     // Pointer conversions (C++ 4.10).
2154     SCS.Second = ICK_Pointer_Conversion;
2155     SCS.IncompatibleObjC = IncompatibleObjC;
2156     FromType = FromType.getUnqualifiedType();
2157   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2158                                          InOverloadResolution, FromType)) {
2159     // Pointer to member conversions (4.11).
2160     SCS.Second = ICK_Pointer_Member;
2161   } else if (IsVectorConversion(S, FromType, ToType, SecondICK, From,
2162                                 InOverloadResolution, CStyle)) {
2163     SCS.Second = SecondICK;
2164     FromType = ToType.getUnqualifiedType();
2165   } else if (!S.getLangOpts().CPlusPlus &&
2166              S.Context.typesAreCompatible(ToType, FromType)) {
2167     // Compatible conversions (Clang extension for C function overloading)
2168     SCS.Second = ICK_Compatible_Conversion;
2169     FromType = ToType.getUnqualifiedType();
2170   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
2171                                              InOverloadResolution,
2172                                              SCS, CStyle)) {
2173     SCS.Second = ICK_TransparentUnionConversion;
2174     FromType = ToType;
2175   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2176                                  CStyle)) {
2177     // tryAtomicConversion has updated the standard conversion sequence
2178     // appropriately.
2179     return true;
2180   } else if (ToType->isEventT() &&
2181              From->isIntegerConstantExpr(S.getASTContext()) &&
2182              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2183     SCS.Second = ICK_Zero_Event_Conversion;
2184     FromType = ToType;
2185   } else if (ToType->isQueueT() &&
2186              From->isIntegerConstantExpr(S.getASTContext()) &&
2187              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2188     SCS.Second = ICK_Zero_Queue_Conversion;
2189     FromType = ToType;
2190   } else if (ToType->isSamplerT() &&
2191              From->isIntegerConstantExpr(S.getASTContext())) {
2192     SCS.Second = ICK_Compatible_Conversion;
2193     FromType = ToType;
2194   } else if (ToType->isFixedPointType() || FromType->isFixedPointType()) {
2195     SCS.Second = ICK_Fixed_Point_Conversion;
2196     FromType = ToType;
2197   } else {
2198     // No second conversion required.
2199     SCS.Second = ICK_Identity;
2200   }
2201   SCS.setToType(1, FromType);
2202 
2203   // The third conversion can be a function pointer conversion or a
2204   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2205   bool ObjCLifetimeConversion;
2206   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
2207     // Function pointer conversions (removing 'noexcept') including removal of
2208     // 'noreturn' (Clang extension).
2209     SCS.Third = ICK_Function_Conversion;
2210   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2211                                          ObjCLifetimeConversion)) {
2212     SCS.Third = ICK_Qualification;
2213     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2214     FromType = ToType;
2215   } else {
2216     // No conversion required
2217     SCS.Third = ICK_Identity;
2218   }
2219 
2220   // C++ [over.best.ics]p6:
2221   //   [...] Any difference in top-level cv-qualification is
2222   //   subsumed by the initialization itself and does not constitute
2223   //   a conversion. [...]
2224   QualType CanonFrom = S.Context.getCanonicalType(FromType);
2225   QualType CanonTo = S.Context.getCanonicalType(ToType);
2226   if (CanonFrom.getLocalUnqualifiedType()
2227                                      == CanonTo.getLocalUnqualifiedType() &&
2228       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2229     FromType = ToType;
2230     CanonFrom = CanonTo;
2231   }
2232 
2233   SCS.setToType(2, FromType);
2234 
2235   if (CanonFrom == CanonTo)
2236     return true;
2237 
2238   // If we have not converted the argument type to the parameter type,
2239   // this is a bad conversion sequence, unless we're resolving an overload in C.
2240   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2241     return false;
2242 
2243   ExprResult ER = ExprResult{From};
2244   Sema::AssignConvertType Conv =
2245       S.CheckSingleAssignmentConstraints(ToType, ER,
2246                                          /*Diagnose=*/false,
2247                                          /*DiagnoseCFAudited=*/false,
2248                                          /*ConvertRHS=*/false);
2249   ImplicitConversionKind SecondConv;
2250   switch (Conv) {
2251   case Sema::Compatible:
2252     SecondConv = ICK_C_Only_Conversion;
2253     break;
2254   // For our purposes, discarding qualifiers is just as bad as using an
2255   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2256   // qualifiers, as well.
2257   case Sema::CompatiblePointerDiscardsQualifiers:
2258   case Sema::IncompatiblePointer:
2259   case Sema::IncompatiblePointerSign:
2260     SecondConv = ICK_Incompatible_Pointer_Conversion;
2261     break;
2262   default:
2263     return false;
2264   }
2265 
2266   // First can only be an lvalue conversion, so we pretend that this was the
2267   // second conversion. First should already be valid from earlier in the
2268   // function.
2269   SCS.Second = SecondConv;
2270   SCS.setToType(1, ToType);
2271 
2272   // Third is Identity, because Second should rank us worse than any other
2273   // conversion. This could also be ICK_Qualification, but it's simpler to just
2274   // lump everything in with the second conversion, and we don't gain anything
2275   // from making this ICK_Qualification.
2276   SCS.Third = ICK_Identity;
2277   SCS.setToType(2, ToType);
2278   return true;
2279 }
2280 
2281 static bool
2282 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2283                                      QualType &ToType,
2284                                      bool InOverloadResolution,
2285                                      StandardConversionSequence &SCS,
2286                                      bool CStyle) {
2287 
2288   const RecordType *UT = ToType->getAsUnionType();
2289   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2290     return false;
2291   // The field to initialize within the transparent union.
2292   RecordDecl *UD = UT->getDecl();
2293   // It's compatible if the expression matches any of the fields.
2294   for (const auto *it : UD->fields()) {
2295     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2296                              CStyle, /*AllowObjCWritebackConversion=*/false)) {
2297       ToType = it->getType();
2298       return true;
2299     }
2300   }
2301   return false;
2302 }
2303 
2304 /// IsIntegralPromotion - Determines whether the conversion from the
2305 /// expression From (whose potentially-adjusted type is FromType) to
2306 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
2307 /// sets PromotedType to the promoted type.
2308 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2309   const BuiltinType *To = ToType->getAs<BuiltinType>();
2310   // All integers are built-in.
2311   if (!To) {
2312     return false;
2313   }
2314 
2315   // An rvalue of type char, signed char, unsigned char, short int, or
2316   // unsigned short int can be converted to an rvalue of type int if
2317   // int can represent all the values of the source type; otherwise,
2318   // the source rvalue can be converted to an rvalue of type unsigned
2319   // int (C++ 4.5p1).
2320   if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2321       !FromType->isEnumeralType()) {
2322     if ( // We can promote any signed, promotable integer type to an int
2323         (FromType->isSignedIntegerType() ||
2324          // We can promote any unsigned integer type whose size is
2325          // less than int to an int.
2326          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2327       return To->getKind() == BuiltinType::Int;
2328     }
2329 
2330     return To->getKind() == BuiltinType::UInt;
2331   }
2332 
2333   // C++11 [conv.prom]p3:
2334   //   A prvalue of an unscoped enumeration type whose underlying type is not
2335   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2336   //   following types that can represent all the values of the enumeration
2337   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
2338   //   unsigned int, long int, unsigned long int, long long int, or unsigned
2339   //   long long int. If none of the types in that list can represent all the
2340   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2341   //   type can be converted to an rvalue a prvalue of the extended integer type
2342   //   with lowest integer conversion rank (4.13) greater than the rank of long
2343   //   long in which all the values of the enumeration can be represented. If
2344   //   there are two such extended types, the signed one is chosen.
2345   // C++11 [conv.prom]p4:
2346   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
2347   //   can be converted to a prvalue of its underlying type. Moreover, if
2348   //   integral promotion can be applied to its underlying type, a prvalue of an
2349   //   unscoped enumeration type whose underlying type is fixed can also be
2350   //   converted to a prvalue of the promoted underlying type.
2351   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2352     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2353     // provided for a scoped enumeration.
2354     if (FromEnumType->getDecl()->isScoped())
2355       return false;
2356 
2357     // We can perform an integral promotion to the underlying type of the enum,
2358     // even if that's not the promoted type. Note that the check for promoting
2359     // the underlying type is based on the type alone, and does not consider
2360     // the bitfield-ness of the actual source expression.
2361     if (FromEnumType->getDecl()->isFixed()) {
2362       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2363       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2364              IsIntegralPromotion(nullptr, Underlying, ToType);
2365     }
2366 
2367     // We have already pre-calculated the promotion type, so this is trivial.
2368     if (ToType->isIntegerType() &&
2369         isCompleteType(From->getBeginLoc(), FromType))
2370       return Context.hasSameUnqualifiedType(
2371           ToType, FromEnumType->getDecl()->getPromotionType());
2372 
2373     // C++ [conv.prom]p5:
2374     //   If the bit-field has an enumerated type, it is treated as any other
2375     //   value of that type for promotion purposes.
2376     //
2377     // ... so do not fall through into the bit-field checks below in C++.
2378     if (getLangOpts().CPlusPlus)
2379       return false;
2380   }
2381 
2382   // C++0x [conv.prom]p2:
2383   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2384   //   to an rvalue a prvalue of the first of the following types that can
2385   //   represent all the values of its underlying type: int, unsigned int,
2386   //   long int, unsigned long int, long long int, or unsigned long long int.
2387   //   If none of the types in that list can represent all the values of its
2388   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2389   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2390   //   type.
2391   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2392       ToType->isIntegerType()) {
2393     // Determine whether the type we're converting from is signed or
2394     // unsigned.
2395     bool FromIsSigned = FromType->isSignedIntegerType();
2396     uint64_t FromSize = Context.getTypeSize(FromType);
2397 
2398     // The types we'll try to promote to, in the appropriate
2399     // order. Try each of these types.
2400     QualType PromoteTypes[6] = {
2401       Context.IntTy, Context.UnsignedIntTy,
2402       Context.LongTy, Context.UnsignedLongTy ,
2403       Context.LongLongTy, Context.UnsignedLongLongTy
2404     };
2405     for (int Idx = 0; Idx < 6; ++Idx) {
2406       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2407       if (FromSize < ToSize ||
2408           (FromSize == ToSize &&
2409            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2410         // We found the type that we can promote to. If this is the
2411         // type we wanted, we have a promotion. Otherwise, no
2412         // promotion.
2413         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2414       }
2415     }
2416   }
2417 
2418   // An rvalue for an integral bit-field (9.6) can be converted to an
2419   // rvalue of type int if int can represent all the values of the
2420   // bit-field; otherwise, it can be converted to unsigned int if
2421   // unsigned int can represent all the values of the bit-field. If
2422   // the bit-field is larger yet, no integral promotion applies to
2423   // it. If the bit-field has an enumerated type, it is treated as any
2424   // other value of that type for promotion purposes (C++ 4.5p3).
2425   // FIXME: We should delay checking of bit-fields until we actually perform the
2426   // conversion.
2427   //
2428   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2429   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2430   // bit-fields and those whose underlying type is larger than int) for GCC
2431   // compatibility.
2432   if (From) {
2433     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2434       std::optional<llvm::APSInt> BitWidth;
2435       if (FromType->isIntegralType(Context) &&
2436           (BitWidth =
2437                MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2438         llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2439         ToSize = Context.getTypeSize(ToType);
2440 
2441         // Are we promoting to an int from a bitfield that fits in an int?
2442         if (*BitWidth < ToSize ||
2443             (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2444           return To->getKind() == BuiltinType::Int;
2445         }
2446 
2447         // Are we promoting to an unsigned int from an unsigned bitfield
2448         // that fits into an unsigned int?
2449         if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2450           return To->getKind() == BuiltinType::UInt;
2451         }
2452 
2453         return false;
2454       }
2455     }
2456   }
2457 
2458   // An rvalue of type bool can be converted to an rvalue of type int,
2459   // with false becoming zero and true becoming one (C++ 4.5p4).
2460   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2461     return true;
2462   }
2463 
2464   return false;
2465 }
2466 
2467 /// IsFloatingPointPromotion - Determines whether the conversion from
2468 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2469 /// returns true and sets PromotedType to the promoted type.
2470 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2471   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2472     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2473       /// An rvalue of type float can be converted to an rvalue of type
2474       /// double. (C++ 4.6p1).
2475       if (FromBuiltin->getKind() == BuiltinType::Float &&
2476           ToBuiltin->getKind() == BuiltinType::Double)
2477         return true;
2478 
2479       // C99 6.3.1.5p1:
2480       //   When a float is promoted to double or long double, or a
2481       //   double is promoted to long double [...].
2482       if (!getLangOpts().CPlusPlus &&
2483           (FromBuiltin->getKind() == BuiltinType::Float ||
2484            FromBuiltin->getKind() == BuiltinType::Double) &&
2485           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2486            ToBuiltin->getKind() == BuiltinType::Float128 ||
2487            ToBuiltin->getKind() == BuiltinType::Ibm128))
2488         return true;
2489 
2490       // Half can be promoted to float.
2491       if (!getLangOpts().NativeHalfType &&
2492            FromBuiltin->getKind() == BuiltinType::Half &&
2493           ToBuiltin->getKind() == BuiltinType::Float)
2494         return true;
2495     }
2496 
2497   return false;
2498 }
2499 
2500 /// Determine if a conversion is a complex promotion.
2501 ///
2502 /// A complex promotion is defined as a complex -> complex conversion
2503 /// where the conversion between the underlying real types is a
2504 /// floating-point or integral promotion.
2505 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2506   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2507   if (!FromComplex)
2508     return false;
2509 
2510   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2511   if (!ToComplex)
2512     return false;
2513 
2514   return IsFloatingPointPromotion(FromComplex->getElementType(),
2515                                   ToComplex->getElementType()) ||
2516     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2517                         ToComplex->getElementType());
2518 }
2519 
2520 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2521 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2522 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2523 /// if non-empty, will be a pointer to ToType that may or may not have
2524 /// the right set of qualifiers on its pointee.
2525 ///
2526 static QualType
2527 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2528                                    QualType ToPointee, QualType ToType,
2529                                    ASTContext &Context,
2530                                    bool StripObjCLifetime = false) {
2531   assert((FromPtr->getTypeClass() == Type::Pointer ||
2532           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2533          "Invalid similarly-qualified pointer type");
2534 
2535   /// Conversions to 'id' subsume cv-qualifier conversions.
2536   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2537     return ToType.getUnqualifiedType();
2538 
2539   QualType CanonFromPointee
2540     = Context.getCanonicalType(FromPtr->getPointeeType());
2541   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2542   Qualifiers Quals = CanonFromPointee.getQualifiers();
2543 
2544   if (StripObjCLifetime)
2545     Quals.removeObjCLifetime();
2546 
2547   // Exact qualifier match -> return the pointer type we're converting to.
2548   if (CanonToPointee.getLocalQualifiers() == Quals) {
2549     // ToType is exactly what we need. Return it.
2550     if (!ToType.isNull())
2551       return ToType.getUnqualifiedType();
2552 
2553     // Build a pointer to ToPointee. It has the right qualifiers
2554     // already.
2555     if (isa<ObjCObjectPointerType>(ToType))
2556       return Context.getObjCObjectPointerType(ToPointee);
2557     return Context.getPointerType(ToPointee);
2558   }
2559 
2560   // Just build a canonical type that has the right qualifiers.
2561   QualType QualifiedCanonToPointee
2562     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2563 
2564   if (isa<ObjCObjectPointerType>(ToType))
2565     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2566   return Context.getPointerType(QualifiedCanonToPointee);
2567 }
2568 
2569 static bool isNullPointerConstantForConversion(Expr *Expr,
2570                                                bool InOverloadResolution,
2571                                                ASTContext &Context) {
2572   // Handle value-dependent integral null pointer constants correctly.
2573   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2574   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2575       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2576     return !InOverloadResolution;
2577 
2578   return Expr->isNullPointerConstant(Context,
2579                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2580                                         : Expr::NPC_ValueDependentIsNull);
2581 }
2582 
2583 /// IsPointerConversion - Determines whether the conversion of the
2584 /// expression From, which has the (possibly adjusted) type FromType,
2585 /// can be converted to the type ToType via a pointer conversion (C++
2586 /// 4.10). If so, returns true and places the converted type (that
2587 /// might differ from ToType in its cv-qualifiers at some level) into
2588 /// ConvertedType.
2589 ///
2590 /// This routine also supports conversions to and from block pointers
2591 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2592 /// pointers to interfaces. FIXME: Once we've determined the
2593 /// appropriate overloading rules for Objective-C, we may want to
2594 /// split the Objective-C checks into a different routine; however,
2595 /// GCC seems to consider all of these conversions to be pointer
2596 /// conversions, so for now they live here. IncompatibleObjC will be
2597 /// set if the conversion is an allowed Objective-C conversion that
2598 /// should result in a warning.
2599 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2600                                bool InOverloadResolution,
2601                                QualType& ConvertedType,
2602                                bool &IncompatibleObjC) {
2603   IncompatibleObjC = false;
2604   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2605                               IncompatibleObjC))
2606     return true;
2607 
2608   // Conversion from a null pointer constant to any Objective-C pointer type.
2609   if (ToType->isObjCObjectPointerType() &&
2610       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2611     ConvertedType = ToType;
2612     return true;
2613   }
2614 
2615   // Blocks: Block pointers can be converted to void*.
2616   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2617       ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2618     ConvertedType = ToType;
2619     return true;
2620   }
2621   // Blocks: A null pointer constant can be converted to a block
2622   // pointer type.
2623   if (ToType->isBlockPointerType() &&
2624       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2625     ConvertedType = ToType;
2626     return true;
2627   }
2628 
2629   // If the left-hand-side is nullptr_t, the right side can be a null
2630   // pointer constant.
2631   if (ToType->isNullPtrType() &&
2632       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2633     ConvertedType = ToType;
2634     return true;
2635   }
2636 
2637   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2638   if (!ToTypePtr)
2639     return false;
2640 
2641   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2642   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2643     ConvertedType = ToType;
2644     return true;
2645   }
2646 
2647   // Beyond this point, both types need to be pointers
2648   // , including objective-c pointers.
2649   QualType ToPointeeType = ToTypePtr->getPointeeType();
2650   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2651       !getLangOpts().ObjCAutoRefCount) {
2652     ConvertedType = BuildSimilarlyQualifiedPointerType(
2653         FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2654         Context);
2655     return true;
2656   }
2657   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2658   if (!FromTypePtr)
2659     return false;
2660 
2661   QualType FromPointeeType = FromTypePtr->getPointeeType();
2662 
2663   // If the unqualified pointee types are the same, this can't be a
2664   // pointer conversion, so don't do all of the work below.
2665   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2666     return false;
2667 
2668   // An rvalue of type "pointer to cv T," where T is an object type,
2669   // can be converted to an rvalue of type "pointer to cv void" (C++
2670   // 4.10p2).
2671   if (FromPointeeType->isIncompleteOrObjectType() &&
2672       ToPointeeType->isVoidType()) {
2673     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2674                                                        ToPointeeType,
2675                                                        ToType, Context,
2676                                                    /*StripObjCLifetime=*/true);
2677     return true;
2678   }
2679 
2680   // MSVC allows implicit function to void* type conversion.
2681   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2682       ToPointeeType->isVoidType()) {
2683     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2684                                                        ToPointeeType,
2685                                                        ToType, Context);
2686     return true;
2687   }
2688 
2689   // When we're overloading in C, we allow a special kind of pointer
2690   // conversion for compatible-but-not-identical pointee types.
2691   if (!getLangOpts().CPlusPlus &&
2692       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2693     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2694                                                        ToPointeeType,
2695                                                        ToType, Context);
2696     return true;
2697   }
2698 
2699   // C++ [conv.ptr]p3:
2700   //
2701   //   An rvalue of type "pointer to cv D," where D is a class type,
2702   //   can be converted to an rvalue of type "pointer to cv B," where
2703   //   B is a base class (clause 10) of D. If B is an inaccessible
2704   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2705   //   necessitates this conversion is ill-formed. The result of the
2706   //   conversion is a pointer to the base class sub-object of the
2707   //   derived class object. The null pointer value is converted to
2708   //   the null pointer value of the destination type.
2709   //
2710   // Note that we do not check for ambiguity or inaccessibility
2711   // here. That is handled by CheckPointerConversion.
2712   if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2713       ToPointeeType->isRecordType() &&
2714       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2715       IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2716     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2717                                                        ToPointeeType,
2718                                                        ToType, Context);
2719     return true;
2720   }
2721 
2722   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2723       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2724     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2725                                                        ToPointeeType,
2726                                                        ToType, Context);
2727     return true;
2728   }
2729 
2730   return false;
2731 }
2732 
2733 /// Adopt the given qualifiers for the given type.
2734 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2735   Qualifiers TQs = T.getQualifiers();
2736 
2737   // Check whether qualifiers already match.
2738   if (TQs == Qs)
2739     return T;
2740 
2741   if (Qs.compatiblyIncludes(TQs))
2742     return Context.getQualifiedType(T, Qs);
2743 
2744   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2745 }
2746 
2747 /// isObjCPointerConversion - Determines whether this is an
2748 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2749 /// with the same arguments and return values.
2750 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2751                                    QualType& ConvertedType,
2752                                    bool &IncompatibleObjC) {
2753   if (!getLangOpts().ObjC)
2754     return false;
2755 
2756   // The set of qualifiers on the type we're converting from.
2757   Qualifiers FromQualifiers = FromType.getQualifiers();
2758 
2759   // First, we handle all conversions on ObjC object pointer types.
2760   const ObjCObjectPointerType* ToObjCPtr =
2761     ToType->getAs<ObjCObjectPointerType>();
2762   const ObjCObjectPointerType *FromObjCPtr =
2763     FromType->getAs<ObjCObjectPointerType>();
2764 
2765   if (ToObjCPtr && FromObjCPtr) {
2766     // If the pointee types are the same (ignoring qualifications),
2767     // then this is not a pointer conversion.
2768     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2769                                        FromObjCPtr->getPointeeType()))
2770       return false;
2771 
2772     // Conversion between Objective-C pointers.
2773     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2774       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2775       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2776       if (getLangOpts().CPlusPlus && LHS && RHS &&
2777           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2778                                                 FromObjCPtr->getPointeeType()))
2779         return false;
2780       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2781                                                    ToObjCPtr->getPointeeType(),
2782                                                          ToType, Context);
2783       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2784       return true;
2785     }
2786 
2787     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2788       // Okay: this is some kind of implicit downcast of Objective-C
2789       // interfaces, which is permitted. However, we're going to
2790       // complain about it.
2791       IncompatibleObjC = true;
2792       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2793                                                    ToObjCPtr->getPointeeType(),
2794                                                          ToType, Context);
2795       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2796       return true;
2797     }
2798   }
2799   // Beyond this point, both types need to be C pointers or block pointers.
2800   QualType ToPointeeType;
2801   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2802     ToPointeeType = ToCPtr->getPointeeType();
2803   else if (const BlockPointerType *ToBlockPtr =
2804             ToType->getAs<BlockPointerType>()) {
2805     // Objective C++: We're able to convert from a pointer to any object
2806     // to a block pointer type.
2807     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2808       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2809       return true;
2810     }
2811     ToPointeeType = ToBlockPtr->getPointeeType();
2812   }
2813   else if (FromType->getAs<BlockPointerType>() &&
2814            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2815     // Objective C++: We're able to convert from a block pointer type to a
2816     // pointer to any object.
2817     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2818     return true;
2819   }
2820   else
2821     return false;
2822 
2823   QualType FromPointeeType;
2824   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2825     FromPointeeType = FromCPtr->getPointeeType();
2826   else if (const BlockPointerType *FromBlockPtr =
2827            FromType->getAs<BlockPointerType>())
2828     FromPointeeType = FromBlockPtr->getPointeeType();
2829   else
2830     return false;
2831 
2832   // If we have pointers to pointers, recursively check whether this
2833   // is an Objective-C conversion.
2834   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2835       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2836                               IncompatibleObjC)) {
2837     // We always complain about this conversion.
2838     IncompatibleObjC = true;
2839     ConvertedType = Context.getPointerType(ConvertedType);
2840     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2841     return true;
2842   }
2843   // Allow conversion of pointee being objective-c pointer to another one;
2844   // as in I* to id.
2845   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2846       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2847       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2848                               IncompatibleObjC)) {
2849 
2850     ConvertedType = Context.getPointerType(ConvertedType);
2851     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2852     return true;
2853   }
2854 
2855   // If we have pointers to functions or blocks, check whether the only
2856   // differences in the argument and result types are in Objective-C
2857   // pointer conversions. If so, we permit the conversion (but
2858   // complain about it).
2859   const FunctionProtoType *FromFunctionType
2860     = FromPointeeType->getAs<FunctionProtoType>();
2861   const FunctionProtoType *ToFunctionType
2862     = ToPointeeType->getAs<FunctionProtoType>();
2863   if (FromFunctionType && ToFunctionType) {
2864     // If the function types are exactly the same, this isn't an
2865     // Objective-C pointer conversion.
2866     if (Context.getCanonicalType(FromPointeeType)
2867           == Context.getCanonicalType(ToPointeeType))
2868       return false;
2869 
2870     // Perform the quick checks that will tell us whether these
2871     // function types are obviously different.
2872     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2873         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2874         FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2875       return false;
2876 
2877     bool HasObjCConversion = false;
2878     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2879         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2880       // Okay, the types match exactly. Nothing to do.
2881     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2882                                        ToFunctionType->getReturnType(),
2883                                        ConvertedType, IncompatibleObjC)) {
2884       // Okay, we have an Objective-C pointer conversion.
2885       HasObjCConversion = true;
2886     } else {
2887       // Function types are too different. Abort.
2888       return false;
2889     }
2890 
2891     // Check argument types.
2892     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2893          ArgIdx != NumArgs; ++ArgIdx) {
2894       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2895       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2896       if (Context.getCanonicalType(FromArgType)
2897             == Context.getCanonicalType(ToArgType)) {
2898         // Okay, the types match exactly. Nothing to do.
2899       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2900                                          ConvertedType, IncompatibleObjC)) {
2901         // Okay, we have an Objective-C pointer conversion.
2902         HasObjCConversion = true;
2903       } else {
2904         // Argument types are too different. Abort.
2905         return false;
2906       }
2907     }
2908 
2909     if (HasObjCConversion) {
2910       // We had an Objective-C conversion. Allow this pointer
2911       // conversion, but complain about it.
2912       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2913       IncompatibleObjC = true;
2914       return true;
2915     }
2916   }
2917 
2918   return false;
2919 }
2920 
2921 /// Determine whether this is an Objective-C writeback conversion,
2922 /// used for parameter passing when performing automatic reference counting.
2923 ///
2924 /// \param FromType The type we're converting form.
2925 ///
2926 /// \param ToType The type we're converting to.
2927 ///
2928 /// \param ConvertedType The type that will be produced after applying
2929 /// this conversion.
2930 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2931                                      QualType &ConvertedType) {
2932   if (!getLangOpts().ObjCAutoRefCount ||
2933       Context.hasSameUnqualifiedType(FromType, ToType))
2934     return false;
2935 
2936   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2937   QualType ToPointee;
2938   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2939     ToPointee = ToPointer->getPointeeType();
2940   else
2941     return false;
2942 
2943   Qualifiers ToQuals = ToPointee.getQualifiers();
2944   if (!ToPointee->isObjCLifetimeType() ||
2945       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2946       !ToQuals.withoutObjCLifetime().empty())
2947     return false;
2948 
2949   // Argument must be a pointer to __strong to __weak.
2950   QualType FromPointee;
2951   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2952     FromPointee = FromPointer->getPointeeType();
2953   else
2954     return false;
2955 
2956   Qualifiers FromQuals = FromPointee.getQualifiers();
2957   if (!FromPointee->isObjCLifetimeType() ||
2958       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2959        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2960     return false;
2961 
2962   // Make sure that we have compatible qualifiers.
2963   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2964   if (!ToQuals.compatiblyIncludes(FromQuals))
2965     return false;
2966 
2967   // Remove qualifiers from the pointee type we're converting from; they
2968   // aren't used in the compatibility check belong, and we'll be adding back
2969   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2970   FromPointee = FromPointee.getUnqualifiedType();
2971 
2972   // The unqualified form of the pointee types must be compatible.
2973   ToPointee = ToPointee.getUnqualifiedType();
2974   bool IncompatibleObjC;
2975   if (Context.typesAreCompatible(FromPointee, ToPointee))
2976     FromPointee = ToPointee;
2977   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2978                                     IncompatibleObjC))
2979     return false;
2980 
2981   /// Construct the type we're converting to, which is a pointer to
2982   /// __autoreleasing pointee.
2983   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2984   ConvertedType = Context.getPointerType(FromPointee);
2985   return true;
2986 }
2987 
2988 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2989                                     QualType& ConvertedType) {
2990   QualType ToPointeeType;
2991   if (const BlockPointerType *ToBlockPtr =
2992         ToType->getAs<BlockPointerType>())
2993     ToPointeeType = ToBlockPtr->getPointeeType();
2994   else
2995     return false;
2996 
2997   QualType FromPointeeType;
2998   if (const BlockPointerType *FromBlockPtr =
2999       FromType->getAs<BlockPointerType>())
3000     FromPointeeType = FromBlockPtr->getPointeeType();
3001   else
3002     return false;
3003   // We have pointer to blocks, check whether the only
3004   // differences in the argument and result types are in Objective-C
3005   // pointer conversions. If so, we permit the conversion.
3006 
3007   const FunctionProtoType *FromFunctionType
3008     = FromPointeeType->getAs<FunctionProtoType>();
3009   const FunctionProtoType *ToFunctionType
3010     = ToPointeeType->getAs<FunctionProtoType>();
3011 
3012   if (!FromFunctionType || !ToFunctionType)
3013     return false;
3014 
3015   if (Context.hasSameType(FromPointeeType, ToPointeeType))
3016     return true;
3017 
3018   // Perform the quick checks that will tell us whether these
3019   // function types are obviously different.
3020   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3021       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3022     return false;
3023 
3024   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3025   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3026   if (FromEInfo != ToEInfo)
3027     return false;
3028 
3029   bool IncompatibleObjC = false;
3030   if (Context.hasSameType(FromFunctionType->getReturnType(),
3031                           ToFunctionType->getReturnType())) {
3032     // Okay, the types match exactly. Nothing to do.
3033   } else {
3034     QualType RHS = FromFunctionType->getReturnType();
3035     QualType LHS = ToFunctionType->getReturnType();
3036     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3037         !RHS.hasQualifiers() && LHS.hasQualifiers())
3038        LHS = LHS.getUnqualifiedType();
3039 
3040      if (Context.hasSameType(RHS,LHS)) {
3041        // OK exact match.
3042      } else if (isObjCPointerConversion(RHS, LHS,
3043                                         ConvertedType, IncompatibleObjC)) {
3044      if (IncompatibleObjC)
3045        return false;
3046      // Okay, we have an Objective-C pointer conversion.
3047      }
3048      else
3049        return false;
3050    }
3051 
3052    // Check argument types.
3053    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3054         ArgIdx != NumArgs; ++ArgIdx) {
3055      IncompatibleObjC = false;
3056      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3057      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3058      if (Context.hasSameType(FromArgType, ToArgType)) {
3059        // Okay, the types match exactly. Nothing to do.
3060      } else if (isObjCPointerConversion(ToArgType, FromArgType,
3061                                         ConvertedType, IncompatibleObjC)) {
3062        if (IncompatibleObjC)
3063          return false;
3064        // Okay, we have an Objective-C pointer conversion.
3065      } else
3066        // Argument types are too different. Abort.
3067        return false;
3068    }
3069 
3070    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
3071    bool CanUseToFPT, CanUseFromFPT;
3072    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3073                                       CanUseToFPT, CanUseFromFPT,
3074                                       NewParamInfos))
3075      return false;
3076 
3077    ConvertedType = ToType;
3078    return true;
3079 }
3080 
3081 enum {
3082   ft_default,
3083   ft_different_class,
3084   ft_parameter_arity,
3085   ft_parameter_mismatch,
3086   ft_return_type,
3087   ft_qualifer_mismatch,
3088   ft_noexcept
3089 };
3090 
3091 /// Attempts to get the FunctionProtoType from a Type. Handles
3092 /// MemberFunctionPointers properly.
3093 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
3094   if (auto *FPT = FromType->getAs<FunctionProtoType>())
3095     return FPT;
3096 
3097   if (auto *MPT = FromType->getAs<MemberPointerType>())
3098     return MPT->getPointeeType()->getAs<FunctionProtoType>();
3099 
3100   return nullptr;
3101 }
3102 
3103 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
3104 /// function types.  Catches different number of parameter, mismatch in
3105 /// parameter types, and different return types.
3106 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
3107                                       QualType FromType, QualType ToType) {
3108   // If either type is not valid, include no extra info.
3109   if (FromType.isNull() || ToType.isNull()) {
3110     PDiag << ft_default;
3111     return;
3112   }
3113 
3114   // Get the function type from the pointers.
3115   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3116     const auto *FromMember = FromType->castAs<MemberPointerType>(),
3117                *ToMember = ToType->castAs<MemberPointerType>();
3118     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
3119       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
3120             << QualType(FromMember->getClass(), 0);
3121       return;
3122     }
3123     FromType = FromMember->getPointeeType();
3124     ToType = ToMember->getPointeeType();
3125   }
3126 
3127   if (FromType->isPointerType())
3128     FromType = FromType->getPointeeType();
3129   if (ToType->isPointerType())
3130     ToType = ToType->getPointeeType();
3131 
3132   // Remove references.
3133   FromType = FromType.getNonReferenceType();
3134   ToType = ToType.getNonReferenceType();
3135 
3136   // Don't print extra info for non-specialized template functions.
3137   if (FromType->isInstantiationDependentType() &&
3138       !FromType->getAs<TemplateSpecializationType>()) {
3139     PDiag << ft_default;
3140     return;
3141   }
3142 
3143   // No extra info for same types.
3144   if (Context.hasSameType(FromType, ToType)) {
3145     PDiag << ft_default;
3146     return;
3147   }
3148 
3149   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3150                           *ToFunction = tryGetFunctionProtoType(ToType);
3151 
3152   // Both types need to be function types.
3153   if (!FromFunction || !ToFunction) {
3154     PDiag << ft_default;
3155     return;
3156   }
3157 
3158   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3159     PDiag << ft_parameter_arity << ToFunction->getNumParams()
3160           << FromFunction->getNumParams();
3161     return;
3162   }
3163 
3164   // Handle different parameter types.
3165   unsigned ArgPos;
3166   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3167     PDiag << ft_parameter_mismatch << ArgPos + 1
3168           << ToFunction->getParamType(ArgPos)
3169           << FromFunction->getParamType(ArgPos);
3170     return;
3171   }
3172 
3173   // Handle different return type.
3174   if (!Context.hasSameType(FromFunction->getReturnType(),
3175                            ToFunction->getReturnType())) {
3176     PDiag << ft_return_type << ToFunction->getReturnType()
3177           << FromFunction->getReturnType();
3178     return;
3179   }
3180 
3181   if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3182     PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3183           << FromFunction->getMethodQuals();
3184     return;
3185   }
3186 
3187   // Handle exception specification differences on canonical type (in C++17
3188   // onwards).
3189   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
3190           ->isNothrow() !=
3191       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3192           ->isNothrow()) {
3193     PDiag << ft_noexcept;
3194     return;
3195   }
3196 
3197   // Unable to find a difference, so add no extra info.
3198   PDiag << ft_default;
3199 }
3200 
3201 /// FunctionParamTypesAreEqual - This routine checks two function proto types
3202 /// for equality of their parameter types. Caller has already checked that
3203 /// they have same number of parameters.  If the parameters are different,
3204 /// ArgPos will have the parameter index of the first different parameter.
3205 /// If `Reversed` is true, the parameters of `NewType` will be compared in
3206 /// reverse order. That's useful if one of the functions is being used as a C++20
3207 /// synthesized operator overload with a reversed parameter order.
3208 bool Sema::FunctionParamTypesAreEqual(ArrayRef<QualType> Old,
3209                                       ArrayRef<QualType> New, unsigned *ArgPos,
3210                                       bool Reversed) {
3211   assert(llvm::size(Old) == llvm::size(New) &&
3212          "Can't compare parameters of functions with different number of "
3213          "parameters!");
3214 
3215   for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3216     // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3217     size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3218 
3219     // Ignore address spaces in pointee type. This is to disallow overloading
3220     // on __ptr32/__ptr64 address spaces.
3221     QualType OldType =
3222         Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3223     QualType NewType =
3224         Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3225 
3226     if (!Context.hasSameType(OldType, NewType)) {
3227       if (ArgPos)
3228         *ArgPos = Idx;
3229       return false;
3230     }
3231   }
3232   return true;
3233 }
3234 
3235 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3236                                       const FunctionProtoType *NewType,
3237                                       unsigned *ArgPos, bool Reversed) {
3238   return FunctionParamTypesAreEqual(OldType->param_types(),
3239                                     NewType->param_types(), ArgPos, Reversed);
3240 }
3241 
3242 bool Sema::FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
3243                                                const FunctionDecl *NewFunction,
3244                                                unsigned *ArgPos,
3245                                                bool Reversed) {
3246 
3247   if (OldFunction->getNumNonObjectParams() !=
3248       NewFunction->getNumNonObjectParams())
3249     return false;
3250 
3251   unsigned OldIgnore =
3252       unsigned(OldFunction->hasCXXExplicitFunctionObjectParameter());
3253   unsigned NewIgnore =
3254       unsigned(NewFunction->hasCXXExplicitFunctionObjectParameter());
3255 
3256   auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3257   auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3258 
3259   return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3260                                     NewPT->param_types().slice(NewIgnore),
3261                                     ArgPos, Reversed);
3262 }
3263 
3264 /// CheckPointerConversion - Check the pointer conversion from the
3265 /// expression From to the type ToType. This routine checks for
3266 /// ambiguous or inaccessible derived-to-base pointer
3267 /// conversions for which IsPointerConversion has already returned
3268 /// true. It returns true and produces a diagnostic if there was an
3269 /// error, or returns false otherwise.
3270 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
3271                                   CastKind &Kind,
3272                                   CXXCastPath& BasePath,
3273                                   bool IgnoreBaseAccess,
3274                                   bool Diagnose) {
3275   QualType FromType = From->getType();
3276   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3277 
3278   Kind = CK_BitCast;
3279 
3280   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3281       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
3282           Expr::NPCK_ZeroExpression) {
3283     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3284       DiagRuntimeBehavior(From->getExprLoc(), From,
3285                           PDiag(diag::warn_impcast_bool_to_null_pointer)
3286                             << ToType << From->getSourceRange());
3287     else if (!isUnevaluatedContext())
3288       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3289         << ToType << From->getSourceRange();
3290   }
3291   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3292     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3293       QualType FromPointeeType = FromPtrType->getPointeeType(),
3294                ToPointeeType   = ToPtrType->getPointeeType();
3295 
3296       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3297           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3298         // We must have a derived-to-base conversion. Check an
3299         // ambiguous or inaccessible conversion.
3300         unsigned InaccessibleID = 0;
3301         unsigned AmbiguousID = 0;
3302         if (Diagnose) {
3303           InaccessibleID = diag::err_upcast_to_inaccessible_base;
3304           AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3305         }
3306         if (CheckDerivedToBaseConversion(
3307                 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3308                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3309                 &BasePath, IgnoreBaseAccess))
3310           return true;
3311 
3312         // The conversion was successful.
3313         Kind = CK_DerivedToBase;
3314       }
3315 
3316       if (Diagnose && !IsCStyleOrFunctionalCast &&
3317           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3318         assert(getLangOpts().MSVCCompat &&
3319                "this should only be possible with MSVCCompat!");
3320         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3321             << From->getSourceRange();
3322       }
3323     }
3324   } else if (const ObjCObjectPointerType *ToPtrType =
3325                ToType->getAs<ObjCObjectPointerType>()) {
3326     if (const ObjCObjectPointerType *FromPtrType =
3327           FromType->getAs<ObjCObjectPointerType>()) {
3328       // Objective-C++ conversions are always okay.
3329       // FIXME: We should have a different class of conversions for the
3330       // Objective-C++ implicit conversions.
3331       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3332         return false;
3333     } else if (FromType->isBlockPointerType()) {
3334       Kind = CK_BlockPointerToObjCPointerCast;
3335     } else {
3336       Kind = CK_CPointerToObjCPointerCast;
3337     }
3338   } else if (ToType->isBlockPointerType()) {
3339     if (!FromType->isBlockPointerType())
3340       Kind = CK_AnyPointerToBlockPointerCast;
3341   }
3342 
3343   // We shouldn't fall into this case unless it's valid for other
3344   // reasons.
3345   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3346     Kind = CK_NullToPointer;
3347 
3348   return false;
3349 }
3350 
3351 /// IsMemberPointerConversion - Determines whether the conversion of the
3352 /// expression From, which has the (possibly adjusted) type FromType, can be
3353 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
3354 /// If so, returns true and places the converted type (that might differ from
3355 /// ToType in its cv-qualifiers at some level) into ConvertedType.
3356 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3357                                      QualType ToType,
3358                                      bool InOverloadResolution,
3359                                      QualType &ConvertedType) {
3360   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3361   if (!ToTypePtr)
3362     return false;
3363 
3364   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3365   if (From->isNullPointerConstant(Context,
3366                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3367                                         : Expr::NPC_ValueDependentIsNull)) {
3368     ConvertedType = ToType;
3369     return true;
3370   }
3371 
3372   // Otherwise, both types have to be member pointers.
3373   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3374   if (!FromTypePtr)
3375     return false;
3376 
3377   // A pointer to member of B can be converted to a pointer to member of D,
3378   // where D is derived from B (C++ 4.11p2).
3379   QualType FromClass(FromTypePtr->getClass(), 0);
3380   QualType ToClass(ToTypePtr->getClass(), 0);
3381 
3382   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3383       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3384     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3385                                                  ToClass.getTypePtr());
3386     return true;
3387   }
3388 
3389   return false;
3390 }
3391 
3392 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3393 /// expression From to the type ToType. This routine checks for ambiguous or
3394 /// virtual or inaccessible base-to-derived member pointer conversions
3395 /// for which IsMemberPointerConversion has already returned true. It returns
3396 /// true and produces a diagnostic if there was an error, or returns false
3397 /// otherwise.
3398 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3399                                         CastKind &Kind,
3400                                         CXXCastPath &BasePath,
3401                                         bool IgnoreBaseAccess) {
3402   QualType FromType = From->getType();
3403   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3404   if (!FromPtrType) {
3405     // This must be a null pointer to member pointer conversion
3406     assert(From->isNullPointerConstant(Context,
3407                                        Expr::NPC_ValueDependentIsNull) &&
3408            "Expr must be null pointer constant!");
3409     Kind = CK_NullToMemberPointer;
3410     return false;
3411   }
3412 
3413   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3414   assert(ToPtrType && "No member pointer cast has a target type "
3415                       "that is not a member pointer.");
3416 
3417   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3418   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3419 
3420   // FIXME: What about dependent types?
3421   assert(FromClass->isRecordType() && "Pointer into non-class.");
3422   assert(ToClass->isRecordType() && "Pointer into non-class.");
3423 
3424   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3425                      /*DetectVirtual=*/true);
3426   bool DerivationOkay =
3427       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3428   assert(DerivationOkay &&
3429          "Should not have been called if derivation isn't OK.");
3430   (void)DerivationOkay;
3431 
3432   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3433                                   getUnqualifiedType())) {
3434     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3435     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3436       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3437     return true;
3438   }
3439 
3440   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3441     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3442       << FromClass << ToClass << QualType(VBase, 0)
3443       << From->getSourceRange();
3444     return true;
3445   }
3446 
3447   if (!IgnoreBaseAccess)
3448     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3449                          Paths.front(),
3450                          diag::err_downcast_from_inaccessible_base);
3451 
3452   // Must be a base to derived member conversion.
3453   BuildBasePathArray(Paths, BasePath);
3454   Kind = CK_BaseToDerivedMemberPointer;
3455   return false;
3456 }
3457 
3458 /// Determine whether the lifetime conversion between the two given
3459 /// qualifiers sets is nontrivial.
3460 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3461                                                Qualifiers ToQuals) {
3462   // Converting anything to const __unsafe_unretained is trivial.
3463   if (ToQuals.hasConst() &&
3464       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3465     return false;
3466 
3467   return true;
3468 }
3469 
3470 /// Perform a single iteration of the loop for checking if a qualification
3471 /// conversion is valid.
3472 ///
3473 /// Specifically, check whether any change between the qualifiers of \p
3474 /// FromType and \p ToType is permissible, given knowledge about whether every
3475 /// outer layer is const-qualified.
3476 static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3477                                           bool CStyle, bool IsTopLevel,
3478                                           bool &PreviousToQualsIncludeConst,
3479                                           bool &ObjCLifetimeConversion) {
3480   Qualifiers FromQuals = FromType.getQualifiers();
3481   Qualifiers ToQuals = ToType.getQualifiers();
3482 
3483   // Ignore __unaligned qualifier.
3484   FromQuals.removeUnaligned();
3485 
3486   // Objective-C ARC:
3487   //   Check Objective-C lifetime conversions.
3488   if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3489     if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3490       if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3491         ObjCLifetimeConversion = true;
3492       FromQuals.removeObjCLifetime();
3493       ToQuals.removeObjCLifetime();
3494     } else {
3495       // Qualification conversions cannot cast between different
3496       // Objective-C lifetime qualifiers.
3497       return false;
3498     }
3499   }
3500 
3501   // Allow addition/removal of GC attributes but not changing GC attributes.
3502   if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3503       (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3504     FromQuals.removeObjCGCAttr();
3505     ToQuals.removeObjCGCAttr();
3506   }
3507 
3508   //   -- for every j > 0, if const is in cv 1,j then const is in cv
3509   //      2,j, and similarly for volatile.
3510   if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3511     return false;
3512 
3513   // If address spaces mismatch:
3514   //  - in top level it is only valid to convert to addr space that is a
3515   //    superset in all cases apart from C-style casts where we allow
3516   //    conversions between overlapping address spaces.
3517   //  - in non-top levels it is not a valid conversion.
3518   if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3519       (!IsTopLevel ||
3520        !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3521          (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3522     return false;
3523 
3524   //   -- if the cv 1,j and cv 2,j are different, then const is in
3525   //      every cv for 0 < k < j.
3526   if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3527       !PreviousToQualsIncludeConst)
3528     return false;
3529 
3530   // The following wording is from C++20, where the result of the conversion
3531   // is T3, not T2.
3532   //   -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3533   //      "array of unknown bound of"
3534   if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3535     return false;
3536 
3537   //   -- if the resulting P3,i is different from P1,i [...], then const is
3538   //      added to every cv 3_k for 0 < k < i.
3539   if (!CStyle && FromType->isConstantArrayType() &&
3540       ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3541     return false;
3542 
3543   // Keep track of whether all prior cv-qualifiers in the "to" type
3544   // include const.
3545   PreviousToQualsIncludeConst =
3546       PreviousToQualsIncludeConst && ToQuals.hasConst();
3547   return true;
3548 }
3549 
3550 /// IsQualificationConversion - Determines whether the conversion from
3551 /// an rvalue of type FromType to ToType is a qualification conversion
3552 /// (C++ 4.4).
3553 ///
3554 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3555 /// when the qualification conversion involves a change in the Objective-C
3556 /// object lifetime.
3557 bool
3558 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3559                                 bool CStyle, bool &ObjCLifetimeConversion) {
3560   FromType = Context.getCanonicalType(FromType);
3561   ToType = Context.getCanonicalType(ToType);
3562   ObjCLifetimeConversion = false;
3563 
3564   // If FromType and ToType are the same type, this is not a
3565   // qualification conversion.
3566   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3567     return false;
3568 
3569   // (C++ 4.4p4):
3570   //   A conversion can add cv-qualifiers at levels other than the first
3571   //   in multi-level pointers, subject to the following rules: [...]
3572   bool PreviousToQualsIncludeConst = true;
3573   bool UnwrappedAnyPointer = false;
3574   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3575     if (!isQualificationConversionStep(
3576             FromType, ToType, CStyle, !UnwrappedAnyPointer,
3577             PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3578       return false;
3579     UnwrappedAnyPointer = true;
3580   }
3581 
3582   // We are left with FromType and ToType being the pointee types
3583   // after unwrapping the original FromType and ToType the same number
3584   // of times. If we unwrapped any pointers, and if FromType and
3585   // ToType have the same unqualified type (since we checked
3586   // qualifiers above), then this is a qualification conversion.
3587   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3588 }
3589 
3590 /// - Determine whether this is a conversion from a scalar type to an
3591 /// atomic type.
3592 ///
3593 /// If successful, updates \c SCS's second and third steps in the conversion
3594 /// sequence to finish the conversion.
3595 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3596                                 bool InOverloadResolution,
3597                                 StandardConversionSequence &SCS,
3598                                 bool CStyle) {
3599   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3600   if (!ToAtomic)
3601     return false;
3602 
3603   StandardConversionSequence InnerSCS;
3604   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3605                             InOverloadResolution, InnerSCS,
3606                             CStyle, /*AllowObjCWritebackConversion=*/false))
3607     return false;
3608 
3609   SCS.Second = InnerSCS.Second;
3610   SCS.setToType(1, InnerSCS.getToType(1));
3611   SCS.Third = InnerSCS.Third;
3612   SCS.QualificationIncludesObjCLifetime
3613     = InnerSCS.QualificationIncludesObjCLifetime;
3614   SCS.setToType(2, InnerSCS.getToType(2));
3615   return true;
3616 }
3617 
3618 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3619                                               CXXConstructorDecl *Constructor,
3620                                               QualType Type) {
3621   const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3622   if (CtorType->getNumParams() > 0) {
3623     QualType FirstArg = CtorType->getParamType(0);
3624     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3625       return true;
3626   }
3627   return false;
3628 }
3629 
3630 static OverloadingResult
3631 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3632                                        CXXRecordDecl *To,
3633                                        UserDefinedConversionSequence &User,
3634                                        OverloadCandidateSet &CandidateSet,
3635                                        bool AllowExplicit) {
3636   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3637   for (auto *D : S.LookupConstructors(To)) {
3638     auto Info = getConstructorInfo(D);
3639     if (!Info)
3640       continue;
3641 
3642     bool Usable = !Info.Constructor->isInvalidDecl() &&
3643                   S.isInitListConstructor(Info.Constructor);
3644     if (Usable) {
3645       bool SuppressUserConversions = false;
3646       if (Info.ConstructorTmpl)
3647         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3648                                        /*ExplicitArgs*/ nullptr, From,
3649                                        CandidateSet, SuppressUserConversions,
3650                                        /*PartialOverloading*/ false,
3651                                        AllowExplicit);
3652       else
3653         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3654                                CandidateSet, SuppressUserConversions,
3655                                /*PartialOverloading*/ false, AllowExplicit);
3656     }
3657   }
3658 
3659   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3660 
3661   OverloadCandidateSet::iterator Best;
3662   switch (auto Result =
3663               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3664   case OR_Deleted:
3665   case OR_Success: {
3666     // Record the standard conversion we used and the conversion function.
3667     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3668     QualType ThisType = Constructor->getFunctionObjectParameterType();
3669     // Initializer lists don't have conversions as such.
3670     User.Before.setAsIdentityConversion();
3671     User.HadMultipleCandidates = HadMultipleCandidates;
3672     User.ConversionFunction = Constructor;
3673     User.FoundConversionFunction = Best->FoundDecl;
3674     User.After.setAsIdentityConversion();
3675     User.After.setFromType(ThisType);
3676     User.After.setAllToTypes(ToType);
3677     return Result;
3678   }
3679 
3680   case OR_No_Viable_Function:
3681     return OR_No_Viable_Function;
3682   case OR_Ambiguous:
3683     return OR_Ambiguous;
3684   }
3685 
3686   llvm_unreachable("Invalid OverloadResult!");
3687 }
3688 
3689 /// Determines whether there is a user-defined conversion sequence
3690 /// (C++ [over.ics.user]) that converts expression From to the type
3691 /// ToType. If such a conversion exists, User will contain the
3692 /// user-defined conversion sequence that performs such a conversion
3693 /// and this routine will return true. Otherwise, this routine returns
3694 /// false and User is unspecified.
3695 ///
3696 /// \param AllowExplicit  true if the conversion should consider C++0x
3697 /// "explicit" conversion functions as well as non-explicit conversion
3698 /// functions (C++0x [class.conv.fct]p2).
3699 ///
3700 /// \param AllowObjCConversionOnExplicit true if the conversion should
3701 /// allow an extra Objective-C pointer conversion on uses of explicit
3702 /// constructors. Requires \c AllowExplicit to also be set.
3703 static OverloadingResult
3704 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3705                         UserDefinedConversionSequence &User,
3706                         OverloadCandidateSet &CandidateSet,
3707                         AllowedExplicit AllowExplicit,
3708                         bool AllowObjCConversionOnExplicit) {
3709   assert(AllowExplicit != AllowedExplicit::None ||
3710          !AllowObjCConversionOnExplicit);
3711   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3712 
3713   // Whether we will only visit constructors.
3714   bool ConstructorsOnly = false;
3715 
3716   // If the type we are conversion to is a class type, enumerate its
3717   // constructors.
3718   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3719     // C++ [over.match.ctor]p1:
3720     //   When objects of class type are direct-initialized (8.5), or
3721     //   copy-initialized from an expression of the same or a
3722     //   derived class type (8.5), overload resolution selects the
3723     //   constructor. [...] For copy-initialization, the candidate
3724     //   functions are all the converting constructors (12.3.1) of
3725     //   that class. The argument list is the expression-list within
3726     //   the parentheses of the initializer.
3727     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3728         (From->getType()->getAs<RecordType>() &&
3729          S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3730       ConstructorsOnly = true;
3731 
3732     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3733       // We're not going to find any constructors.
3734     } else if (CXXRecordDecl *ToRecordDecl
3735                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3736 
3737       Expr **Args = &From;
3738       unsigned NumArgs = 1;
3739       bool ListInitializing = false;
3740       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3741         // But first, see if there is an init-list-constructor that will work.
3742         OverloadingResult Result = IsInitializerListConstructorConversion(
3743             S, From, ToType, ToRecordDecl, User, CandidateSet,
3744             AllowExplicit == AllowedExplicit::All);
3745         if (Result != OR_No_Viable_Function)
3746           return Result;
3747         // Never mind.
3748         CandidateSet.clear(
3749             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3750 
3751         // If we're list-initializing, we pass the individual elements as
3752         // arguments, not the entire list.
3753         Args = InitList->getInits();
3754         NumArgs = InitList->getNumInits();
3755         ListInitializing = true;
3756       }
3757 
3758       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3759         auto Info = getConstructorInfo(D);
3760         if (!Info)
3761           continue;
3762 
3763         bool Usable = !Info.Constructor->isInvalidDecl();
3764         if (!ListInitializing)
3765           Usable = Usable && Info.Constructor->isConvertingConstructor(
3766                                  /*AllowExplicit*/ true);
3767         if (Usable) {
3768           bool SuppressUserConversions = !ConstructorsOnly;
3769           // C++20 [over.best.ics.general]/4.5:
3770           //   if the target is the first parameter of a constructor [of class
3771           //   X] and the constructor [...] is a candidate by [...] the second
3772           //   phase of [over.match.list] when the initializer list has exactly
3773           //   one element that is itself an initializer list, [...] and the
3774           //   conversion is to X or reference to cv X, user-defined conversion
3775           //   sequences are not cnosidered.
3776           if (SuppressUserConversions && ListInitializing) {
3777             SuppressUserConversions =
3778                 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
3779                 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3780                                                   ToType);
3781           }
3782           if (Info.ConstructorTmpl)
3783             S.AddTemplateOverloadCandidate(
3784                 Info.ConstructorTmpl, Info.FoundDecl,
3785                 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
3786                 CandidateSet, SuppressUserConversions,
3787                 /*PartialOverloading*/ false,
3788                 AllowExplicit == AllowedExplicit::All);
3789           else
3790             // Allow one user-defined conversion when user specifies a
3791             // From->ToType conversion via an static cast (c-style, etc).
3792             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3793                                    llvm::ArrayRef(Args, NumArgs), CandidateSet,
3794                                    SuppressUserConversions,
3795                                    /*PartialOverloading*/ false,
3796                                    AllowExplicit == AllowedExplicit::All);
3797         }
3798       }
3799     }
3800   }
3801 
3802   // Enumerate conversion functions, if we're allowed to.
3803   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3804   } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3805     // No conversion functions from incomplete types.
3806   } else if (const RecordType *FromRecordType =
3807                  From->getType()->getAs<RecordType>()) {
3808     if (CXXRecordDecl *FromRecordDecl
3809          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3810       // Add all of the conversion functions as candidates.
3811       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3812       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3813         DeclAccessPair FoundDecl = I.getPair();
3814         NamedDecl *D = FoundDecl.getDecl();
3815         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3816         if (isa<UsingShadowDecl>(D))
3817           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3818 
3819         CXXConversionDecl *Conv;
3820         FunctionTemplateDecl *ConvTemplate;
3821         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3822           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3823         else
3824           Conv = cast<CXXConversionDecl>(D);
3825 
3826         if (ConvTemplate)
3827           S.AddTemplateConversionCandidate(
3828               ConvTemplate, FoundDecl, ActingContext, From, ToType,
3829               CandidateSet, AllowObjCConversionOnExplicit,
3830               AllowExplicit != AllowedExplicit::None);
3831         else
3832           S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3833                                    CandidateSet, AllowObjCConversionOnExplicit,
3834                                    AllowExplicit != AllowedExplicit::None);
3835       }
3836     }
3837   }
3838 
3839   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3840 
3841   OverloadCandidateSet::iterator Best;
3842   switch (auto Result =
3843               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3844   case OR_Success:
3845   case OR_Deleted:
3846     // Record the standard conversion we used and the conversion function.
3847     if (CXXConstructorDecl *Constructor
3848           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3849       // C++ [over.ics.user]p1:
3850       //   If the user-defined conversion is specified by a
3851       //   constructor (12.3.1), the initial standard conversion
3852       //   sequence converts the source type to the type required by
3853       //   the argument of the constructor.
3854       //
3855       if (isa<InitListExpr>(From)) {
3856         // Initializer lists don't have conversions as such.
3857         User.Before.setAsIdentityConversion();
3858       } else {
3859         if (Best->Conversions[0].isEllipsis())
3860           User.EllipsisConversion = true;
3861         else {
3862           User.Before = Best->Conversions[0].Standard;
3863           User.EllipsisConversion = false;
3864         }
3865       }
3866       User.HadMultipleCandidates = HadMultipleCandidates;
3867       User.ConversionFunction = Constructor;
3868       User.FoundConversionFunction = Best->FoundDecl;
3869       User.After.setAsIdentityConversion();
3870       User.After.setFromType(Constructor->getFunctionObjectParameterType());
3871       User.After.setAllToTypes(ToType);
3872       return Result;
3873     }
3874     if (CXXConversionDecl *Conversion
3875                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3876       // C++ [over.ics.user]p1:
3877       //
3878       //   [...] If the user-defined conversion is specified by a
3879       //   conversion function (12.3.2), the initial standard
3880       //   conversion sequence converts the source type to the
3881       //   implicit object parameter of the conversion function.
3882       User.Before = Best->Conversions[0].Standard;
3883       User.HadMultipleCandidates = HadMultipleCandidates;
3884       User.ConversionFunction = Conversion;
3885       User.FoundConversionFunction = Best->FoundDecl;
3886       User.EllipsisConversion = false;
3887 
3888       // C++ [over.ics.user]p2:
3889       //   The second standard conversion sequence converts the
3890       //   result of the user-defined conversion to the target type
3891       //   for the sequence. Since an implicit conversion sequence
3892       //   is an initialization, the special rules for
3893       //   initialization by user-defined conversion apply when
3894       //   selecting the best user-defined conversion for a
3895       //   user-defined conversion sequence (see 13.3.3 and
3896       //   13.3.3.1).
3897       User.After = Best->FinalConversion;
3898       return Result;
3899     }
3900     llvm_unreachable("Not a constructor or conversion function?");
3901 
3902   case OR_No_Viable_Function:
3903     return OR_No_Viable_Function;
3904 
3905   case OR_Ambiguous:
3906     return OR_Ambiguous;
3907   }
3908 
3909   llvm_unreachable("Invalid OverloadResult!");
3910 }
3911 
3912 bool
3913 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3914   ImplicitConversionSequence ICS;
3915   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3916                                     OverloadCandidateSet::CSK_Normal);
3917   OverloadingResult OvResult =
3918     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3919                             CandidateSet, AllowedExplicit::None, false);
3920 
3921   if (!(OvResult == OR_Ambiguous ||
3922         (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3923     return false;
3924 
3925   auto Cands = CandidateSet.CompleteCandidates(
3926       *this,
3927       OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3928       From);
3929   if (OvResult == OR_Ambiguous)
3930     Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3931         << From->getType() << ToType << From->getSourceRange();
3932   else { // OR_No_Viable_Function && !CandidateSet.empty()
3933     if (!RequireCompleteType(From->getBeginLoc(), ToType,
3934                              diag::err_typecheck_nonviable_condition_incomplete,
3935                              From->getType(), From->getSourceRange()))
3936       Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3937           << false << From->getType() << From->getSourceRange() << ToType;
3938   }
3939 
3940   CandidateSet.NoteCandidates(
3941                               *this, From, Cands);
3942   return true;
3943 }
3944 
3945 // Helper for compareConversionFunctions that gets the FunctionType that the
3946 // conversion-operator return  value 'points' to, or nullptr.
3947 static const FunctionType *
3948 getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
3949   const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
3950   const PointerType *RetPtrTy =
3951       ConvFuncTy->getReturnType()->getAs<PointerType>();
3952 
3953   if (!RetPtrTy)
3954     return nullptr;
3955 
3956   return RetPtrTy->getPointeeType()->getAs<FunctionType>();
3957 }
3958 
3959 /// Compare the user-defined conversion functions or constructors
3960 /// of two user-defined conversion sequences to determine whether any ordering
3961 /// is possible.
3962 static ImplicitConversionSequence::CompareKind
3963 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3964                            FunctionDecl *Function2) {
3965   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3966   CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
3967   if (!Conv1 || !Conv2)
3968     return ImplicitConversionSequence::Indistinguishable;
3969 
3970   if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
3971     return ImplicitConversionSequence::Indistinguishable;
3972 
3973   // Objective-C++:
3974   //   If both conversion functions are implicitly-declared conversions from
3975   //   a lambda closure type to a function pointer and a block pointer,
3976   //   respectively, always prefer the conversion to a function pointer,
3977   //   because the function pointer is more lightweight and is more likely
3978   //   to keep code working.
3979   if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
3980     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3981     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3982     if (Block1 != Block2)
3983       return Block1 ? ImplicitConversionSequence::Worse
3984                     : ImplicitConversionSequence::Better;
3985   }
3986 
3987   // In order to support multiple calling conventions for the lambda conversion
3988   // operator (such as when the free and member function calling convention is
3989   // different), prefer the 'free' mechanism, followed by the calling-convention
3990   // of operator(). The latter is in place to support the MSVC-like solution of
3991   // defining ALL of the possible conversions in regards to calling-convention.
3992   const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
3993   const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
3994 
3995   if (Conv1FuncRet && Conv2FuncRet &&
3996       Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
3997     CallingConv Conv1CC = Conv1FuncRet->getCallConv();
3998     CallingConv Conv2CC = Conv2FuncRet->getCallConv();
3999 
4000     CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4001     const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4002 
4003     CallingConv CallOpCC =
4004         CallOp->getType()->castAs<FunctionType>()->getCallConv();
4005     CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
4006         CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4007     CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
4008         CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4009 
4010     CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4011     for (CallingConv CC : PrefOrder) {
4012       if (Conv1CC == CC)
4013         return ImplicitConversionSequence::Better;
4014       if (Conv2CC == CC)
4015         return ImplicitConversionSequence::Worse;
4016     }
4017   }
4018 
4019   return ImplicitConversionSequence::Indistinguishable;
4020 }
4021 
4022 static bool hasDeprecatedStringLiteralToCharPtrConversion(
4023     const ImplicitConversionSequence &ICS) {
4024   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
4025          (ICS.isUserDefined() &&
4026           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
4027 }
4028 
4029 /// CompareImplicitConversionSequences - Compare two implicit
4030 /// conversion sequences to determine whether one is better than the
4031 /// other or if they are indistinguishable (C++ 13.3.3.2).
4032 static ImplicitConversionSequence::CompareKind
4033 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
4034                                    const ImplicitConversionSequence& ICS1,
4035                                    const ImplicitConversionSequence& ICS2)
4036 {
4037   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4038   // conversion sequences (as defined in 13.3.3.1)
4039   //   -- a standard conversion sequence (13.3.3.1.1) is a better
4040   //      conversion sequence than a user-defined conversion sequence or
4041   //      an ellipsis conversion sequence, and
4042   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
4043   //      conversion sequence than an ellipsis conversion sequence
4044   //      (13.3.3.1.3).
4045   //
4046   // C++0x [over.best.ics]p10:
4047   //   For the purpose of ranking implicit conversion sequences as
4048   //   described in 13.3.3.2, the ambiguous conversion sequence is
4049   //   treated as a user-defined sequence that is indistinguishable
4050   //   from any other user-defined conversion sequence.
4051 
4052   // String literal to 'char *' conversion has been deprecated in C++03. It has
4053   // been removed from C++11. We still accept this conversion, if it happens at
4054   // the best viable function. Otherwise, this conversion is considered worse
4055   // than ellipsis conversion. Consider this as an extension; this is not in the
4056   // standard. For example:
4057   //
4058   // int &f(...);    // #1
4059   // void f(char*);  // #2
4060   // void g() { int &r = f("foo"); }
4061   //
4062   // In C++03, we pick #2 as the best viable function.
4063   // In C++11, we pick #1 as the best viable function, because ellipsis
4064   // conversion is better than string-literal to char* conversion (since there
4065   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4066   // convert arguments, #2 would be the best viable function in C++11.
4067   // If the best viable function has this conversion, a warning will be issued
4068   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4069 
4070   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4071       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
4072           hasDeprecatedStringLiteralToCharPtrConversion(ICS2) &&
4073       // Ill-formedness must not differ
4074       ICS1.isBad() == ICS2.isBad())
4075     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
4076                ? ImplicitConversionSequence::Worse
4077                : ImplicitConversionSequence::Better;
4078 
4079   if (ICS1.getKindRank() < ICS2.getKindRank())
4080     return ImplicitConversionSequence::Better;
4081   if (ICS2.getKindRank() < ICS1.getKindRank())
4082     return ImplicitConversionSequence::Worse;
4083 
4084   // The following checks require both conversion sequences to be of
4085   // the same kind.
4086   if (ICS1.getKind() != ICS2.getKind())
4087     return ImplicitConversionSequence::Indistinguishable;
4088 
4089   ImplicitConversionSequence::CompareKind Result =
4090       ImplicitConversionSequence::Indistinguishable;
4091 
4092   // Two implicit conversion sequences of the same form are
4093   // indistinguishable conversion sequences unless one of the
4094   // following rules apply: (C++ 13.3.3.2p3):
4095 
4096   // List-initialization sequence L1 is a better conversion sequence than
4097   // list-initialization sequence L2 if:
4098   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4099   //   if not that,
4100   // — L1 and L2 convert to arrays of the same element type, and either the
4101   //   number of elements n_1 initialized by L1 is less than the number of
4102   //   elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4103   //   an array of unknown bound and L1 does not,
4104   // even if one of the other rules in this paragraph would otherwise apply.
4105   if (!ICS1.isBad()) {
4106     bool StdInit1 = false, StdInit2 = false;
4107     if (ICS1.hasInitializerListContainerType())
4108       StdInit1 = S.isStdInitializerList(ICS1.getInitializerListContainerType(),
4109                                         nullptr);
4110     if (ICS2.hasInitializerListContainerType())
4111       StdInit2 = S.isStdInitializerList(ICS2.getInitializerListContainerType(),
4112                                         nullptr);
4113     if (StdInit1 != StdInit2)
4114       return StdInit1 ? ImplicitConversionSequence::Better
4115                       : ImplicitConversionSequence::Worse;
4116 
4117     if (ICS1.hasInitializerListContainerType() &&
4118         ICS2.hasInitializerListContainerType())
4119       if (auto *CAT1 = S.Context.getAsConstantArrayType(
4120               ICS1.getInitializerListContainerType()))
4121         if (auto *CAT2 = S.Context.getAsConstantArrayType(
4122                 ICS2.getInitializerListContainerType())) {
4123           if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4124                                                CAT2->getElementType())) {
4125             // Both to arrays of the same element type
4126             if (CAT1->getSize() != CAT2->getSize())
4127               // Different sized, the smaller wins
4128               return CAT1->getSize().ult(CAT2->getSize())
4129                          ? ImplicitConversionSequence::Better
4130                          : ImplicitConversionSequence::Worse;
4131             if (ICS1.isInitializerListOfIncompleteArray() !=
4132                 ICS2.isInitializerListOfIncompleteArray())
4133               // One is incomplete, it loses
4134               return ICS2.isInitializerListOfIncompleteArray()
4135                          ? ImplicitConversionSequence::Better
4136                          : ImplicitConversionSequence::Worse;
4137           }
4138         }
4139   }
4140 
4141   if (ICS1.isStandard())
4142     // Standard conversion sequence S1 is a better conversion sequence than
4143     // standard conversion sequence S2 if [...]
4144     Result = CompareStandardConversionSequences(S, Loc,
4145                                                 ICS1.Standard, ICS2.Standard);
4146   else if (ICS1.isUserDefined()) {
4147     // User-defined conversion sequence U1 is a better conversion
4148     // sequence than another user-defined conversion sequence U2 if
4149     // they contain the same user-defined conversion function or
4150     // constructor and if the second standard conversion sequence of
4151     // U1 is better than the second standard conversion sequence of
4152     // U2 (C++ 13.3.3.2p3).
4153     if (ICS1.UserDefined.ConversionFunction ==
4154           ICS2.UserDefined.ConversionFunction)
4155       Result = CompareStandardConversionSequences(S, Loc,
4156                                                   ICS1.UserDefined.After,
4157                                                   ICS2.UserDefined.After);
4158     else
4159       Result = compareConversionFunctions(S,
4160                                           ICS1.UserDefined.ConversionFunction,
4161                                           ICS2.UserDefined.ConversionFunction);
4162   }
4163 
4164   return Result;
4165 }
4166 
4167 // Per 13.3.3.2p3, compare the given standard conversion sequences to
4168 // determine if one is a proper subset of the other.
4169 static ImplicitConversionSequence::CompareKind
4170 compareStandardConversionSubsets(ASTContext &Context,
4171                                  const StandardConversionSequence& SCS1,
4172                                  const StandardConversionSequence& SCS2) {
4173   ImplicitConversionSequence::CompareKind Result
4174     = ImplicitConversionSequence::Indistinguishable;
4175 
4176   // the identity conversion sequence is considered to be a subsequence of
4177   // any non-identity conversion sequence
4178   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4179     return ImplicitConversionSequence::Better;
4180   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4181     return ImplicitConversionSequence::Worse;
4182 
4183   if (SCS1.Second != SCS2.Second) {
4184     if (SCS1.Second == ICK_Identity)
4185       Result = ImplicitConversionSequence::Better;
4186     else if (SCS2.Second == ICK_Identity)
4187       Result = ImplicitConversionSequence::Worse;
4188     else
4189       return ImplicitConversionSequence::Indistinguishable;
4190   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4191     return ImplicitConversionSequence::Indistinguishable;
4192 
4193   if (SCS1.Third == SCS2.Third) {
4194     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4195                              : ImplicitConversionSequence::Indistinguishable;
4196   }
4197 
4198   if (SCS1.Third == ICK_Identity)
4199     return Result == ImplicitConversionSequence::Worse
4200              ? ImplicitConversionSequence::Indistinguishable
4201              : ImplicitConversionSequence::Better;
4202 
4203   if (SCS2.Third == ICK_Identity)
4204     return Result == ImplicitConversionSequence::Better
4205              ? ImplicitConversionSequence::Indistinguishable
4206              : ImplicitConversionSequence::Worse;
4207 
4208   return ImplicitConversionSequence::Indistinguishable;
4209 }
4210 
4211 /// Determine whether one of the given reference bindings is better
4212 /// than the other based on what kind of bindings they are.
4213 static bool
4214 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
4215                              const StandardConversionSequence &SCS2) {
4216   // C++0x [over.ics.rank]p3b4:
4217   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4218   //      implicit object parameter of a non-static member function declared
4219   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
4220   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
4221   //      lvalue reference to a function lvalue and S2 binds an rvalue
4222   //      reference*.
4223   //
4224   // FIXME: Rvalue references. We're going rogue with the above edits,
4225   // because the semantics in the current C++0x working paper (N3225 at the
4226   // time of this writing) break the standard definition of std::forward
4227   // and std::reference_wrapper when dealing with references to functions.
4228   // Proposed wording changes submitted to CWG for consideration.
4229   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
4230       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
4231     return false;
4232 
4233   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4234           SCS2.IsLvalueReference) ||
4235          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
4236           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
4237 }
4238 
4239 enum class FixedEnumPromotion {
4240   None,
4241   ToUnderlyingType,
4242   ToPromotedUnderlyingType
4243 };
4244 
4245 /// Returns kind of fixed enum promotion the \a SCS uses.
4246 static FixedEnumPromotion
4247 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
4248 
4249   if (SCS.Second != ICK_Integral_Promotion)
4250     return FixedEnumPromotion::None;
4251 
4252   QualType FromType = SCS.getFromType();
4253   if (!FromType->isEnumeralType())
4254     return FixedEnumPromotion::None;
4255 
4256   EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
4257   if (!Enum->isFixed())
4258     return FixedEnumPromotion::None;
4259 
4260   QualType UnderlyingType = Enum->getIntegerType();
4261   if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4262     return FixedEnumPromotion::ToUnderlyingType;
4263 
4264   return FixedEnumPromotion::ToPromotedUnderlyingType;
4265 }
4266 
4267 /// CompareStandardConversionSequences - Compare two standard
4268 /// conversion sequences to determine whether one is better than the
4269 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
4270 static ImplicitConversionSequence::CompareKind
4271 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
4272                                    const StandardConversionSequence& SCS1,
4273                                    const StandardConversionSequence& SCS2)
4274 {
4275   // Standard conversion sequence S1 is a better conversion sequence
4276   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4277 
4278   //  -- S1 is a proper subsequence of S2 (comparing the conversion
4279   //     sequences in the canonical form defined by 13.3.3.1.1,
4280   //     excluding any Lvalue Transformation; the identity conversion
4281   //     sequence is considered to be a subsequence of any
4282   //     non-identity conversion sequence) or, if not that,
4283   if (ImplicitConversionSequence::CompareKind CK
4284         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
4285     return CK;
4286 
4287   //  -- the rank of S1 is better than the rank of S2 (by the rules
4288   //     defined below), or, if not that,
4289   ImplicitConversionRank Rank1 = SCS1.getRank();
4290   ImplicitConversionRank Rank2 = SCS2.getRank();
4291   if (Rank1 < Rank2)
4292     return ImplicitConversionSequence::Better;
4293   else if (Rank2 < Rank1)
4294     return ImplicitConversionSequence::Worse;
4295 
4296   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4297   // are indistinguishable unless one of the following rules
4298   // applies:
4299 
4300   //   A conversion that is not a conversion of a pointer, or
4301   //   pointer to member, to bool is better than another conversion
4302   //   that is such a conversion.
4303   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4304     return SCS2.isPointerConversionToBool()
4305              ? ImplicitConversionSequence::Better
4306              : ImplicitConversionSequence::Worse;
4307 
4308   // C++14 [over.ics.rank]p4b2:
4309   // This is retroactively applied to C++11 by CWG 1601.
4310   //
4311   //   A conversion that promotes an enumeration whose underlying type is fixed
4312   //   to its underlying type is better than one that promotes to the promoted
4313   //   underlying type, if the two are different.
4314   FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
4315   FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
4316   if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4317       FEP1 != FEP2)
4318     return FEP1 == FixedEnumPromotion::ToUnderlyingType
4319                ? ImplicitConversionSequence::Better
4320                : ImplicitConversionSequence::Worse;
4321 
4322   // C++ [over.ics.rank]p4b2:
4323   //
4324   //   If class B is derived directly or indirectly from class A,
4325   //   conversion of B* to A* is better than conversion of B* to
4326   //   void*, and conversion of A* to void* is better than conversion
4327   //   of B* to void*.
4328   bool SCS1ConvertsToVoid
4329     = SCS1.isPointerConversionToVoidPointer(S.Context);
4330   bool SCS2ConvertsToVoid
4331     = SCS2.isPointerConversionToVoidPointer(S.Context);
4332   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4333     // Exactly one of the conversion sequences is a conversion to
4334     // a void pointer; it's the worse conversion.
4335     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4336                               : ImplicitConversionSequence::Worse;
4337   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4338     // Neither conversion sequence converts to a void pointer; compare
4339     // their derived-to-base conversions.
4340     if (ImplicitConversionSequence::CompareKind DerivedCK
4341           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4342       return DerivedCK;
4343   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4344              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4345     // Both conversion sequences are conversions to void
4346     // pointers. Compare the source types to determine if there's an
4347     // inheritance relationship in their sources.
4348     QualType FromType1 = SCS1.getFromType();
4349     QualType FromType2 = SCS2.getFromType();
4350 
4351     // Adjust the types we're converting from via the array-to-pointer
4352     // conversion, if we need to.
4353     if (SCS1.First == ICK_Array_To_Pointer)
4354       FromType1 = S.Context.getArrayDecayedType(FromType1);
4355     if (SCS2.First == ICK_Array_To_Pointer)
4356       FromType2 = S.Context.getArrayDecayedType(FromType2);
4357 
4358     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4359     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4360 
4361     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4362       return ImplicitConversionSequence::Better;
4363     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4364       return ImplicitConversionSequence::Worse;
4365 
4366     // Objective-C++: If one interface is more specific than the
4367     // other, it is the better one.
4368     const ObjCObjectPointerType* FromObjCPtr1
4369       = FromType1->getAs<ObjCObjectPointerType>();
4370     const ObjCObjectPointerType* FromObjCPtr2
4371       = FromType2->getAs<ObjCObjectPointerType>();
4372     if (FromObjCPtr1 && FromObjCPtr2) {
4373       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4374                                                           FromObjCPtr2);
4375       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4376                                                            FromObjCPtr1);
4377       if (AssignLeft != AssignRight) {
4378         return AssignLeft? ImplicitConversionSequence::Better
4379                          : ImplicitConversionSequence::Worse;
4380       }
4381     }
4382   }
4383 
4384   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4385     // Check for a better reference binding based on the kind of bindings.
4386     if (isBetterReferenceBindingKind(SCS1, SCS2))
4387       return ImplicitConversionSequence::Better;
4388     else if (isBetterReferenceBindingKind(SCS2, SCS1))
4389       return ImplicitConversionSequence::Worse;
4390   }
4391 
4392   // Compare based on qualification conversions (C++ 13.3.3.2p3,
4393   // bullet 3).
4394   if (ImplicitConversionSequence::CompareKind QualCK
4395         = CompareQualificationConversions(S, SCS1, SCS2))
4396     return QualCK;
4397 
4398   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4399     // C++ [over.ics.rank]p3b4:
4400     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
4401     //      which the references refer are the same type except for
4402     //      top-level cv-qualifiers, and the type to which the reference
4403     //      initialized by S2 refers is more cv-qualified than the type
4404     //      to which the reference initialized by S1 refers.
4405     QualType T1 = SCS1.getToType(2);
4406     QualType T2 = SCS2.getToType(2);
4407     T1 = S.Context.getCanonicalType(T1);
4408     T2 = S.Context.getCanonicalType(T2);
4409     Qualifiers T1Quals, T2Quals;
4410     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4411     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4412     if (UnqualT1 == UnqualT2) {
4413       // Objective-C++ ARC: If the references refer to objects with different
4414       // lifetimes, prefer bindings that don't change lifetime.
4415       if (SCS1.ObjCLifetimeConversionBinding !=
4416                                           SCS2.ObjCLifetimeConversionBinding) {
4417         return SCS1.ObjCLifetimeConversionBinding
4418                                            ? ImplicitConversionSequence::Worse
4419                                            : ImplicitConversionSequence::Better;
4420       }
4421 
4422       // If the type is an array type, promote the element qualifiers to the
4423       // type for comparison.
4424       if (isa<ArrayType>(T1) && T1Quals)
4425         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4426       if (isa<ArrayType>(T2) && T2Quals)
4427         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4428       if (T2.isMoreQualifiedThan(T1))
4429         return ImplicitConversionSequence::Better;
4430       if (T1.isMoreQualifiedThan(T2))
4431         return ImplicitConversionSequence::Worse;
4432     }
4433   }
4434 
4435   // In Microsoft mode (below 19.28), prefer an integral conversion to a
4436   // floating-to-integral conversion if the integral conversion
4437   // is between types of the same size.
4438   // For example:
4439   // void f(float);
4440   // void f(int);
4441   // int main {
4442   //    long a;
4443   //    f(a);
4444   // }
4445   // Here, MSVC will call f(int) instead of generating a compile error
4446   // as clang will do in standard mode.
4447   if (S.getLangOpts().MSVCCompat &&
4448       !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) &&
4449       SCS1.Second == ICK_Integral_Conversion &&
4450       SCS2.Second == ICK_Floating_Integral &&
4451       S.Context.getTypeSize(SCS1.getFromType()) ==
4452           S.Context.getTypeSize(SCS1.getToType(2)))
4453     return ImplicitConversionSequence::Better;
4454 
4455   // Prefer a compatible vector conversion over a lax vector conversion
4456   // For example:
4457   //
4458   // typedef float __v4sf __attribute__((__vector_size__(16)));
4459   // void f(vector float);
4460   // void f(vector signed int);
4461   // int main() {
4462   //   __v4sf a;
4463   //   f(a);
4464   // }
4465   // Here, we'd like to choose f(vector float) and not
4466   // report an ambiguous call error
4467   if (SCS1.Second == ICK_Vector_Conversion &&
4468       SCS2.Second == ICK_Vector_Conversion) {
4469     bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4470         SCS1.getFromType(), SCS1.getToType(2));
4471     bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4472         SCS2.getFromType(), SCS2.getToType(2));
4473 
4474     if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4475       return SCS1IsCompatibleVectorConversion
4476                  ? ImplicitConversionSequence::Better
4477                  : ImplicitConversionSequence::Worse;
4478   }
4479 
4480   if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4481       SCS2.Second == ICK_SVE_Vector_Conversion) {
4482     bool SCS1IsCompatibleSVEVectorConversion =
4483         S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4484     bool SCS2IsCompatibleSVEVectorConversion =
4485         S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4486 
4487     if (SCS1IsCompatibleSVEVectorConversion !=
4488         SCS2IsCompatibleSVEVectorConversion)
4489       return SCS1IsCompatibleSVEVectorConversion
4490                  ? ImplicitConversionSequence::Better
4491                  : ImplicitConversionSequence::Worse;
4492   }
4493 
4494   if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4495       SCS2.Second == ICK_RVV_Vector_Conversion) {
4496     bool SCS1IsCompatibleRVVVectorConversion =
4497         S.Context.areCompatibleRVVTypes(SCS1.getFromType(), SCS1.getToType(2));
4498     bool SCS2IsCompatibleRVVVectorConversion =
4499         S.Context.areCompatibleRVVTypes(SCS2.getFromType(), SCS2.getToType(2));
4500 
4501     if (SCS1IsCompatibleRVVVectorConversion !=
4502         SCS2IsCompatibleRVVVectorConversion)
4503       return SCS1IsCompatibleRVVVectorConversion
4504                  ? ImplicitConversionSequence::Better
4505                  : ImplicitConversionSequence::Worse;
4506   }
4507 
4508   return ImplicitConversionSequence::Indistinguishable;
4509 }
4510 
4511 /// CompareQualificationConversions - Compares two standard conversion
4512 /// sequences to determine whether they can be ranked based on their
4513 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4514 static ImplicitConversionSequence::CompareKind
4515 CompareQualificationConversions(Sema &S,
4516                                 const StandardConversionSequence& SCS1,
4517                                 const StandardConversionSequence& SCS2) {
4518   // C++ [over.ics.rank]p3:
4519   //  -- S1 and S2 differ only in their qualification conversion and
4520   //     yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4521   // [C++98]
4522   //     [...] and the cv-qualification signature of type T1 is a proper subset
4523   //     of the cv-qualification signature of type T2, and S1 is not the
4524   //     deprecated string literal array-to-pointer conversion (4.2).
4525   // [C++2a]
4526   //     [...] where T1 can be converted to T2 by a qualification conversion.
4527   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4528       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4529     return ImplicitConversionSequence::Indistinguishable;
4530 
4531   // FIXME: the example in the standard doesn't use a qualification
4532   // conversion (!)
4533   QualType T1 = SCS1.getToType(2);
4534   QualType T2 = SCS2.getToType(2);
4535   T1 = S.Context.getCanonicalType(T1);
4536   T2 = S.Context.getCanonicalType(T2);
4537   assert(!T1->isReferenceType() && !T2->isReferenceType());
4538   Qualifiers T1Quals, T2Quals;
4539   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4540   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4541 
4542   // If the types are the same, we won't learn anything by unwrapping
4543   // them.
4544   if (UnqualT1 == UnqualT2)
4545     return ImplicitConversionSequence::Indistinguishable;
4546 
4547   // Don't ever prefer a standard conversion sequence that uses the deprecated
4548   // string literal array to pointer conversion.
4549   bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4550   bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4551 
4552   // Objective-C++ ARC:
4553   //   Prefer qualification conversions not involving a change in lifetime
4554   //   to qualification conversions that do change lifetime.
4555   if (SCS1.QualificationIncludesObjCLifetime &&
4556       !SCS2.QualificationIncludesObjCLifetime)
4557     CanPick1 = false;
4558   if (SCS2.QualificationIncludesObjCLifetime &&
4559       !SCS1.QualificationIncludesObjCLifetime)
4560     CanPick2 = false;
4561 
4562   bool ObjCLifetimeConversion;
4563   if (CanPick1 &&
4564       !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4565     CanPick1 = false;
4566   // FIXME: In Objective-C ARC, we can have qualification conversions in both
4567   // directions, so we can't short-cut this second check in general.
4568   if (CanPick2 &&
4569       !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4570     CanPick2 = false;
4571 
4572   if (CanPick1 != CanPick2)
4573     return CanPick1 ? ImplicitConversionSequence::Better
4574                     : ImplicitConversionSequence::Worse;
4575   return ImplicitConversionSequence::Indistinguishable;
4576 }
4577 
4578 /// CompareDerivedToBaseConversions - Compares two standard conversion
4579 /// sequences to determine whether they can be ranked based on their
4580 /// various kinds of derived-to-base conversions (C++
4581 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4582 /// conversions between Objective-C interface types.
4583 static ImplicitConversionSequence::CompareKind
4584 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4585                                 const StandardConversionSequence& SCS1,
4586                                 const StandardConversionSequence& SCS2) {
4587   QualType FromType1 = SCS1.getFromType();
4588   QualType ToType1 = SCS1.getToType(1);
4589   QualType FromType2 = SCS2.getFromType();
4590   QualType ToType2 = SCS2.getToType(1);
4591 
4592   // Adjust the types we're converting from via the array-to-pointer
4593   // conversion, if we need to.
4594   if (SCS1.First == ICK_Array_To_Pointer)
4595     FromType1 = S.Context.getArrayDecayedType(FromType1);
4596   if (SCS2.First == ICK_Array_To_Pointer)
4597     FromType2 = S.Context.getArrayDecayedType(FromType2);
4598 
4599   // Canonicalize all of the types.
4600   FromType1 = S.Context.getCanonicalType(FromType1);
4601   ToType1 = S.Context.getCanonicalType(ToType1);
4602   FromType2 = S.Context.getCanonicalType(FromType2);
4603   ToType2 = S.Context.getCanonicalType(ToType2);
4604 
4605   // C++ [over.ics.rank]p4b3:
4606   //
4607   //   If class B is derived directly or indirectly from class A and
4608   //   class C is derived directly or indirectly from B,
4609   //
4610   // Compare based on pointer conversions.
4611   if (SCS1.Second == ICK_Pointer_Conversion &&
4612       SCS2.Second == ICK_Pointer_Conversion &&
4613       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4614       FromType1->isPointerType() && FromType2->isPointerType() &&
4615       ToType1->isPointerType() && ToType2->isPointerType()) {
4616     QualType FromPointee1 =
4617         FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4618     QualType ToPointee1 =
4619         ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4620     QualType FromPointee2 =
4621         FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4622     QualType ToPointee2 =
4623         ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4624 
4625     //   -- conversion of C* to B* is better than conversion of C* to A*,
4626     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4627       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4628         return ImplicitConversionSequence::Better;
4629       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4630         return ImplicitConversionSequence::Worse;
4631     }
4632 
4633     //   -- conversion of B* to A* is better than conversion of C* to A*,
4634     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4635       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4636         return ImplicitConversionSequence::Better;
4637       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4638         return ImplicitConversionSequence::Worse;
4639     }
4640   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4641              SCS2.Second == ICK_Pointer_Conversion) {
4642     const ObjCObjectPointerType *FromPtr1
4643       = FromType1->getAs<ObjCObjectPointerType>();
4644     const ObjCObjectPointerType *FromPtr2
4645       = FromType2->getAs<ObjCObjectPointerType>();
4646     const ObjCObjectPointerType *ToPtr1
4647       = ToType1->getAs<ObjCObjectPointerType>();
4648     const ObjCObjectPointerType *ToPtr2
4649       = ToType2->getAs<ObjCObjectPointerType>();
4650 
4651     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4652       // Apply the same conversion ranking rules for Objective-C pointer types
4653       // that we do for C++ pointers to class types. However, we employ the
4654       // Objective-C pseudo-subtyping relationship used for assignment of
4655       // Objective-C pointer types.
4656       bool FromAssignLeft
4657         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4658       bool FromAssignRight
4659         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4660       bool ToAssignLeft
4661         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4662       bool ToAssignRight
4663         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4664 
4665       // A conversion to an a non-id object pointer type or qualified 'id'
4666       // type is better than a conversion to 'id'.
4667       if (ToPtr1->isObjCIdType() &&
4668           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4669         return ImplicitConversionSequence::Worse;
4670       if (ToPtr2->isObjCIdType() &&
4671           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4672         return ImplicitConversionSequence::Better;
4673 
4674       // A conversion to a non-id object pointer type is better than a
4675       // conversion to a qualified 'id' type
4676       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4677         return ImplicitConversionSequence::Worse;
4678       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4679         return ImplicitConversionSequence::Better;
4680 
4681       // A conversion to an a non-Class object pointer type or qualified 'Class'
4682       // type is better than a conversion to 'Class'.
4683       if (ToPtr1->isObjCClassType() &&
4684           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4685         return ImplicitConversionSequence::Worse;
4686       if (ToPtr2->isObjCClassType() &&
4687           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4688         return ImplicitConversionSequence::Better;
4689 
4690       // A conversion to a non-Class object pointer type is better than a
4691       // conversion to a qualified 'Class' type.
4692       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4693         return ImplicitConversionSequence::Worse;
4694       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4695         return ImplicitConversionSequence::Better;
4696 
4697       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4698       if (S.Context.hasSameType(FromType1, FromType2) &&
4699           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4700           (ToAssignLeft != ToAssignRight)) {
4701         if (FromPtr1->isSpecialized()) {
4702           // "conversion of B<A> * to B * is better than conversion of B * to
4703           // C *.
4704           bool IsFirstSame =
4705               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4706           bool IsSecondSame =
4707               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4708           if (IsFirstSame) {
4709             if (!IsSecondSame)
4710               return ImplicitConversionSequence::Better;
4711           } else if (IsSecondSame)
4712             return ImplicitConversionSequence::Worse;
4713         }
4714         return ToAssignLeft? ImplicitConversionSequence::Worse
4715                            : ImplicitConversionSequence::Better;
4716       }
4717 
4718       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4719       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4720           (FromAssignLeft != FromAssignRight))
4721         return FromAssignLeft? ImplicitConversionSequence::Better
4722         : ImplicitConversionSequence::Worse;
4723     }
4724   }
4725 
4726   // Ranking of member-pointer types.
4727   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4728       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4729       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4730     const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4731     const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4732     const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4733     const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4734     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4735     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4736     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4737     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4738     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4739     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4740     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4741     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4742     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4743     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4744       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4745         return ImplicitConversionSequence::Worse;
4746       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4747         return ImplicitConversionSequence::Better;
4748     }
4749     // conversion of B::* to C::* is better than conversion of A::* to C::*
4750     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4751       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4752         return ImplicitConversionSequence::Better;
4753       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4754         return ImplicitConversionSequence::Worse;
4755     }
4756   }
4757 
4758   if (SCS1.Second == ICK_Derived_To_Base) {
4759     //   -- conversion of C to B is better than conversion of C to A,
4760     //   -- binding of an expression of type C to a reference of type
4761     //      B& is better than binding an expression of type C to a
4762     //      reference of type A&,
4763     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4764         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4765       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4766         return ImplicitConversionSequence::Better;
4767       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4768         return ImplicitConversionSequence::Worse;
4769     }
4770 
4771     //   -- conversion of B to A is better than conversion of C to A.
4772     //   -- binding of an expression of type B to a reference of type
4773     //      A& is better than binding an expression of type C to a
4774     //      reference of type A&,
4775     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4776         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4777       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4778         return ImplicitConversionSequence::Better;
4779       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4780         return ImplicitConversionSequence::Worse;
4781     }
4782   }
4783 
4784   return ImplicitConversionSequence::Indistinguishable;
4785 }
4786 
4787 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4788   if (!T.getQualifiers().hasUnaligned())
4789     return T;
4790 
4791   Qualifiers Q;
4792   T = Ctx.getUnqualifiedArrayType(T, Q);
4793   Q.removeUnaligned();
4794   return Ctx.getQualifiedType(T, Q);
4795 }
4796 
4797 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4798 /// determine whether they are reference-compatible,
4799 /// reference-related, or incompatible, for use in C++ initialization by
4800 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4801 /// type, and the first type (T1) is the pointee type of the reference
4802 /// type being initialized.
4803 Sema::ReferenceCompareResult
4804 Sema::CompareReferenceRelationship(SourceLocation Loc,
4805                                    QualType OrigT1, QualType OrigT2,
4806                                    ReferenceConversions *ConvOut) {
4807   assert(!OrigT1->isReferenceType() &&
4808     "T1 must be the pointee type of the reference type");
4809   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4810 
4811   QualType T1 = Context.getCanonicalType(OrigT1);
4812   QualType T2 = Context.getCanonicalType(OrigT2);
4813   Qualifiers T1Quals, T2Quals;
4814   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4815   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4816 
4817   ReferenceConversions ConvTmp;
4818   ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4819   Conv = ReferenceConversions();
4820 
4821   // C++2a [dcl.init.ref]p4:
4822   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4823   //   reference-related to "cv2 T2" if T1 is similar to T2, or
4824   //   T1 is a base class of T2.
4825   //   "cv1 T1" is reference-compatible with "cv2 T2" if
4826   //   a prvalue of type "pointer to cv2 T2" can be converted to the type
4827   //   "pointer to cv1 T1" via a standard conversion sequence.
4828 
4829   // Check for standard conversions we can apply to pointers: derived-to-base
4830   // conversions, ObjC pointer conversions, and function pointer conversions.
4831   // (Qualification conversions are checked last.)
4832   QualType ConvertedT2;
4833   if (UnqualT1 == UnqualT2) {
4834     // Nothing to do.
4835   } else if (isCompleteType(Loc, OrigT2) &&
4836              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4837     Conv |= ReferenceConversions::DerivedToBase;
4838   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4839            UnqualT2->isObjCObjectOrInterfaceType() &&
4840            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4841     Conv |= ReferenceConversions::ObjC;
4842   else if (UnqualT2->isFunctionType() &&
4843            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4844     Conv |= ReferenceConversions::Function;
4845     // No need to check qualifiers; function types don't have them.
4846     return Ref_Compatible;
4847   }
4848   bool ConvertedReferent = Conv != 0;
4849 
4850   // We can have a qualification conversion. Compute whether the types are
4851   // similar at the same time.
4852   bool PreviousToQualsIncludeConst = true;
4853   bool TopLevel = true;
4854   do {
4855     if (T1 == T2)
4856       break;
4857 
4858     // We will need a qualification conversion.
4859     Conv |= ReferenceConversions::Qualification;
4860 
4861     // Track whether we performed a qualification conversion anywhere other
4862     // than the top level. This matters for ranking reference bindings in
4863     // overload resolution.
4864     if (!TopLevel)
4865       Conv |= ReferenceConversions::NestedQualification;
4866 
4867     // MS compiler ignores __unaligned qualifier for references; do the same.
4868     T1 = withoutUnaligned(Context, T1);
4869     T2 = withoutUnaligned(Context, T2);
4870 
4871     // If we find a qualifier mismatch, the types are not reference-compatible,
4872     // but are still be reference-related if they're similar.
4873     bool ObjCLifetimeConversion = false;
4874     if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4875                                        PreviousToQualsIncludeConst,
4876                                        ObjCLifetimeConversion))
4877       return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4878                  ? Ref_Related
4879                  : Ref_Incompatible;
4880 
4881     // FIXME: Should we track this for any level other than the first?
4882     if (ObjCLifetimeConversion)
4883       Conv |= ReferenceConversions::ObjCLifetime;
4884 
4885     TopLevel = false;
4886   } while (Context.UnwrapSimilarTypes(T1, T2));
4887 
4888   // At this point, if the types are reference-related, we must either have the
4889   // same inner type (ignoring qualifiers), or must have already worked out how
4890   // to convert the referent.
4891   return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4892              ? Ref_Compatible
4893              : Ref_Incompatible;
4894 }
4895 
4896 /// Look for a user-defined conversion to a value reference-compatible
4897 ///        with DeclType. Return true if something definite is found.
4898 static bool
4899 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4900                          QualType DeclType, SourceLocation DeclLoc,
4901                          Expr *Init, QualType T2, bool AllowRvalues,
4902                          bool AllowExplicit) {
4903   assert(T2->isRecordType() && "Can only find conversions of record types.");
4904   auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4905 
4906   OverloadCandidateSet CandidateSet(
4907       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4908   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4909   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4910     NamedDecl *D = *I;
4911     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4912     if (isa<UsingShadowDecl>(D))
4913       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4914 
4915     FunctionTemplateDecl *ConvTemplate
4916       = dyn_cast<FunctionTemplateDecl>(D);
4917     CXXConversionDecl *Conv;
4918     if (ConvTemplate)
4919       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4920     else
4921       Conv = cast<CXXConversionDecl>(D);
4922 
4923     if (AllowRvalues) {
4924       // If we are initializing an rvalue reference, don't permit conversion
4925       // functions that return lvalues.
4926       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4927         const ReferenceType *RefType
4928           = Conv->getConversionType()->getAs<LValueReferenceType>();
4929         if (RefType && !RefType->getPointeeType()->isFunctionType())
4930           continue;
4931       }
4932 
4933       if (!ConvTemplate &&
4934           S.CompareReferenceRelationship(
4935               DeclLoc,
4936               Conv->getConversionType()
4937                   .getNonReferenceType()
4938                   .getUnqualifiedType(),
4939               DeclType.getNonReferenceType().getUnqualifiedType()) ==
4940               Sema::Ref_Incompatible)
4941         continue;
4942     } else {
4943       // If the conversion function doesn't return a reference type,
4944       // it can't be considered for this conversion. An rvalue reference
4945       // is only acceptable if its referencee is a function type.
4946 
4947       const ReferenceType *RefType =
4948         Conv->getConversionType()->getAs<ReferenceType>();
4949       if (!RefType ||
4950           (!RefType->isLValueReferenceType() &&
4951            !RefType->getPointeeType()->isFunctionType()))
4952         continue;
4953     }
4954 
4955     if (ConvTemplate)
4956       S.AddTemplateConversionCandidate(
4957           ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4958           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4959     else
4960       S.AddConversionCandidate(
4961           Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4962           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4963   }
4964 
4965   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4966 
4967   OverloadCandidateSet::iterator Best;
4968   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4969   case OR_Success:
4970     // C++ [over.ics.ref]p1:
4971     //
4972     //   [...] If the parameter binds directly to the result of
4973     //   applying a conversion function to the argument
4974     //   expression, the implicit conversion sequence is a
4975     //   user-defined conversion sequence (13.3.3.1.2), with the
4976     //   second standard conversion sequence either an identity
4977     //   conversion or, if the conversion function returns an
4978     //   entity of a type that is a derived class of the parameter
4979     //   type, a derived-to-base Conversion.
4980     if (!Best->FinalConversion.DirectBinding)
4981       return false;
4982 
4983     ICS.setUserDefined();
4984     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4985     ICS.UserDefined.After = Best->FinalConversion;
4986     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4987     ICS.UserDefined.ConversionFunction = Best->Function;
4988     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4989     ICS.UserDefined.EllipsisConversion = false;
4990     assert(ICS.UserDefined.After.ReferenceBinding &&
4991            ICS.UserDefined.After.DirectBinding &&
4992            "Expected a direct reference binding!");
4993     return true;
4994 
4995   case OR_Ambiguous:
4996     ICS.setAmbiguous();
4997     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4998          Cand != CandidateSet.end(); ++Cand)
4999       if (Cand->Best)
5000         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5001     return true;
5002 
5003   case OR_No_Viable_Function:
5004   case OR_Deleted:
5005     // There was no suitable conversion, or we found a deleted
5006     // conversion; continue with other checks.
5007     return false;
5008   }
5009 
5010   llvm_unreachable("Invalid OverloadResult!");
5011 }
5012 
5013 /// Compute an implicit conversion sequence for reference
5014 /// initialization.
5015 static ImplicitConversionSequence
5016 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
5017                  SourceLocation DeclLoc,
5018                  bool SuppressUserConversions,
5019                  bool AllowExplicit) {
5020   assert(DeclType->isReferenceType() && "Reference init needs a reference");
5021 
5022   // Most paths end in a failed conversion.
5023   ImplicitConversionSequence ICS;
5024   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
5025 
5026   QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5027   QualType T2 = Init->getType();
5028 
5029   // If the initializer is the address of an overloaded function, try
5030   // to resolve the overloaded function. If all goes well, T2 is the
5031   // type of the resulting function.
5032   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5033     DeclAccessPair Found;
5034     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
5035                                                                 false, Found))
5036       T2 = Fn->getType();
5037   }
5038 
5039   // Compute some basic properties of the types and the initializer.
5040   bool isRValRef = DeclType->isRValueReferenceType();
5041   Expr::Classification InitCategory = Init->Classify(S.Context);
5042 
5043   Sema::ReferenceConversions RefConv;
5044   Sema::ReferenceCompareResult RefRelationship =
5045       S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5046 
5047   auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5048     ICS.setStandard();
5049     ICS.Standard.First = ICK_Identity;
5050     // FIXME: A reference binding can be a function conversion too. We should
5051     // consider that when ordering reference-to-function bindings.
5052     ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5053                               ? ICK_Derived_To_Base
5054                               : (RefConv & Sema::ReferenceConversions::ObjC)
5055                                     ? ICK_Compatible_Conversion
5056                                     : ICK_Identity;
5057     // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5058     // a reference binding that performs a non-top-level qualification
5059     // conversion as a qualification conversion, not as an identity conversion.
5060     ICS.Standard.Third = (RefConv &
5061                               Sema::ReferenceConversions::NestedQualification)
5062                              ? ICK_Qualification
5063                              : ICK_Identity;
5064     ICS.Standard.setFromType(T2);
5065     ICS.Standard.setToType(0, T2);
5066     ICS.Standard.setToType(1, T1);
5067     ICS.Standard.setToType(2, T1);
5068     ICS.Standard.ReferenceBinding = true;
5069     ICS.Standard.DirectBinding = BindsDirectly;
5070     ICS.Standard.IsLvalueReference = !isRValRef;
5071     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
5072     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5073     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5074     ICS.Standard.ObjCLifetimeConversionBinding =
5075         (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5076     ICS.Standard.CopyConstructor = nullptr;
5077     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
5078   };
5079 
5080   // C++0x [dcl.init.ref]p5:
5081   //   A reference to type "cv1 T1" is initialized by an expression
5082   //   of type "cv2 T2" as follows:
5083 
5084   //     -- If reference is an lvalue reference and the initializer expression
5085   if (!isRValRef) {
5086     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5087     //        reference-compatible with "cv2 T2," or
5088     //
5089     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5090     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5091       // C++ [over.ics.ref]p1:
5092       //   When a parameter of reference type binds directly (8.5.3)
5093       //   to an argument expression, the implicit conversion sequence
5094       //   is the identity conversion, unless the argument expression
5095       //   has a type that is a derived class of the parameter type,
5096       //   in which case the implicit conversion sequence is a
5097       //   derived-to-base Conversion (13.3.3.1).
5098       SetAsReferenceBinding(/*BindsDirectly=*/true);
5099 
5100       // Nothing more to do: the inaccessibility/ambiguity check for
5101       // derived-to-base conversions is suppressed when we're
5102       // computing the implicit conversion sequence (C++
5103       // [over.best.ics]p2).
5104       return ICS;
5105     }
5106 
5107     //       -- has a class type (i.e., T2 is a class type), where T1 is
5108     //          not reference-related to T2, and can be implicitly
5109     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
5110     //          is reference-compatible with "cv3 T3" 92) (this
5111     //          conversion is selected by enumerating the applicable
5112     //          conversion functions (13.3.1.6) and choosing the best
5113     //          one through overload resolution (13.3)),
5114     if (!SuppressUserConversions && T2->isRecordType() &&
5115         S.isCompleteType(DeclLoc, T2) &&
5116         RefRelationship == Sema::Ref_Incompatible) {
5117       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5118                                    Init, T2, /*AllowRvalues=*/false,
5119                                    AllowExplicit))
5120         return ICS;
5121     }
5122   }
5123 
5124   //     -- Otherwise, the reference shall be an lvalue reference to a
5125   //        non-volatile const type (i.e., cv1 shall be const), or the reference
5126   //        shall be an rvalue reference.
5127   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5128     if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5129       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
5130     return ICS;
5131   }
5132 
5133   //       -- If the initializer expression
5134   //
5135   //            -- is an xvalue, class prvalue, array prvalue or function
5136   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5137   if (RefRelationship == Sema::Ref_Compatible &&
5138       (InitCategory.isXValue() ||
5139        (InitCategory.isPRValue() &&
5140           (T2->isRecordType() || T2->isArrayType())) ||
5141        (InitCategory.isLValue() && T2->isFunctionType()))) {
5142     // In C++11, this is always a direct binding. In C++98/03, it's a direct
5143     // binding unless we're binding to a class prvalue.
5144     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5145     // allow the use of rvalue references in C++98/03 for the benefit of
5146     // standard library implementors; therefore, we need the xvalue check here.
5147     SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5148                           !(InitCategory.isPRValue() || T2->isRecordType()));
5149     return ICS;
5150   }
5151 
5152   //            -- has a class type (i.e., T2 is a class type), where T1 is not
5153   //               reference-related to T2, and can be implicitly converted to
5154   //               an xvalue, class prvalue, or function lvalue of type
5155   //               "cv3 T3", where "cv1 T1" is reference-compatible with
5156   //               "cv3 T3",
5157   //
5158   //          then the reference is bound to the value of the initializer
5159   //          expression in the first case and to the result of the conversion
5160   //          in the second case (or, in either case, to an appropriate base
5161   //          class subobject).
5162   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5163       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5164       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5165                                Init, T2, /*AllowRvalues=*/true,
5166                                AllowExplicit)) {
5167     // In the second case, if the reference is an rvalue reference
5168     // and the second standard conversion sequence of the
5169     // user-defined conversion sequence includes an lvalue-to-rvalue
5170     // conversion, the program is ill-formed.
5171     if (ICS.isUserDefined() && isRValRef &&
5172         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
5173       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
5174 
5175     return ICS;
5176   }
5177 
5178   // A temporary of function type cannot be created; don't even try.
5179   if (T1->isFunctionType())
5180     return ICS;
5181 
5182   //       -- Otherwise, a temporary of type "cv1 T1" is created and
5183   //          initialized from the initializer expression using the
5184   //          rules for a non-reference copy initialization (8.5). The
5185   //          reference is then bound to the temporary. If T1 is
5186   //          reference-related to T2, cv1 must be the same
5187   //          cv-qualification as, or greater cv-qualification than,
5188   //          cv2; otherwise, the program is ill-formed.
5189   if (RefRelationship == Sema::Ref_Related) {
5190     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5191     // we would be reference-compatible or reference-compatible with
5192     // added qualification. But that wasn't the case, so the reference
5193     // initialization fails.
5194     //
5195     // Note that we only want to check address spaces and cvr-qualifiers here.
5196     // ObjC GC, lifetime and unaligned qualifiers aren't important.
5197     Qualifiers T1Quals = T1.getQualifiers();
5198     Qualifiers T2Quals = T2.getQualifiers();
5199     T1Quals.removeObjCGCAttr();
5200     T1Quals.removeObjCLifetime();
5201     T2Quals.removeObjCGCAttr();
5202     T2Quals.removeObjCLifetime();
5203     // MS compiler ignores __unaligned qualifier for references; do the same.
5204     T1Quals.removeUnaligned();
5205     T2Quals.removeUnaligned();
5206     if (!T1Quals.compatiblyIncludes(T2Quals))
5207       return ICS;
5208   }
5209 
5210   // If at least one of the types is a class type, the types are not
5211   // related, and we aren't allowed any user conversions, the
5212   // reference binding fails. This case is important for breaking
5213   // recursion, since TryImplicitConversion below will attempt to
5214   // create a temporary through the use of a copy constructor.
5215   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5216       (T1->isRecordType() || T2->isRecordType()))
5217     return ICS;
5218 
5219   // If T1 is reference-related to T2 and the reference is an rvalue
5220   // reference, the initializer expression shall not be an lvalue.
5221   if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5222       Init->Classify(S.Context).isLValue()) {
5223     ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType);
5224     return ICS;
5225   }
5226 
5227   // C++ [over.ics.ref]p2:
5228   //   When a parameter of reference type is not bound directly to
5229   //   an argument expression, the conversion sequence is the one
5230   //   required to convert the argument expression to the
5231   //   underlying type of the reference according to
5232   //   13.3.3.1. Conceptually, this conversion sequence corresponds
5233   //   to copy-initializing a temporary of the underlying type with
5234   //   the argument expression. Any difference in top-level
5235   //   cv-qualification is subsumed by the initialization itself
5236   //   and does not constitute a conversion.
5237   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5238                               AllowedExplicit::None,
5239                               /*InOverloadResolution=*/false,
5240                               /*CStyle=*/false,
5241                               /*AllowObjCWritebackConversion=*/false,
5242                               /*AllowObjCConversionOnExplicit=*/false);
5243 
5244   // Of course, that's still a reference binding.
5245   if (ICS.isStandard()) {
5246     ICS.Standard.ReferenceBinding = true;
5247     ICS.Standard.IsLvalueReference = !isRValRef;
5248     ICS.Standard.BindsToFunctionLvalue = false;
5249     ICS.Standard.BindsToRvalue = true;
5250     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5251     ICS.Standard.ObjCLifetimeConversionBinding = false;
5252   } else if (ICS.isUserDefined()) {
5253     const ReferenceType *LValRefType =
5254         ICS.UserDefined.ConversionFunction->getReturnType()
5255             ->getAs<LValueReferenceType>();
5256 
5257     // C++ [over.ics.ref]p3:
5258     //   Except for an implicit object parameter, for which see 13.3.1, a
5259     //   standard conversion sequence cannot be formed if it requires [...]
5260     //   binding an rvalue reference to an lvalue other than a function
5261     //   lvalue.
5262     // Note that the function case is not possible here.
5263     if (isRValRef && LValRefType) {
5264       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
5265       return ICS;
5266     }
5267 
5268     ICS.UserDefined.After.ReferenceBinding = true;
5269     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5270     ICS.UserDefined.After.BindsToFunctionLvalue = false;
5271     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5272     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5273     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
5274   }
5275 
5276   return ICS;
5277 }
5278 
5279 static ImplicitConversionSequence
5280 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5281                       bool SuppressUserConversions,
5282                       bool InOverloadResolution,
5283                       bool AllowObjCWritebackConversion,
5284                       bool AllowExplicit = false);
5285 
5286 /// TryListConversion - Try to copy-initialize a value of type ToType from the
5287 /// initializer list From.
5288 static ImplicitConversionSequence
5289 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5290                   bool SuppressUserConversions,
5291                   bool InOverloadResolution,
5292                   bool AllowObjCWritebackConversion) {
5293   // C++11 [over.ics.list]p1:
5294   //   When an argument is an initializer list, it is not an expression and
5295   //   special rules apply for converting it to a parameter type.
5296 
5297   ImplicitConversionSequence Result;
5298   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5299 
5300   // We need a complete type for what follows.  With one C++20 exception,
5301   // incomplete types can never be initialized from init lists.
5302   QualType InitTy = ToType;
5303   const ArrayType *AT = S.Context.getAsArrayType(ToType);
5304   if (AT && S.getLangOpts().CPlusPlus20)
5305     if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5306       // C++20 allows list initialization of an incomplete array type.
5307       InitTy = IAT->getElementType();
5308   if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5309     return Result;
5310 
5311   // C++20 [over.ics.list]/2:
5312   //   If the initializer list is a designated-initializer-list, a conversion
5313   //   is only possible if the parameter has an aggregate type
5314   //
5315   // FIXME: The exception for reference initialization here is not part of the
5316   // language rules, but follow other compilers in adding it as a tentative DR
5317   // resolution.
5318   bool IsDesignatedInit = From->hasDesignatedInit();
5319   if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5320       IsDesignatedInit)
5321     return Result;
5322 
5323   // Per DR1467:
5324   //   If the parameter type is a class X and the initializer list has a single
5325   //   element of type cv U, where U is X or a class derived from X, the
5326   //   implicit conversion sequence is the one required to convert the element
5327   //   to the parameter type.
5328   //
5329   //   Otherwise, if the parameter type is a character array [... ]
5330   //   and the initializer list has a single element that is an
5331   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5332   //   implicit conversion sequence is the identity conversion.
5333   if (From->getNumInits() == 1 && !IsDesignatedInit) {
5334     if (ToType->isRecordType()) {
5335       QualType InitType = From->getInit(0)->getType();
5336       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5337           S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5338         return TryCopyInitialization(S, From->getInit(0), ToType,
5339                                      SuppressUserConversions,
5340                                      InOverloadResolution,
5341                                      AllowObjCWritebackConversion);
5342     }
5343 
5344     if (AT && S.IsStringInit(From->getInit(0), AT)) {
5345       InitializedEntity Entity =
5346           InitializedEntity::InitializeParameter(S.Context, ToType,
5347                                                  /*Consumed=*/false);
5348       if (S.CanPerformCopyInitialization(Entity, From)) {
5349         Result.setStandard();
5350         Result.Standard.setAsIdentityConversion();
5351         Result.Standard.setFromType(ToType);
5352         Result.Standard.setAllToTypes(ToType);
5353         return Result;
5354       }
5355     }
5356   }
5357 
5358   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5359   // C++11 [over.ics.list]p2:
5360   //   If the parameter type is std::initializer_list<X> or "array of X" and
5361   //   all the elements can be implicitly converted to X, the implicit
5362   //   conversion sequence is the worst conversion necessary to convert an
5363   //   element of the list to X.
5364   //
5365   // C++14 [over.ics.list]p3:
5366   //   Otherwise, if the parameter type is "array of N X", if the initializer
5367   //   list has exactly N elements or if it has fewer than N elements and X is
5368   //   default-constructible, and if all the elements of the initializer list
5369   //   can be implicitly converted to X, the implicit conversion sequence is
5370   //   the worst conversion necessary to convert an element of the list to X.
5371   if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5372     unsigned e = From->getNumInits();
5373     ImplicitConversionSequence DfltElt;
5374     DfltElt.setBad(BadConversionSequence::no_conversion, QualType(),
5375                    QualType());
5376     QualType ContTy = ToType;
5377     bool IsUnbounded = false;
5378     if (AT) {
5379       InitTy = AT->getElementType();
5380       if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5381         if (CT->getSize().ult(e)) {
5382           // Too many inits, fatally bad
5383           Result.setBad(BadConversionSequence::too_many_initializers, From,
5384                         ToType);
5385           Result.setInitializerListContainerType(ContTy, IsUnbounded);
5386           return Result;
5387         }
5388         if (CT->getSize().ugt(e)) {
5389           // Need an init from empty {}, is there one?
5390           InitListExpr EmptyList(S.Context, From->getEndLoc(), std::nullopt,
5391                                  From->getEndLoc());
5392           EmptyList.setType(S.Context.VoidTy);
5393           DfltElt = TryListConversion(
5394               S, &EmptyList, InitTy, SuppressUserConversions,
5395               InOverloadResolution, AllowObjCWritebackConversion);
5396           if (DfltElt.isBad()) {
5397             // No {} init, fatally bad
5398             Result.setBad(BadConversionSequence::too_few_initializers, From,
5399                           ToType);
5400             Result.setInitializerListContainerType(ContTy, IsUnbounded);
5401             return Result;
5402           }
5403         }
5404       } else {
5405         assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5406         IsUnbounded = true;
5407         if (!e) {
5408           // Cannot convert to zero-sized.
5409           Result.setBad(BadConversionSequence::too_few_initializers, From,
5410                         ToType);
5411           Result.setInitializerListContainerType(ContTy, IsUnbounded);
5412           return Result;
5413         }
5414         llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5415         ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5416                                                 ArraySizeModifier::Normal, 0);
5417       }
5418     }
5419 
5420     Result.setStandard();
5421     Result.Standard.setAsIdentityConversion();
5422     Result.Standard.setFromType(InitTy);
5423     Result.Standard.setAllToTypes(InitTy);
5424     for (unsigned i = 0; i < e; ++i) {
5425       Expr *Init = From->getInit(i);
5426       ImplicitConversionSequence ICS = TryCopyInitialization(
5427           S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5428           AllowObjCWritebackConversion);
5429 
5430       // Keep the worse conversion seen so far.
5431       // FIXME: Sequences are not totally ordered, so 'worse' can be
5432       // ambiguous. CWG has been informed.
5433       if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS,
5434                                              Result) ==
5435           ImplicitConversionSequence::Worse) {
5436         Result = ICS;
5437         // Bail as soon as we find something unconvertible.
5438         if (Result.isBad()) {
5439           Result.setInitializerListContainerType(ContTy, IsUnbounded);
5440           return Result;
5441         }
5442       }
5443     }
5444 
5445     // If we needed any implicit {} initialization, compare that now.
5446     // over.ics.list/6 indicates we should compare that conversion.  Again CWG
5447     // has been informed that this might not be the best thing.
5448     if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5449                                 S, From->getEndLoc(), DfltElt, Result) ==
5450                                 ImplicitConversionSequence::Worse)
5451       Result = DfltElt;
5452     // Record the type being initialized so that we may compare sequences
5453     Result.setInitializerListContainerType(ContTy, IsUnbounded);
5454     return Result;
5455   }
5456 
5457   // C++14 [over.ics.list]p4:
5458   // C++11 [over.ics.list]p3:
5459   //   Otherwise, if the parameter is a non-aggregate class X and overload
5460   //   resolution chooses a single best constructor [...] the implicit
5461   //   conversion sequence is a user-defined conversion sequence. If multiple
5462   //   constructors are viable but none is better than the others, the
5463   //   implicit conversion sequence is a user-defined conversion sequence.
5464   if (ToType->isRecordType() && !ToType->isAggregateType()) {
5465     // This function can deal with initializer lists.
5466     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5467                                     AllowedExplicit::None,
5468                                     InOverloadResolution, /*CStyle=*/false,
5469                                     AllowObjCWritebackConversion,
5470                                     /*AllowObjCConversionOnExplicit=*/false);
5471   }
5472 
5473   // C++14 [over.ics.list]p5:
5474   // C++11 [over.ics.list]p4:
5475   //   Otherwise, if the parameter has an aggregate type which can be
5476   //   initialized from the initializer list [...] the implicit conversion
5477   //   sequence is a user-defined conversion sequence.
5478   if (ToType->isAggregateType()) {
5479     // Type is an aggregate, argument is an init list. At this point it comes
5480     // down to checking whether the initialization works.
5481     // FIXME: Find out whether this parameter is consumed or not.
5482     InitializedEntity Entity =
5483         InitializedEntity::InitializeParameter(S.Context, ToType,
5484                                                /*Consumed=*/false);
5485     if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5486                                                                  From)) {
5487       Result.setUserDefined();
5488       Result.UserDefined.Before.setAsIdentityConversion();
5489       // Initializer lists don't have a type.
5490       Result.UserDefined.Before.setFromType(QualType());
5491       Result.UserDefined.Before.setAllToTypes(QualType());
5492 
5493       Result.UserDefined.After.setAsIdentityConversion();
5494       Result.UserDefined.After.setFromType(ToType);
5495       Result.UserDefined.After.setAllToTypes(ToType);
5496       Result.UserDefined.ConversionFunction = nullptr;
5497     }
5498     return Result;
5499   }
5500 
5501   // C++14 [over.ics.list]p6:
5502   // C++11 [over.ics.list]p5:
5503   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5504   if (ToType->isReferenceType()) {
5505     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5506     // mention initializer lists in any way. So we go by what list-
5507     // initialization would do and try to extrapolate from that.
5508 
5509     QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5510 
5511     // If the initializer list has a single element that is reference-related
5512     // to the parameter type, we initialize the reference from that.
5513     if (From->getNumInits() == 1 && !IsDesignatedInit) {
5514       Expr *Init = From->getInit(0);
5515 
5516       QualType T2 = Init->getType();
5517 
5518       // If the initializer is the address of an overloaded function, try
5519       // to resolve the overloaded function. If all goes well, T2 is the
5520       // type of the resulting function.
5521       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5522         DeclAccessPair Found;
5523         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5524                                    Init, ToType, false, Found))
5525           T2 = Fn->getType();
5526       }
5527 
5528       // Compute some basic properties of the types and the initializer.
5529       Sema::ReferenceCompareResult RefRelationship =
5530           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5531 
5532       if (RefRelationship >= Sema::Ref_Related) {
5533         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5534                                 SuppressUserConversions,
5535                                 /*AllowExplicit=*/false);
5536       }
5537     }
5538 
5539     // Otherwise, we bind the reference to a temporary created from the
5540     // initializer list.
5541     Result = TryListConversion(S, From, T1, SuppressUserConversions,
5542                                InOverloadResolution,
5543                                AllowObjCWritebackConversion);
5544     if (Result.isFailure())
5545       return Result;
5546     assert(!Result.isEllipsis() &&
5547            "Sub-initialization cannot result in ellipsis conversion.");
5548 
5549     // Can we even bind to a temporary?
5550     if (ToType->isRValueReferenceType() ||
5551         (T1.isConstQualified() && !T1.isVolatileQualified())) {
5552       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5553                                             Result.UserDefined.After;
5554       SCS.ReferenceBinding = true;
5555       SCS.IsLvalueReference = ToType->isLValueReferenceType();
5556       SCS.BindsToRvalue = true;
5557       SCS.BindsToFunctionLvalue = false;
5558       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5559       SCS.ObjCLifetimeConversionBinding = false;
5560     } else
5561       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5562                     From, ToType);
5563     return Result;
5564   }
5565 
5566   // C++14 [over.ics.list]p7:
5567   // C++11 [over.ics.list]p6:
5568   //   Otherwise, if the parameter type is not a class:
5569   if (!ToType->isRecordType()) {
5570     //    - if the initializer list has one element that is not itself an
5571     //      initializer list, the implicit conversion sequence is the one
5572     //      required to convert the element to the parameter type.
5573     unsigned NumInits = From->getNumInits();
5574     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5575       Result = TryCopyInitialization(S, From->getInit(0), ToType,
5576                                      SuppressUserConversions,
5577                                      InOverloadResolution,
5578                                      AllowObjCWritebackConversion);
5579     //    - if the initializer list has no elements, the implicit conversion
5580     //      sequence is the identity conversion.
5581     else if (NumInits == 0) {
5582       Result.setStandard();
5583       Result.Standard.setAsIdentityConversion();
5584       Result.Standard.setFromType(ToType);
5585       Result.Standard.setAllToTypes(ToType);
5586     }
5587     return Result;
5588   }
5589 
5590   // C++14 [over.ics.list]p8:
5591   // C++11 [over.ics.list]p7:
5592   //   In all cases other than those enumerated above, no conversion is possible
5593   return Result;
5594 }
5595 
5596 /// TryCopyInitialization - Try to copy-initialize a value of type
5597 /// ToType from the expression From. Return the implicit conversion
5598 /// sequence required to pass this argument, which may be a bad
5599 /// conversion sequence (meaning that the argument cannot be passed to
5600 /// a parameter of this type). If @p SuppressUserConversions, then we
5601 /// do not permit any user-defined conversion sequences.
5602 static ImplicitConversionSequence
5603 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5604                       bool SuppressUserConversions,
5605                       bool InOverloadResolution,
5606                       bool AllowObjCWritebackConversion,
5607                       bool AllowExplicit) {
5608   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5609     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5610                              InOverloadResolution,AllowObjCWritebackConversion);
5611 
5612   if (ToType->isReferenceType())
5613     return TryReferenceInit(S, From, ToType,
5614                             /*FIXME:*/ From->getBeginLoc(),
5615                             SuppressUserConversions, AllowExplicit);
5616 
5617   return TryImplicitConversion(S, From, ToType,
5618                                SuppressUserConversions,
5619                                AllowedExplicit::None,
5620                                InOverloadResolution,
5621                                /*CStyle=*/false,
5622                                AllowObjCWritebackConversion,
5623                                /*AllowObjCConversionOnExplicit=*/false);
5624 }
5625 
5626 static bool TryCopyInitialization(const CanQualType FromQTy,
5627                                   const CanQualType ToQTy,
5628                                   Sema &S,
5629                                   SourceLocation Loc,
5630                                   ExprValueKind FromVK) {
5631   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5632   ImplicitConversionSequence ICS =
5633     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5634 
5635   return !ICS.isBad();
5636 }
5637 
5638 /// TryObjectArgumentInitialization - Try to initialize the object
5639 /// parameter of the given member function (@c Method) from the
5640 /// expression @p From.
5641 static ImplicitConversionSequence TryObjectArgumentInitialization(
5642     Sema &S, SourceLocation Loc, QualType FromType,
5643     Expr::Classification FromClassification, CXXMethodDecl *Method,
5644     const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
5645     QualType ExplicitParameterType = QualType(),
5646     bool SuppressUserConversion = false) {
5647 
5648   // We need to have an object of class type.
5649   if (const auto *PT = FromType->getAs<PointerType>()) {
5650     FromType = PT->getPointeeType();
5651 
5652     // When we had a pointer, it's implicitly dereferenced, so we
5653     // better have an lvalue.
5654     assert(FromClassification.isLValue());
5655   }
5656 
5657   auto ValueKindFromClassification = [](Expr::Classification C) {
5658     if (C.isPRValue())
5659       return clang::VK_PRValue;
5660     if (C.isXValue())
5661       return VK_XValue;
5662     return clang::VK_LValue;
5663   };
5664 
5665   if (Method->isExplicitObjectMemberFunction()) {
5666     if (ExplicitParameterType.isNull())
5667       ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
5668     OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
5669                             ValueKindFromClassification(FromClassification));
5670     ImplicitConversionSequence ICS = TryCopyInitialization(
5671         S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
5672         /*InOverloadResolution=*/true, false);
5673     if (ICS.isBad())
5674       ICS.Bad.FromExpr = nullptr;
5675     return ICS;
5676   }
5677 
5678   assert(FromType->isRecordType());
5679 
5680   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5681   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5682   //                 const volatile object.
5683   Qualifiers Quals = Method->getMethodQualifiers();
5684   if (isa<CXXDestructorDecl>(Method)) {
5685     Quals.addConst();
5686     Quals.addVolatile();
5687   }
5688 
5689   QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5690 
5691   // Set up the conversion sequence as a "bad" conversion, to allow us
5692   // to exit early.
5693   ImplicitConversionSequence ICS;
5694 
5695   // C++0x [over.match.funcs]p4:
5696   //   For non-static member functions, the type of the implicit object
5697   //   parameter is
5698   //
5699   //     - "lvalue reference to cv X" for functions declared without a
5700   //        ref-qualifier or with the & ref-qualifier
5701   //     - "rvalue reference to cv X" for functions declared with the &&
5702   //        ref-qualifier
5703   //
5704   // where X is the class of which the function is a member and cv is the
5705   // cv-qualification on the member function declaration.
5706   //
5707   // However, when finding an implicit conversion sequence for the argument, we
5708   // are not allowed to perform user-defined conversions
5709   // (C++ [over.match.funcs]p5). We perform a simplified version of
5710   // reference binding here, that allows class rvalues to bind to
5711   // non-constant references.
5712 
5713   // First check the qualifiers.
5714   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5715   // MSVC ignores __unaligned qualifier for overload candidates; do the same.
5716   if (ImplicitParamType.getCVRQualifiers() !=
5717           FromTypeCanon.getLocalCVRQualifiers() &&
5718       !ImplicitParamType.isAtLeastAsQualifiedAs(
5719           withoutUnaligned(S.Context, FromTypeCanon))) {
5720     ICS.setBad(BadConversionSequence::bad_qualifiers,
5721                FromType, ImplicitParamType);
5722     return ICS;
5723   }
5724 
5725   if (FromTypeCanon.hasAddressSpace()) {
5726     Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5727     Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5728     if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5729       ICS.setBad(BadConversionSequence::bad_qualifiers,
5730                  FromType, ImplicitParamType);
5731       return ICS;
5732     }
5733   }
5734 
5735   // Check that we have either the same type or a derived type. It
5736   // affects the conversion rank.
5737   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5738   ImplicitConversionKind SecondKind;
5739   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5740     SecondKind = ICK_Identity;
5741   } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
5742     SecondKind = ICK_Derived_To_Base;
5743   } else if (!Method->isExplicitObjectMemberFunction()) {
5744     ICS.setBad(BadConversionSequence::unrelated_class,
5745                FromType, ImplicitParamType);
5746     return ICS;
5747   }
5748 
5749   // Check the ref-qualifier.
5750   switch (Method->getRefQualifier()) {
5751   case RQ_None:
5752     // Do nothing; we don't care about lvalueness or rvalueness.
5753     break;
5754 
5755   case RQ_LValue:
5756     if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5757       // non-const lvalue reference cannot bind to an rvalue
5758       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5759                  ImplicitParamType);
5760       return ICS;
5761     }
5762     break;
5763 
5764   case RQ_RValue:
5765     if (!FromClassification.isRValue()) {
5766       // rvalue reference cannot bind to an lvalue
5767       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5768                  ImplicitParamType);
5769       return ICS;
5770     }
5771     break;
5772   }
5773 
5774   // Success. Mark this as a reference binding.
5775   ICS.setStandard();
5776   ICS.Standard.setAsIdentityConversion();
5777   ICS.Standard.Second = SecondKind;
5778   ICS.Standard.setFromType(FromType);
5779   ICS.Standard.setAllToTypes(ImplicitParamType);
5780   ICS.Standard.ReferenceBinding = true;
5781   ICS.Standard.DirectBinding = true;
5782   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5783   ICS.Standard.BindsToFunctionLvalue = false;
5784   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5785   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5786     = (Method->getRefQualifier() == RQ_None);
5787   return ICS;
5788 }
5789 
5790 /// PerformObjectArgumentInitialization - Perform initialization of
5791 /// the implicit object parameter for the given Method with the given
5792 /// expression.
5793 ExprResult Sema::PerformImplicitObjectArgumentInitialization(
5794     Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl,
5795     CXXMethodDecl *Method) {
5796   QualType FromRecordType, DestType;
5797   QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
5798 
5799   Expr::Classification FromClassification;
5800   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5801     FromRecordType = PT->getPointeeType();
5802     DestType = Method->getThisType();
5803     FromClassification = Expr::Classification::makeSimpleLValue();
5804   } else {
5805     FromRecordType = From->getType();
5806     DestType = ImplicitParamRecordType;
5807     FromClassification = From->Classify(Context);
5808 
5809     // When performing member access on a prvalue, materialize a temporary.
5810     if (From->isPRValue()) {
5811       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5812                                             Method->getRefQualifier() !=
5813                                                 RefQualifierKind::RQ_RValue);
5814     }
5815   }
5816 
5817   // Note that we always use the true parent context when performing
5818   // the actual argument initialization.
5819   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5820       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5821       Method->getParent());
5822   if (ICS.isBad()) {
5823     switch (ICS.Bad.Kind) {
5824     case BadConversionSequence::bad_qualifiers: {
5825       Qualifiers FromQs = FromRecordType.getQualifiers();
5826       Qualifiers ToQs = DestType.getQualifiers();
5827       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5828       if (CVR) {
5829         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5830             << Method->getDeclName() << FromRecordType << (CVR - 1)
5831             << From->getSourceRange();
5832         Diag(Method->getLocation(), diag::note_previous_decl)
5833           << Method->getDeclName();
5834         return ExprError();
5835       }
5836       break;
5837     }
5838 
5839     case BadConversionSequence::lvalue_ref_to_rvalue:
5840     case BadConversionSequence::rvalue_ref_to_lvalue: {
5841       bool IsRValueQualified =
5842         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5843       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5844           << Method->getDeclName() << FromClassification.isRValue()
5845           << IsRValueQualified;
5846       Diag(Method->getLocation(), diag::note_previous_decl)
5847         << Method->getDeclName();
5848       return ExprError();
5849     }
5850 
5851     case BadConversionSequence::no_conversion:
5852     case BadConversionSequence::unrelated_class:
5853       break;
5854 
5855     case BadConversionSequence::too_few_initializers:
5856     case BadConversionSequence::too_many_initializers:
5857       llvm_unreachable("Lists are not objects");
5858     }
5859 
5860     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5861            << ImplicitParamRecordType << FromRecordType
5862            << From->getSourceRange();
5863   }
5864 
5865   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5866     ExprResult FromRes =
5867       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5868     if (FromRes.isInvalid())
5869       return ExprError();
5870     From = FromRes.get();
5871   }
5872 
5873   if (!Context.hasSameType(From->getType(), DestType)) {
5874     CastKind CK;
5875     QualType PteeTy = DestType->getPointeeType();
5876     LangAS DestAS =
5877         PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5878     if (FromRecordType.getAddressSpace() != DestAS)
5879       CK = CK_AddressSpaceConversion;
5880     else
5881       CK = CK_NoOp;
5882     From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5883   }
5884   return From;
5885 }
5886 
5887 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5888 /// expression From to bool (C++0x [conv]p3).
5889 static ImplicitConversionSequence
5890 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5891   // C++ [dcl.init]/17.8:
5892   //   - Otherwise, if the initialization is direct-initialization, the source
5893   //     type is std::nullptr_t, and the destination type is bool, the initial
5894   //     value of the object being initialized is false.
5895   if (From->getType()->isNullPtrType())
5896     return ImplicitConversionSequence::getNullptrToBool(From->getType(),
5897                                                         S.Context.BoolTy,
5898                                                         From->isGLValue());
5899 
5900   // All other direct-initialization of bool is equivalent to an implicit
5901   // conversion to bool in which explicit conversions are permitted.
5902   return TryImplicitConversion(S, From, S.Context.BoolTy,
5903                                /*SuppressUserConversions=*/false,
5904                                AllowedExplicit::Conversions,
5905                                /*InOverloadResolution=*/false,
5906                                /*CStyle=*/false,
5907                                /*AllowObjCWritebackConversion=*/false,
5908                                /*AllowObjCConversionOnExplicit=*/false);
5909 }
5910 
5911 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5912 /// of the expression From to bool (C++0x [conv]p3).
5913 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5914   if (checkPlaceholderForOverload(*this, From))
5915     return ExprError();
5916 
5917   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5918   if (!ICS.isBad())
5919     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5920 
5921   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5922     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5923            << From->getType() << From->getSourceRange();
5924   return ExprError();
5925 }
5926 
5927 /// Check that the specified conversion is permitted in a converted constant
5928 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5929 /// is acceptable.
5930 static bool CheckConvertedConstantConversions(Sema &S,
5931                                               StandardConversionSequence &SCS) {
5932   // Since we know that the target type is an integral or unscoped enumeration
5933   // type, most conversion kinds are impossible. All possible First and Third
5934   // conversions are fine.
5935   switch (SCS.Second) {
5936   case ICK_Identity:
5937   case ICK_Integral_Promotion:
5938   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5939   case ICK_Zero_Queue_Conversion:
5940     return true;
5941 
5942   case ICK_Boolean_Conversion:
5943     // Conversion from an integral or unscoped enumeration type to bool is
5944     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5945     // conversion, so we allow it in a converted constant expression.
5946     //
5947     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5948     // a lot of popular code. We should at least add a warning for this
5949     // (non-conforming) extension.
5950     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5951            SCS.getToType(2)->isBooleanType();
5952 
5953   case ICK_Pointer_Conversion:
5954   case ICK_Pointer_Member:
5955     // C++1z: null pointer conversions and null member pointer conversions are
5956     // only permitted if the source type is std::nullptr_t.
5957     return SCS.getFromType()->isNullPtrType();
5958 
5959   case ICK_Floating_Promotion:
5960   case ICK_Complex_Promotion:
5961   case ICK_Floating_Conversion:
5962   case ICK_Complex_Conversion:
5963   case ICK_Floating_Integral:
5964   case ICK_Compatible_Conversion:
5965   case ICK_Derived_To_Base:
5966   case ICK_Vector_Conversion:
5967   case ICK_SVE_Vector_Conversion:
5968   case ICK_RVV_Vector_Conversion:
5969   case ICK_Vector_Splat:
5970   case ICK_Complex_Real:
5971   case ICK_Block_Pointer_Conversion:
5972   case ICK_TransparentUnionConversion:
5973   case ICK_Writeback_Conversion:
5974   case ICK_Zero_Event_Conversion:
5975   case ICK_C_Only_Conversion:
5976   case ICK_Incompatible_Pointer_Conversion:
5977   case ICK_Fixed_Point_Conversion:
5978     return false;
5979 
5980   case ICK_Lvalue_To_Rvalue:
5981   case ICK_Array_To_Pointer:
5982   case ICK_Function_To_Pointer:
5983     llvm_unreachable("found a first conversion kind in Second");
5984 
5985   case ICK_Function_Conversion:
5986   case ICK_Qualification:
5987     llvm_unreachable("found a third conversion kind in Second");
5988 
5989   case ICK_Num_Conversion_Kinds:
5990     break;
5991   }
5992 
5993   llvm_unreachable("unknown conversion kind");
5994 }
5995 
5996 /// BuildConvertedConstantExpression - Check that the expression From is a
5997 /// converted constant expression of type T, perform the conversion but
5998 /// does not evaluate the expression
5999 static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From,
6000                                                    QualType T,
6001                                                    Sema::CCEKind CCE,
6002                                                    NamedDecl *Dest,
6003                                                    APValue &PreNarrowingValue) {
6004   assert(S.getLangOpts().CPlusPlus11 &&
6005          "converted constant expression outside C++11");
6006 
6007   if (checkPlaceholderForOverload(S, From))
6008     return ExprError();
6009 
6010   // C++1z [expr.const]p3:
6011   //  A converted constant expression of type T is an expression,
6012   //  implicitly converted to type T, where the converted
6013   //  expression is a constant expression and the implicit conversion
6014   //  sequence contains only [... list of conversions ...].
6015   ImplicitConversionSequence ICS =
6016       (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept)
6017           ? TryContextuallyConvertToBool(S, From)
6018           : TryCopyInitialization(S, From, T,
6019                                   /*SuppressUserConversions=*/false,
6020                                   /*InOverloadResolution=*/false,
6021                                   /*AllowObjCWritebackConversion=*/false,
6022                                   /*AllowExplicit=*/false);
6023   StandardConversionSequence *SCS = nullptr;
6024   switch (ICS.getKind()) {
6025   case ImplicitConversionSequence::StandardConversion:
6026     SCS = &ICS.Standard;
6027     break;
6028   case ImplicitConversionSequence::UserDefinedConversion:
6029     if (T->isRecordType())
6030       SCS = &ICS.UserDefined.Before;
6031     else
6032       SCS = &ICS.UserDefined.After;
6033     break;
6034   case ImplicitConversionSequence::AmbiguousConversion:
6035   case ImplicitConversionSequence::BadConversion:
6036     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
6037       return S.Diag(From->getBeginLoc(),
6038                     diag::err_typecheck_converted_constant_expression)
6039              << From->getType() << From->getSourceRange() << T;
6040     return ExprError();
6041 
6042   case ImplicitConversionSequence::EllipsisConversion:
6043   case ImplicitConversionSequence::StaticObjectArgumentConversion:
6044     llvm_unreachable("bad conversion in converted constant expression");
6045   }
6046 
6047   // Check that we would only use permitted conversions.
6048   if (!CheckConvertedConstantConversions(S, *SCS)) {
6049     return S.Diag(From->getBeginLoc(),
6050                   diag::err_typecheck_converted_constant_expression_disallowed)
6051            << From->getType() << From->getSourceRange() << T;
6052   }
6053   // [...] and where the reference binding (if any) binds directly.
6054   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6055     return S.Diag(From->getBeginLoc(),
6056                   diag::err_typecheck_converted_constant_expression_indirect)
6057            << From->getType() << From->getSourceRange() << T;
6058   }
6059 
6060   // Usually we can simply apply the ImplicitConversionSequence we formed
6061   // earlier, but that's not guaranteed to work when initializing an object of
6062   // class type.
6063   ExprResult Result;
6064   if (T->isRecordType()) {
6065     assert(CCE == Sema::CCEK_TemplateArg &&
6066            "unexpected class type converted constant expr");
6067     Result = S.PerformCopyInitialization(
6068         InitializedEntity::InitializeTemplateParameter(
6069             T, cast<NonTypeTemplateParmDecl>(Dest)),
6070         SourceLocation(), From);
6071   } else {
6072     Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
6073   }
6074   if (Result.isInvalid())
6075     return Result;
6076 
6077   // C++2a [intro.execution]p5:
6078   //   A full-expression is [...] a constant-expression [...]
6079   Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6080                                  /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6081                                  CCE == Sema::CCEKind::CCEK_TemplateArg);
6082   if (Result.isInvalid())
6083     return Result;
6084 
6085   // Check for a narrowing implicit conversion.
6086   bool ReturnPreNarrowingValue = false;
6087   QualType PreNarrowingType;
6088   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
6089                                 PreNarrowingType)) {
6090   case NK_Dependent_Narrowing:
6091     // Implicit conversion to a narrower type, but the expression is
6092     // value-dependent so we can't tell whether it's actually narrowing.
6093   case NK_Variable_Narrowing:
6094     // Implicit conversion to a narrower type, and the value is not a constant
6095     // expression. We'll diagnose this in a moment.
6096   case NK_Not_Narrowing:
6097     break;
6098 
6099   case NK_Constant_Narrowing:
6100     if (CCE == Sema::CCEK_ArrayBound &&
6101         PreNarrowingType->isIntegralOrEnumerationType() &&
6102         PreNarrowingValue.isInt()) {
6103       // Don't diagnose array bound narrowing here; we produce more precise
6104       // errors by allowing the un-narrowed value through.
6105       ReturnPreNarrowingValue = true;
6106       break;
6107     }
6108     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6109         << CCE << /*Constant*/ 1
6110         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6111     break;
6112 
6113   case NK_Type_Narrowing:
6114     // FIXME: It would be better to diagnose that the expression is not a
6115     // constant expression.
6116     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6117         << CCE << /*Constant*/ 0 << From->getType() << T;
6118     break;
6119   }
6120   if (!ReturnPreNarrowingValue)
6121     PreNarrowingValue = {};
6122 
6123   return Result;
6124 }
6125 
6126 /// CheckConvertedConstantExpression - Check that the expression From is a
6127 /// converted constant expression of type T, perform the conversion and produce
6128 /// the converted expression, per C++11 [expr.const]p3.
6129 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
6130                                                    QualType T, APValue &Value,
6131                                                    Sema::CCEKind CCE,
6132                                                    bool RequireInt,
6133                                                    NamedDecl *Dest) {
6134 
6135   APValue PreNarrowingValue;
6136   ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6137                                                        PreNarrowingValue);
6138   if (Result.isInvalid() || Result.get()->isValueDependent()) {
6139     Value = APValue();
6140     return Result;
6141   }
6142   return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6143                                                RequireInt, PreNarrowingValue);
6144 }
6145 
6146 ExprResult Sema::BuildConvertedConstantExpression(Expr *From, QualType T,
6147                                                   CCEKind CCE,
6148                                                   NamedDecl *Dest) {
6149   APValue PreNarrowingValue;
6150   return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6151                                             PreNarrowingValue);
6152 }
6153 
6154 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6155                                                   APValue &Value, CCEKind CCE,
6156                                                   NamedDecl *Dest) {
6157   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6158                                             Dest);
6159 }
6160 
6161 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6162                                                   llvm::APSInt &Value,
6163                                                   CCEKind CCE) {
6164   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6165 
6166   APValue V;
6167   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6168                                               /*Dest=*/nullptr);
6169   if (!R.isInvalid() && !R.get()->isValueDependent())
6170     Value = V.getInt();
6171   return R;
6172 }
6173 
6174 /// EvaluateConvertedConstantExpression - Evaluate an Expression
6175 /// That is a converted constant expression
6176 /// (which was built with BuildConvertedConstantExpression)
6177 ExprResult
6178 Sema::EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value,
6179                                           Sema::CCEKind CCE, bool RequireInt,
6180                                           const APValue &PreNarrowingValue) {
6181 
6182   ExprResult Result = E;
6183   // Check the expression is a constant expression.
6184   SmallVector<PartialDiagnosticAt, 8> Notes;
6185   Expr::EvalResult Eval;
6186   Eval.Diag = &Notes;
6187 
6188   ConstantExprKind Kind;
6189   if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
6190     Kind = ConstantExprKind::ClassTemplateArgument;
6191   else if (CCE == Sema::CCEK_TemplateArg)
6192     Kind = ConstantExprKind::NonClassTemplateArgument;
6193   else
6194     Kind = ConstantExprKind::Normal;
6195 
6196   if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6197       (RequireInt && !Eval.Val.isInt())) {
6198     // The expression can't be folded, so we can't keep it at this position in
6199     // the AST.
6200     Result = ExprError();
6201   } else {
6202     Value = Eval.Val;
6203 
6204     if (Notes.empty()) {
6205       // It's a constant expression.
6206       Expr *E = ConstantExpr::Create(Context, Result.get(), Value);
6207       if (!PreNarrowingValue.isAbsent())
6208         Value = std::move(PreNarrowingValue);
6209       return E;
6210     }
6211   }
6212 
6213   // It's not a constant expression. Produce an appropriate diagnostic.
6214   if (Notes.size() == 1 &&
6215       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6216     Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6217   } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6218                                    diag::note_constexpr_invalid_template_arg) {
6219     Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6220     for (unsigned I = 0; I < Notes.size(); ++I)
6221       Diag(Notes[I].first, Notes[I].second);
6222   } else {
6223     Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6224         << CCE << E->getSourceRange();
6225     for (unsigned I = 0; I < Notes.size(); ++I)
6226       Diag(Notes[I].first, Notes[I].second);
6227   }
6228   return ExprError();
6229 }
6230 
6231 /// dropPointerConversions - If the given standard conversion sequence
6232 /// involves any pointer conversions, remove them.  This may change
6233 /// the result type of the conversion sequence.
6234 static void dropPointerConversion(StandardConversionSequence &SCS) {
6235   if (SCS.Second == ICK_Pointer_Conversion) {
6236     SCS.Second = ICK_Identity;
6237     SCS.Third = ICK_Identity;
6238     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6239   }
6240 }
6241 
6242 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
6243 /// convert the expression From to an Objective-C pointer type.
6244 static ImplicitConversionSequence
6245 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
6246   // Do an implicit conversion to 'id'.
6247   QualType Ty = S.Context.getObjCIdType();
6248   ImplicitConversionSequence ICS
6249     = TryImplicitConversion(S, From, Ty,
6250                             // FIXME: Are these flags correct?
6251                             /*SuppressUserConversions=*/false,
6252                             AllowedExplicit::Conversions,
6253                             /*InOverloadResolution=*/false,
6254                             /*CStyle=*/false,
6255                             /*AllowObjCWritebackConversion=*/false,
6256                             /*AllowObjCConversionOnExplicit=*/true);
6257 
6258   // Strip off any final conversions to 'id'.
6259   switch (ICS.getKind()) {
6260   case ImplicitConversionSequence::BadConversion:
6261   case ImplicitConversionSequence::AmbiguousConversion:
6262   case ImplicitConversionSequence::EllipsisConversion:
6263   case ImplicitConversionSequence::StaticObjectArgumentConversion:
6264     break;
6265 
6266   case ImplicitConversionSequence::UserDefinedConversion:
6267     dropPointerConversion(ICS.UserDefined.After);
6268     break;
6269 
6270   case ImplicitConversionSequence::StandardConversion:
6271     dropPointerConversion(ICS.Standard);
6272     break;
6273   }
6274 
6275   return ICS;
6276 }
6277 
6278 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
6279 /// conversion of the expression From to an Objective-C pointer type.
6280 /// Returns a valid but null ExprResult if no conversion sequence exists.
6281 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
6282   if (checkPlaceholderForOverload(*this, From))
6283     return ExprError();
6284 
6285   QualType Ty = Context.getObjCIdType();
6286   ImplicitConversionSequence ICS =
6287     TryContextuallyConvertToObjCPointer(*this, From);
6288   if (!ICS.isBad())
6289     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
6290   return ExprResult();
6291 }
6292 
6293 static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6294   const Expr *Base = nullptr;
6295   assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6296          "expected a member expression");
6297 
6298   if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6299       M && !M->isImplicitAccess())
6300     Base = M->getBase();
6301   else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6302            M && !M->isImplicitAccess())
6303     Base = M->getBase();
6304 
6305   QualType T = Base ? Base->getType() : S.getCurrentThisType();
6306 
6307   if (T->isPointerType())
6308     T = T->getPointeeType();
6309 
6310   return T;
6311 }
6312 
6313 static Expr *GetExplicitObjectExpr(Sema &S, Expr *Obj,
6314                                    const FunctionDecl *Fun) {
6315   QualType ObjType = Obj->getType();
6316   if (ObjType->isPointerType()) {
6317     ObjType = ObjType->getPointeeType();
6318     Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6319                                 VK_LValue, OK_Ordinary, SourceLocation(),
6320                                 /*CanOverflow=*/false, FPOptionsOverride());
6321   }
6322   if (Obj->Classify(S.getASTContext()).isPRValue()) {
6323     Obj = S.CreateMaterializeTemporaryExpr(
6324         ObjType, Obj,
6325         !Fun->getParamDecl(0)->getType()->isRValueReferenceType());
6326   }
6327   return Obj;
6328 }
6329 
6330 ExprResult Sema::InitializeExplicitObjectArgument(Sema &S, Expr *Obj,
6331                                                   FunctionDecl *Fun) {
6332   Obj = GetExplicitObjectExpr(S, Obj, Fun);
6333   return S.PerformCopyInitialization(
6334       InitializedEntity::InitializeParameter(S.Context, Fun->getParamDecl(0)),
6335       Obj->getExprLoc(), Obj);
6336 }
6337 
6338 static void PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method,
6339                                           Expr *Object, MultiExprArg &Args,
6340                                           SmallVectorImpl<Expr *> &NewArgs) {
6341   assert(Method->isExplicitObjectMemberFunction() &&
6342          "Method is not an explicit member function");
6343   assert(NewArgs.empty() && "NewArgs should be empty");
6344   NewArgs.reserve(Args.size() + 1);
6345   Expr *This = GetExplicitObjectExpr(S, Object, Method);
6346   NewArgs.push_back(This);
6347   NewArgs.append(Args.begin(), Args.end());
6348   Args = NewArgs;
6349 }
6350 
6351 /// Determine whether the provided type is an integral type, or an enumeration
6352 /// type of a permitted flavor.
6353 bool Sema::ICEConvertDiagnoser::match(QualType T) {
6354   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6355                                  : T->isIntegralOrUnscopedEnumerationType();
6356 }
6357 
6358 static ExprResult
6359 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
6360                             Sema::ContextualImplicitConverter &Converter,
6361                             QualType T, UnresolvedSetImpl &ViableConversions) {
6362 
6363   if (Converter.Suppress)
6364     return ExprError();
6365 
6366   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6367   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6368     CXXConversionDecl *Conv =
6369         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6370     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
6371     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6372   }
6373   return From;
6374 }
6375 
6376 static bool
6377 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6378                            Sema::ContextualImplicitConverter &Converter,
6379                            QualType T, bool HadMultipleCandidates,
6380                            UnresolvedSetImpl &ExplicitConversions) {
6381   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6382     DeclAccessPair Found = ExplicitConversions[0];
6383     CXXConversionDecl *Conversion =
6384         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6385 
6386     // The user probably meant to invoke the given explicit
6387     // conversion; use it.
6388     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6389     std::string TypeStr;
6390     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6391 
6392     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6393         << FixItHint::CreateInsertion(From->getBeginLoc(),
6394                                       "static_cast<" + TypeStr + ">(")
6395         << FixItHint::CreateInsertion(
6396                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6397     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6398 
6399     // If we aren't in a SFINAE context, build a call to the
6400     // explicit conversion function.
6401     if (SemaRef.isSFINAEContext())
6402       return true;
6403 
6404     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6405     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6406                                                        HadMultipleCandidates);
6407     if (Result.isInvalid())
6408       return true;
6409     // Record usage of conversion in an implicit cast.
6410     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6411                                     CK_UserDefinedConversion, Result.get(),
6412                                     nullptr, Result.get()->getValueKind(),
6413                                     SemaRef.CurFPFeatureOverrides());
6414   }
6415   return false;
6416 }
6417 
6418 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6419                              Sema::ContextualImplicitConverter &Converter,
6420                              QualType T, bool HadMultipleCandidates,
6421                              DeclAccessPair &Found) {
6422   CXXConversionDecl *Conversion =
6423       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6424   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6425 
6426   QualType ToType = Conversion->getConversionType().getNonReferenceType();
6427   if (!Converter.SuppressConversion) {
6428     if (SemaRef.isSFINAEContext())
6429       return true;
6430 
6431     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6432         << From->getSourceRange();
6433   }
6434 
6435   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6436                                                      HadMultipleCandidates);
6437   if (Result.isInvalid())
6438     return true;
6439   // Record usage of conversion in an implicit cast.
6440   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6441                                   CK_UserDefinedConversion, Result.get(),
6442                                   nullptr, Result.get()->getValueKind(),
6443                                   SemaRef.CurFPFeatureOverrides());
6444   return false;
6445 }
6446 
6447 static ExprResult finishContextualImplicitConversion(
6448     Sema &SemaRef, SourceLocation Loc, Expr *From,
6449     Sema::ContextualImplicitConverter &Converter) {
6450   if (!Converter.match(From->getType()) && !Converter.Suppress)
6451     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6452         << From->getSourceRange();
6453 
6454   return SemaRef.DefaultLvalueConversion(From);
6455 }
6456 
6457 static void
6458 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
6459                                   UnresolvedSetImpl &ViableConversions,
6460                                   OverloadCandidateSet &CandidateSet) {
6461   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6462     DeclAccessPair FoundDecl = ViableConversions[I];
6463     NamedDecl *D = FoundDecl.getDecl();
6464     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6465     if (isa<UsingShadowDecl>(D))
6466       D = cast<UsingShadowDecl>(D)->getTargetDecl();
6467 
6468     CXXConversionDecl *Conv;
6469     FunctionTemplateDecl *ConvTemplate;
6470     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
6471       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6472     else
6473       Conv = cast<CXXConversionDecl>(D);
6474 
6475     if (ConvTemplate)
6476       SemaRef.AddTemplateConversionCandidate(
6477           ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6478           /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
6479     else
6480       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
6481                                      ToType, CandidateSet,
6482                                      /*AllowObjCConversionOnExplicit=*/false,
6483                                      /*AllowExplicit*/ true);
6484   }
6485 }
6486 
6487 /// Attempt to convert the given expression to a type which is accepted
6488 /// by the given converter.
6489 ///
6490 /// This routine will attempt to convert an expression of class type to a
6491 /// type accepted by the specified converter. In C++11 and before, the class
6492 /// must have a single non-explicit conversion function converting to a matching
6493 /// type. In C++1y, there can be multiple such conversion functions, but only
6494 /// one target type.
6495 ///
6496 /// \param Loc The source location of the construct that requires the
6497 /// conversion.
6498 ///
6499 /// \param From The expression we're converting from.
6500 ///
6501 /// \param Converter Used to control and diagnose the conversion process.
6502 ///
6503 /// \returns The expression, converted to an integral or enumeration type if
6504 /// successful.
6505 ExprResult Sema::PerformContextualImplicitConversion(
6506     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6507   // We can't perform any more checking for type-dependent expressions.
6508   if (From->isTypeDependent())
6509     return From;
6510 
6511   // Process placeholders immediately.
6512   if (From->hasPlaceholderType()) {
6513     ExprResult result = CheckPlaceholderExpr(From);
6514     if (result.isInvalid())
6515       return result;
6516     From = result.get();
6517   }
6518 
6519   // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6520   ExprResult Converted = DefaultLvalueConversion(From);
6521   QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
6522   // If the expression already has a matching type, we're golden.
6523   if (Converter.match(T))
6524     return Converted;
6525 
6526   // FIXME: Check for missing '()' if T is a function type?
6527 
6528   // We can only perform contextual implicit conversions on objects of class
6529   // type.
6530   const RecordType *RecordTy = T->getAs<RecordType>();
6531   if (!RecordTy || !getLangOpts().CPlusPlus) {
6532     if (!Converter.Suppress)
6533       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6534     return From;
6535   }
6536 
6537   // We must have a complete class type.
6538   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6539     ContextualImplicitConverter &Converter;
6540     Expr *From;
6541 
6542     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6543         : Converter(Converter), From(From) {}
6544 
6545     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6546       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6547     }
6548   } IncompleteDiagnoser(Converter, From);
6549 
6550   if (Converter.Suppress ? !isCompleteType(Loc, T)
6551                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6552     return From;
6553 
6554   // Look for a conversion to an integral or enumeration type.
6555   UnresolvedSet<4>
6556       ViableConversions; // These are *potentially* viable in C++1y.
6557   UnresolvedSet<4> ExplicitConversions;
6558   const auto &Conversions =
6559       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
6560 
6561   bool HadMultipleCandidates =
6562       (std::distance(Conversions.begin(), Conversions.end()) > 1);
6563 
6564   // To check that there is only one target type, in C++1y:
6565   QualType ToType;
6566   bool HasUniqueTargetType = true;
6567 
6568   // Collect explicit or viable (potentially in C++1y) conversions.
6569   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6570     NamedDecl *D = (*I)->getUnderlyingDecl();
6571     CXXConversionDecl *Conversion;
6572     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6573     if (ConvTemplate) {
6574       if (getLangOpts().CPlusPlus14)
6575         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6576       else
6577         continue; // C++11 does not consider conversion operator templates(?).
6578     } else
6579       Conversion = cast<CXXConversionDecl>(D);
6580 
6581     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6582            "Conversion operator templates are considered potentially "
6583            "viable in C++1y");
6584 
6585     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6586     if (Converter.match(CurToType) || ConvTemplate) {
6587 
6588       if (Conversion->isExplicit()) {
6589         // FIXME: For C++1y, do we need this restriction?
6590         // cf. diagnoseNoViableConversion()
6591         if (!ConvTemplate)
6592           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6593       } else {
6594         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6595           if (ToType.isNull())
6596             ToType = CurToType.getUnqualifiedType();
6597           else if (HasUniqueTargetType &&
6598                    (CurToType.getUnqualifiedType() != ToType))
6599             HasUniqueTargetType = false;
6600         }
6601         ViableConversions.addDecl(I.getDecl(), I.getAccess());
6602       }
6603     }
6604   }
6605 
6606   if (getLangOpts().CPlusPlus14) {
6607     // C++1y [conv]p6:
6608     // ... An expression e of class type E appearing in such a context
6609     // is said to be contextually implicitly converted to a specified
6610     // type T and is well-formed if and only if e can be implicitly
6611     // converted to a type T that is determined as follows: E is searched
6612     // for conversion functions whose return type is cv T or reference to
6613     // cv T such that T is allowed by the context. There shall be
6614     // exactly one such T.
6615 
6616     // If no unique T is found:
6617     if (ToType.isNull()) {
6618       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6619                                      HadMultipleCandidates,
6620                                      ExplicitConversions))
6621         return ExprError();
6622       return finishContextualImplicitConversion(*this, Loc, From, Converter);
6623     }
6624 
6625     // If more than one unique Ts are found:
6626     if (!HasUniqueTargetType)
6627       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6628                                          ViableConversions);
6629 
6630     // If one unique T is found:
6631     // First, build a candidate set from the previously recorded
6632     // potentially viable conversions.
6633     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6634     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6635                                       CandidateSet);
6636 
6637     // Then, perform overload resolution over the candidate set.
6638     OverloadCandidateSet::iterator Best;
6639     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6640     case OR_Success: {
6641       // Apply this conversion.
6642       DeclAccessPair Found =
6643           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6644       if (recordConversion(*this, Loc, From, Converter, T,
6645                            HadMultipleCandidates, Found))
6646         return ExprError();
6647       break;
6648     }
6649     case OR_Ambiguous:
6650       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6651                                          ViableConversions);
6652     case OR_No_Viable_Function:
6653       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6654                                      HadMultipleCandidates,
6655                                      ExplicitConversions))
6656         return ExprError();
6657       [[fallthrough]];
6658     case OR_Deleted:
6659       // We'll complain below about a non-integral condition type.
6660       break;
6661     }
6662   } else {
6663     switch (ViableConversions.size()) {
6664     case 0: {
6665       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6666                                      HadMultipleCandidates,
6667                                      ExplicitConversions))
6668         return ExprError();
6669 
6670       // We'll complain below about a non-integral condition type.
6671       break;
6672     }
6673     case 1: {
6674       // Apply this conversion.
6675       DeclAccessPair Found = ViableConversions[0];
6676       if (recordConversion(*this, Loc, From, Converter, T,
6677                            HadMultipleCandidates, Found))
6678         return ExprError();
6679       break;
6680     }
6681     default:
6682       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6683                                          ViableConversions);
6684     }
6685   }
6686 
6687   return finishContextualImplicitConversion(*this, Loc, From, Converter);
6688 }
6689 
6690 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6691 /// an acceptable non-member overloaded operator for a call whose
6692 /// arguments have types T1 (and, if non-empty, T2). This routine
6693 /// implements the check in C++ [over.match.oper]p3b2 concerning
6694 /// enumeration types.
6695 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6696                                                    FunctionDecl *Fn,
6697                                                    ArrayRef<Expr *> Args) {
6698   QualType T1 = Args[0]->getType();
6699   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6700 
6701   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6702     return true;
6703 
6704   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6705     return true;
6706 
6707   const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6708   if (Proto->getNumParams() < 1)
6709     return false;
6710 
6711   if (T1->isEnumeralType()) {
6712     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6713     if (Context.hasSameUnqualifiedType(T1, ArgType))
6714       return true;
6715   }
6716 
6717   if (Proto->getNumParams() < 2)
6718     return false;
6719 
6720   if (!T2.isNull() && T2->isEnumeralType()) {
6721     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6722     if (Context.hasSameUnqualifiedType(T2, ArgType))
6723       return true;
6724   }
6725 
6726   return false;
6727 }
6728 
6729 /// AddOverloadCandidate - Adds the given function to the set of
6730 /// candidate functions, using the given function call arguments.  If
6731 /// @p SuppressUserConversions, then don't allow user-defined
6732 /// conversions via constructors or conversion operators.
6733 ///
6734 /// \param PartialOverloading true if we are performing "partial" overloading
6735 /// based on an incomplete set of function arguments. This feature is used by
6736 /// code completion.
6737 void Sema::AddOverloadCandidate(
6738     FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6739     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6740     bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6741     ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6742     OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
6743   const FunctionProtoType *Proto
6744     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6745   assert(Proto && "Functions without a prototype cannot be overloaded");
6746   assert(!Function->getDescribedFunctionTemplate() &&
6747          "Use AddTemplateOverloadCandidate for function templates");
6748 
6749   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6750     if (!isa<CXXConstructorDecl>(Method)) {
6751       // If we get here, it's because we're calling a member function
6752       // that is named without a member access expression (e.g.,
6753       // "this->f") that was either written explicitly or created
6754       // implicitly. This can happen with a qualified call to a member
6755       // function, e.g., X::f(). We use an empty type for the implied
6756       // object argument (C++ [over.call.func]p3), and the acting context
6757       // is irrelevant.
6758       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6759                          Expr::Classification::makeSimpleLValue(), Args,
6760                          CandidateSet, SuppressUserConversions,
6761                          PartialOverloading, EarlyConversions, PO);
6762       return;
6763     }
6764     // We treat a constructor like a non-member function, since its object
6765     // argument doesn't participate in overload resolution.
6766   }
6767 
6768   if (!CandidateSet.isNewCandidate(Function, PO))
6769     return;
6770 
6771   // C++11 [class.copy]p11: [DR1402]
6772   //   A defaulted move constructor that is defined as deleted is ignored by
6773   //   overload resolution.
6774   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6775   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6776       Constructor->isMoveConstructor())
6777     return;
6778 
6779   // Overload resolution is always an unevaluated context.
6780   EnterExpressionEvaluationContext Unevaluated(
6781       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6782 
6783   // C++ [over.match.oper]p3:
6784   //   if no operand has a class type, only those non-member functions in the
6785   //   lookup set that have a first parameter of type T1 or "reference to
6786   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6787   //   is a right operand) a second parameter of type T2 or "reference to
6788   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
6789   //   candidate functions.
6790   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6791       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6792     return;
6793 
6794   // Add this candidate
6795   OverloadCandidate &Candidate =
6796       CandidateSet.addCandidate(Args.size(), EarlyConversions);
6797   Candidate.FoundDecl = FoundDecl;
6798   Candidate.Function = Function;
6799   Candidate.Viable = true;
6800   Candidate.RewriteKind =
6801       CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6802   Candidate.IsSurrogate = false;
6803   Candidate.IsADLCandidate = IsADLCandidate;
6804   Candidate.IgnoreObjectArgument = false;
6805   Candidate.ExplicitCallArguments = Args.size();
6806 
6807   // Explicit functions are not actually candidates at all if we're not
6808   // allowing them in this context, but keep them around so we can point
6809   // to them in diagnostics.
6810   if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6811     Candidate.Viable = false;
6812     Candidate.FailureKind = ovl_fail_explicit;
6813     return;
6814   }
6815 
6816   // Functions with internal linkage are only viable in the same module unit.
6817   if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
6818     /// FIXME: Currently, the semantics of linkage in clang is slightly
6819     /// different from the semantics in C++ spec. In C++ spec, only names
6820     /// have linkage. So that all entities of the same should share one
6821     /// linkage. But in clang, different entities of the same could have
6822     /// different linkage.
6823     NamedDecl *ND = Function;
6824     if (auto *SpecInfo = Function->getTemplateSpecializationInfo())
6825       ND = SpecInfo->getTemplate();
6826 
6827     if (ND->getFormalLinkage() == Linkage::Internal) {
6828       Candidate.Viable = false;
6829       Candidate.FailureKind = ovl_fail_module_mismatched;
6830       return;
6831     }
6832   }
6833 
6834   if (Function->isMultiVersion() &&
6835       ((Function->hasAttr<TargetAttr>() &&
6836         !Function->getAttr<TargetAttr>()->isDefaultVersion()) ||
6837        (Function->hasAttr<TargetVersionAttr>() &&
6838         !Function->getAttr<TargetVersionAttr>()->isDefaultVersion()))) {
6839     Candidate.Viable = false;
6840     Candidate.FailureKind = ovl_non_default_multiversion_function;
6841     return;
6842   }
6843 
6844   if (Constructor) {
6845     // C++ [class.copy]p3:
6846     //   A member function template is never instantiated to perform the copy
6847     //   of a class object to an object of its class type.
6848     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6849     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6850         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6851          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6852                        ClassType))) {
6853       Candidate.Viable = false;
6854       Candidate.FailureKind = ovl_fail_illegal_constructor;
6855       return;
6856     }
6857 
6858     // C++ [over.match.funcs]p8: (proposed DR resolution)
6859     //   A constructor inherited from class type C that has a first parameter
6860     //   of type "reference to P" (including such a constructor instantiated
6861     //   from a template) is excluded from the set of candidate functions when
6862     //   constructing an object of type cv D if the argument list has exactly
6863     //   one argument and D is reference-related to P and P is reference-related
6864     //   to C.
6865     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6866     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6867         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6868       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6869       QualType C = Context.getRecordType(Constructor->getParent());
6870       QualType D = Context.getRecordType(Shadow->getParent());
6871       SourceLocation Loc = Args.front()->getExprLoc();
6872       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6873           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6874         Candidate.Viable = false;
6875         Candidate.FailureKind = ovl_fail_inhctor_slice;
6876         return;
6877       }
6878     }
6879 
6880     // Check that the constructor is capable of constructing an object in the
6881     // destination address space.
6882     if (!Qualifiers::isAddressSpaceSupersetOf(
6883             Constructor->getMethodQualifiers().getAddressSpace(),
6884             CandidateSet.getDestAS())) {
6885       Candidate.Viable = false;
6886       Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6887     }
6888   }
6889 
6890   unsigned NumParams = Proto->getNumParams();
6891 
6892   // (C++ 13.3.2p2): A candidate function having fewer than m
6893   // parameters is viable only if it has an ellipsis in its parameter
6894   // list (8.3.5).
6895   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6896       !Proto->isVariadic() &&
6897       shouldEnforceArgLimit(PartialOverloading, Function)) {
6898     Candidate.Viable = false;
6899     Candidate.FailureKind = ovl_fail_too_many_arguments;
6900     return;
6901   }
6902 
6903   // (C++ 13.3.2p2): A candidate function having more than m parameters
6904   // is viable only if the (m+1)st parameter has a default argument
6905   // (8.3.6). For the purposes of overload resolution, the
6906   // parameter list is truncated on the right, so that there are
6907   // exactly m parameters.
6908   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6909   if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
6910       !PartialOverloading) {
6911     // Not enough arguments.
6912     Candidate.Viable = false;
6913     Candidate.FailureKind = ovl_fail_too_few_arguments;
6914     return;
6915   }
6916 
6917   // (CUDA B.1): Check for invalid calls between targets.
6918   if (getLangOpts().CUDA) {
6919     const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
6920     // Skip the check for callers that are implicit members, because in this
6921     // case we may not yet know what the member's target is; the target is
6922     // inferred for the member automatically, based on the bases and fields of
6923     // the class.
6924     if (!(Caller && Caller->isImplicit()) &&
6925         !IsAllowedCUDACall(Caller, Function)) {
6926       Candidate.Viable = false;
6927       Candidate.FailureKind = ovl_fail_bad_target;
6928       return;
6929     }
6930   }
6931 
6932   if (Function->getTrailingRequiresClause()) {
6933     ConstraintSatisfaction Satisfaction;
6934     if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
6935                                  /*ForOverloadResolution*/ true) ||
6936         !Satisfaction.IsSatisfied) {
6937       Candidate.Viable = false;
6938       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6939       return;
6940     }
6941   }
6942 
6943   // Determine the implicit conversion sequences for each of the
6944   // arguments.
6945   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6946     unsigned ConvIdx =
6947         PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6948     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6949       // We already formed a conversion sequence for this parameter during
6950       // template argument deduction.
6951     } else if (ArgIdx < NumParams) {
6952       // (C++ 13.3.2p3): for F to be a viable function, there shall
6953       // exist for each argument an implicit conversion sequence
6954       // (13.3.3.1) that converts that argument to the corresponding
6955       // parameter of F.
6956       QualType ParamType = Proto->getParamType(ArgIdx);
6957       Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6958           *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6959           /*InOverloadResolution=*/true,
6960           /*AllowObjCWritebackConversion=*/
6961           getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6962       if (Candidate.Conversions[ConvIdx].isBad()) {
6963         Candidate.Viable = false;
6964         Candidate.FailureKind = ovl_fail_bad_conversion;
6965         return;
6966       }
6967     } else {
6968       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6969       // argument for which there is no corresponding parameter is
6970       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6971       Candidate.Conversions[ConvIdx].setEllipsis();
6972     }
6973   }
6974 
6975   if (EnableIfAttr *FailedAttr =
6976           CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
6977     Candidate.Viable = false;
6978     Candidate.FailureKind = ovl_fail_enable_if;
6979     Candidate.DeductionFailure.Data = FailedAttr;
6980     return;
6981   }
6982 }
6983 
6984 ObjCMethodDecl *
6985 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6986                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6987   if (Methods.size() <= 1)
6988     return nullptr;
6989 
6990   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6991     bool Match = true;
6992     ObjCMethodDecl *Method = Methods[b];
6993     unsigned NumNamedArgs = Sel.getNumArgs();
6994     // Method might have more arguments than selector indicates. This is due
6995     // to addition of c-style arguments in method.
6996     if (Method->param_size() > NumNamedArgs)
6997       NumNamedArgs = Method->param_size();
6998     if (Args.size() < NumNamedArgs)
6999       continue;
7000 
7001     for (unsigned i = 0; i < NumNamedArgs; i++) {
7002       // We can't do any type-checking on a type-dependent argument.
7003       if (Args[i]->isTypeDependent()) {
7004         Match = false;
7005         break;
7006       }
7007 
7008       ParmVarDecl *param = Method->parameters()[i];
7009       Expr *argExpr = Args[i];
7010       assert(argExpr && "SelectBestMethod(): missing expression");
7011 
7012       // Strip the unbridged-cast placeholder expression off unless it's
7013       // a consumed argument.
7014       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7015           !param->hasAttr<CFConsumedAttr>())
7016         argExpr = stripARCUnbridgedCast(argExpr);
7017 
7018       // If the parameter is __unknown_anytype, move on to the next method.
7019       if (param->getType() == Context.UnknownAnyTy) {
7020         Match = false;
7021         break;
7022       }
7023 
7024       ImplicitConversionSequence ConversionState
7025         = TryCopyInitialization(*this, argExpr, param->getType(),
7026                                 /*SuppressUserConversions*/false,
7027                                 /*InOverloadResolution=*/true,
7028                                 /*AllowObjCWritebackConversion=*/
7029                                 getLangOpts().ObjCAutoRefCount,
7030                                 /*AllowExplicit*/false);
7031       // This function looks for a reasonably-exact match, so we consider
7032       // incompatible pointer conversions to be a failure here.
7033       if (ConversionState.isBad() ||
7034           (ConversionState.isStandard() &&
7035            ConversionState.Standard.Second ==
7036                ICK_Incompatible_Pointer_Conversion)) {
7037         Match = false;
7038         break;
7039       }
7040     }
7041     // Promote additional arguments to variadic methods.
7042     if (Match && Method->isVariadic()) {
7043       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7044         if (Args[i]->isTypeDependent()) {
7045           Match = false;
7046           break;
7047         }
7048         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
7049                                                           nullptr);
7050         if (Arg.isInvalid()) {
7051           Match = false;
7052           break;
7053         }
7054       }
7055     } else {
7056       // Check for extra arguments to non-variadic methods.
7057       if (Args.size() != NumNamedArgs)
7058         Match = false;
7059       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7060         // Special case when selectors have no argument. In this case, select
7061         // one with the most general result type of 'id'.
7062         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7063           QualType ReturnT = Methods[b]->getReturnType();
7064           if (ReturnT->isObjCIdType())
7065             return Methods[b];
7066         }
7067       }
7068     }
7069 
7070     if (Match)
7071       return Method;
7072   }
7073   return nullptr;
7074 }
7075 
7076 static bool convertArgsForAvailabilityChecks(
7077     Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7078     ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7079     Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7080   if (ThisArg) {
7081     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7082     assert(!isa<CXXConstructorDecl>(Method) &&
7083            "Shouldn't have `this` for ctors!");
7084     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7085     ExprResult R = S.PerformImplicitObjectArgumentInitialization(
7086         ThisArg, /*Qualifier=*/nullptr, Method, Method);
7087     if (R.isInvalid())
7088       return false;
7089     ConvertedThis = R.get();
7090   } else {
7091     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7092       (void)MD;
7093       assert((MissingImplicitThis || MD->isStatic() ||
7094               isa<CXXConstructorDecl>(MD)) &&
7095              "Expected `this` for non-ctor instance methods");
7096     }
7097     ConvertedThis = nullptr;
7098   }
7099 
7100   // Ignore any variadic arguments. Converting them is pointless, since the
7101   // user can't refer to them in the function condition.
7102   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7103 
7104   // Convert the arguments.
7105   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7106     ExprResult R;
7107     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
7108                                         S.Context, Function->getParamDecl(I)),
7109                                     SourceLocation(), Args[I]);
7110 
7111     if (R.isInvalid())
7112       return false;
7113 
7114     ConvertedArgs.push_back(R.get());
7115   }
7116 
7117   if (Trap.hasErrorOccurred())
7118     return false;
7119 
7120   // Push default arguments if needed.
7121   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7122     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7123       ParmVarDecl *P = Function->getParamDecl(i);
7124       if (!P->hasDefaultArg())
7125         return false;
7126       ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
7127       if (R.isInvalid())
7128         return false;
7129       ConvertedArgs.push_back(R.get());
7130     }
7131 
7132     if (Trap.hasErrorOccurred())
7133       return false;
7134   }
7135   return true;
7136 }
7137 
7138 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
7139                                   SourceLocation CallLoc,
7140                                   ArrayRef<Expr *> Args,
7141                                   bool MissingImplicitThis) {
7142   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7143   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7144     return nullptr;
7145 
7146   SFINAETrap Trap(*this);
7147   SmallVector<Expr *, 16> ConvertedArgs;
7148   // FIXME: We should look into making enable_if late-parsed.
7149   Expr *DiscardedThis;
7150   if (!convertArgsForAvailabilityChecks(
7151           *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7152           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7153     return *EnableIfAttrs.begin();
7154 
7155   for (auto *EIA : EnableIfAttrs) {
7156     APValue Result;
7157     // FIXME: This doesn't consider value-dependent cases, because doing so is
7158     // very difficult. Ideally, we should handle them more gracefully.
7159     if (EIA->getCond()->isValueDependent() ||
7160         !EIA->getCond()->EvaluateWithSubstitution(
7161             Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7162       return EIA;
7163 
7164     if (!Result.isInt() || !Result.getInt().getBoolValue())
7165       return EIA;
7166   }
7167   return nullptr;
7168 }
7169 
7170 template <typename CheckFn>
7171 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
7172                                         bool ArgDependent, SourceLocation Loc,
7173                                         CheckFn &&IsSuccessful) {
7174   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
7175   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7176     if (ArgDependent == DIA->getArgDependent())
7177       Attrs.push_back(DIA);
7178   }
7179 
7180   // Common case: No diagnose_if attributes, so we can quit early.
7181   if (Attrs.empty())
7182     return false;
7183 
7184   auto WarningBegin = std::stable_partition(
7185       Attrs.begin(), Attrs.end(),
7186       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
7187 
7188   // Note that diagnose_if attributes are late-parsed, so they appear in the
7189   // correct order (unlike enable_if attributes).
7190   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7191                                IsSuccessful);
7192   if (ErrAttr != WarningBegin) {
7193     const DiagnoseIfAttr *DIA = *ErrAttr;
7194     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7195     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7196         << DIA->getParent() << DIA->getCond()->getSourceRange();
7197     return true;
7198   }
7199 
7200   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7201     if (IsSuccessful(DIA)) {
7202       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7203       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7204           << DIA->getParent() << DIA->getCond()->getSourceRange();
7205     }
7206 
7207   return false;
7208 }
7209 
7210 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
7211                                                const Expr *ThisArg,
7212                                                ArrayRef<const Expr *> Args,
7213                                                SourceLocation Loc) {
7214   return diagnoseDiagnoseIfAttrsWith(
7215       *this, Function, /*ArgDependent=*/true, Loc,
7216       [&](const DiagnoseIfAttr *DIA) {
7217         APValue Result;
7218         // It's sane to use the same Args for any redecl of this function, since
7219         // EvaluateWithSubstitution only cares about the position of each
7220         // argument in the arg list, not the ParmVarDecl* it maps to.
7221         if (!DIA->getCond()->EvaluateWithSubstitution(
7222                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7223           return false;
7224         return Result.isInt() && Result.getInt().getBoolValue();
7225       });
7226 }
7227 
7228 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
7229                                                  SourceLocation Loc) {
7230   return diagnoseDiagnoseIfAttrsWith(
7231       *this, ND, /*ArgDependent=*/false, Loc,
7232       [&](const DiagnoseIfAttr *DIA) {
7233         bool Result;
7234         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7235                Result;
7236       });
7237 }
7238 
7239 /// Add all of the function declarations in the given function set to
7240 /// the overload candidate set.
7241 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
7242                                  ArrayRef<Expr *> Args,
7243                                  OverloadCandidateSet &CandidateSet,
7244                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
7245                                  bool SuppressUserConversions,
7246                                  bool PartialOverloading,
7247                                  bool FirstArgumentIsBase) {
7248   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7249     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7250     ArrayRef<Expr *> FunctionArgs = Args;
7251 
7252     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7253     FunctionDecl *FD =
7254         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7255 
7256     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7257       QualType ObjectType;
7258       Expr::Classification ObjectClassification;
7259       if (Args.size() > 0) {
7260         if (Expr *E = Args[0]) {
7261           // Use the explicit base to restrict the lookup:
7262           ObjectType = E->getType();
7263           // Pointers in the object arguments are implicitly dereferenced, so we
7264           // always classify them as l-values.
7265           if (!ObjectType.isNull() && ObjectType->isPointerType())
7266             ObjectClassification = Expr::Classification::makeSimpleLValue();
7267           else
7268             ObjectClassification = E->Classify(Context);
7269         } // .. else there is an implicit base.
7270         FunctionArgs = Args.slice(1);
7271       }
7272       if (FunTmpl) {
7273         AddMethodTemplateCandidate(
7274             FunTmpl, F.getPair(),
7275             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
7276             ExplicitTemplateArgs, ObjectType, ObjectClassification,
7277             FunctionArgs, CandidateSet, SuppressUserConversions,
7278             PartialOverloading);
7279       } else {
7280         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7281                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7282                            ObjectClassification, FunctionArgs, CandidateSet,
7283                            SuppressUserConversions, PartialOverloading);
7284       }
7285     } else {
7286       // This branch handles both standalone functions and static methods.
7287 
7288       // Slice the first argument (which is the base) when we access
7289       // static method as non-static.
7290       if (Args.size() > 0 &&
7291           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7292                         !isa<CXXConstructorDecl>(FD)))) {
7293         assert(cast<CXXMethodDecl>(FD)->isStatic());
7294         FunctionArgs = Args.slice(1);
7295       }
7296       if (FunTmpl) {
7297         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7298                                      ExplicitTemplateArgs, FunctionArgs,
7299                                      CandidateSet, SuppressUserConversions,
7300                                      PartialOverloading);
7301       } else {
7302         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7303                              SuppressUserConversions, PartialOverloading);
7304       }
7305     }
7306   }
7307 }
7308 
7309 /// AddMethodCandidate - Adds a named decl (which is some kind of
7310 /// method) as a method candidate to the given overload set.
7311 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
7312                               Expr::Classification ObjectClassification,
7313                               ArrayRef<Expr *> Args,
7314                               OverloadCandidateSet &CandidateSet,
7315                               bool SuppressUserConversions,
7316                               OverloadCandidateParamOrder PO) {
7317   NamedDecl *Decl = FoundDecl.getDecl();
7318   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
7319 
7320   if (isa<UsingShadowDecl>(Decl))
7321     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7322 
7323   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7324     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7325            "Expected a member function template");
7326     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7327                                /*ExplicitArgs*/ nullptr, ObjectType,
7328                                ObjectClassification, Args, CandidateSet,
7329                                SuppressUserConversions, false, PO);
7330   } else {
7331     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7332                        ObjectType, ObjectClassification, Args, CandidateSet,
7333                        SuppressUserConversions, false, std::nullopt, PO);
7334   }
7335 }
7336 
7337 /// AddMethodCandidate - Adds the given C++ member function to the set
7338 /// of candidate functions, using the given function call arguments
7339 /// and the object argument (@c Object). For example, in a call
7340 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
7341 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
7342 /// allow user-defined conversions via constructors or conversion
7343 /// operators.
7344 void
7345 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
7346                          CXXRecordDecl *ActingContext, QualType ObjectType,
7347                          Expr::Classification ObjectClassification,
7348                          ArrayRef<Expr *> Args,
7349                          OverloadCandidateSet &CandidateSet,
7350                          bool SuppressUserConversions,
7351                          bool PartialOverloading,
7352                          ConversionSequenceList EarlyConversions,
7353                          OverloadCandidateParamOrder PO) {
7354   const FunctionProtoType *Proto
7355     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7356   assert(Proto && "Methods without a prototype cannot be overloaded");
7357   assert(!isa<CXXConstructorDecl>(Method) &&
7358          "Use AddOverloadCandidate for constructors");
7359 
7360   if (!CandidateSet.isNewCandidate(Method, PO))
7361     return;
7362 
7363   // C++11 [class.copy]p23: [DR1402]
7364   //   A defaulted move assignment operator that is defined as deleted is
7365   //   ignored by overload resolution.
7366   if (Method->isDefaulted() && Method->isDeleted() &&
7367       Method->isMoveAssignmentOperator())
7368     return;
7369 
7370   // Overload resolution is always an unevaluated context.
7371   EnterExpressionEvaluationContext Unevaluated(
7372       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7373 
7374   // Add this candidate
7375   OverloadCandidate &Candidate =
7376       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
7377   Candidate.FoundDecl = FoundDecl;
7378   Candidate.Function = Method;
7379   Candidate.RewriteKind =
7380       CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7381   Candidate.IsSurrogate = false;
7382   Candidate.IgnoreObjectArgument = false;
7383   Candidate.ExplicitCallArguments = Args.size();
7384 
7385   unsigned NumParams = Method->getNumExplicitParams();
7386   unsigned ExplicitOffset = Method->isExplicitObjectMemberFunction() ? 1 : 0;
7387 
7388   // (C++ 13.3.2p2): A candidate function having fewer than m
7389   // parameters is viable only if it has an ellipsis in its parameter
7390   // list (8.3.5).
7391   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7392       !Proto->isVariadic() &&
7393       shouldEnforceArgLimit(PartialOverloading, Method)) {
7394     Candidate.Viable = false;
7395     Candidate.FailureKind = ovl_fail_too_many_arguments;
7396     return;
7397   }
7398 
7399   // (C++ 13.3.2p2): A candidate function having more than m parameters
7400   // is viable only if the (m+1)st parameter has a default argument
7401   // (8.3.6). For the purposes of overload resolution, the
7402   // parameter list is truncated on the right, so that there are
7403   // exactly m parameters.
7404   unsigned MinRequiredArgs = Method->getMinRequiredExplicitArguments();
7405   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7406     // Not enough arguments.
7407     Candidate.Viable = false;
7408     Candidate.FailureKind = ovl_fail_too_few_arguments;
7409     return;
7410   }
7411 
7412   Candidate.Viable = true;
7413 
7414   unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7415   if (ObjectType.isNull())
7416     Candidate.IgnoreObjectArgument = true;
7417   else if (Method->isStatic()) {
7418     // [over.best.ics.general]p8
7419     // When the parameter is the implicit object parameter of a static member
7420     // function, the implicit conversion sequence is a standard conversion
7421     // sequence that is neither better nor worse than any other standard
7422     // conversion sequence.
7423     //
7424     // This is a rule that was introduced in C++23 to support static lambdas. We
7425     // apply it retroactively because we want to support static lambdas as an
7426     // extension and it doesn't hurt previous code.
7427     Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7428   } else {
7429     // Determine the implicit conversion sequence for the object
7430     // parameter.
7431     Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7432         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7433         Method, ActingContext, /*InOverloadResolution=*/true);
7434     if (Candidate.Conversions[FirstConvIdx].isBad()) {
7435       Candidate.Viable = false;
7436       Candidate.FailureKind = ovl_fail_bad_conversion;
7437       return;
7438     }
7439   }
7440 
7441   // (CUDA B.1): Check for invalid calls between targets.
7442   if (getLangOpts().CUDA)
7443     if (!IsAllowedCUDACall(getCurFunctionDecl(/*AllowLambda=*/true), Method)) {
7444       Candidate.Viable = false;
7445       Candidate.FailureKind = ovl_fail_bad_target;
7446       return;
7447     }
7448 
7449   if (Method->getTrailingRequiresClause()) {
7450     ConstraintSatisfaction Satisfaction;
7451     if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
7452                                  /*ForOverloadResolution*/ true) ||
7453         !Satisfaction.IsSatisfied) {
7454       Candidate.Viable = false;
7455       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7456       return;
7457     }
7458   }
7459 
7460   // Determine the implicit conversion sequences for each of the
7461   // arguments.
7462   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7463     unsigned ConvIdx =
7464         PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
7465     if (Candidate.Conversions[ConvIdx].isInitialized()) {
7466       // We already formed a conversion sequence for this parameter during
7467       // template argument deduction.
7468     } else if (ArgIdx < NumParams) {
7469       // (C++ 13.3.2p3): for F to be a viable function, there shall
7470       // exist for each argument an implicit conversion sequence
7471       // (13.3.3.1) that converts that argument to the corresponding
7472       // parameter of F.
7473       QualType ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
7474       Candidate.Conversions[ConvIdx]
7475         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7476                                 SuppressUserConversions,
7477                                 /*InOverloadResolution=*/true,
7478                                 /*AllowObjCWritebackConversion=*/
7479                                   getLangOpts().ObjCAutoRefCount);
7480       if (Candidate.Conversions[ConvIdx].isBad()) {
7481         Candidate.Viable = false;
7482         Candidate.FailureKind = ovl_fail_bad_conversion;
7483         return;
7484       }
7485     } else {
7486       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7487       // argument for which there is no corresponding parameter is
7488       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7489       Candidate.Conversions[ConvIdx].setEllipsis();
7490     }
7491   }
7492 
7493   if (EnableIfAttr *FailedAttr =
7494           CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7495     Candidate.Viable = false;
7496     Candidate.FailureKind = ovl_fail_enable_if;
7497     Candidate.DeductionFailure.Data = FailedAttr;
7498     return;
7499   }
7500 
7501   if (Method->isMultiVersion() &&
7502       ((Method->hasAttr<TargetAttr>() &&
7503         !Method->getAttr<TargetAttr>()->isDefaultVersion()) ||
7504        (Method->hasAttr<TargetVersionAttr>() &&
7505         !Method->getAttr<TargetVersionAttr>()->isDefaultVersion()))) {
7506     Candidate.Viable = false;
7507     Candidate.FailureKind = ovl_non_default_multiversion_function;
7508   }
7509 }
7510 
7511 /// Add a C++ member function template as a candidate to the candidate
7512 /// set, using template argument deduction to produce an appropriate member
7513 /// function template specialization.
7514 void Sema::AddMethodTemplateCandidate(
7515     FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7516     CXXRecordDecl *ActingContext,
7517     TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7518     Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7519     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7520     bool PartialOverloading, OverloadCandidateParamOrder PO) {
7521   if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7522     return;
7523 
7524   // C++ [over.match.funcs]p7:
7525   //   In each case where a candidate is a function template, candidate
7526   //   function template specializations are generated using template argument
7527   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
7528   //   candidate functions in the usual way.113) A given name can refer to one
7529   //   or more function templates and also to a set of overloaded non-template
7530   //   functions. In such a case, the candidate functions generated from each
7531   //   function template are combined with the set of non-template candidate
7532   //   functions.
7533   TemplateDeductionInfo Info(CandidateSet.getLocation());
7534   FunctionDecl *Specialization = nullptr;
7535   ConversionSequenceList Conversions;
7536   if (TemplateDeductionResult Result = DeduceTemplateArguments(
7537           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7538           PartialOverloading, /*AggregateDeductionCandidate=*/false, ObjectType,
7539           ObjectClassification, [&](ArrayRef<QualType> ParamTypes) {
7540             return CheckNonDependentConversions(
7541                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7542                 SuppressUserConversions, ActingContext, ObjectType,
7543                 ObjectClassification, PO);
7544           })) {
7545     OverloadCandidate &Candidate =
7546         CandidateSet.addCandidate(Conversions.size(), Conversions);
7547     Candidate.FoundDecl = FoundDecl;
7548     Candidate.Function = MethodTmpl->getTemplatedDecl();
7549     Candidate.Viable = false;
7550     Candidate.RewriteKind =
7551       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7552     Candidate.IsSurrogate = false;
7553     Candidate.IgnoreObjectArgument =
7554         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
7555         ObjectType.isNull();
7556     Candidate.ExplicitCallArguments = Args.size();
7557     if (Result == TDK_NonDependentConversionFailure)
7558       Candidate.FailureKind = ovl_fail_bad_conversion;
7559     else {
7560       Candidate.FailureKind = ovl_fail_bad_deduction;
7561       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7562                                                             Info);
7563     }
7564     return;
7565   }
7566 
7567   // Add the function template specialization produced by template argument
7568   // deduction as a candidate.
7569   assert(Specialization && "Missing member function template specialization?");
7570   assert(isa<CXXMethodDecl>(Specialization) &&
7571          "Specialization is not a member function?");
7572   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
7573                      ActingContext, ObjectType, ObjectClassification, Args,
7574                      CandidateSet, SuppressUserConversions, PartialOverloading,
7575                      Conversions, PO);
7576 }
7577 
7578 /// Determine whether a given function template has a simple explicit specifier
7579 /// or a non-value-dependent explicit-specification that evaluates to true.
7580 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
7581   return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
7582 }
7583 
7584 /// Add a C++ function template specialization as a candidate
7585 /// in the candidate set, using template argument deduction to produce
7586 /// an appropriate function template specialization.
7587 void Sema::AddTemplateOverloadCandidate(
7588     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7589     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7590     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7591     bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7592     OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
7593   if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
7594     return;
7595 
7596   // If the function template has a non-dependent explicit specification,
7597   // exclude it now if appropriate; we are not permitted to perform deduction
7598   // and substitution in this case.
7599   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7600     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7601     Candidate.FoundDecl = FoundDecl;
7602     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7603     Candidate.Viable = false;
7604     Candidate.FailureKind = ovl_fail_explicit;
7605     return;
7606   }
7607 
7608   // C++ [over.match.funcs]p7:
7609   //   In each case where a candidate is a function template, candidate
7610   //   function template specializations are generated using template argument
7611   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
7612   //   candidate functions in the usual way.113) A given name can refer to one
7613   //   or more function templates and also to a set of overloaded non-template
7614   //   functions. In such a case, the candidate functions generated from each
7615   //   function template are combined with the set of non-template candidate
7616   //   functions.
7617   TemplateDeductionInfo Info(CandidateSet.getLocation());
7618   FunctionDecl *Specialization = nullptr;
7619   ConversionSequenceList Conversions;
7620   if (TemplateDeductionResult Result = DeduceTemplateArguments(
7621           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7622           PartialOverloading, AggregateCandidateDeduction,
7623           /*ObjectType=*/QualType(),
7624           /*ObjectClassification=*/Expr::Classification(),
7625           [&](ArrayRef<QualType> ParamTypes) {
7626             return CheckNonDependentConversions(
7627                 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7628                 SuppressUserConversions, nullptr, QualType(), {}, PO);
7629           })) {
7630     OverloadCandidate &Candidate =
7631         CandidateSet.addCandidate(Conversions.size(), Conversions);
7632     Candidate.FoundDecl = FoundDecl;
7633     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7634     Candidate.Viable = false;
7635     Candidate.RewriteKind =
7636       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7637     Candidate.IsSurrogate = false;
7638     Candidate.IsADLCandidate = IsADLCandidate;
7639     // Ignore the object argument if there is one, since we don't have an object
7640     // type.
7641     Candidate.IgnoreObjectArgument =
7642         isa<CXXMethodDecl>(Candidate.Function) &&
7643         !isa<CXXConstructorDecl>(Candidate.Function);
7644     Candidate.ExplicitCallArguments = Args.size();
7645     if (Result == TDK_NonDependentConversionFailure)
7646       Candidate.FailureKind = ovl_fail_bad_conversion;
7647     else {
7648       Candidate.FailureKind = ovl_fail_bad_deduction;
7649       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7650                                                             Info);
7651     }
7652     return;
7653   }
7654 
7655   // Add the function template specialization produced by template argument
7656   // deduction as a candidate.
7657   assert(Specialization && "Missing function template specialization?");
7658   AddOverloadCandidate(
7659       Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7660       PartialOverloading, AllowExplicit,
7661       /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
7662       Info.AggregateDeductionCandidateHasMismatchedArity);
7663 }
7664 
7665 /// Check that implicit conversion sequences can be formed for each argument
7666 /// whose corresponding parameter has a non-dependent type, per DR1391's
7667 /// [temp.deduct.call]p10.
7668 bool Sema::CheckNonDependentConversions(
7669     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7670     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7671     ConversionSequenceList &Conversions, bool SuppressUserConversions,
7672     CXXRecordDecl *ActingContext, QualType ObjectType,
7673     Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7674   // FIXME: The cases in which we allow explicit conversions for constructor
7675   // arguments never consider calling a constructor template. It's not clear
7676   // that is correct.
7677   const bool AllowExplicit = false;
7678 
7679   auto *FD = FunctionTemplate->getTemplatedDecl();
7680   auto *Method = dyn_cast<CXXMethodDecl>(FD);
7681   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7682   unsigned ThisConversions = HasThisConversion ? 1 : 0;
7683 
7684   Conversions =
7685       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7686 
7687   // Overload resolution is always an unevaluated context.
7688   EnterExpressionEvaluationContext Unevaluated(
7689       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7690 
7691   // For a method call, check the 'this' conversion here too. DR1391 doesn't
7692   // require that, but this check should never result in a hard error, and
7693   // overload resolution is permitted to sidestep instantiations.
7694   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7695       !ObjectType.isNull()) {
7696     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7697     if (!FD->hasCXXExplicitFunctionObjectParameter() ||
7698         !ParamTypes[0]->isDependentType()) {
7699       Conversions[ConvIdx] = TryObjectArgumentInitialization(
7700           *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7701           Method, ActingContext, /*InOverloadResolution=*/true,
7702           FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
7703                                                       : QualType());
7704       if (Conversions[ConvIdx].isBad())
7705         return true;
7706     }
7707   }
7708 
7709   unsigned Offset =
7710       Method && Method->hasCXXExplicitFunctionObjectParameter() ? 1 : 0;
7711 
7712   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
7713        ++I) {
7714     QualType ParamType = ParamTypes[I + Offset];
7715     if (!ParamType->isDependentType()) {
7716       unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
7717                              ? 0
7718                              : (ThisConversions + I);
7719       Conversions[ConvIdx]
7720         = TryCopyInitialization(*this, Args[I], ParamType,
7721                                 SuppressUserConversions,
7722                                 /*InOverloadResolution=*/true,
7723                                 /*AllowObjCWritebackConversion=*/
7724                                   getLangOpts().ObjCAutoRefCount,
7725                                 AllowExplicit);
7726       if (Conversions[ConvIdx].isBad())
7727         return true;
7728     }
7729   }
7730 
7731   return false;
7732 }
7733 
7734 /// Determine whether this is an allowable conversion from the result
7735 /// of an explicit conversion operator to the expected type, per C++
7736 /// [over.match.conv]p1 and [over.match.ref]p1.
7737 ///
7738 /// \param ConvType The return type of the conversion function.
7739 ///
7740 /// \param ToType The type we are converting to.
7741 ///
7742 /// \param AllowObjCPointerConversion Allow a conversion from one
7743 /// Objective-C pointer to another.
7744 ///
7745 /// \returns true if the conversion is allowable, false otherwise.
7746 static bool isAllowableExplicitConversion(Sema &S,
7747                                           QualType ConvType, QualType ToType,
7748                                           bool AllowObjCPointerConversion) {
7749   QualType ToNonRefType = ToType.getNonReferenceType();
7750 
7751   // Easy case: the types are the same.
7752   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7753     return true;
7754 
7755   // Allow qualification conversions.
7756   bool ObjCLifetimeConversion;
7757   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7758                                   ObjCLifetimeConversion))
7759     return true;
7760 
7761   // If we're not allowed to consider Objective-C pointer conversions,
7762   // we're done.
7763   if (!AllowObjCPointerConversion)
7764     return false;
7765 
7766   // Is this an Objective-C pointer conversion?
7767   bool IncompatibleObjC = false;
7768   QualType ConvertedType;
7769   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7770                                    IncompatibleObjC);
7771 }
7772 
7773 /// AddConversionCandidate - Add a C++ conversion function as a
7774 /// candidate in the candidate set (C++ [over.match.conv],
7775 /// C++ [over.match.copy]). From is the expression we're converting from,
7776 /// and ToType is the type that we're eventually trying to convert to
7777 /// (which may or may not be the same type as the type that the
7778 /// conversion function produces).
7779 void Sema::AddConversionCandidate(
7780     CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7781     CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7782     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7783     bool AllowExplicit, bool AllowResultConversion) {
7784   assert(!Conversion->getDescribedFunctionTemplate() &&
7785          "Conversion function templates use AddTemplateConversionCandidate");
7786   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7787   if (!CandidateSet.isNewCandidate(Conversion))
7788     return;
7789 
7790   // If the conversion function has an undeduced return type, trigger its
7791   // deduction now.
7792   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7793     if (DeduceReturnType(Conversion, From->getExprLoc()))
7794       return;
7795     ConvType = Conversion->getConversionType().getNonReferenceType();
7796   }
7797 
7798   // If we don't allow any conversion of the result type, ignore conversion
7799   // functions that don't convert to exactly (possibly cv-qualified) T.
7800   if (!AllowResultConversion &&
7801       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7802     return;
7803 
7804   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7805   // operator is only a candidate if its return type is the target type or
7806   // can be converted to the target type with a qualification conversion.
7807   //
7808   // FIXME: Include such functions in the candidate list and explain why we
7809   // can't select them.
7810   if (Conversion->isExplicit() &&
7811       !isAllowableExplicitConversion(*this, ConvType, ToType,
7812                                      AllowObjCConversionOnExplicit))
7813     return;
7814 
7815   // Overload resolution is always an unevaluated context.
7816   EnterExpressionEvaluationContext Unevaluated(
7817       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7818 
7819   // Add this candidate
7820   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7821   Candidate.FoundDecl = FoundDecl;
7822   Candidate.Function = Conversion;
7823   Candidate.IsSurrogate = false;
7824   Candidate.IgnoreObjectArgument = false;
7825   Candidate.FinalConversion.setAsIdentityConversion();
7826   Candidate.FinalConversion.setFromType(ConvType);
7827   Candidate.FinalConversion.setAllToTypes(ToType);
7828   Candidate.Viable = true;
7829   Candidate.ExplicitCallArguments = 1;
7830 
7831   // Explicit functions are not actually candidates at all if we're not
7832   // allowing them in this context, but keep them around so we can point
7833   // to them in diagnostics.
7834   if (!AllowExplicit && Conversion->isExplicit()) {
7835     Candidate.Viable = false;
7836     Candidate.FailureKind = ovl_fail_explicit;
7837     return;
7838   }
7839 
7840   // C++ [over.match.funcs]p4:
7841   //   For conversion functions, the function is considered to be a member of
7842   //   the class of the implicit implied object argument for the purpose of
7843   //   defining the type of the implicit object parameter.
7844   //
7845   // Determine the implicit conversion sequence for the implicit
7846   // object parameter.
7847   QualType ObjectType = From->getType();
7848   if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
7849     ObjectType = FromPtrType->getPointeeType();
7850   const auto *ConversionContext =
7851       cast<CXXRecordDecl>(ObjectType->castAs<RecordType>()->getDecl());
7852 
7853   // C++23 [over.best.ics.general]
7854   // However, if the target is [...]
7855   // - the object parameter of a user-defined conversion function
7856   // [...] user-defined conversion sequences are not considered.
7857   Candidate.Conversions[0] = TryObjectArgumentInitialization(
7858       *this, CandidateSet.getLocation(), From->getType(),
7859       From->Classify(Context), Conversion, ConversionContext,
7860       /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
7861       /*SuppressUserConversion*/ true);
7862 
7863   if (Candidate.Conversions[0].isBad()) {
7864     Candidate.Viable = false;
7865     Candidate.FailureKind = ovl_fail_bad_conversion;
7866     return;
7867   }
7868 
7869   if (Conversion->getTrailingRequiresClause()) {
7870     ConstraintSatisfaction Satisfaction;
7871     if (CheckFunctionConstraints(Conversion, Satisfaction) ||
7872         !Satisfaction.IsSatisfied) {
7873       Candidate.Viable = false;
7874       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7875       return;
7876     }
7877   }
7878 
7879   // We won't go through a user-defined type conversion function to convert a
7880   // derived to base as such conversions are given Conversion Rank. They only
7881   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7882   QualType FromCanon
7883     = Context.getCanonicalType(From->getType().getUnqualifiedType());
7884   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7885   if (FromCanon == ToCanon ||
7886       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7887     Candidate.Viable = false;
7888     Candidate.FailureKind = ovl_fail_trivial_conversion;
7889     return;
7890   }
7891 
7892   // To determine what the conversion from the result of calling the
7893   // conversion function to the type we're eventually trying to
7894   // convert to (ToType), we need to synthesize a call to the
7895   // conversion function and attempt copy initialization from it. This
7896   // makes sure that we get the right semantics with respect to
7897   // lvalues/rvalues and the type. Fortunately, we can allocate this
7898   // call on the stack and we don't need its arguments to be
7899   // well-formed.
7900   DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7901                             VK_LValue, From->getBeginLoc());
7902   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7903                                 Context.getPointerType(Conversion->getType()),
7904                                 CK_FunctionToPointerDecay, &ConversionRef,
7905                                 VK_PRValue, FPOptionsOverride());
7906 
7907   QualType ConversionType = Conversion->getConversionType();
7908   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7909     Candidate.Viable = false;
7910     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7911     return;
7912   }
7913 
7914   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7915 
7916   // Note that it is safe to allocate CallExpr on the stack here because
7917   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7918   // allocator).
7919   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7920 
7921   alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7922   CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7923       Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7924 
7925   ImplicitConversionSequence ICS =
7926       TryCopyInitialization(*this, TheTemporaryCall, ToType,
7927                             /*SuppressUserConversions=*/true,
7928                             /*InOverloadResolution=*/false,
7929                             /*AllowObjCWritebackConversion=*/false);
7930 
7931   switch (ICS.getKind()) {
7932   case ImplicitConversionSequence::StandardConversion:
7933     Candidate.FinalConversion = ICS.Standard;
7934 
7935     // C++ [over.ics.user]p3:
7936     //   If the user-defined conversion is specified by a specialization of a
7937     //   conversion function template, the second standard conversion sequence
7938     //   shall have exact match rank.
7939     if (Conversion->getPrimaryTemplate() &&
7940         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7941       Candidate.Viable = false;
7942       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7943       return;
7944     }
7945 
7946     // C++0x [dcl.init.ref]p5:
7947     //    In the second case, if the reference is an rvalue reference and
7948     //    the second standard conversion sequence of the user-defined
7949     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7950     //    program is ill-formed.
7951     if (ToType->isRValueReferenceType() &&
7952         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7953       Candidate.Viable = false;
7954       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7955       return;
7956     }
7957     break;
7958 
7959   case ImplicitConversionSequence::BadConversion:
7960     Candidate.Viable = false;
7961     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7962     return;
7963 
7964   default:
7965     llvm_unreachable(
7966            "Can only end up with a standard conversion sequence or failure");
7967   }
7968 
7969   if (EnableIfAttr *FailedAttr =
7970           CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) {
7971     Candidate.Viable = false;
7972     Candidate.FailureKind = ovl_fail_enable_if;
7973     Candidate.DeductionFailure.Data = FailedAttr;
7974     return;
7975   }
7976 
7977   if (Conversion->isMultiVersion() &&
7978       ((Conversion->hasAttr<TargetAttr>() &&
7979         !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) ||
7980        (Conversion->hasAttr<TargetVersionAttr>() &&
7981         !Conversion->getAttr<TargetVersionAttr>()->isDefaultVersion()))) {
7982     Candidate.Viable = false;
7983     Candidate.FailureKind = ovl_non_default_multiversion_function;
7984   }
7985 }
7986 
7987 /// Adds a conversion function template specialization
7988 /// candidate to the overload set, using template argument deduction
7989 /// to deduce the template arguments of the conversion function
7990 /// template from the type that we are converting to (C++
7991 /// [temp.deduct.conv]).
7992 void Sema::AddTemplateConversionCandidate(
7993     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7994     CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7995     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7996     bool AllowExplicit, bool AllowResultConversion) {
7997   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7998          "Only conversion function templates permitted here");
7999 
8000   if (!CandidateSet.isNewCandidate(FunctionTemplate))
8001     return;
8002 
8003   // If the function template has a non-dependent explicit specification,
8004   // exclude it now if appropriate; we are not permitted to perform deduction
8005   // and substitution in this case.
8006   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8007     OverloadCandidate &Candidate = CandidateSet.addCandidate();
8008     Candidate.FoundDecl = FoundDecl;
8009     Candidate.Function = FunctionTemplate->getTemplatedDecl();
8010     Candidate.Viable = false;
8011     Candidate.FailureKind = ovl_fail_explicit;
8012     return;
8013   }
8014 
8015   QualType ObjectType = From->getType();
8016   Expr::Classification ObjectClassification = From->Classify(getASTContext());
8017 
8018   TemplateDeductionInfo Info(CandidateSet.getLocation());
8019   CXXConversionDecl *Specialization = nullptr;
8020   if (TemplateDeductionResult Result = DeduceTemplateArguments(
8021           FunctionTemplate, ObjectType, ObjectClassification, ToType,
8022           Specialization, Info)) {
8023     OverloadCandidate &Candidate = CandidateSet.addCandidate();
8024     Candidate.FoundDecl = FoundDecl;
8025     Candidate.Function = FunctionTemplate->getTemplatedDecl();
8026     Candidate.Viable = false;
8027     Candidate.FailureKind = ovl_fail_bad_deduction;
8028     Candidate.IsSurrogate = false;
8029     Candidate.IgnoreObjectArgument = false;
8030     Candidate.ExplicitCallArguments = 1;
8031     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
8032                                                           Info);
8033     return;
8034   }
8035 
8036   // Add the conversion function template specialization produced by
8037   // template argument deduction as a candidate.
8038   assert(Specialization && "Missing function template specialization?");
8039   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
8040                          CandidateSet, AllowObjCConversionOnExplicit,
8041                          AllowExplicit, AllowResultConversion);
8042 }
8043 
8044 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
8045 /// converts the given @c Object to a function pointer via the
8046 /// conversion function @c Conversion, and then attempts to call it
8047 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
8048 /// the type of function that we'll eventually be calling.
8049 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
8050                                  DeclAccessPair FoundDecl,
8051                                  CXXRecordDecl *ActingContext,
8052                                  const FunctionProtoType *Proto,
8053                                  Expr *Object,
8054                                  ArrayRef<Expr *> Args,
8055                                  OverloadCandidateSet& CandidateSet) {
8056   if (!CandidateSet.isNewCandidate(Conversion))
8057     return;
8058 
8059   // Overload resolution is always an unevaluated context.
8060   EnterExpressionEvaluationContext Unevaluated(
8061       *this, Sema::ExpressionEvaluationContext::Unevaluated);
8062 
8063   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8064   Candidate.FoundDecl = FoundDecl;
8065   Candidate.Function = nullptr;
8066   Candidate.Surrogate = Conversion;
8067   Candidate.Viable = true;
8068   Candidate.IsSurrogate = true;
8069   Candidate.IgnoreObjectArgument = false;
8070   Candidate.ExplicitCallArguments = Args.size();
8071 
8072   // Determine the implicit conversion sequence for the implicit
8073   // object parameter.
8074   ImplicitConversionSequence ObjectInit;
8075   if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8076     ObjectInit = TryCopyInitialization(*this, Object,
8077                                        Conversion->getParamDecl(0)->getType(),
8078                                        /*SuppressUserConversions=*/false,
8079                                        /*InOverloadResolution=*/true, false);
8080   } else {
8081     ObjectInit = TryObjectArgumentInitialization(
8082         *this, CandidateSet.getLocation(), Object->getType(),
8083         Object->Classify(Context), Conversion, ActingContext);
8084   }
8085 
8086   if (ObjectInit.isBad()) {
8087     Candidate.Viable = false;
8088     Candidate.FailureKind = ovl_fail_bad_conversion;
8089     Candidate.Conversions[0] = ObjectInit;
8090     return;
8091   }
8092 
8093   // The first conversion is actually a user-defined conversion whose
8094   // first conversion is ObjectInit's standard conversion (which is
8095   // effectively a reference binding). Record it as such.
8096   Candidate.Conversions[0].setUserDefined();
8097   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8098   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8099   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8100   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8101   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8102   Candidate.Conversions[0].UserDefined.After
8103     = Candidate.Conversions[0].UserDefined.Before;
8104   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8105 
8106   // Find the
8107   unsigned NumParams = Proto->getNumParams();
8108 
8109   // (C++ 13.3.2p2): A candidate function having fewer than m
8110   // parameters is viable only if it has an ellipsis in its parameter
8111   // list (8.3.5).
8112   if (Args.size() > NumParams && !Proto->isVariadic()) {
8113     Candidate.Viable = false;
8114     Candidate.FailureKind = ovl_fail_too_many_arguments;
8115     return;
8116   }
8117 
8118   // Function types don't have any default arguments, so just check if
8119   // we have enough arguments.
8120   if (Args.size() < NumParams) {
8121     // Not enough arguments.
8122     Candidate.Viable = false;
8123     Candidate.FailureKind = ovl_fail_too_few_arguments;
8124     return;
8125   }
8126 
8127   // Determine the implicit conversion sequences for each of the
8128   // arguments.
8129   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8130     if (ArgIdx < NumParams) {
8131       // (C++ 13.3.2p3): for F to be a viable function, there shall
8132       // exist for each argument an implicit conversion sequence
8133       // (13.3.3.1) that converts that argument to the corresponding
8134       // parameter of F.
8135       QualType ParamType = Proto->getParamType(ArgIdx);
8136       Candidate.Conversions[ArgIdx + 1]
8137         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8138                                 /*SuppressUserConversions=*/false,
8139                                 /*InOverloadResolution=*/false,
8140                                 /*AllowObjCWritebackConversion=*/
8141                                   getLangOpts().ObjCAutoRefCount);
8142       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8143         Candidate.Viable = false;
8144         Candidate.FailureKind = ovl_fail_bad_conversion;
8145         return;
8146       }
8147     } else {
8148       // (C++ 13.3.2p2): For the purposes of overload resolution, any
8149       // argument for which there is no corresponding parameter is
8150       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8151       Candidate.Conversions[ArgIdx + 1].setEllipsis();
8152     }
8153   }
8154 
8155   if (Conversion->getTrailingRequiresClause()) {
8156     ConstraintSatisfaction Satisfaction;
8157     if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8158                                  /*ForOverloadResolution*/ true) ||
8159         !Satisfaction.IsSatisfied) {
8160       Candidate.Viable = false;
8161       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8162       return;
8163     }
8164   }
8165 
8166   if (EnableIfAttr *FailedAttr =
8167           CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) {
8168     Candidate.Viable = false;
8169     Candidate.FailureKind = ovl_fail_enable_if;
8170     Candidate.DeductionFailure.Data = FailedAttr;
8171     return;
8172   }
8173 }
8174 
8175 /// Add all of the non-member operator function declarations in the given
8176 /// function set to the overload candidate set.
8177 void Sema::AddNonMemberOperatorCandidates(
8178     const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8179     OverloadCandidateSet &CandidateSet,
8180     TemplateArgumentListInfo *ExplicitTemplateArgs) {
8181   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8182     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8183     ArrayRef<Expr *> FunctionArgs = Args;
8184 
8185     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8186     FunctionDecl *FD =
8187         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8188 
8189     // Don't consider rewritten functions if we're not rewriting.
8190     if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8191       continue;
8192 
8193     assert(!isa<CXXMethodDecl>(FD) &&
8194            "unqualified operator lookup found a member function");
8195 
8196     if (FunTmpl) {
8197       AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8198                                    FunctionArgs, CandidateSet);
8199       if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8200         AddTemplateOverloadCandidate(
8201             FunTmpl, F.getPair(), ExplicitTemplateArgs,
8202             {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
8203             true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
8204     } else {
8205       if (ExplicitTemplateArgs)
8206         continue;
8207       AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8208       if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8209         AddOverloadCandidate(
8210             FD, F.getPair(), {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8211             false, false, true, false, ADLCallKind::NotADL, std::nullopt,
8212             OverloadCandidateParamOrder::Reversed);
8213     }
8214   }
8215 }
8216 
8217 /// Add overload candidates for overloaded operators that are
8218 /// member functions.
8219 ///
8220 /// Add the overloaded operator candidates that are member functions
8221 /// for the operator Op that was used in an operator expression such
8222 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
8223 /// CandidateSet will store the added overload candidates. (C++
8224 /// [over.match.oper]).
8225 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
8226                                        SourceLocation OpLoc,
8227                                        ArrayRef<Expr *> Args,
8228                                        OverloadCandidateSet &CandidateSet,
8229                                        OverloadCandidateParamOrder PO) {
8230   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8231 
8232   // C++ [over.match.oper]p3:
8233   //   For a unary operator @ with an operand of a type whose
8234   //   cv-unqualified version is T1, and for a binary operator @ with
8235   //   a left operand of a type whose cv-unqualified version is T1 and
8236   //   a right operand of a type whose cv-unqualified version is T2,
8237   //   three sets of candidate functions, designated member
8238   //   candidates, non-member candidates and built-in candidates, are
8239   //   constructed as follows:
8240   QualType T1 = Args[0]->getType();
8241 
8242   //     -- If T1 is a complete class type or a class currently being
8243   //        defined, the set of member candidates is the result of the
8244   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8245   //        the set of member candidates is empty.
8246   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
8247     // Complete the type if it can be completed.
8248     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
8249       return;
8250     // If the type is neither complete nor being defined, bail out now.
8251     if (!T1Rec->getDecl()->getDefinition())
8252       return;
8253 
8254     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8255     LookupQualifiedName(Operators, T1Rec->getDecl());
8256     Operators.suppressAccessDiagnostics();
8257 
8258     for (LookupResult::iterator Oper = Operators.begin(),
8259                                 OperEnd = Operators.end();
8260          Oper != OperEnd; ++Oper) {
8261       if (Oper->getAsFunction() &&
8262           PO == OverloadCandidateParamOrder::Reversed &&
8263           !CandidateSet.getRewriteInfo().shouldAddReversed(
8264               *this, {Args[1], Args[0]}, Oper->getAsFunction()))
8265         continue;
8266       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
8267                          Args[0]->Classify(Context), Args.slice(1),
8268                          CandidateSet, /*SuppressUserConversion=*/false, PO);
8269     }
8270   }
8271 }
8272 
8273 /// AddBuiltinCandidate - Add a candidate for a built-in
8274 /// operator. ResultTy and ParamTys are the result and parameter types
8275 /// of the built-in candidate, respectively. Args and NumArgs are the
8276 /// arguments being passed to the candidate. IsAssignmentOperator
8277 /// should be true when this built-in candidate is an assignment
8278 /// operator. NumContextualBoolArguments is the number of arguments
8279 /// (at the beginning of the argument list) that will be contextually
8280 /// converted to bool.
8281 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
8282                                OverloadCandidateSet& CandidateSet,
8283                                bool IsAssignmentOperator,
8284                                unsigned NumContextualBoolArguments) {
8285   // Overload resolution is always an unevaluated context.
8286   EnterExpressionEvaluationContext Unevaluated(
8287       *this, Sema::ExpressionEvaluationContext::Unevaluated);
8288 
8289   // Add this candidate
8290   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
8291   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
8292   Candidate.Function = nullptr;
8293   Candidate.IsSurrogate = false;
8294   Candidate.IgnoreObjectArgument = false;
8295   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
8296 
8297   // Determine the implicit conversion sequences for each of the
8298   // arguments.
8299   Candidate.Viable = true;
8300   Candidate.ExplicitCallArguments = Args.size();
8301   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8302     // C++ [over.match.oper]p4:
8303     //   For the built-in assignment operators, conversions of the
8304     //   left operand are restricted as follows:
8305     //     -- no temporaries are introduced to hold the left operand, and
8306     //     -- no user-defined conversions are applied to the left
8307     //        operand to achieve a type match with the left-most
8308     //        parameter of a built-in candidate.
8309     //
8310     // We block these conversions by turning off user-defined
8311     // conversions, since that is the only way that initialization of
8312     // a reference to a non-class type can occur from something that
8313     // is not of the same type.
8314     if (ArgIdx < NumContextualBoolArguments) {
8315       assert(ParamTys[ArgIdx] == Context.BoolTy &&
8316              "Contextual conversion to bool requires bool type");
8317       Candidate.Conversions[ArgIdx]
8318         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
8319     } else {
8320       Candidate.Conversions[ArgIdx]
8321         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
8322                                 ArgIdx == 0 && IsAssignmentOperator,
8323                                 /*InOverloadResolution=*/false,
8324                                 /*AllowObjCWritebackConversion=*/
8325                                   getLangOpts().ObjCAutoRefCount);
8326     }
8327     if (Candidate.Conversions[ArgIdx].isBad()) {
8328       Candidate.Viable = false;
8329       Candidate.FailureKind = ovl_fail_bad_conversion;
8330       break;
8331     }
8332   }
8333 }
8334 
8335 namespace {
8336 
8337 /// BuiltinCandidateTypeSet - A set of types that will be used for the
8338 /// candidate operator functions for built-in operators (C++
8339 /// [over.built]). The types are separated into pointer types and
8340 /// enumeration types.
8341 class BuiltinCandidateTypeSet  {
8342   /// TypeSet - A set of types.
8343   typedef llvm::SmallSetVector<QualType, 8> TypeSet;
8344 
8345   /// PointerTypes - The set of pointer types that will be used in the
8346   /// built-in candidates.
8347   TypeSet PointerTypes;
8348 
8349   /// MemberPointerTypes - The set of member pointer types that will be
8350   /// used in the built-in candidates.
8351   TypeSet MemberPointerTypes;
8352 
8353   /// EnumerationTypes - The set of enumeration types that will be
8354   /// used in the built-in candidates.
8355   TypeSet EnumerationTypes;
8356 
8357   /// The set of vector types that will be used in the built-in
8358   /// candidates.
8359   TypeSet VectorTypes;
8360 
8361   /// The set of matrix types that will be used in the built-in
8362   /// candidates.
8363   TypeSet MatrixTypes;
8364 
8365   /// A flag indicating non-record types are viable candidates
8366   bool HasNonRecordTypes;
8367 
8368   /// A flag indicating whether either arithmetic or enumeration types
8369   /// were present in the candidate set.
8370   bool HasArithmeticOrEnumeralTypes;
8371 
8372   /// A flag indicating whether the nullptr type was present in the
8373   /// candidate set.
8374   bool HasNullPtrType;
8375 
8376   /// Sema - The semantic analysis instance where we are building the
8377   /// candidate type set.
8378   Sema &SemaRef;
8379 
8380   /// Context - The AST context in which we will build the type sets.
8381   ASTContext &Context;
8382 
8383   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8384                                                const Qualifiers &VisibleQuals);
8385   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8386 
8387 public:
8388   /// iterator - Iterates through the types that are part of the set.
8389   typedef TypeSet::iterator iterator;
8390 
8391   BuiltinCandidateTypeSet(Sema &SemaRef)
8392     : HasNonRecordTypes(false),
8393       HasArithmeticOrEnumeralTypes(false),
8394       HasNullPtrType(false),
8395       SemaRef(SemaRef),
8396       Context(SemaRef.Context) { }
8397 
8398   void AddTypesConvertedFrom(QualType Ty,
8399                              SourceLocation Loc,
8400                              bool AllowUserConversions,
8401                              bool AllowExplicitConversions,
8402                              const Qualifiers &VisibleTypeConversionsQuals);
8403 
8404   llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
8405   llvm::iterator_range<iterator> member_pointer_types() {
8406     return MemberPointerTypes;
8407   }
8408   llvm::iterator_range<iterator> enumeration_types() {
8409     return EnumerationTypes;
8410   }
8411   llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
8412   llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
8413 
8414   bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
8415   bool hasNonRecordTypes() { return HasNonRecordTypes; }
8416   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
8417   bool hasNullPtrType() const { return HasNullPtrType; }
8418 };
8419 
8420 } // end anonymous namespace
8421 
8422 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8423 /// the set of pointer types along with any more-qualified variants of
8424 /// that type. For example, if @p Ty is "int const *", this routine
8425 /// will add "int const *", "int const volatile *", "int const
8426 /// restrict *", and "int const volatile restrict *" to the set of
8427 /// pointer types. Returns true if the add of @p Ty itself succeeded,
8428 /// false otherwise.
8429 ///
8430 /// FIXME: what to do about extended qualifiers?
8431 bool
8432 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8433                                              const Qualifiers &VisibleQuals) {
8434 
8435   // Insert this type.
8436   if (!PointerTypes.insert(Ty))
8437     return false;
8438 
8439   QualType PointeeTy;
8440   const PointerType *PointerTy = Ty->getAs<PointerType>();
8441   bool buildObjCPtr = false;
8442   if (!PointerTy) {
8443     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
8444     PointeeTy = PTy->getPointeeType();
8445     buildObjCPtr = true;
8446   } else {
8447     PointeeTy = PointerTy->getPointeeType();
8448   }
8449 
8450   // Don't add qualified variants of arrays. For one, they're not allowed
8451   // (the qualifier would sink to the element type), and for another, the
8452   // only overload situation where it matters is subscript or pointer +- int,
8453   // and those shouldn't have qualifier variants anyway.
8454   if (PointeeTy->isArrayType())
8455     return true;
8456 
8457   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8458   bool hasVolatile = VisibleQuals.hasVolatile();
8459   bool hasRestrict = VisibleQuals.hasRestrict();
8460 
8461   // Iterate through all strict supersets of BaseCVR.
8462   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8463     if ((CVR | BaseCVR) != CVR) continue;
8464     // Skip over volatile if no volatile found anywhere in the types.
8465     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
8466 
8467     // Skip over restrict if no restrict found anywhere in the types, or if
8468     // the type cannot be restrict-qualified.
8469     if ((CVR & Qualifiers::Restrict) &&
8470         (!hasRestrict ||
8471          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
8472       continue;
8473 
8474     // Build qualified pointee type.
8475     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8476 
8477     // Build qualified pointer type.
8478     QualType QPointerTy;
8479     if (!buildObjCPtr)
8480       QPointerTy = Context.getPointerType(QPointeeTy);
8481     else
8482       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
8483 
8484     // Insert qualified pointer type.
8485     PointerTypes.insert(QPointerTy);
8486   }
8487 
8488   return true;
8489 }
8490 
8491 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8492 /// to the set of pointer types along with any more-qualified variants of
8493 /// that type. For example, if @p Ty is "int const *", this routine
8494 /// will add "int const *", "int const volatile *", "int const
8495 /// restrict *", and "int const volatile restrict *" to the set of
8496 /// pointer types. Returns true if the add of @p Ty itself succeeded,
8497 /// false otherwise.
8498 ///
8499 /// FIXME: what to do about extended qualifiers?
8500 bool
8501 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8502     QualType Ty) {
8503   // Insert this type.
8504   if (!MemberPointerTypes.insert(Ty))
8505     return false;
8506 
8507   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8508   assert(PointerTy && "type was not a member pointer type!");
8509 
8510   QualType PointeeTy = PointerTy->getPointeeType();
8511   // Don't add qualified variants of arrays. For one, they're not allowed
8512   // (the qualifier would sink to the element type), and for another, the
8513   // only overload situation where it matters is subscript or pointer +- int,
8514   // and those shouldn't have qualifier variants anyway.
8515   if (PointeeTy->isArrayType())
8516     return true;
8517   const Type *ClassTy = PointerTy->getClass();
8518 
8519   // Iterate through all strict supersets of the pointee type's CVR
8520   // qualifiers.
8521   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8522   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8523     if ((CVR | BaseCVR) != CVR) continue;
8524 
8525     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8526     MemberPointerTypes.insert(
8527       Context.getMemberPointerType(QPointeeTy, ClassTy));
8528   }
8529 
8530   return true;
8531 }
8532 
8533 /// AddTypesConvertedFrom - Add each of the types to which the type @p
8534 /// Ty can be implicit converted to the given set of @p Types. We're
8535 /// primarily interested in pointer types and enumeration types. We also
8536 /// take member pointer types, for the conditional operator.
8537 /// AllowUserConversions is true if we should look at the conversion
8538 /// functions of a class type, and AllowExplicitConversions if we
8539 /// should also include the explicit conversion functions of a class
8540 /// type.
8541 void
8542 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
8543                                                SourceLocation Loc,
8544                                                bool AllowUserConversions,
8545                                                bool AllowExplicitConversions,
8546                                                const Qualifiers &VisibleQuals) {
8547   // Only deal with canonical types.
8548   Ty = Context.getCanonicalType(Ty);
8549 
8550   // Look through reference types; they aren't part of the type of an
8551   // expression for the purposes of conversions.
8552   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
8553     Ty = RefTy->getPointeeType();
8554 
8555   // If we're dealing with an array type, decay to the pointer.
8556   if (Ty->isArrayType())
8557     Ty = SemaRef.Context.getArrayDecayedType(Ty);
8558 
8559   // Otherwise, we don't care about qualifiers on the type.
8560   Ty = Ty.getLocalUnqualifiedType();
8561 
8562   // Flag if we ever add a non-record type.
8563   const RecordType *TyRec = Ty->getAs<RecordType>();
8564   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
8565 
8566   // Flag if we encounter an arithmetic type.
8567   HasArithmeticOrEnumeralTypes =
8568     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
8569 
8570   if (Ty->isObjCIdType() || Ty->isObjCClassType())
8571     PointerTypes.insert(Ty);
8572   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
8573     // Insert our type, and its more-qualified variants, into the set
8574     // of types.
8575     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
8576       return;
8577   } else if (Ty->isMemberPointerType()) {
8578     // Member pointers are far easier, since the pointee can't be converted.
8579     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
8580       return;
8581   } else if (Ty->isEnumeralType()) {
8582     HasArithmeticOrEnumeralTypes = true;
8583     EnumerationTypes.insert(Ty);
8584   } else if (Ty->isVectorType()) {
8585     // We treat vector types as arithmetic types in many contexts as an
8586     // extension.
8587     HasArithmeticOrEnumeralTypes = true;
8588     VectorTypes.insert(Ty);
8589   } else if (Ty->isMatrixType()) {
8590     // Similar to vector types, we treat vector types as arithmetic types in
8591     // many contexts as an extension.
8592     HasArithmeticOrEnumeralTypes = true;
8593     MatrixTypes.insert(Ty);
8594   } else if (Ty->isNullPtrType()) {
8595     HasNullPtrType = true;
8596   } else if (AllowUserConversions && TyRec) {
8597     // No conversion functions in incomplete types.
8598     if (!SemaRef.isCompleteType(Loc, Ty))
8599       return;
8600 
8601     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8602     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8603       if (isa<UsingShadowDecl>(D))
8604         D = cast<UsingShadowDecl>(D)->getTargetDecl();
8605 
8606       // Skip conversion function templates; they don't tell us anything
8607       // about which builtin types we can convert to.
8608       if (isa<FunctionTemplateDecl>(D))
8609         continue;
8610 
8611       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
8612       if (AllowExplicitConversions || !Conv->isExplicit()) {
8613         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
8614                               VisibleQuals);
8615       }
8616     }
8617   }
8618 }
8619 /// Helper function for adjusting address spaces for the pointer or reference
8620 /// operands of builtin operators depending on the argument.
8621 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
8622                                                         Expr *Arg) {
8623   return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
8624 }
8625 
8626 /// Helper function for AddBuiltinOperatorCandidates() that adds
8627 /// the volatile- and non-volatile-qualified assignment operators for the
8628 /// given type to the candidate set.
8629 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
8630                                                    QualType T,
8631                                                    ArrayRef<Expr *> Args,
8632                                     OverloadCandidateSet &CandidateSet) {
8633   QualType ParamTypes[2];
8634 
8635   // T& operator=(T&, T)
8636   ParamTypes[0] = S.Context.getLValueReferenceType(
8637       AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
8638   ParamTypes[1] = T;
8639   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8640                         /*IsAssignmentOperator=*/true);
8641 
8642   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
8643     // volatile T& operator=(volatile T&, T)
8644     ParamTypes[0] = S.Context.getLValueReferenceType(
8645         AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
8646                                                 Args[0]));
8647     ParamTypes[1] = T;
8648     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8649                           /*IsAssignmentOperator=*/true);
8650   }
8651 }
8652 
8653 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8654 /// if any, found in visible type conversion functions found in ArgExpr's type.
8655 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8656     Qualifiers VRQuals;
8657     const RecordType *TyRec;
8658     if (const MemberPointerType *RHSMPType =
8659         ArgExpr->getType()->getAs<MemberPointerType>())
8660       TyRec = RHSMPType->getClass()->getAs<RecordType>();
8661     else
8662       TyRec = ArgExpr->getType()->getAs<RecordType>();
8663     if (!TyRec) {
8664       // Just to be safe, assume the worst case.
8665       VRQuals.addVolatile();
8666       VRQuals.addRestrict();
8667       return VRQuals;
8668     }
8669 
8670     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8671     if (!ClassDecl->hasDefinition())
8672       return VRQuals;
8673 
8674     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8675       if (isa<UsingShadowDecl>(D))
8676         D = cast<UsingShadowDecl>(D)->getTargetDecl();
8677       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8678         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8679         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8680           CanTy = ResTypeRef->getPointeeType();
8681         // Need to go down the pointer/mempointer chain and add qualifiers
8682         // as see them.
8683         bool done = false;
8684         while (!done) {
8685           if (CanTy.isRestrictQualified())
8686             VRQuals.addRestrict();
8687           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8688             CanTy = ResTypePtr->getPointeeType();
8689           else if (const MemberPointerType *ResTypeMPtr =
8690                 CanTy->getAs<MemberPointerType>())
8691             CanTy = ResTypeMPtr->getPointeeType();
8692           else
8693             done = true;
8694           if (CanTy.isVolatileQualified())
8695             VRQuals.addVolatile();
8696           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8697             return VRQuals;
8698         }
8699       }
8700     }
8701     return VRQuals;
8702 }
8703 
8704 // Note: We're currently only handling qualifiers that are meaningful for the
8705 // LHS of compound assignment overloading.
8706 static void forAllQualifierCombinationsImpl(
8707     QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
8708     llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8709   // _Atomic
8710   if (Available.hasAtomic()) {
8711     Available.removeAtomic();
8712     forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
8713     forAllQualifierCombinationsImpl(Available, Applied, Callback);
8714     return;
8715   }
8716 
8717   // volatile
8718   if (Available.hasVolatile()) {
8719     Available.removeVolatile();
8720     assert(!Applied.hasVolatile());
8721     forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
8722                                     Callback);
8723     forAllQualifierCombinationsImpl(Available, Applied, Callback);
8724     return;
8725   }
8726 
8727   Callback(Applied);
8728 }
8729 
8730 static void forAllQualifierCombinations(
8731     QualifiersAndAtomic Quals,
8732     llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8733   return forAllQualifierCombinationsImpl(Quals, QualifiersAndAtomic(),
8734                                          Callback);
8735 }
8736 
8737 static QualType makeQualifiedLValueReferenceType(QualType Base,
8738                                                  QualifiersAndAtomic Quals,
8739                                                  Sema &S) {
8740   if (Quals.hasAtomic())
8741     Base = S.Context.getAtomicType(Base);
8742   if (Quals.hasVolatile())
8743     Base = S.Context.getVolatileType(Base);
8744   return S.Context.getLValueReferenceType(Base);
8745 }
8746 
8747 namespace {
8748 
8749 /// Helper class to manage the addition of builtin operator overload
8750 /// candidates. It provides shared state and utility methods used throughout
8751 /// the process, as well as a helper method to add each group of builtin
8752 /// operator overloads from the standard to a candidate set.
8753 class BuiltinOperatorOverloadBuilder {
8754   // Common instance state available to all overload candidate addition methods.
8755   Sema &S;
8756   ArrayRef<Expr *> Args;
8757   QualifiersAndAtomic VisibleTypeConversionsQuals;
8758   bool HasArithmeticOrEnumeralCandidateType;
8759   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8760   OverloadCandidateSet &CandidateSet;
8761 
8762   static constexpr int ArithmeticTypesCap = 24;
8763   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8764 
8765   // Define some indices used to iterate over the arithmetic types in
8766   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
8767   // types are that preserved by promotion (C++ [over.built]p2).
8768   unsigned FirstIntegralType,
8769            LastIntegralType;
8770   unsigned FirstPromotedIntegralType,
8771            LastPromotedIntegralType;
8772   unsigned FirstPromotedArithmeticType,
8773            LastPromotedArithmeticType;
8774   unsigned NumArithmeticTypes;
8775 
8776   void InitArithmeticTypes() {
8777     // Start of promoted types.
8778     FirstPromotedArithmeticType = 0;
8779     ArithmeticTypes.push_back(S.Context.FloatTy);
8780     ArithmeticTypes.push_back(S.Context.DoubleTy);
8781     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8782     if (S.Context.getTargetInfo().hasFloat128Type())
8783       ArithmeticTypes.push_back(S.Context.Float128Ty);
8784     if (S.Context.getTargetInfo().hasIbm128Type())
8785       ArithmeticTypes.push_back(S.Context.Ibm128Ty);
8786 
8787     // Start of integral types.
8788     FirstIntegralType = ArithmeticTypes.size();
8789     FirstPromotedIntegralType = ArithmeticTypes.size();
8790     ArithmeticTypes.push_back(S.Context.IntTy);
8791     ArithmeticTypes.push_back(S.Context.LongTy);
8792     ArithmeticTypes.push_back(S.Context.LongLongTy);
8793     if (S.Context.getTargetInfo().hasInt128Type() ||
8794         (S.Context.getAuxTargetInfo() &&
8795          S.Context.getAuxTargetInfo()->hasInt128Type()))
8796       ArithmeticTypes.push_back(S.Context.Int128Ty);
8797     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8798     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8799     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8800     if (S.Context.getTargetInfo().hasInt128Type() ||
8801         (S.Context.getAuxTargetInfo() &&
8802          S.Context.getAuxTargetInfo()->hasInt128Type()))
8803       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8804     LastPromotedIntegralType = ArithmeticTypes.size();
8805     LastPromotedArithmeticType = ArithmeticTypes.size();
8806     // End of promoted types.
8807 
8808     ArithmeticTypes.push_back(S.Context.BoolTy);
8809     ArithmeticTypes.push_back(S.Context.CharTy);
8810     ArithmeticTypes.push_back(S.Context.WCharTy);
8811     if (S.Context.getLangOpts().Char8)
8812       ArithmeticTypes.push_back(S.Context.Char8Ty);
8813     ArithmeticTypes.push_back(S.Context.Char16Ty);
8814     ArithmeticTypes.push_back(S.Context.Char32Ty);
8815     ArithmeticTypes.push_back(S.Context.SignedCharTy);
8816     ArithmeticTypes.push_back(S.Context.ShortTy);
8817     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8818     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8819     LastIntegralType = ArithmeticTypes.size();
8820     NumArithmeticTypes = ArithmeticTypes.size();
8821     // End of integral types.
8822     // FIXME: What about complex? What about half?
8823 
8824     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
8825            "Enough inline storage for all arithmetic types.");
8826   }
8827 
8828   /// Helper method to factor out the common pattern of adding overloads
8829   /// for '++' and '--' builtin operators.
8830   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8831                                            bool HasVolatile,
8832                                            bool HasRestrict) {
8833     QualType ParamTypes[2] = {
8834       S.Context.getLValueReferenceType(CandidateTy),
8835       S.Context.IntTy
8836     };
8837 
8838     // Non-volatile version.
8839     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8840 
8841     // Use a heuristic to reduce number of builtin candidates in the set:
8842     // add volatile version only if there are conversions to a volatile type.
8843     if (HasVolatile) {
8844       ParamTypes[0] =
8845         S.Context.getLValueReferenceType(
8846           S.Context.getVolatileType(CandidateTy));
8847       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8848     }
8849 
8850     // Add restrict version only if there are conversions to a restrict type
8851     // and our candidate type is a non-restrict-qualified pointer.
8852     if (HasRestrict && CandidateTy->isAnyPointerType() &&
8853         !CandidateTy.isRestrictQualified()) {
8854       ParamTypes[0]
8855         = S.Context.getLValueReferenceType(
8856             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8857       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8858 
8859       if (HasVolatile) {
8860         ParamTypes[0]
8861           = S.Context.getLValueReferenceType(
8862               S.Context.getCVRQualifiedType(CandidateTy,
8863                                             (Qualifiers::Volatile |
8864                                              Qualifiers::Restrict)));
8865         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8866       }
8867     }
8868 
8869   }
8870 
8871   /// Helper to add an overload candidate for a binary builtin with types \p L
8872   /// and \p R.
8873   void AddCandidate(QualType L, QualType R) {
8874     QualType LandR[2] = {L, R};
8875     S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8876   }
8877 
8878 public:
8879   BuiltinOperatorOverloadBuilder(
8880     Sema &S, ArrayRef<Expr *> Args,
8881     QualifiersAndAtomic VisibleTypeConversionsQuals,
8882     bool HasArithmeticOrEnumeralCandidateType,
8883     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8884     OverloadCandidateSet &CandidateSet)
8885     : S(S), Args(Args),
8886       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8887       HasArithmeticOrEnumeralCandidateType(
8888         HasArithmeticOrEnumeralCandidateType),
8889       CandidateTypes(CandidateTypes),
8890       CandidateSet(CandidateSet) {
8891 
8892     InitArithmeticTypes();
8893   }
8894 
8895   // Increment is deprecated for bool since C++17.
8896   //
8897   // C++ [over.built]p3:
8898   //
8899   //   For every pair (T, VQ), where T is an arithmetic type other
8900   //   than bool, and VQ is either volatile or empty, there exist
8901   //   candidate operator functions of the form
8902   //
8903   //       VQ T&      operator++(VQ T&);
8904   //       T          operator++(VQ T&, int);
8905   //
8906   // C++ [over.built]p4:
8907   //
8908   //   For every pair (T, VQ), where T is an arithmetic type other
8909   //   than bool, and VQ is either volatile or empty, there exist
8910   //   candidate operator functions of the form
8911   //
8912   //       VQ T&      operator--(VQ T&);
8913   //       T          operator--(VQ T&, int);
8914   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8915     if (!HasArithmeticOrEnumeralCandidateType)
8916       return;
8917 
8918     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8919       const auto TypeOfT = ArithmeticTypes[Arith];
8920       if (TypeOfT == S.Context.BoolTy) {
8921         if (Op == OO_MinusMinus)
8922           continue;
8923         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8924           continue;
8925       }
8926       addPlusPlusMinusMinusStyleOverloads(
8927         TypeOfT,
8928         VisibleTypeConversionsQuals.hasVolatile(),
8929         VisibleTypeConversionsQuals.hasRestrict());
8930     }
8931   }
8932 
8933   // C++ [over.built]p5:
8934   //
8935   //   For every pair (T, VQ), where T is a cv-qualified or
8936   //   cv-unqualified object type, and VQ is either volatile or
8937   //   empty, there exist candidate operator functions of the form
8938   //
8939   //       T*VQ&      operator++(T*VQ&);
8940   //       T*VQ&      operator--(T*VQ&);
8941   //       T*         operator++(T*VQ&, int);
8942   //       T*         operator--(T*VQ&, int);
8943   void addPlusPlusMinusMinusPointerOverloads() {
8944     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
8945       // Skip pointer types that aren't pointers to object types.
8946       if (!PtrTy->getPointeeType()->isObjectType())
8947         continue;
8948 
8949       addPlusPlusMinusMinusStyleOverloads(
8950           PtrTy,
8951           (!PtrTy.isVolatileQualified() &&
8952            VisibleTypeConversionsQuals.hasVolatile()),
8953           (!PtrTy.isRestrictQualified() &&
8954            VisibleTypeConversionsQuals.hasRestrict()));
8955     }
8956   }
8957 
8958   // C++ [over.built]p6:
8959   //   For every cv-qualified or cv-unqualified object type T, there
8960   //   exist candidate operator functions of the form
8961   //
8962   //       T&         operator*(T*);
8963   //
8964   // C++ [over.built]p7:
8965   //   For every function type T that does not have cv-qualifiers or a
8966   //   ref-qualifier, there exist candidate operator functions of the form
8967   //       T&         operator*(T*);
8968   void addUnaryStarPointerOverloads() {
8969     for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
8970       QualType PointeeTy = ParamTy->getPointeeType();
8971       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8972         continue;
8973 
8974       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8975         if (Proto->getMethodQuals() || Proto->getRefQualifier())
8976           continue;
8977 
8978       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8979     }
8980   }
8981 
8982   // C++ [over.built]p9:
8983   //  For every promoted arithmetic type T, there exist candidate
8984   //  operator functions of the form
8985   //
8986   //       T         operator+(T);
8987   //       T         operator-(T);
8988   void addUnaryPlusOrMinusArithmeticOverloads() {
8989     if (!HasArithmeticOrEnumeralCandidateType)
8990       return;
8991 
8992     for (unsigned Arith = FirstPromotedArithmeticType;
8993          Arith < LastPromotedArithmeticType; ++Arith) {
8994       QualType ArithTy = ArithmeticTypes[Arith];
8995       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8996     }
8997 
8998     // Extension: We also add these operators for vector types.
8999     for (QualType VecTy : CandidateTypes[0].vector_types())
9000       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9001   }
9002 
9003   // C++ [over.built]p8:
9004   //   For every type T, there exist candidate operator functions of
9005   //   the form
9006   //
9007   //       T*         operator+(T*);
9008   void addUnaryPlusPointerOverloads() {
9009     for (QualType ParamTy : CandidateTypes[0].pointer_types())
9010       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9011   }
9012 
9013   // C++ [over.built]p10:
9014   //   For every promoted integral type T, there exist candidate
9015   //   operator functions of the form
9016   //
9017   //        T         operator~(T);
9018   void addUnaryTildePromotedIntegralOverloads() {
9019     if (!HasArithmeticOrEnumeralCandidateType)
9020       return;
9021 
9022     for (unsigned Int = FirstPromotedIntegralType;
9023          Int < LastPromotedIntegralType; ++Int) {
9024       QualType IntTy = ArithmeticTypes[Int];
9025       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9026     }
9027 
9028     // Extension: We also add this operator for vector types.
9029     for (QualType VecTy : CandidateTypes[0].vector_types())
9030       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9031   }
9032 
9033   // C++ [over.match.oper]p16:
9034   //   For every pointer to member type T or type std::nullptr_t, there
9035   //   exist candidate operator functions of the form
9036   //
9037   //        bool operator==(T,T);
9038   //        bool operator!=(T,T);
9039   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9040     /// Set of (canonical) types that we've already handled.
9041     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9042 
9043     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9044       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9045         // Don't add the same builtin candidate twice.
9046         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9047           continue;
9048 
9049         QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9050         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9051       }
9052 
9053       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9054         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
9055         if (AddedTypes.insert(NullPtrTy).second) {
9056           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9057           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9058         }
9059       }
9060     }
9061   }
9062 
9063   // C++ [over.built]p15:
9064   //
9065   //   For every T, where T is an enumeration type or a pointer type,
9066   //   there exist candidate operator functions of the form
9067   //
9068   //        bool       operator<(T, T);
9069   //        bool       operator>(T, T);
9070   //        bool       operator<=(T, T);
9071   //        bool       operator>=(T, T);
9072   //        bool       operator==(T, T);
9073   //        bool       operator!=(T, T);
9074   //           R       operator<=>(T, T)
9075   void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9076     // C++ [over.match.oper]p3:
9077     //   [...]the built-in candidates include all of the candidate operator
9078     //   functions defined in 13.6 that, compared to the given operator, [...]
9079     //   do not have the same parameter-type-list as any non-template non-member
9080     //   candidate.
9081     //
9082     // Note that in practice, this only affects enumeration types because there
9083     // aren't any built-in candidates of record type, and a user-defined operator
9084     // must have an operand of record or enumeration type. Also, the only other
9085     // overloaded operator with enumeration arguments, operator=,
9086     // cannot be overloaded for enumeration types, so this is the only place
9087     // where we must suppress candidates like this.
9088     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9089       UserDefinedBinaryOperators;
9090 
9091     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9092       if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9093         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9094                                          CEnd = CandidateSet.end();
9095              C != CEnd; ++C) {
9096           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9097             continue;
9098 
9099           if (C->Function->isFunctionTemplateSpecialization())
9100             continue;
9101 
9102           // We interpret "same parameter-type-list" as applying to the
9103           // "synthesized candidate, with the order of the two parameters
9104           // reversed", not to the original function.
9105           bool Reversed = C->isReversed();
9106           QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9107                                         ->getType()
9108                                         .getUnqualifiedType();
9109           QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9110                                          ->getType()
9111                                          .getUnqualifiedType();
9112 
9113           // Skip if either parameter isn't of enumeral type.
9114           if (!FirstParamType->isEnumeralType() ||
9115               !SecondParamType->isEnumeralType())
9116             continue;
9117 
9118           // Add this operator to the set of known user-defined operators.
9119           UserDefinedBinaryOperators.insert(
9120             std::make_pair(S.Context.getCanonicalType(FirstParamType),
9121                            S.Context.getCanonicalType(SecondParamType)));
9122         }
9123       }
9124     }
9125 
9126     /// Set of (canonical) types that we've already handled.
9127     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9128 
9129     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9130       for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9131         // Don't add the same builtin candidate twice.
9132         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9133           continue;
9134         if (IsSpaceship && PtrTy->isFunctionPointerType())
9135           continue;
9136 
9137         QualType ParamTypes[2] = {PtrTy, PtrTy};
9138         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9139       }
9140       for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9141         CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9142 
9143         // Don't add the same builtin candidate twice, or if a user defined
9144         // candidate exists.
9145         if (!AddedTypes.insert(CanonType).second ||
9146             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9147                                                             CanonType)))
9148           continue;
9149         QualType ParamTypes[2] = {EnumTy, EnumTy};
9150         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9151       }
9152     }
9153   }
9154 
9155   // C++ [over.built]p13:
9156   //
9157   //   For every cv-qualified or cv-unqualified object type T
9158   //   there exist candidate operator functions of the form
9159   //
9160   //      T*         operator+(T*, ptrdiff_t);
9161   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
9162   //      T*         operator-(T*, ptrdiff_t);
9163   //      T*         operator+(ptrdiff_t, T*);
9164   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
9165   //
9166   // C++ [over.built]p14:
9167   //
9168   //   For every T, where T is a pointer to object type, there
9169   //   exist candidate operator functions of the form
9170   //
9171   //      ptrdiff_t  operator-(T, T);
9172   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9173     /// Set of (canonical) types that we've already handled.
9174     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9175 
9176     for (int Arg = 0; Arg < 2; ++Arg) {
9177       QualType AsymmetricParamTypes[2] = {
9178         S.Context.getPointerDiffType(),
9179         S.Context.getPointerDiffType(),
9180       };
9181       for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9182         QualType PointeeTy = PtrTy->getPointeeType();
9183         if (!PointeeTy->isObjectType())
9184           continue;
9185 
9186         AsymmetricParamTypes[Arg] = PtrTy;
9187         if (Arg == 0 || Op == OO_Plus) {
9188           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9189           // T* operator+(ptrdiff_t, T*);
9190           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9191         }
9192         if (Op == OO_Minus) {
9193           // ptrdiff_t operator-(T, T);
9194           if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9195             continue;
9196 
9197           QualType ParamTypes[2] = {PtrTy, PtrTy};
9198           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9199         }
9200       }
9201     }
9202   }
9203 
9204   // C++ [over.built]p12:
9205   //
9206   //   For every pair of promoted arithmetic types L and R, there
9207   //   exist candidate operator functions of the form
9208   //
9209   //        LR         operator*(L, R);
9210   //        LR         operator/(L, R);
9211   //        LR         operator+(L, R);
9212   //        LR         operator-(L, R);
9213   //        bool       operator<(L, R);
9214   //        bool       operator>(L, R);
9215   //        bool       operator<=(L, R);
9216   //        bool       operator>=(L, R);
9217   //        bool       operator==(L, R);
9218   //        bool       operator!=(L, R);
9219   //
9220   //   where LR is the result of the usual arithmetic conversions
9221   //   between types L and R.
9222   //
9223   // C++ [over.built]p24:
9224   //
9225   //   For every pair of promoted arithmetic types L and R, there exist
9226   //   candidate operator functions of the form
9227   //
9228   //        LR       operator?(bool, L, R);
9229   //
9230   //   where LR is the result of the usual arithmetic conversions
9231   //   between types L and R.
9232   // Our candidates ignore the first parameter.
9233   void addGenericBinaryArithmeticOverloads() {
9234     if (!HasArithmeticOrEnumeralCandidateType)
9235       return;
9236 
9237     for (unsigned Left = FirstPromotedArithmeticType;
9238          Left < LastPromotedArithmeticType; ++Left) {
9239       for (unsigned Right = FirstPromotedArithmeticType;
9240            Right < LastPromotedArithmeticType; ++Right) {
9241         QualType LandR[2] = { ArithmeticTypes[Left],
9242                               ArithmeticTypes[Right] };
9243         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9244       }
9245     }
9246 
9247     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9248     // conditional operator for vector types.
9249     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9250       for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9251         QualType LandR[2] = {Vec1Ty, Vec2Ty};
9252         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9253       }
9254   }
9255 
9256   /// Add binary operator overloads for each candidate matrix type M1, M2:
9257   ///  * (M1, M1) -> M1
9258   ///  * (M1, M1.getElementType()) -> M1
9259   ///  * (M2.getElementType(), M2) -> M2
9260   ///  * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9261   void addMatrixBinaryArithmeticOverloads() {
9262     if (!HasArithmeticOrEnumeralCandidateType)
9263       return;
9264 
9265     for (QualType M1 : CandidateTypes[0].matrix_types()) {
9266       AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
9267       AddCandidate(M1, M1);
9268     }
9269 
9270     for (QualType M2 : CandidateTypes[1].matrix_types()) {
9271       AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
9272       if (!CandidateTypes[0].containsMatrixType(M2))
9273         AddCandidate(M2, M2);
9274     }
9275   }
9276 
9277   // C++2a [over.built]p14:
9278   //
9279   //   For every integral type T there exists a candidate operator function
9280   //   of the form
9281   //
9282   //        std::strong_ordering operator<=>(T, T)
9283   //
9284   // C++2a [over.built]p15:
9285   //
9286   //   For every pair of floating-point types L and R, there exists a candidate
9287   //   operator function of the form
9288   //
9289   //       std::partial_ordering operator<=>(L, R);
9290   //
9291   // FIXME: The current specification for integral types doesn't play nice with
9292   // the direction of p0946r0, which allows mixed integral and unscoped-enum
9293   // comparisons. Under the current spec this can lead to ambiguity during
9294   // overload resolution. For example:
9295   //
9296   //   enum A : int {a};
9297   //   auto x = (a <=> (long)42);
9298   //
9299   //   error: call is ambiguous for arguments 'A' and 'long'.
9300   //   note: candidate operator<=>(int, int)
9301   //   note: candidate operator<=>(long, long)
9302   //
9303   // To avoid this error, this function deviates from the specification and adds
9304   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9305   // arithmetic types (the same as the generic relational overloads).
9306   //
9307   // For now this function acts as a placeholder.
9308   void addThreeWayArithmeticOverloads() {
9309     addGenericBinaryArithmeticOverloads();
9310   }
9311 
9312   // C++ [over.built]p17:
9313   //
9314   //   For every pair of promoted integral types L and R, there
9315   //   exist candidate operator functions of the form
9316   //
9317   //      LR         operator%(L, R);
9318   //      LR         operator&(L, R);
9319   //      LR         operator^(L, R);
9320   //      LR         operator|(L, R);
9321   //      L          operator<<(L, R);
9322   //      L          operator>>(L, R);
9323   //
9324   //   where LR is the result of the usual arithmetic conversions
9325   //   between types L and R.
9326   void addBinaryBitwiseArithmeticOverloads() {
9327     if (!HasArithmeticOrEnumeralCandidateType)
9328       return;
9329 
9330     for (unsigned Left = FirstPromotedIntegralType;
9331          Left < LastPromotedIntegralType; ++Left) {
9332       for (unsigned Right = FirstPromotedIntegralType;
9333            Right < LastPromotedIntegralType; ++Right) {
9334         QualType LandR[2] = { ArithmeticTypes[Left],
9335                               ArithmeticTypes[Right] };
9336         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9337       }
9338     }
9339   }
9340 
9341   // C++ [over.built]p20:
9342   //
9343   //   For every pair (T, VQ), where T is an enumeration or
9344   //   pointer to member type and VQ is either volatile or
9345   //   empty, there exist candidate operator functions of the form
9346   //
9347   //        VQ T&      operator=(VQ T&, T);
9348   void addAssignmentMemberPointerOrEnumeralOverloads() {
9349     /// Set of (canonical) types that we've already handled.
9350     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9351 
9352     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9353       for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9354         if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9355           continue;
9356 
9357         AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
9358       }
9359 
9360       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9361         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9362           continue;
9363 
9364         AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
9365       }
9366     }
9367   }
9368 
9369   // C++ [over.built]p19:
9370   //
9371   //   For every pair (T, VQ), where T is any type and VQ is either
9372   //   volatile or empty, there exist candidate operator functions
9373   //   of the form
9374   //
9375   //        T*VQ&      operator=(T*VQ&, T*);
9376   //
9377   // C++ [over.built]p21:
9378   //
9379   //   For every pair (T, VQ), where T is a cv-qualified or
9380   //   cv-unqualified object type and VQ is either volatile or
9381   //   empty, there exist candidate operator functions of the form
9382   //
9383   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
9384   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
9385   void addAssignmentPointerOverloads(bool isEqualOp) {
9386     /// Set of (canonical) types that we've already handled.
9387     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9388 
9389     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9390       // If this is operator=, keep track of the builtin candidates we added.
9391       if (isEqualOp)
9392         AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
9393       else if (!PtrTy->getPointeeType()->isObjectType())
9394         continue;
9395 
9396       // non-volatile version
9397       QualType ParamTypes[2] = {
9398           S.Context.getLValueReferenceType(PtrTy),
9399           isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9400       };
9401       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9402                             /*IsAssignmentOperator=*/ isEqualOp);
9403 
9404       bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9405                           VisibleTypeConversionsQuals.hasVolatile();
9406       if (NeedVolatile) {
9407         // volatile version
9408         ParamTypes[0] =
9409             S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy));
9410         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9411                               /*IsAssignmentOperator=*/isEqualOp);
9412       }
9413 
9414       if (!PtrTy.isRestrictQualified() &&
9415           VisibleTypeConversionsQuals.hasRestrict()) {
9416         // restrict version
9417         ParamTypes[0] =
9418             S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy));
9419         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9420                               /*IsAssignmentOperator=*/isEqualOp);
9421 
9422         if (NeedVolatile) {
9423           // volatile restrict version
9424           ParamTypes[0] =
9425               S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
9426                   PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
9427           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9428                                 /*IsAssignmentOperator=*/isEqualOp);
9429         }
9430       }
9431     }
9432 
9433     if (isEqualOp) {
9434       for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9435         // Make sure we don't add the same candidate twice.
9436         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9437           continue;
9438 
9439         QualType ParamTypes[2] = {
9440             S.Context.getLValueReferenceType(PtrTy),
9441             PtrTy,
9442         };
9443 
9444         // non-volatile version
9445         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9446                               /*IsAssignmentOperator=*/true);
9447 
9448         bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9449                             VisibleTypeConversionsQuals.hasVolatile();
9450         if (NeedVolatile) {
9451           // volatile version
9452           ParamTypes[0] = S.Context.getLValueReferenceType(
9453               S.Context.getVolatileType(PtrTy));
9454           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9455                                 /*IsAssignmentOperator=*/true);
9456         }
9457 
9458         if (!PtrTy.isRestrictQualified() &&
9459             VisibleTypeConversionsQuals.hasRestrict()) {
9460           // restrict version
9461           ParamTypes[0] = S.Context.getLValueReferenceType(
9462               S.Context.getRestrictType(PtrTy));
9463           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9464                                 /*IsAssignmentOperator=*/true);
9465 
9466           if (NeedVolatile) {
9467             // volatile restrict version
9468             ParamTypes[0] =
9469                 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
9470                     PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
9471             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9472                                   /*IsAssignmentOperator=*/true);
9473           }
9474         }
9475       }
9476     }
9477   }
9478 
9479   // C++ [over.built]p18:
9480   //
9481   //   For every triple (L, VQ, R), where L is an arithmetic type,
9482   //   VQ is either volatile or empty, and R is a promoted
9483   //   arithmetic type, there exist candidate operator functions of
9484   //   the form
9485   //
9486   //        VQ L&      operator=(VQ L&, R);
9487   //        VQ L&      operator*=(VQ L&, R);
9488   //        VQ L&      operator/=(VQ L&, R);
9489   //        VQ L&      operator+=(VQ L&, R);
9490   //        VQ L&      operator-=(VQ L&, R);
9491   void addAssignmentArithmeticOverloads(bool isEqualOp) {
9492     if (!HasArithmeticOrEnumeralCandidateType)
9493       return;
9494 
9495     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
9496       for (unsigned Right = FirstPromotedArithmeticType;
9497            Right < LastPromotedArithmeticType; ++Right) {
9498         QualType ParamTypes[2];
9499         ParamTypes[1] = ArithmeticTypes[Right];
9500         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
9501             S, ArithmeticTypes[Left], Args[0]);
9502 
9503         forAllQualifierCombinations(
9504             VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9505               ParamTypes[0] =
9506                   makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9507               S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9508                                     /*IsAssignmentOperator=*/isEqualOp);
9509             });
9510       }
9511     }
9512 
9513     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
9514     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9515       for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
9516         QualType ParamTypes[2];
9517         ParamTypes[1] = Vec2Ty;
9518         // Add this built-in operator as a candidate (VQ is empty).
9519         ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
9520         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9521                               /*IsAssignmentOperator=*/isEqualOp);
9522 
9523         // Add this built-in operator as a candidate (VQ is 'volatile').
9524         if (VisibleTypeConversionsQuals.hasVolatile()) {
9525           ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
9526           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
9527           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9528                                 /*IsAssignmentOperator=*/isEqualOp);
9529         }
9530       }
9531   }
9532 
9533   // C++ [over.built]p22:
9534   //
9535   //   For every triple (L, VQ, R), where L is an integral type, VQ
9536   //   is either volatile or empty, and R is a promoted integral
9537   //   type, there exist candidate operator functions of the form
9538   //
9539   //        VQ L&       operator%=(VQ L&, R);
9540   //        VQ L&       operator<<=(VQ L&, R);
9541   //        VQ L&       operator>>=(VQ L&, R);
9542   //        VQ L&       operator&=(VQ L&, R);
9543   //        VQ L&       operator^=(VQ L&, R);
9544   //        VQ L&       operator|=(VQ L&, R);
9545   void addAssignmentIntegralOverloads() {
9546     if (!HasArithmeticOrEnumeralCandidateType)
9547       return;
9548 
9549     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
9550       for (unsigned Right = FirstPromotedIntegralType;
9551            Right < LastPromotedIntegralType; ++Right) {
9552         QualType ParamTypes[2];
9553         ParamTypes[1] = ArithmeticTypes[Right];
9554         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
9555             S, ArithmeticTypes[Left], Args[0]);
9556 
9557         forAllQualifierCombinations(
9558             VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9559               ParamTypes[0] =
9560                   makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9561               S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9562             });
9563       }
9564     }
9565   }
9566 
9567   // C++ [over.operator]p23:
9568   //
9569   //   There also exist candidate operator functions of the form
9570   //
9571   //        bool        operator!(bool);
9572   //        bool        operator&&(bool, bool);
9573   //        bool        operator||(bool, bool);
9574   void addExclaimOverload() {
9575     QualType ParamTy = S.Context.BoolTy;
9576     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
9577                           /*IsAssignmentOperator=*/false,
9578                           /*NumContextualBoolArguments=*/1);
9579   }
9580   void addAmpAmpOrPipePipeOverload() {
9581     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
9582     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9583                           /*IsAssignmentOperator=*/false,
9584                           /*NumContextualBoolArguments=*/2);
9585   }
9586 
9587   // C++ [over.built]p13:
9588   //
9589   //   For every cv-qualified or cv-unqualified object type T there
9590   //   exist candidate operator functions of the form
9591   //
9592   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
9593   //        T&         operator[](T*, ptrdiff_t);
9594   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
9595   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
9596   //        T&         operator[](ptrdiff_t, T*);
9597   void addSubscriptOverloads() {
9598     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9599       QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
9600       QualType PointeeType = PtrTy->getPointeeType();
9601       if (!PointeeType->isObjectType())
9602         continue;
9603 
9604       // T& operator[](T*, ptrdiff_t)
9605       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9606     }
9607 
9608     for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9609       QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
9610       QualType PointeeType = PtrTy->getPointeeType();
9611       if (!PointeeType->isObjectType())
9612         continue;
9613 
9614       // T& operator[](ptrdiff_t, T*)
9615       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9616     }
9617   }
9618 
9619   // C++ [over.built]p11:
9620   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9621   //    C1 is the same type as C2 or is a derived class of C2, T is an object
9622   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9623   //    there exist candidate operator functions of the form
9624   //
9625   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9626   //
9627   //    where CV12 is the union of CV1 and CV2.
9628   void addArrowStarOverloads() {
9629     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9630       QualType C1Ty = PtrTy;
9631       QualType C1;
9632       QualifierCollector Q1;
9633       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
9634       if (!isa<RecordType>(C1))
9635         continue;
9636       // heuristic to reduce number of builtin candidates in the set.
9637       // Add volatile/restrict version only if there are conversions to a
9638       // volatile/restrict type.
9639       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9640         continue;
9641       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9642         continue;
9643       for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
9644         const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
9645         QualType C2 = QualType(mptr->getClass(), 0);
9646         C2 = C2.getUnqualifiedType();
9647         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9648           break;
9649         QualType ParamTypes[2] = {PtrTy, MemPtrTy};
9650         // build CV12 T&
9651         QualType T = mptr->getPointeeType();
9652         if (!VisibleTypeConversionsQuals.hasVolatile() &&
9653             T.isVolatileQualified())
9654           continue;
9655         if (!VisibleTypeConversionsQuals.hasRestrict() &&
9656             T.isRestrictQualified())
9657           continue;
9658         T = Q1.apply(S.Context, T);
9659         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9660       }
9661     }
9662   }
9663 
9664   // Note that we don't consider the first argument, since it has been
9665   // contextually converted to bool long ago. The candidates below are
9666   // therefore added as binary.
9667   //
9668   // C++ [over.built]p25:
9669   //   For every type T, where T is a pointer, pointer-to-member, or scoped
9670   //   enumeration type, there exist candidate operator functions of the form
9671   //
9672   //        T        operator?(bool, T, T);
9673   //
9674   void addConditionalOperatorOverloads() {
9675     /// Set of (canonical) types that we've already handled.
9676     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9677 
9678     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9679       for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9680         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9681           continue;
9682 
9683         QualType ParamTypes[2] = {PtrTy, PtrTy};
9684         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9685       }
9686 
9687       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9688         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9689           continue;
9690 
9691         QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9692         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9693       }
9694 
9695       if (S.getLangOpts().CPlusPlus11) {
9696         for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9697           if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
9698             continue;
9699 
9700           if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9701             continue;
9702 
9703           QualType ParamTypes[2] = {EnumTy, EnumTy};
9704           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9705         }
9706       }
9707     }
9708   }
9709 };
9710 
9711 } // end anonymous namespace
9712 
9713 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
9714 /// operator overloads to the candidate set (C++ [over.built]), based
9715 /// on the operator @p Op and the arguments given. For example, if the
9716 /// operator is a binary '+', this routine might add "int
9717 /// operator+(int, int)" to cover integer addition.
9718 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9719                                         SourceLocation OpLoc,
9720                                         ArrayRef<Expr *> Args,
9721                                         OverloadCandidateSet &CandidateSet) {
9722   // Find all of the types that the arguments can convert to, but only
9723   // if the operator we're looking at has built-in operator candidates
9724   // that make use of these types. Also record whether we encounter non-record
9725   // candidate types or either arithmetic or enumeral candidate types.
9726   QualifiersAndAtomic VisibleTypeConversionsQuals;
9727   VisibleTypeConversionsQuals.addConst();
9728   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9729     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9730     if (Args[ArgIdx]->getType()->isAtomicType())
9731       VisibleTypeConversionsQuals.addAtomic();
9732   }
9733 
9734   bool HasNonRecordCandidateType = false;
9735   bool HasArithmeticOrEnumeralCandidateType = false;
9736   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9737   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9738     CandidateTypes.emplace_back(*this);
9739     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9740                                                  OpLoc,
9741                                                  true,
9742                                                  (Op == OO_Exclaim ||
9743                                                   Op == OO_AmpAmp ||
9744                                                   Op == OO_PipePipe),
9745                                                  VisibleTypeConversionsQuals);
9746     HasNonRecordCandidateType = HasNonRecordCandidateType ||
9747         CandidateTypes[ArgIdx].hasNonRecordTypes();
9748     HasArithmeticOrEnumeralCandidateType =
9749         HasArithmeticOrEnumeralCandidateType ||
9750         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9751   }
9752 
9753   // Exit early when no non-record types have been added to the candidate set
9754   // for any of the arguments to the operator.
9755   //
9756   // We can't exit early for !, ||, or &&, since there we have always have
9757   // 'bool' overloads.
9758   if (!HasNonRecordCandidateType &&
9759       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9760     return;
9761 
9762   // Setup an object to manage the common state for building overloads.
9763   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9764                                            VisibleTypeConversionsQuals,
9765                                            HasArithmeticOrEnumeralCandidateType,
9766                                            CandidateTypes, CandidateSet);
9767 
9768   // Dispatch over the operation to add in only those overloads which apply.
9769   switch (Op) {
9770   case OO_None:
9771   case NUM_OVERLOADED_OPERATORS:
9772     llvm_unreachable("Expected an overloaded operator");
9773 
9774   case OO_New:
9775   case OO_Delete:
9776   case OO_Array_New:
9777   case OO_Array_Delete:
9778   case OO_Call:
9779     llvm_unreachable(
9780                     "Special operators don't use AddBuiltinOperatorCandidates");
9781 
9782   case OO_Comma:
9783   case OO_Arrow:
9784   case OO_Coawait:
9785     // C++ [over.match.oper]p3:
9786     //   -- For the operator ',', the unary operator '&', the
9787     //      operator '->', or the operator 'co_await', the
9788     //      built-in candidates set is empty.
9789     break;
9790 
9791   case OO_Plus: // '+' is either unary or binary
9792     if (Args.size() == 1)
9793       OpBuilder.addUnaryPlusPointerOverloads();
9794     [[fallthrough]];
9795 
9796   case OO_Minus: // '-' is either unary or binary
9797     if (Args.size() == 1) {
9798       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9799     } else {
9800       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9801       OpBuilder.addGenericBinaryArithmeticOverloads();
9802       OpBuilder.addMatrixBinaryArithmeticOverloads();
9803     }
9804     break;
9805 
9806   case OO_Star: // '*' is either unary or binary
9807     if (Args.size() == 1)
9808       OpBuilder.addUnaryStarPointerOverloads();
9809     else {
9810       OpBuilder.addGenericBinaryArithmeticOverloads();
9811       OpBuilder.addMatrixBinaryArithmeticOverloads();
9812     }
9813     break;
9814 
9815   case OO_Slash:
9816     OpBuilder.addGenericBinaryArithmeticOverloads();
9817     break;
9818 
9819   case OO_PlusPlus:
9820   case OO_MinusMinus:
9821     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9822     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9823     break;
9824 
9825   case OO_EqualEqual:
9826   case OO_ExclaimEqual:
9827     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9828     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9829     OpBuilder.addGenericBinaryArithmeticOverloads();
9830     break;
9831 
9832   case OO_Less:
9833   case OO_Greater:
9834   case OO_LessEqual:
9835   case OO_GreaterEqual:
9836     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9837     OpBuilder.addGenericBinaryArithmeticOverloads();
9838     break;
9839 
9840   case OO_Spaceship:
9841     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
9842     OpBuilder.addThreeWayArithmeticOverloads();
9843     break;
9844 
9845   case OO_Percent:
9846   case OO_Caret:
9847   case OO_Pipe:
9848   case OO_LessLess:
9849   case OO_GreaterGreater:
9850     OpBuilder.addBinaryBitwiseArithmeticOverloads();
9851     break;
9852 
9853   case OO_Amp: // '&' is either unary or binary
9854     if (Args.size() == 1)
9855       // C++ [over.match.oper]p3:
9856       //   -- For the operator ',', the unary operator '&', or the
9857       //      operator '->', the built-in candidates set is empty.
9858       break;
9859 
9860     OpBuilder.addBinaryBitwiseArithmeticOverloads();
9861     break;
9862 
9863   case OO_Tilde:
9864     OpBuilder.addUnaryTildePromotedIntegralOverloads();
9865     break;
9866 
9867   case OO_Equal:
9868     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9869     [[fallthrough]];
9870 
9871   case OO_PlusEqual:
9872   case OO_MinusEqual:
9873     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9874     [[fallthrough]];
9875 
9876   case OO_StarEqual:
9877   case OO_SlashEqual:
9878     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9879     break;
9880 
9881   case OO_PercentEqual:
9882   case OO_LessLessEqual:
9883   case OO_GreaterGreaterEqual:
9884   case OO_AmpEqual:
9885   case OO_CaretEqual:
9886   case OO_PipeEqual:
9887     OpBuilder.addAssignmentIntegralOverloads();
9888     break;
9889 
9890   case OO_Exclaim:
9891     OpBuilder.addExclaimOverload();
9892     break;
9893 
9894   case OO_AmpAmp:
9895   case OO_PipePipe:
9896     OpBuilder.addAmpAmpOrPipePipeOverload();
9897     break;
9898 
9899   case OO_Subscript:
9900     if (Args.size() == 2)
9901       OpBuilder.addSubscriptOverloads();
9902     break;
9903 
9904   case OO_ArrowStar:
9905     OpBuilder.addArrowStarOverloads();
9906     break;
9907 
9908   case OO_Conditional:
9909     OpBuilder.addConditionalOperatorOverloads();
9910     OpBuilder.addGenericBinaryArithmeticOverloads();
9911     break;
9912   }
9913 }
9914 
9915 /// Add function candidates found via argument-dependent lookup
9916 /// to the set of overloading candidates.
9917 ///
9918 /// This routine performs argument-dependent name lookup based on the
9919 /// given function name (which may also be an operator name) and adds
9920 /// all of the overload candidates found by ADL to the overload
9921 /// candidate set (C++ [basic.lookup.argdep]).
9922 void
9923 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9924                                            SourceLocation Loc,
9925                                            ArrayRef<Expr *> Args,
9926                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
9927                                            OverloadCandidateSet& CandidateSet,
9928                                            bool PartialOverloading) {
9929   ADLResult Fns;
9930 
9931   // FIXME: This approach for uniquing ADL results (and removing
9932   // redundant candidates from the set) relies on pointer-equality,
9933   // which means we need to key off the canonical decl.  However,
9934   // always going back to the canonical decl might not get us the
9935   // right set of default arguments.  What default arguments are
9936   // we supposed to consider on ADL candidates, anyway?
9937 
9938   // FIXME: Pass in the explicit template arguments?
9939   ArgumentDependentLookup(Name, Loc, Args, Fns);
9940 
9941   // Erase all of the candidates we already knew about.
9942   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9943                                    CandEnd = CandidateSet.end();
9944        Cand != CandEnd; ++Cand)
9945     if (Cand->Function) {
9946       Fns.erase(Cand->Function);
9947       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9948         Fns.erase(FunTmpl);
9949     }
9950 
9951   // For each of the ADL candidates we found, add it to the overload
9952   // set.
9953   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9954     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9955 
9956     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9957       if (ExplicitTemplateArgs)
9958         continue;
9959 
9960       AddOverloadCandidate(
9961           FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
9962           PartialOverloading, /*AllowExplicit=*/true,
9963           /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
9964       if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
9965         AddOverloadCandidate(
9966             FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
9967             /*SuppressUserConversions=*/false, PartialOverloading,
9968             /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
9969             ADLCallKind::UsesADL, std::nullopt,
9970             OverloadCandidateParamOrder::Reversed);
9971       }
9972     } else {
9973       auto *FTD = cast<FunctionTemplateDecl>(*I);
9974       AddTemplateOverloadCandidate(
9975           FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
9976           /*SuppressUserConversions=*/false, PartialOverloading,
9977           /*AllowExplicit=*/true, ADLCallKind::UsesADL);
9978       if (CandidateSet.getRewriteInfo().shouldAddReversed(
9979               *this, Args, FTD->getTemplatedDecl())) {
9980         AddTemplateOverloadCandidate(
9981             FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
9982             CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
9983             /*AllowExplicit=*/true, ADLCallKind::UsesADL,
9984             OverloadCandidateParamOrder::Reversed);
9985       }
9986     }
9987   }
9988 }
9989 
9990 namespace {
9991 enum class Comparison { Equal, Better, Worse };
9992 }
9993 
9994 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9995 /// overload resolution.
9996 ///
9997 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9998 /// Cand1's first N enable_if attributes have precisely the same conditions as
9999 /// Cand2's first N enable_if attributes (where N = the number of enable_if
10000 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10001 ///
10002 /// Note that you can have a pair of candidates such that Cand1's enable_if
10003 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10004 /// worse than Cand1's.
10005 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10006                                        const FunctionDecl *Cand2) {
10007   // Common case: One (or both) decls don't have enable_if attrs.
10008   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10009   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10010   if (!Cand1Attr || !Cand2Attr) {
10011     if (Cand1Attr == Cand2Attr)
10012       return Comparison::Equal;
10013     return Cand1Attr ? Comparison::Better : Comparison::Worse;
10014   }
10015 
10016   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10017   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10018 
10019   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10020   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10021     std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10022     std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10023 
10024     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10025     // has fewer enable_if attributes than Cand2, and vice versa.
10026     if (!Cand1A)
10027       return Comparison::Worse;
10028     if (!Cand2A)
10029       return Comparison::Better;
10030 
10031     Cand1ID.clear();
10032     Cand2ID.clear();
10033 
10034     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10035     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10036     if (Cand1ID != Cand2ID)
10037       return Comparison::Worse;
10038   }
10039 
10040   return Comparison::Equal;
10041 }
10042 
10043 static Comparison
10044 isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
10045                               const OverloadCandidate &Cand2) {
10046   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10047       !Cand2.Function->isMultiVersion())
10048     return Comparison::Equal;
10049 
10050   // If both are invalid, they are equal. If one of them is invalid, the other
10051   // is better.
10052   if (Cand1.Function->isInvalidDecl()) {
10053     if (Cand2.Function->isInvalidDecl())
10054       return Comparison::Equal;
10055     return Comparison::Worse;
10056   }
10057   if (Cand2.Function->isInvalidDecl())
10058     return Comparison::Better;
10059 
10060   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10061   // cpu_dispatch, else arbitrarily based on the identifiers.
10062   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10063   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10064   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10065   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10066 
10067   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10068     return Comparison::Equal;
10069 
10070   if (Cand1CPUDisp && !Cand2CPUDisp)
10071     return Comparison::Better;
10072   if (Cand2CPUDisp && !Cand1CPUDisp)
10073     return Comparison::Worse;
10074 
10075   if (Cand1CPUSpec && Cand2CPUSpec) {
10076     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10077       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10078                  ? Comparison::Better
10079                  : Comparison::Worse;
10080 
10081     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10082         FirstDiff = std::mismatch(
10083             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10084             Cand2CPUSpec->cpus_begin(),
10085             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10086               return LHS->getName() == RHS->getName();
10087             });
10088 
10089     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10090            "Two different cpu-specific versions should not have the same "
10091            "identifier list, otherwise they'd be the same decl!");
10092     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10093                ? Comparison::Better
10094                : Comparison::Worse;
10095   }
10096   llvm_unreachable("No way to get here unless both had cpu_dispatch");
10097 }
10098 
10099 /// Compute the type of the implicit object parameter for the given function,
10100 /// if any. Returns std::nullopt if there is no implicit object parameter, and a
10101 /// null QualType if there is a 'matches anything' implicit object parameter.
10102 static std::optional<QualType>
10103 getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F) {
10104   if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
10105     return std::nullopt;
10106 
10107   auto *M = cast<CXXMethodDecl>(F);
10108   // Static member functions' object parameters match all types.
10109   if (M->isStatic())
10110     return QualType();
10111   return M->getFunctionObjectParameterReferenceType();
10112 }
10113 
10114 static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1,
10115                                    const FunctionDecl *F2) {
10116   if (declaresSameEntity(F1, F2))
10117     return true;
10118 
10119   auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10120     if (First) {
10121       if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10122         return *T;
10123     }
10124     assert(I < F->getNumParams());
10125     return F->getParamDecl(I++)->getType();
10126   };
10127 
10128   unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10129   unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10130 
10131   if (F1NumParams != F2NumParams)
10132     return false;
10133 
10134   unsigned I1 = 0, I2 = 0;
10135   for (unsigned I = 0; I != F1NumParams; ++I) {
10136     QualType T1 = NextParam(F1, I1, I == 0);
10137     QualType T2 = NextParam(F2, I2, I == 0);
10138     assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10139     if (!Context.hasSameUnqualifiedType(T1, T2))
10140       return false;
10141   }
10142   return true;
10143 }
10144 
10145 /// We're allowed to use constraints partial ordering only if the candidates
10146 /// have the same parameter types:
10147 /// [over.match.best.general]p2.6
10148 /// F1 and F2 are non-template functions with the same
10149 /// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10150 static bool sameFunctionParameterTypeLists(Sema &S,
10151                                            const OverloadCandidate &Cand1,
10152                                            const OverloadCandidate &Cand2) {
10153   if (!Cand1.Function || !Cand2.Function)
10154     return false;
10155 
10156   FunctionDecl *Fn1 = Cand1.Function;
10157   FunctionDecl *Fn2 = Cand2.Function;
10158 
10159   if (Fn1->isVariadic() != Fn1->isVariadic())
10160     return false;
10161 
10162   if (!S.FunctionNonObjectParamTypesAreEqual(
10163           Fn1, Fn2, nullptr, Cand1.isReversed() ^ Cand2.isReversed()))
10164     return false;
10165 
10166   auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10167   auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10168   if (Mem1 && Mem2) {
10169     // if they are member functions, both are direct members of the same class,
10170     // and
10171     if (Mem1->getParent() != Mem2->getParent())
10172       return false;
10173     // if both are non-static member functions, they have the same types for
10174     // their object parameters
10175     if (Mem1->isInstance() && Mem2->isInstance() &&
10176         !S.getASTContext().hasSameType(
10177             Mem1->getFunctionObjectParameterReferenceType(),
10178             Mem1->getFunctionObjectParameterReferenceType()))
10179       return false;
10180   }
10181   return true;
10182 }
10183 
10184 /// isBetterOverloadCandidate - Determines whether the first overload
10185 /// candidate is a better candidate than the second (C++ 13.3.3p1).
10186 bool clang::isBetterOverloadCandidate(
10187     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10188     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
10189   // Define viable functions to be better candidates than non-viable
10190   // functions.
10191   if (!Cand2.Viable)
10192     return Cand1.Viable;
10193   else if (!Cand1.Viable)
10194     return false;
10195 
10196   // [CUDA] A function with 'never' preference is marked not viable, therefore
10197   // is never shown up here. The worst preference shown up here is 'wrong side',
10198   // e.g. an H function called by a HD function in device compilation. This is
10199   // valid AST as long as the HD function is not emitted, e.g. it is an inline
10200   // function which is called only by an H function. A deferred diagnostic will
10201   // be triggered if it is emitted. However a wrong-sided function is still
10202   // a viable candidate here.
10203   //
10204   // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10205   // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10206   // can be emitted, Cand1 is not better than Cand2. This rule should have
10207   // precedence over other rules.
10208   //
10209   // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10210   // other rules should be used to determine which is better. This is because
10211   // host/device based overloading resolution is mostly for determining
10212   // viability of a function. If two functions are both viable, other factors
10213   // should take precedence in preference, e.g. the standard-defined preferences
10214   // like argument conversion ranks or enable_if partial-ordering. The
10215   // preference for pass-object-size parameters is probably most similar to a
10216   // type-based-overloading decision and so should take priority.
10217   //
10218   // If other rules cannot determine which is better, CUDA preference will be
10219   // used again to determine which is better.
10220   //
10221   // TODO: Currently IdentifyCUDAPreference does not return correct values
10222   // for functions called in global variable initializers due to missing
10223   // correct context about device/host. Therefore we can only enforce this
10224   // rule when there is a caller. We should enforce this rule for functions
10225   // in global variable initializers once proper context is added.
10226   //
10227   // TODO: We can only enable the hostness based overloading resolution when
10228   // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10229   // overloading resolution diagnostics.
10230   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10231       S.getLangOpts().GPUExcludeWrongSideOverloads) {
10232     if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10233       bool IsCallerImplicitHD = Sema::isCUDAImplicitHostDeviceFunction(Caller);
10234       bool IsCand1ImplicitHD =
10235           Sema::isCUDAImplicitHostDeviceFunction(Cand1.Function);
10236       bool IsCand2ImplicitHD =
10237           Sema::isCUDAImplicitHostDeviceFunction(Cand2.Function);
10238       auto P1 = S.IdentifyCUDAPreference(Caller, Cand1.Function);
10239       auto P2 = S.IdentifyCUDAPreference(Caller, Cand2.Function);
10240       assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never);
10241       // The implicit HD function may be a function in a system header which
10242       // is forced by pragma. In device compilation, if we prefer HD candidates
10243       // over wrong-sided candidates, overloading resolution may change, which
10244       // may result in non-deferrable diagnostics. As a workaround, we let
10245       // implicit HD candidates take equal preference as wrong-sided candidates.
10246       // This will preserve the overloading resolution.
10247       // TODO: We still need special handling of implicit HD functions since
10248       // they may incur other diagnostics to be deferred. We should make all
10249       // host/device related diagnostics deferrable and remove special handling
10250       // of implicit HD functions.
10251       auto EmitThreshold =
10252           (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
10253            (IsCand1ImplicitHD || IsCand2ImplicitHD))
10254               ? Sema::CFP_Never
10255               : Sema::CFP_WrongSide;
10256       auto Cand1Emittable = P1 > EmitThreshold;
10257       auto Cand2Emittable = P2 > EmitThreshold;
10258       if (Cand1Emittable && !Cand2Emittable)
10259         return true;
10260       if (!Cand1Emittable && Cand2Emittable)
10261         return false;
10262     }
10263   }
10264 
10265   // C++ [over.match.best]p1: (Changed in C++23)
10266   //
10267   //   -- if F is a static member function, ICS1(F) is defined such
10268   //      that ICS1(F) is neither better nor worse than ICS1(G) for
10269   //      any function G, and, symmetrically, ICS1(G) is neither
10270   //      better nor worse than ICS1(F).
10271   unsigned StartArg = 0;
10272   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
10273     StartArg = 1;
10274 
10275   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
10276     // We don't allow incompatible pointer conversions in C++.
10277     if (!S.getLangOpts().CPlusPlus)
10278       return ICS.isStandard() &&
10279              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
10280 
10281     // The only ill-formed conversion we allow in C++ is the string literal to
10282     // char* conversion, which is only considered ill-formed after C++11.
10283     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
10284            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
10285   };
10286 
10287   // Define functions that don't require ill-formed conversions for a given
10288   // argument to be better candidates than functions that do.
10289   unsigned NumArgs = Cand1.Conversions.size();
10290   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
10291   bool HasBetterConversion = false;
10292   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10293     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
10294     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
10295     if (Cand1Bad != Cand2Bad) {
10296       if (Cand1Bad)
10297         return false;
10298       HasBetterConversion = true;
10299     }
10300   }
10301 
10302   if (HasBetterConversion)
10303     return true;
10304 
10305   // C++ [over.match.best]p1:
10306   //   A viable function F1 is defined to be a better function than another
10307   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
10308   //   conversion sequence than ICSi(F2), and then...
10309   bool HasWorseConversion = false;
10310   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10311     switch (CompareImplicitConversionSequences(S, Loc,
10312                                                Cand1.Conversions[ArgIdx],
10313                                                Cand2.Conversions[ArgIdx])) {
10314     case ImplicitConversionSequence::Better:
10315       // Cand1 has a better conversion sequence.
10316       HasBetterConversion = true;
10317       break;
10318 
10319     case ImplicitConversionSequence::Worse:
10320       if (Cand1.Function && Cand2.Function &&
10321           Cand1.isReversed() != Cand2.isReversed() &&
10322           haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function)) {
10323         // Work around large-scale breakage caused by considering reversed
10324         // forms of operator== in C++20:
10325         //
10326         // When comparing a function against a reversed function with the same
10327         // parameter types, if we have a better conversion for one argument and
10328         // a worse conversion for the other, the implicit conversion sequences
10329         // are treated as being equally good.
10330         //
10331         // This prevents a comparison function from being considered ambiguous
10332         // with a reversed form that is written in the same way.
10333         //
10334         // We diagnose this as an extension from CreateOverloadedBinOp.
10335         HasWorseConversion = true;
10336         break;
10337       }
10338 
10339       // Cand1 can't be better than Cand2.
10340       return false;
10341 
10342     case ImplicitConversionSequence::Indistinguishable:
10343       // Do nothing.
10344       break;
10345     }
10346   }
10347 
10348   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
10349   //       ICSj(F2), or, if not that,
10350   if (HasBetterConversion && !HasWorseConversion)
10351     return true;
10352 
10353   //   -- the context is an initialization by user-defined conversion
10354   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
10355   //      from the return type of F1 to the destination type (i.e.,
10356   //      the type of the entity being initialized) is a better
10357   //      conversion sequence than the standard conversion sequence
10358   //      from the return type of F2 to the destination type.
10359   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
10360       Cand1.Function && Cand2.Function &&
10361       isa<CXXConversionDecl>(Cand1.Function) &&
10362       isa<CXXConversionDecl>(Cand2.Function)) {
10363     // First check whether we prefer one of the conversion functions over the
10364     // other. This only distinguishes the results in non-standard, extension
10365     // cases such as the conversion from a lambda closure type to a function
10366     // pointer or block.
10367     ImplicitConversionSequence::CompareKind Result =
10368         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
10369     if (Result == ImplicitConversionSequence::Indistinguishable)
10370       Result = CompareStandardConversionSequences(S, Loc,
10371                                                   Cand1.FinalConversion,
10372                                                   Cand2.FinalConversion);
10373 
10374     if (Result != ImplicitConversionSequence::Indistinguishable)
10375       return Result == ImplicitConversionSequence::Better;
10376 
10377     // FIXME: Compare kind of reference binding if conversion functions
10378     // convert to a reference type used in direct reference binding, per
10379     // C++14 [over.match.best]p1 section 2 bullet 3.
10380   }
10381 
10382   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
10383   // as combined with the resolution to CWG issue 243.
10384   //
10385   // When the context is initialization by constructor ([over.match.ctor] or
10386   // either phase of [over.match.list]), a constructor is preferred over
10387   // a conversion function.
10388   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
10389       Cand1.Function && Cand2.Function &&
10390       isa<CXXConstructorDecl>(Cand1.Function) !=
10391           isa<CXXConstructorDecl>(Cand2.Function))
10392     return isa<CXXConstructorDecl>(Cand1.Function);
10393 
10394   //    -- F1 is a non-template function and F2 is a function template
10395   //       specialization, or, if not that,
10396   bool Cand1IsSpecialization = Cand1.Function &&
10397                                Cand1.Function->getPrimaryTemplate();
10398   bool Cand2IsSpecialization = Cand2.Function &&
10399                                Cand2.Function->getPrimaryTemplate();
10400   if (Cand1IsSpecialization != Cand2IsSpecialization)
10401     return Cand2IsSpecialization;
10402 
10403   //   -- F1 and F2 are function template specializations, and the function
10404   //      template for F1 is more specialized than the template for F2
10405   //      according to the partial ordering rules described in 14.5.5.2, or,
10406   //      if not that,
10407   if (Cand1IsSpecialization && Cand2IsSpecialization) {
10408     if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
10409             Cand1.Function->getPrimaryTemplate(),
10410             Cand2.Function->getPrimaryTemplate(), Loc,
10411             isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
10412                                                    : TPOC_Call,
10413             Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments,
10414             Cand1.isReversed() ^ Cand2.isReversed()))
10415       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
10416   }
10417 
10418   //   -— F1 and F2 are non-template functions with the same
10419   //      parameter-type-lists, and F1 is more constrained than F2 [...],
10420   if (!Cand1IsSpecialization && !Cand2IsSpecialization &&
10421       sameFunctionParameterTypeLists(S, Cand1, Cand2)) {
10422     FunctionDecl *Function1 = Cand1.Function;
10423     FunctionDecl *Function2 = Cand2.Function;
10424     if (FunctionDecl *MF = Function1->getInstantiatedFromMemberFunction())
10425       Function1 = MF;
10426     if (FunctionDecl *MF = Function2->getInstantiatedFromMemberFunction())
10427       Function2 = MF;
10428 
10429     const Expr *RC1 = Function1->getTrailingRequiresClause();
10430     const Expr *RC2 = Function2->getTrailingRequiresClause();
10431     if (RC1 && RC2) {
10432       bool AtLeastAsConstrained1, AtLeastAsConstrained2;
10433       if (S.IsAtLeastAsConstrained(Function1, RC1, Function2, RC2,
10434                                    AtLeastAsConstrained1) ||
10435           S.IsAtLeastAsConstrained(Function2, RC2, Function1, RC1,
10436                                    AtLeastAsConstrained2))
10437         return false;
10438       if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
10439         return AtLeastAsConstrained1;
10440     } else if (RC1 || RC2) {
10441       return RC1 != nullptr;
10442     }
10443   }
10444 
10445   //   -- F1 is a constructor for a class D, F2 is a constructor for a base
10446   //      class B of D, and for all arguments the corresponding parameters of
10447   //      F1 and F2 have the same type.
10448   // FIXME: Implement the "all parameters have the same type" check.
10449   bool Cand1IsInherited =
10450       isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
10451   bool Cand2IsInherited =
10452       isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
10453   if (Cand1IsInherited != Cand2IsInherited)
10454     return Cand2IsInherited;
10455   else if (Cand1IsInherited) {
10456     assert(Cand2IsInherited);
10457     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
10458     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
10459     if (Cand1Class->isDerivedFrom(Cand2Class))
10460       return true;
10461     if (Cand2Class->isDerivedFrom(Cand1Class))
10462       return false;
10463     // Inherited from sibling base classes: still ambiguous.
10464   }
10465 
10466   //   -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
10467   //   -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
10468   //      with reversed order of parameters and F1 is not
10469   //
10470   // We rank reversed + different operator as worse than just reversed, but
10471   // that comparison can never happen, because we only consider reversing for
10472   // the maximally-rewritten operator (== or <=>).
10473   if (Cand1.RewriteKind != Cand2.RewriteKind)
10474     return Cand1.RewriteKind < Cand2.RewriteKind;
10475 
10476   // Check C++17 tie-breakers for deduction guides.
10477   {
10478     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
10479     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
10480     if (Guide1 && Guide2) {
10481       //  -- F1 is generated from a deduction-guide and F2 is not
10482       if (Guide1->isImplicit() != Guide2->isImplicit())
10483         return Guide2->isImplicit();
10484 
10485       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
10486       if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
10487         return true;
10488       if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
10489         return false;
10490 
10491       //  --F1 is generated from a non-template constructor and F2 is generated
10492       //  from a constructor template
10493       const auto *Constructor1 = Guide1->getCorrespondingConstructor();
10494       const auto *Constructor2 = Guide2->getCorrespondingConstructor();
10495       if (Constructor1 && Constructor2) {
10496         bool isC1Templated = Constructor1->getTemplatedKind() !=
10497                              FunctionDecl::TemplatedKind::TK_NonTemplate;
10498         bool isC2Templated = Constructor2->getTemplatedKind() !=
10499                              FunctionDecl::TemplatedKind::TK_NonTemplate;
10500         if (isC1Templated != isC2Templated)
10501           return isC2Templated;
10502       }
10503     }
10504   }
10505 
10506   // Check for enable_if value-based overload resolution.
10507   if (Cand1.Function && Cand2.Function) {
10508     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
10509     if (Cmp != Comparison::Equal)
10510       return Cmp == Comparison::Better;
10511   }
10512 
10513   bool HasPS1 = Cand1.Function != nullptr &&
10514                 functionHasPassObjectSizeParams(Cand1.Function);
10515   bool HasPS2 = Cand2.Function != nullptr &&
10516                 functionHasPassObjectSizeParams(Cand2.Function);
10517   if (HasPS1 != HasPS2 && HasPS1)
10518     return true;
10519 
10520   auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
10521   if (MV == Comparison::Better)
10522     return true;
10523   if (MV == Comparison::Worse)
10524     return false;
10525 
10526   // If other rules cannot determine which is better, CUDA preference is used
10527   // to determine which is better.
10528   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
10529     FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10530     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
10531            S.IdentifyCUDAPreference(Caller, Cand2.Function);
10532   }
10533 
10534   // General member function overloading is handled above, so this only handles
10535   // constructors with address spaces.
10536   // This only handles address spaces since C++ has no other
10537   // qualifier that can be used with constructors.
10538   const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
10539   const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
10540   if (CD1 && CD2) {
10541     LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
10542     LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
10543     if (AS1 != AS2) {
10544       if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
10545         return true;
10546       if (Qualifiers::isAddressSpaceSupersetOf(AS1, AS2))
10547         return false;
10548     }
10549   }
10550 
10551   return false;
10552 }
10553 
10554 /// Determine whether two declarations are "equivalent" for the purposes of
10555 /// name lookup and overload resolution. This applies when the same internal/no
10556 /// linkage entity is defined by two modules (probably by textually including
10557 /// the same header). In such a case, we don't consider the declarations to
10558 /// declare the same entity, but we also don't want lookups with both
10559 /// declarations visible to be ambiguous in some cases (this happens when using
10560 /// a modularized libstdc++).
10561 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
10562                                                   const NamedDecl *B) {
10563   auto *VA = dyn_cast_or_null<ValueDecl>(A);
10564   auto *VB = dyn_cast_or_null<ValueDecl>(B);
10565   if (!VA || !VB)
10566     return false;
10567 
10568   // The declarations must be declaring the same name as an internal linkage
10569   // entity in different modules.
10570   if (!VA->getDeclContext()->getRedeclContext()->Equals(
10571           VB->getDeclContext()->getRedeclContext()) ||
10572       getOwningModule(VA) == getOwningModule(VB) ||
10573       VA->isExternallyVisible() || VB->isExternallyVisible())
10574     return false;
10575 
10576   // Check that the declarations appear to be equivalent.
10577   //
10578   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
10579   // For constants and functions, we should check the initializer or body is
10580   // the same. For non-constant variables, we shouldn't allow it at all.
10581   if (Context.hasSameType(VA->getType(), VB->getType()))
10582     return true;
10583 
10584   // Enum constants within unnamed enumerations will have different types, but
10585   // may still be similar enough to be interchangeable for our purposes.
10586   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
10587     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
10588       // Only handle anonymous enums. If the enumerations were named and
10589       // equivalent, they would have been merged to the same type.
10590       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
10591       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
10592       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
10593           !Context.hasSameType(EnumA->getIntegerType(),
10594                                EnumB->getIntegerType()))
10595         return false;
10596       // Allow this only if the value is the same for both enumerators.
10597       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
10598     }
10599   }
10600 
10601   // Nothing else is sufficiently similar.
10602   return false;
10603 }
10604 
10605 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
10606     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
10607   assert(D && "Unknown declaration");
10608   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
10609 
10610   Module *M = getOwningModule(D);
10611   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
10612       << !M << (M ? M->getFullModuleName() : "");
10613 
10614   for (auto *E : Equiv) {
10615     Module *M = getOwningModule(E);
10616     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
10617         << !M << (M ? M->getFullModuleName() : "");
10618   }
10619 }
10620 
10621 bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const {
10622   return FailureKind == ovl_fail_bad_deduction &&
10623          DeductionFailure.Result == Sema::TDK_ConstraintsNotSatisfied &&
10624          static_cast<CNSInfo *>(DeductionFailure.Data)
10625              ->Satisfaction.ContainsErrors;
10626 }
10627 
10628 /// Computes the best viable function (C++ 13.3.3)
10629 /// within an overload candidate set.
10630 ///
10631 /// \param Loc The location of the function name (or operator symbol) for
10632 /// which overload resolution occurs.
10633 ///
10634 /// \param Best If overload resolution was successful or found a deleted
10635 /// function, \p Best points to the candidate function found.
10636 ///
10637 /// \returns The result of overload resolution.
10638 OverloadingResult
10639 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
10640                                          iterator &Best) {
10641   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
10642   std::transform(begin(), end(), std::back_inserter(Candidates),
10643                  [](OverloadCandidate &Cand) { return &Cand; });
10644 
10645   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
10646   // are accepted by both clang and NVCC. However, during a particular
10647   // compilation mode only one call variant is viable. We need to
10648   // exclude non-viable overload candidates from consideration based
10649   // only on their host/device attributes. Specifically, if one
10650   // candidate call is WrongSide and the other is SameSide, we ignore
10651   // the WrongSide candidate.
10652   // We only need to remove wrong-sided candidates here if
10653   // -fgpu-exclude-wrong-side-overloads is off. When
10654   // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
10655   // uniformly in isBetterOverloadCandidate.
10656   if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) {
10657     const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10658     bool ContainsSameSideCandidate =
10659         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
10660           // Check viable function only.
10661           return Cand->Viable && Cand->Function &&
10662                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
10663                      Sema::CFP_SameSide;
10664         });
10665     if (ContainsSameSideCandidate) {
10666       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
10667         // Check viable function only to avoid unnecessary data copying/moving.
10668         return Cand->Viable && Cand->Function &&
10669                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
10670                    Sema::CFP_WrongSide;
10671       };
10672       llvm::erase_if(Candidates, IsWrongSideCandidate);
10673     }
10674   }
10675 
10676   // Find the best viable function.
10677   Best = end();
10678   for (auto *Cand : Candidates) {
10679     Cand->Best = false;
10680     if (Cand->Viable) {
10681       if (Best == end() ||
10682           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
10683         Best = Cand;
10684     } else if (Cand->NotValidBecauseConstraintExprHasError()) {
10685       // This candidate has constraint that we were unable to evaluate because
10686       // it referenced an expression that contained an error. Rather than fall
10687       // back onto a potentially unintended candidate (made worse by
10688       // subsuming constraints), treat this as 'no viable candidate'.
10689       Best = end();
10690       return OR_No_Viable_Function;
10691     }
10692   }
10693 
10694   // If we didn't find any viable functions, abort.
10695   if (Best == end())
10696     return OR_No_Viable_Function;
10697 
10698   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
10699 
10700   llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
10701   PendingBest.push_back(&*Best);
10702   Best->Best = true;
10703 
10704   // Make sure that this function is better than every other viable
10705   // function. If not, we have an ambiguity.
10706   while (!PendingBest.empty()) {
10707     auto *Curr = PendingBest.pop_back_val();
10708     for (auto *Cand : Candidates) {
10709       if (Cand->Viable && !Cand->Best &&
10710           !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
10711         PendingBest.push_back(Cand);
10712         Cand->Best = true;
10713 
10714         if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
10715                                                      Curr->Function))
10716           EquivalentCands.push_back(Cand->Function);
10717         else
10718           Best = end();
10719       }
10720     }
10721   }
10722 
10723   // If we found more than one best candidate, this is ambiguous.
10724   if (Best == end())
10725     return OR_Ambiguous;
10726 
10727   // Best is the best viable function.
10728   if (Best->Function && Best->Function->isDeleted())
10729     return OR_Deleted;
10730 
10731   if (!EquivalentCands.empty())
10732     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
10733                                                     EquivalentCands);
10734 
10735   return OR_Success;
10736 }
10737 
10738 namespace {
10739 
10740 enum OverloadCandidateKind {
10741   oc_function,
10742   oc_method,
10743   oc_reversed_binary_operator,
10744   oc_constructor,
10745   oc_implicit_default_constructor,
10746   oc_implicit_copy_constructor,
10747   oc_implicit_move_constructor,
10748   oc_implicit_copy_assignment,
10749   oc_implicit_move_assignment,
10750   oc_implicit_equality_comparison,
10751   oc_inherited_constructor
10752 };
10753 
10754 enum OverloadCandidateSelect {
10755   ocs_non_template,
10756   ocs_template,
10757   ocs_described_template,
10758 };
10759 
10760 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
10761 ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
10762                           const FunctionDecl *Fn,
10763                           OverloadCandidateRewriteKind CRK,
10764                           std::string &Description) {
10765 
10766   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
10767   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
10768     isTemplate = true;
10769     Description = S.getTemplateArgumentBindingsText(
10770         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
10771   }
10772 
10773   OverloadCandidateSelect Select = [&]() {
10774     if (!Description.empty())
10775       return ocs_described_template;
10776     return isTemplate ? ocs_template : ocs_non_template;
10777   }();
10778 
10779   OverloadCandidateKind Kind = [&]() {
10780     if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
10781       return oc_implicit_equality_comparison;
10782 
10783     if (CRK & CRK_Reversed)
10784       return oc_reversed_binary_operator;
10785 
10786     if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
10787       if (!Ctor->isImplicit()) {
10788         if (isa<ConstructorUsingShadowDecl>(Found))
10789           return oc_inherited_constructor;
10790         else
10791           return oc_constructor;
10792       }
10793 
10794       if (Ctor->isDefaultConstructor())
10795         return oc_implicit_default_constructor;
10796 
10797       if (Ctor->isMoveConstructor())
10798         return oc_implicit_move_constructor;
10799 
10800       assert(Ctor->isCopyConstructor() &&
10801              "unexpected sort of implicit constructor");
10802       return oc_implicit_copy_constructor;
10803     }
10804 
10805     if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
10806       // This actually gets spelled 'candidate function' for now, but
10807       // it doesn't hurt to split it out.
10808       if (!Meth->isImplicit())
10809         return oc_method;
10810 
10811       if (Meth->isMoveAssignmentOperator())
10812         return oc_implicit_move_assignment;
10813 
10814       if (Meth->isCopyAssignmentOperator())
10815         return oc_implicit_copy_assignment;
10816 
10817       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
10818       return oc_method;
10819     }
10820 
10821     return oc_function;
10822   }();
10823 
10824   return std::make_pair(Kind, Select);
10825 }
10826 
10827 void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
10828   // FIXME: It'd be nice to only emit a note once per using-decl per overload
10829   // set.
10830   if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
10831     S.Diag(FoundDecl->getLocation(),
10832            diag::note_ovl_candidate_inherited_constructor)
10833       << Shadow->getNominatedBaseClass();
10834 }
10835 
10836 } // end anonymous namespace
10837 
10838 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
10839                                     const FunctionDecl *FD) {
10840   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
10841     bool AlwaysTrue;
10842     if (EnableIf->getCond()->isValueDependent() ||
10843         !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
10844       return false;
10845     if (!AlwaysTrue)
10846       return false;
10847   }
10848   return true;
10849 }
10850 
10851 /// Returns true if we can take the address of the function.
10852 ///
10853 /// \param Complain - If true, we'll emit a diagnostic
10854 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
10855 ///   we in overload resolution?
10856 /// \param Loc - The location of the statement we're complaining about. Ignored
10857 ///   if we're not complaining, or if we're in overload resolution.
10858 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
10859                                               bool Complain,
10860                                               bool InOverloadResolution,
10861                                               SourceLocation Loc) {
10862   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
10863     if (Complain) {
10864       if (InOverloadResolution)
10865         S.Diag(FD->getBeginLoc(),
10866                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
10867       else
10868         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
10869     }
10870     return false;
10871   }
10872 
10873   if (FD->getTrailingRequiresClause()) {
10874     ConstraintSatisfaction Satisfaction;
10875     if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
10876       return false;
10877     if (!Satisfaction.IsSatisfied) {
10878       if (Complain) {
10879         if (InOverloadResolution) {
10880           SmallString<128> TemplateArgString;
10881           if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
10882             TemplateArgString += " ";
10883             TemplateArgString += S.getTemplateArgumentBindingsText(
10884                 FunTmpl->getTemplateParameters(),
10885                 *FD->getTemplateSpecializationArgs());
10886           }
10887 
10888           S.Diag(FD->getBeginLoc(),
10889                  diag::note_ovl_candidate_unsatisfied_constraints)
10890               << TemplateArgString;
10891         } else
10892           S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
10893               << FD;
10894         S.DiagnoseUnsatisfiedConstraint(Satisfaction);
10895       }
10896       return false;
10897     }
10898   }
10899 
10900   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
10901     return P->hasAttr<PassObjectSizeAttr>();
10902   });
10903   if (I == FD->param_end())
10904     return true;
10905 
10906   if (Complain) {
10907     // Add one to ParamNo because it's user-facing
10908     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
10909     if (InOverloadResolution)
10910       S.Diag(FD->getLocation(),
10911              diag::note_ovl_candidate_has_pass_object_size_params)
10912           << ParamNo;
10913     else
10914       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
10915           << FD << ParamNo;
10916   }
10917   return false;
10918 }
10919 
10920 static bool checkAddressOfCandidateIsAvailable(Sema &S,
10921                                                const FunctionDecl *FD) {
10922   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
10923                                            /*InOverloadResolution=*/true,
10924                                            /*Loc=*/SourceLocation());
10925 }
10926 
10927 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10928                                              bool Complain,
10929                                              SourceLocation Loc) {
10930   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
10931                                              /*InOverloadResolution=*/false,
10932                                              Loc);
10933 }
10934 
10935 // Don't print candidates other than the one that matches the calling
10936 // convention of the call operator, since that is guaranteed to exist.
10937 static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn) {
10938   const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
10939 
10940   if (!ConvD)
10941     return false;
10942   const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
10943   if (!RD->isLambda())
10944     return false;
10945 
10946   CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
10947   CallingConv CallOpCC =
10948       CallOp->getType()->castAs<FunctionType>()->getCallConv();
10949   QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
10950   CallingConv ConvToCC =
10951       ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
10952 
10953   return ConvToCC != CallOpCC;
10954 }
10955 
10956 // Notes the location of an overload candidate.
10957 void Sema::NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn,
10958                                  OverloadCandidateRewriteKind RewriteKind,
10959                                  QualType DestType, bool TakingAddress) {
10960   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
10961     return;
10962   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
10963       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
10964     return;
10965   if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
10966       !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
10967     return;
10968   if (shouldSkipNotingLambdaConversionDecl(Fn))
10969     return;
10970 
10971   std::string FnDesc;
10972   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
10973       ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
10974   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
10975                          << (unsigned)KSPair.first << (unsigned)KSPair.second
10976                          << Fn << FnDesc;
10977 
10978   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
10979   Diag(Fn->getLocation(), PD);
10980   MaybeEmitInheritedConstructorNote(*this, Found);
10981 }
10982 
10983 static void
10984 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
10985   // Perhaps the ambiguity was caused by two atomic constraints that are
10986   // 'identical' but not equivalent:
10987   //
10988   // void foo() requires (sizeof(T) > 4) { } // #1
10989   // void foo() requires (sizeof(T) > 4) && T::value { } // #2
10990   //
10991   // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
10992   // #2 to subsume #1, but these constraint are not considered equivalent
10993   // according to the subsumption rules because they are not the same
10994   // source-level construct. This behavior is quite confusing and we should try
10995   // to help the user figure out what happened.
10996 
10997   SmallVector<const Expr *, 3> FirstAC, SecondAC;
10998   FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
10999   for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11000     if (!I->Function)
11001       continue;
11002     SmallVector<const Expr *, 3> AC;
11003     if (auto *Template = I->Function->getPrimaryTemplate())
11004       Template->getAssociatedConstraints(AC);
11005     else
11006       I->Function->getAssociatedConstraints(AC);
11007     if (AC.empty())
11008       continue;
11009     if (FirstCand == nullptr) {
11010       FirstCand = I->Function;
11011       FirstAC = AC;
11012     } else if (SecondCand == nullptr) {
11013       SecondCand = I->Function;
11014       SecondAC = AC;
11015     } else {
11016       // We have more than one pair of constrained functions - this check is
11017       // expensive and we'd rather not try to diagnose it.
11018       return;
11019     }
11020   }
11021   if (!SecondCand)
11022     return;
11023   // The diagnostic can only happen if there are associated constraints on
11024   // both sides (there needs to be some identical atomic constraint).
11025   if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11026                                                       SecondCand, SecondAC))
11027     // Just show the user one diagnostic, they'll probably figure it out
11028     // from here.
11029     return;
11030 }
11031 
11032 // Notes the location of all overload candidates designated through
11033 // OverloadedExpr
11034 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11035                                      bool TakingAddress) {
11036   assert(OverloadedExpr->getType() == Context.OverloadTy);
11037 
11038   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
11039   OverloadExpr *OvlExpr = Ovl.Expression;
11040 
11041   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11042                             IEnd = OvlExpr->decls_end();
11043        I != IEnd; ++I) {
11044     if (FunctionTemplateDecl *FunTmpl =
11045                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
11046       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
11047                             TakingAddress);
11048     } else if (FunctionDecl *Fun
11049                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
11050       NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
11051     }
11052   }
11053 }
11054 
11055 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
11056 /// "lead" diagnostic; it will be given two arguments, the source and
11057 /// target types of the conversion.
11058 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
11059                                  Sema &S,
11060                                  SourceLocation CaretLoc,
11061                                  const PartialDiagnostic &PDiag) const {
11062   S.Diag(CaretLoc, PDiag)
11063     << Ambiguous.getFromType() << Ambiguous.getToType();
11064   unsigned CandsShown = 0;
11065   AmbiguousConversionSequence::const_iterator I, E;
11066   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11067     if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11068       break;
11069     ++CandsShown;
11070     S.NoteOverloadCandidate(I->first, I->second);
11071   }
11072   S.Diags.overloadCandidatesShown(CandsShown);
11073   if (I != E)
11074     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
11075 }
11076 
11077 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
11078                                   unsigned I, bool TakingCandidateAddress) {
11079   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11080   assert(Conv.isBad());
11081   assert(Cand->Function && "for now, candidate must be a function");
11082   FunctionDecl *Fn = Cand->Function;
11083 
11084   // There's a conversion slot for the object argument if this is a
11085   // non-constructor method.  Note that 'I' corresponds the
11086   // conversion-slot index.
11087   bool isObjectArgument = false;
11088   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
11089     if (I == 0)
11090       isObjectArgument = true;
11091     else
11092       I--;
11093   }
11094 
11095   std::string FnDesc;
11096   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11097       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
11098                                 FnDesc);
11099 
11100   Expr *FromExpr = Conv.Bad.FromExpr;
11101   QualType FromTy = Conv.Bad.getFromType();
11102   QualType ToTy = Conv.Bad.getToType();
11103   SourceRange ToParamRange =
11104       !isObjectArgument ? Fn->getParamDecl(I)->getSourceRange() : SourceRange();
11105 
11106   if (FromTy == S.Context.OverloadTy) {
11107     assert(FromExpr && "overload set argument came from implicit argument?");
11108     Expr *E = FromExpr->IgnoreParens();
11109     if (isa<UnaryOperator>(E))
11110       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11111     DeclarationName Name = cast<OverloadExpr>(E)->getName();
11112 
11113     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
11114         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11115         << ToParamRange << ToTy << Name << I + 1;
11116     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11117     return;
11118   }
11119 
11120   // Do some hand-waving analysis to see if the non-viability is due
11121   // to a qualifier mismatch.
11122   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
11123   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
11124   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
11125     CToTy = RT->getPointeeType();
11126   else {
11127     // TODO: detect and diagnose the full richness of const mismatches.
11128     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
11129       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
11130         CFromTy = FromPT->getPointeeType();
11131         CToTy = ToPT->getPointeeType();
11132       }
11133   }
11134 
11135   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
11136       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
11137     Qualifiers FromQs = CFromTy.getQualifiers();
11138     Qualifiers ToQs = CToTy.getQualifiers();
11139 
11140     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
11141       if (isObjectArgument)
11142         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
11143             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11144             << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
11145       else
11146         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
11147             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11148             << FnDesc << ToParamRange << FromQs.getAddressSpace()
11149             << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
11150       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11151       return;
11152     }
11153 
11154     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11155       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
11156           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11157           << ToParamRange << FromTy << FromQs.getObjCLifetime()
11158           << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
11159       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11160       return;
11161     }
11162 
11163     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
11164       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
11165           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11166           << ToParamRange << FromTy << FromQs.getObjCGCAttr()
11167           << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
11168       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11169       return;
11170     }
11171 
11172     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
11173     assert(CVR && "expected qualifiers mismatch");
11174 
11175     if (isObjectArgument) {
11176       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
11177           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11178           << FromTy << (CVR - 1);
11179     } else {
11180       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
11181           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11182           << ToParamRange << FromTy << (CVR - 1) << I + 1;
11183     }
11184     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11185     return;
11186   }
11187 
11188   if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
11189       Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
11190     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
11191         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11192         << (unsigned)isObjectArgument << I + 1
11193         << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
11194         << ToParamRange;
11195     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11196     return;
11197   }
11198 
11199   // Special diagnostic for failure to convert an initializer list, since
11200   // telling the user that it has type void is not useful.
11201   if (FromExpr && isa<InitListExpr>(FromExpr)) {
11202     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
11203         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11204         << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11205         << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1
11206             : Conv.Bad.Kind == BadConversionSequence::too_many_initializers
11207                 ? 2
11208                 : 0);
11209     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11210     return;
11211   }
11212 
11213   // Diagnose references or pointers to incomplete types differently,
11214   // since it's far from impossible that the incompleteness triggered
11215   // the failure.
11216   QualType TempFromTy = FromTy.getNonReferenceType();
11217   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
11218     TempFromTy = PTy->getPointeeType();
11219   if (TempFromTy->isIncompleteType()) {
11220     // Emit the generic diagnostic and, optionally, add the hints to it.
11221     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
11222         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11223         << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11224         << (unsigned)(Cand->Fix.Kind);
11225 
11226     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11227     return;
11228   }
11229 
11230   // Diagnose base -> derived pointer conversions.
11231   unsigned BaseToDerivedConversion = 0;
11232   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
11233     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
11234       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11235                                                FromPtrTy->getPointeeType()) &&
11236           !FromPtrTy->getPointeeType()->isIncompleteType() &&
11237           !ToPtrTy->getPointeeType()->isIncompleteType() &&
11238           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
11239                           FromPtrTy->getPointeeType()))
11240         BaseToDerivedConversion = 1;
11241     }
11242   } else if (const ObjCObjectPointerType *FromPtrTy
11243                                     = FromTy->getAs<ObjCObjectPointerType>()) {
11244     if (const ObjCObjectPointerType *ToPtrTy
11245                                         = ToTy->getAs<ObjCObjectPointerType>())
11246       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
11247         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
11248           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11249                                                 FromPtrTy->getPointeeType()) &&
11250               FromIface->isSuperClassOf(ToIface))
11251             BaseToDerivedConversion = 2;
11252   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
11253     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
11254         !FromTy->isIncompleteType() &&
11255         !ToRefTy->getPointeeType()->isIncompleteType() &&
11256         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
11257       BaseToDerivedConversion = 3;
11258     }
11259   }
11260 
11261   if (BaseToDerivedConversion) {
11262     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
11263         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11264         << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
11265         << I + 1;
11266     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11267     return;
11268   }
11269 
11270   if (isa<ObjCObjectPointerType>(CFromTy) &&
11271       isa<PointerType>(CToTy)) {
11272     Qualifiers FromQs = CFromTy.getQualifiers();
11273     Qualifiers ToQs = CToTy.getQualifiers();
11274     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11275       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
11276           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11277           << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
11278           << I + 1;
11279       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11280       return;
11281     }
11282   }
11283 
11284   if (TakingCandidateAddress &&
11285       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
11286     return;
11287 
11288   // Emit the generic diagnostic and, optionally, add the hints to it.
11289   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
11290   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11291         << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11292         << (unsigned)(Cand->Fix.Kind);
11293 
11294   // Check that location of Fn is not in system header.
11295   if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
11296     // If we can fix the conversion, suggest the FixIts.
11297     for (const FixItHint &HI : Cand->Fix.Hints)
11298         FDiag << HI;
11299   }
11300 
11301   S.Diag(Fn->getLocation(), FDiag);
11302 
11303   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11304 }
11305 
11306 /// Additional arity mismatch diagnosis specific to a function overload
11307 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
11308 /// over a candidate in any candidate set.
11309 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
11310                                unsigned NumArgs) {
11311   FunctionDecl *Fn = Cand->Function;
11312   unsigned MinParams = Fn->getMinRequiredArguments();
11313 
11314   // With invalid overloaded operators, it's possible that we think we
11315   // have an arity mismatch when in fact it looks like we have the
11316   // right number of arguments, because only overloaded operators have
11317   // the weird behavior of overloading member and non-member functions.
11318   // Just don't report anything.
11319   if (Fn->isInvalidDecl() &&
11320       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
11321     return true;
11322 
11323   if (NumArgs < MinParams) {
11324     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
11325            (Cand->FailureKind == ovl_fail_bad_deduction &&
11326             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
11327   } else {
11328     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
11329            (Cand->FailureKind == ovl_fail_bad_deduction &&
11330             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
11331   }
11332 
11333   return false;
11334 }
11335 
11336 /// General arity mismatch diagnosis over a candidate in a candidate set.
11337 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
11338                                   unsigned NumFormalArgs) {
11339   assert(isa<FunctionDecl>(D) &&
11340       "The templated declaration should at least be a function"
11341       " when diagnosing bad template argument deduction due to too many"
11342       " or too few arguments");
11343 
11344   FunctionDecl *Fn = cast<FunctionDecl>(D);
11345 
11346   // TODO: treat calls to a missing default constructor as a special case
11347   const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
11348   unsigned MinParams = Fn->getMinRequiredExplicitArguments();
11349 
11350   // at least / at most / exactly
11351   bool HasExplicitObjectParam = Fn->hasCXXExplicitFunctionObjectParameter();
11352   unsigned ParamCount = FnTy->getNumParams() - (HasExplicitObjectParam ? 1 : 0);
11353   unsigned mode, modeCount;
11354   if (NumFormalArgs < MinParams) {
11355     if (MinParams != ParamCount || FnTy->isVariadic() ||
11356         FnTy->isTemplateVariadic())
11357       mode = 0; // "at least"
11358     else
11359       mode = 2; // "exactly"
11360     modeCount = MinParams;
11361   } else {
11362     if (MinParams != ParamCount)
11363       mode = 1; // "at most"
11364     else
11365       mode = 2; // "exactly"
11366     modeCount = ParamCount;
11367   }
11368 
11369   std::string Description;
11370   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11371       ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
11372 
11373   if (modeCount == 1 &&
11374       Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName())
11375     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
11376         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11377         << Description << mode
11378         << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs
11379         << HasExplicitObjectParam << Fn->getParametersSourceRange();
11380   else
11381     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
11382         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11383         << Description << mode << modeCount << NumFormalArgs
11384         << HasExplicitObjectParam << Fn->getParametersSourceRange();
11385 
11386   MaybeEmitInheritedConstructorNote(S, Found);
11387 }
11388 
11389 /// Arity mismatch diagnosis specific to a function overload candidate.
11390 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
11391                                   unsigned NumFormalArgs) {
11392   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
11393     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
11394 }
11395 
11396 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
11397   if (TemplateDecl *TD = Templated->getDescribedTemplate())
11398     return TD;
11399   llvm_unreachable("Unsupported: Getting the described template declaration"
11400                    " for bad deduction diagnosis");
11401 }
11402 
11403 /// Diagnose a failed template-argument deduction.
11404 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
11405                                  DeductionFailureInfo &DeductionFailure,
11406                                  unsigned NumArgs,
11407                                  bool TakingCandidateAddress) {
11408   TemplateParameter Param = DeductionFailure.getTemplateParameter();
11409   NamedDecl *ParamD;
11410   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
11411   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
11412   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
11413   switch (DeductionFailure.Result) {
11414   case Sema::TDK_Success:
11415     llvm_unreachable("TDK_success while diagnosing bad deduction");
11416 
11417   case Sema::TDK_Incomplete: {
11418     assert(ParamD && "no parameter found for incomplete deduction result");
11419     S.Diag(Templated->getLocation(),
11420            diag::note_ovl_candidate_incomplete_deduction)
11421         << ParamD->getDeclName();
11422     MaybeEmitInheritedConstructorNote(S, Found);
11423     return;
11424   }
11425 
11426   case Sema::TDK_IncompletePack: {
11427     assert(ParamD && "no parameter found for incomplete deduction result");
11428     S.Diag(Templated->getLocation(),
11429            diag::note_ovl_candidate_incomplete_deduction_pack)
11430         << ParamD->getDeclName()
11431         << (DeductionFailure.getFirstArg()->pack_size() + 1)
11432         << *DeductionFailure.getFirstArg();
11433     MaybeEmitInheritedConstructorNote(S, Found);
11434     return;
11435   }
11436 
11437   case Sema::TDK_Underqualified: {
11438     assert(ParamD && "no parameter found for bad qualifiers deduction result");
11439     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
11440 
11441     QualType Param = DeductionFailure.getFirstArg()->getAsType();
11442 
11443     // Param will have been canonicalized, but it should just be a
11444     // qualified version of ParamD, so move the qualifiers to that.
11445     QualifierCollector Qs;
11446     Qs.strip(Param);
11447     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
11448     assert(S.Context.hasSameType(Param, NonCanonParam));
11449 
11450     // Arg has also been canonicalized, but there's nothing we can do
11451     // about that.  It also doesn't matter as much, because it won't
11452     // have any template parameters in it (because deduction isn't
11453     // done on dependent types).
11454     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
11455 
11456     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
11457         << ParamD->getDeclName() << Arg << NonCanonParam;
11458     MaybeEmitInheritedConstructorNote(S, Found);
11459     return;
11460   }
11461 
11462   case Sema::TDK_Inconsistent: {
11463     assert(ParamD && "no parameter found for inconsistent deduction result");
11464     int which = 0;
11465     if (isa<TemplateTypeParmDecl>(ParamD))
11466       which = 0;
11467     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
11468       // Deduction might have failed because we deduced arguments of two
11469       // different types for a non-type template parameter.
11470       // FIXME: Use a different TDK value for this.
11471       QualType T1 =
11472           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
11473       QualType T2 =
11474           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
11475       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
11476         S.Diag(Templated->getLocation(),
11477                diag::note_ovl_candidate_inconsistent_deduction_types)
11478           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
11479           << *DeductionFailure.getSecondArg() << T2;
11480         MaybeEmitInheritedConstructorNote(S, Found);
11481         return;
11482       }
11483 
11484       which = 1;
11485     } else {
11486       which = 2;
11487     }
11488 
11489     // Tweak the diagnostic if the problem is that we deduced packs of
11490     // different arities. We'll print the actual packs anyway in case that
11491     // includes additional useful information.
11492     if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
11493         DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
11494         DeductionFailure.getFirstArg()->pack_size() !=
11495             DeductionFailure.getSecondArg()->pack_size()) {
11496       which = 3;
11497     }
11498 
11499     S.Diag(Templated->getLocation(),
11500            diag::note_ovl_candidate_inconsistent_deduction)
11501         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
11502         << *DeductionFailure.getSecondArg();
11503     MaybeEmitInheritedConstructorNote(S, Found);
11504     return;
11505   }
11506 
11507   case Sema::TDK_InvalidExplicitArguments:
11508     assert(ParamD && "no parameter found for invalid explicit arguments");
11509     if (ParamD->getDeclName())
11510       S.Diag(Templated->getLocation(),
11511              diag::note_ovl_candidate_explicit_arg_mismatch_named)
11512           << ParamD->getDeclName();
11513     else {
11514       int index = 0;
11515       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
11516         index = TTP->getIndex();
11517       else if (NonTypeTemplateParmDecl *NTTP
11518                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
11519         index = NTTP->getIndex();
11520       else
11521         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
11522       S.Diag(Templated->getLocation(),
11523              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
11524           << (index + 1);
11525     }
11526     MaybeEmitInheritedConstructorNote(S, Found);
11527     return;
11528 
11529   case Sema::TDK_ConstraintsNotSatisfied: {
11530     // Format the template argument list into the argument string.
11531     SmallString<128> TemplateArgString;
11532     TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
11533     TemplateArgString = " ";
11534     TemplateArgString += S.getTemplateArgumentBindingsText(
11535         getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11536     if (TemplateArgString.size() == 1)
11537       TemplateArgString.clear();
11538     S.Diag(Templated->getLocation(),
11539            diag::note_ovl_candidate_unsatisfied_constraints)
11540         << TemplateArgString;
11541 
11542     S.DiagnoseUnsatisfiedConstraint(
11543         static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
11544     return;
11545   }
11546   case Sema::TDK_TooManyArguments:
11547   case Sema::TDK_TooFewArguments:
11548     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
11549     return;
11550 
11551   case Sema::TDK_InstantiationDepth:
11552     S.Diag(Templated->getLocation(),
11553            diag::note_ovl_candidate_instantiation_depth);
11554     MaybeEmitInheritedConstructorNote(S, Found);
11555     return;
11556 
11557   case Sema::TDK_SubstitutionFailure: {
11558     // Format the template argument list into the argument string.
11559     SmallString<128> TemplateArgString;
11560     if (TemplateArgumentList *Args =
11561             DeductionFailure.getTemplateArgumentList()) {
11562       TemplateArgString = " ";
11563       TemplateArgString += S.getTemplateArgumentBindingsText(
11564           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11565       if (TemplateArgString.size() == 1)
11566         TemplateArgString.clear();
11567     }
11568 
11569     // If this candidate was disabled by enable_if, say so.
11570     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
11571     if (PDiag && PDiag->second.getDiagID() ==
11572           diag::err_typename_nested_not_found_enable_if) {
11573       // FIXME: Use the source range of the condition, and the fully-qualified
11574       //        name of the enable_if template. These are both present in PDiag.
11575       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
11576         << "'enable_if'" << TemplateArgString;
11577       return;
11578     }
11579 
11580     // We found a specific requirement that disabled the enable_if.
11581     if (PDiag && PDiag->second.getDiagID() ==
11582         diag::err_typename_nested_not_found_requirement) {
11583       S.Diag(Templated->getLocation(),
11584              diag::note_ovl_candidate_disabled_by_requirement)
11585         << PDiag->second.getStringArg(0) << TemplateArgString;
11586       return;
11587     }
11588 
11589     // Format the SFINAE diagnostic into the argument string.
11590     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
11591     //        formatted message in another diagnostic.
11592     SmallString<128> SFINAEArgString;
11593     SourceRange R;
11594     if (PDiag) {
11595       SFINAEArgString = ": ";
11596       R = SourceRange(PDiag->first, PDiag->first);
11597       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
11598     }
11599 
11600     S.Diag(Templated->getLocation(),
11601            diag::note_ovl_candidate_substitution_failure)
11602         << TemplateArgString << SFINAEArgString << R;
11603     MaybeEmitInheritedConstructorNote(S, Found);
11604     return;
11605   }
11606 
11607   case Sema::TDK_DeducedMismatch:
11608   case Sema::TDK_DeducedMismatchNested: {
11609     // Format the template argument list into the argument string.
11610     SmallString<128> TemplateArgString;
11611     if (TemplateArgumentList *Args =
11612             DeductionFailure.getTemplateArgumentList()) {
11613       TemplateArgString = " ";
11614       TemplateArgString += S.getTemplateArgumentBindingsText(
11615           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11616       if (TemplateArgString.size() == 1)
11617         TemplateArgString.clear();
11618     }
11619 
11620     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
11621         << (*DeductionFailure.getCallArgIndex() + 1)
11622         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
11623         << TemplateArgString
11624         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
11625     break;
11626   }
11627 
11628   case Sema::TDK_NonDeducedMismatch: {
11629     // FIXME: Provide a source location to indicate what we couldn't match.
11630     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
11631     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
11632     if (FirstTA.getKind() == TemplateArgument::Template &&
11633         SecondTA.getKind() == TemplateArgument::Template) {
11634       TemplateName FirstTN = FirstTA.getAsTemplate();
11635       TemplateName SecondTN = SecondTA.getAsTemplate();
11636       if (FirstTN.getKind() == TemplateName::Template &&
11637           SecondTN.getKind() == TemplateName::Template) {
11638         if (FirstTN.getAsTemplateDecl()->getName() ==
11639             SecondTN.getAsTemplateDecl()->getName()) {
11640           // FIXME: This fixes a bad diagnostic where both templates are named
11641           // the same.  This particular case is a bit difficult since:
11642           // 1) It is passed as a string to the diagnostic printer.
11643           // 2) The diagnostic printer only attempts to find a better
11644           //    name for types, not decls.
11645           // Ideally, this should folded into the diagnostic printer.
11646           S.Diag(Templated->getLocation(),
11647                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
11648               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
11649           return;
11650         }
11651       }
11652     }
11653 
11654     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
11655         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
11656       return;
11657 
11658     // FIXME: For generic lambda parameters, check if the function is a lambda
11659     // call operator, and if so, emit a prettier and more informative
11660     // diagnostic that mentions 'auto' and lambda in addition to
11661     // (or instead of?) the canonical template type parameters.
11662     S.Diag(Templated->getLocation(),
11663            diag::note_ovl_candidate_non_deduced_mismatch)
11664         << FirstTA << SecondTA;
11665     return;
11666   }
11667   // TODO: diagnose these individually, then kill off
11668   // note_ovl_candidate_bad_deduction, which is uselessly vague.
11669   case Sema::TDK_MiscellaneousDeductionFailure:
11670     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
11671     MaybeEmitInheritedConstructorNote(S, Found);
11672     return;
11673   case Sema::TDK_CUDATargetMismatch:
11674     S.Diag(Templated->getLocation(),
11675            diag::note_cuda_ovl_candidate_target_mismatch);
11676     return;
11677   }
11678 }
11679 
11680 /// Diagnose a failed template-argument deduction, for function calls.
11681 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
11682                                  unsigned NumArgs,
11683                                  bool TakingCandidateAddress) {
11684   unsigned TDK = Cand->DeductionFailure.Result;
11685   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
11686     if (CheckArityMismatch(S, Cand, NumArgs))
11687       return;
11688   }
11689   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
11690                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
11691 }
11692 
11693 /// CUDA: diagnose an invalid call across targets.
11694 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
11695   FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11696   FunctionDecl *Callee = Cand->Function;
11697 
11698   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
11699                            CalleeTarget = S.IdentifyCUDATarget(Callee);
11700 
11701   std::string FnDesc;
11702   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11703       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
11704                                 Cand->getRewriteKind(), FnDesc);
11705 
11706   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
11707       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11708       << FnDesc /* Ignored */
11709       << CalleeTarget << CallerTarget;
11710 
11711   // This could be an implicit constructor for which we could not infer the
11712   // target due to a collsion. Diagnose that case.
11713   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
11714   if (Meth != nullptr && Meth->isImplicit()) {
11715     CXXRecordDecl *ParentClass = Meth->getParent();
11716     Sema::CXXSpecialMember CSM;
11717 
11718     switch (FnKindPair.first) {
11719     default:
11720       return;
11721     case oc_implicit_default_constructor:
11722       CSM = Sema::CXXDefaultConstructor;
11723       break;
11724     case oc_implicit_copy_constructor:
11725       CSM = Sema::CXXCopyConstructor;
11726       break;
11727     case oc_implicit_move_constructor:
11728       CSM = Sema::CXXMoveConstructor;
11729       break;
11730     case oc_implicit_copy_assignment:
11731       CSM = Sema::CXXCopyAssignment;
11732       break;
11733     case oc_implicit_move_assignment:
11734       CSM = Sema::CXXMoveAssignment;
11735       break;
11736     };
11737 
11738     bool ConstRHS = false;
11739     if (Meth->getNumParams()) {
11740       if (const ReferenceType *RT =
11741               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
11742         ConstRHS = RT->getPointeeType().isConstQualified();
11743       }
11744     }
11745 
11746     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
11747                                               /* ConstRHS */ ConstRHS,
11748                                               /* Diagnose */ true);
11749   }
11750 }
11751 
11752 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
11753   FunctionDecl *Callee = Cand->Function;
11754   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
11755 
11756   S.Diag(Callee->getLocation(),
11757          diag::note_ovl_candidate_disabled_by_function_cond_attr)
11758       << Attr->getCond()->getSourceRange() << Attr->getMessage();
11759 }
11760 
11761 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
11762   ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function);
11763   assert(ES.isExplicit() && "not an explicit candidate");
11764 
11765   unsigned Kind;
11766   switch (Cand->Function->getDeclKind()) {
11767   case Decl::Kind::CXXConstructor:
11768     Kind = 0;
11769     break;
11770   case Decl::Kind::CXXConversion:
11771     Kind = 1;
11772     break;
11773   case Decl::Kind::CXXDeductionGuide:
11774     Kind = Cand->Function->isImplicit() ? 0 : 2;
11775     break;
11776   default:
11777     llvm_unreachable("invalid Decl");
11778   }
11779 
11780   // Note the location of the first (in-class) declaration; a redeclaration
11781   // (particularly an out-of-class definition) will typically lack the
11782   // 'explicit' specifier.
11783   // FIXME: This is probably a good thing to do for all 'candidate' notes.
11784   FunctionDecl *First = Cand->Function->getFirstDecl();
11785   if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
11786     First = Pattern->getFirstDecl();
11787 
11788   S.Diag(First->getLocation(),
11789          diag::note_ovl_candidate_explicit)
11790       << Kind << (ES.getExpr() ? 1 : 0)
11791       << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
11792 }
11793 
11794 /// Generates a 'note' diagnostic for an overload candidate.  We've
11795 /// already generated a primary error at the call site.
11796 ///
11797 /// It really does need to be a single diagnostic with its caret
11798 /// pointed at the candidate declaration.  Yes, this creates some
11799 /// major challenges of technical writing.  Yes, this makes pointing
11800 /// out problems with specific arguments quite awkward.  It's still
11801 /// better than generating twenty screens of text for every failed
11802 /// overload.
11803 ///
11804 /// It would be great to be able to express per-candidate problems
11805 /// more richly for those diagnostic clients that cared, but we'd
11806 /// still have to be just as careful with the default diagnostics.
11807 /// \param CtorDestAS Addr space of object being constructed (for ctor
11808 /// candidates only).
11809 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
11810                                   unsigned NumArgs,
11811                                   bool TakingCandidateAddress,
11812                                   LangAS CtorDestAS = LangAS::Default) {
11813   FunctionDecl *Fn = Cand->Function;
11814   if (shouldSkipNotingLambdaConversionDecl(Fn))
11815     return;
11816 
11817   // There is no physical candidate declaration to point to for OpenCL builtins.
11818   // Except for failed conversions, the notes are identical for each candidate,
11819   // so do not generate such notes.
11820   if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
11821       Cand->FailureKind != ovl_fail_bad_conversion)
11822     return;
11823 
11824   // Note deleted candidates, but only if they're viable.
11825   if (Cand->Viable) {
11826     if (Fn->isDeleted()) {
11827       std::string FnDesc;
11828       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11829           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11830                                     Cand->getRewriteKind(), FnDesc);
11831 
11832       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
11833           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11834           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
11835       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11836       return;
11837     }
11838 
11839     // We don't really have anything else to say about viable candidates.
11840     S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11841     return;
11842   }
11843 
11844   switch (Cand->FailureKind) {
11845   case ovl_fail_too_many_arguments:
11846   case ovl_fail_too_few_arguments:
11847     return DiagnoseArityMismatch(S, Cand, NumArgs);
11848 
11849   case ovl_fail_bad_deduction:
11850     return DiagnoseBadDeduction(S, Cand, NumArgs,
11851                                 TakingCandidateAddress);
11852 
11853   case ovl_fail_illegal_constructor: {
11854     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
11855       << (Fn->getPrimaryTemplate() ? 1 : 0);
11856     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11857     return;
11858   }
11859 
11860   case ovl_fail_object_addrspace_mismatch: {
11861     Qualifiers QualsForPrinting;
11862     QualsForPrinting.setAddressSpace(CtorDestAS);
11863     S.Diag(Fn->getLocation(),
11864            diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
11865         << QualsForPrinting;
11866     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11867     return;
11868   }
11869 
11870   case ovl_fail_trivial_conversion:
11871   case ovl_fail_bad_final_conversion:
11872   case ovl_fail_final_conversion_not_exact:
11873     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11874 
11875   case ovl_fail_bad_conversion: {
11876     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
11877     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
11878       if (Cand->Conversions[I].isBad())
11879         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
11880 
11881     // FIXME: this currently happens when we're called from SemaInit
11882     // when user-conversion overload fails.  Figure out how to handle
11883     // those conditions and diagnose them well.
11884     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11885   }
11886 
11887   case ovl_fail_bad_target:
11888     return DiagnoseBadTarget(S, Cand);
11889 
11890   case ovl_fail_enable_if:
11891     return DiagnoseFailedEnableIfAttr(S, Cand);
11892 
11893   case ovl_fail_explicit:
11894     return DiagnoseFailedExplicitSpec(S, Cand);
11895 
11896   case ovl_fail_inhctor_slice:
11897     // It's generally not interesting to note copy/move constructors here.
11898     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
11899       return;
11900     S.Diag(Fn->getLocation(),
11901            diag::note_ovl_candidate_inherited_constructor_slice)
11902       << (Fn->getPrimaryTemplate() ? 1 : 0)
11903       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
11904     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11905     return;
11906 
11907   case ovl_fail_addr_not_available: {
11908     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
11909     (void)Available;
11910     assert(!Available);
11911     break;
11912   }
11913   case ovl_non_default_multiversion_function:
11914     // Do nothing, these should simply be ignored.
11915     break;
11916 
11917   case ovl_fail_constraints_not_satisfied: {
11918     std::string FnDesc;
11919     std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11920         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11921                                   Cand->getRewriteKind(), FnDesc);
11922 
11923     S.Diag(Fn->getLocation(),
11924            diag::note_ovl_candidate_constraints_not_satisfied)
11925         << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11926         << FnDesc /* Ignored */;
11927     ConstraintSatisfaction Satisfaction;
11928     if (S.CheckFunctionConstraints(Fn, Satisfaction))
11929       break;
11930     S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11931   }
11932   }
11933 }
11934 
11935 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
11936   if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate))
11937     return;
11938 
11939   // Desugar the type of the surrogate down to a function type,
11940   // retaining as many typedefs as possible while still showing
11941   // the function type (and, therefore, its parameter types).
11942   QualType FnType = Cand->Surrogate->getConversionType();
11943   bool isLValueReference = false;
11944   bool isRValueReference = false;
11945   bool isPointer = false;
11946   if (const LValueReferenceType *FnTypeRef =
11947         FnType->getAs<LValueReferenceType>()) {
11948     FnType = FnTypeRef->getPointeeType();
11949     isLValueReference = true;
11950   } else if (const RValueReferenceType *FnTypeRef =
11951                FnType->getAs<RValueReferenceType>()) {
11952     FnType = FnTypeRef->getPointeeType();
11953     isRValueReference = true;
11954   }
11955   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
11956     FnType = FnTypePtr->getPointeeType();
11957     isPointer = true;
11958   }
11959   // Desugar down to a function type.
11960   FnType = QualType(FnType->getAs<FunctionType>(), 0);
11961   // Reconstruct the pointer/reference as appropriate.
11962   if (isPointer) FnType = S.Context.getPointerType(FnType);
11963   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
11964   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
11965 
11966   if (!Cand->Viable &&
11967       Cand->FailureKind == ovl_fail_constraints_not_satisfied) {
11968     S.Diag(Cand->Surrogate->getLocation(),
11969            diag::note_ovl_surrogate_constraints_not_satisfied)
11970         << Cand->Surrogate;
11971     ConstraintSatisfaction Satisfaction;
11972     if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
11973       S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11974   } else {
11975     S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
11976         << FnType;
11977   }
11978 }
11979 
11980 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
11981                                          SourceLocation OpLoc,
11982                                          OverloadCandidate *Cand) {
11983   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
11984   std::string TypeStr("operator");
11985   TypeStr += Opc;
11986   TypeStr += "(";
11987   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
11988   if (Cand->Conversions.size() == 1) {
11989     TypeStr += ")";
11990     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11991   } else {
11992     TypeStr += ", ";
11993     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
11994     TypeStr += ")";
11995     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11996   }
11997 }
11998 
11999 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
12000                                          OverloadCandidate *Cand) {
12001   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
12002     if (ICS.isBad()) break; // all meaningless after first invalid
12003     if (!ICS.isAmbiguous()) continue;
12004 
12005     ICS.DiagnoseAmbiguousConversion(
12006         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
12007   }
12008 }
12009 
12010 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
12011   if (Cand->Function)
12012     return Cand->Function->getLocation();
12013   if (Cand->IsSurrogate)
12014     return Cand->Surrogate->getLocation();
12015   return SourceLocation();
12016 }
12017 
12018 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
12019   switch ((Sema::TemplateDeductionResult)DFI.Result) {
12020   case Sema::TDK_Success:
12021   case Sema::TDK_NonDependentConversionFailure:
12022   case Sema::TDK_AlreadyDiagnosed:
12023     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
12024 
12025   case Sema::TDK_Invalid:
12026   case Sema::TDK_Incomplete:
12027   case Sema::TDK_IncompletePack:
12028     return 1;
12029 
12030   case Sema::TDK_Underqualified:
12031   case Sema::TDK_Inconsistent:
12032     return 2;
12033 
12034   case Sema::TDK_SubstitutionFailure:
12035   case Sema::TDK_DeducedMismatch:
12036   case Sema::TDK_ConstraintsNotSatisfied:
12037   case Sema::TDK_DeducedMismatchNested:
12038   case Sema::TDK_NonDeducedMismatch:
12039   case Sema::TDK_MiscellaneousDeductionFailure:
12040   case Sema::TDK_CUDATargetMismatch:
12041     return 3;
12042 
12043   case Sema::TDK_InstantiationDepth:
12044     return 4;
12045 
12046   case Sema::TDK_InvalidExplicitArguments:
12047     return 5;
12048 
12049   case Sema::TDK_TooManyArguments:
12050   case Sema::TDK_TooFewArguments:
12051     return 6;
12052   }
12053   llvm_unreachable("Unhandled deduction result");
12054 }
12055 
12056 namespace {
12057 
12058 struct CompareOverloadCandidatesForDisplay {
12059   Sema &S;
12060   SourceLocation Loc;
12061   size_t NumArgs;
12062   OverloadCandidateSet::CandidateSetKind CSK;
12063 
12064   CompareOverloadCandidatesForDisplay(
12065       Sema &S, SourceLocation Loc, size_t NArgs,
12066       OverloadCandidateSet::CandidateSetKind CSK)
12067       : S(S), NumArgs(NArgs), CSK(CSK) {}
12068 
12069   OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
12070     // If there are too many or too few arguments, that's the high-order bit we
12071     // want to sort by, even if the immediate failure kind was something else.
12072     if (C->FailureKind == ovl_fail_too_many_arguments ||
12073         C->FailureKind == ovl_fail_too_few_arguments)
12074       return static_cast<OverloadFailureKind>(C->FailureKind);
12075 
12076     if (C->Function) {
12077       if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
12078         return ovl_fail_too_many_arguments;
12079       if (NumArgs < C->Function->getMinRequiredArguments())
12080         return ovl_fail_too_few_arguments;
12081     }
12082 
12083     return static_cast<OverloadFailureKind>(C->FailureKind);
12084   }
12085 
12086   bool operator()(const OverloadCandidate *L,
12087                   const OverloadCandidate *R) {
12088     // Fast-path this check.
12089     if (L == R) return false;
12090 
12091     // Order first by viability.
12092     if (L->Viable) {
12093       if (!R->Viable) return true;
12094 
12095       if (int Ord = CompareConversions(*L, *R))
12096         return Ord < 0;
12097       // Use other tie breakers.
12098     } else if (R->Viable)
12099       return false;
12100 
12101     assert(L->Viable == R->Viable);
12102 
12103     // Criteria by which we can sort non-viable candidates:
12104     if (!L->Viable) {
12105       OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
12106       OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
12107 
12108       // 1. Arity mismatches come after other candidates.
12109       if (LFailureKind == ovl_fail_too_many_arguments ||
12110           LFailureKind == ovl_fail_too_few_arguments) {
12111         if (RFailureKind == ovl_fail_too_many_arguments ||
12112             RFailureKind == ovl_fail_too_few_arguments) {
12113           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
12114           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
12115           if (LDist == RDist) {
12116             if (LFailureKind == RFailureKind)
12117               // Sort non-surrogates before surrogates.
12118               return !L->IsSurrogate && R->IsSurrogate;
12119             // Sort candidates requiring fewer parameters than there were
12120             // arguments given after candidates requiring more parameters
12121             // than there were arguments given.
12122             return LFailureKind == ovl_fail_too_many_arguments;
12123           }
12124           return LDist < RDist;
12125         }
12126         return false;
12127       }
12128       if (RFailureKind == ovl_fail_too_many_arguments ||
12129           RFailureKind == ovl_fail_too_few_arguments)
12130         return true;
12131 
12132       // 2. Bad conversions come first and are ordered by the number
12133       // of bad conversions and quality of good conversions.
12134       if (LFailureKind == ovl_fail_bad_conversion) {
12135         if (RFailureKind != ovl_fail_bad_conversion)
12136           return true;
12137 
12138         // The conversion that can be fixed with a smaller number of changes,
12139         // comes first.
12140         unsigned numLFixes = L->Fix.NumConversionsFixed;
12141         unsigned numRFixes = R->Fix.NumConversionsFixed;
12142         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
12143         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
12144         if (numLFixes != numRFixes) {
12145           return numLFixes < numRFixes;
12146         }
12147 
12148         // If there's any ordering between the defined conversions...
12149         if (int Ord = CompareConversions(*L, *R))
12150           return Ord < 0;
12151       } else if (RFailureKind == ovl_fail_bad_conversion)
12152         return false;
12153 
12154       if (LFailureKind == ovl_fail_bad_deduction) {
12155         if (RFailureKind != ovl_fail_bad_deduction)
12156           return true;
12157 
12158         if (L->DeductionFailure.Result != R->DeductionFailure.Result) {
12159           unsigned LRank = RankDeductionFailure(L->DeductionFailure);
12160           unsigned RRank = RankDeductionFailure(R->DeductionFailure);
12161           if (LRank != RRank)
12162             return LRank < RRank;
12163         }
12164       } else if (RFailureKind == ovl_fail_bad_deduction)
12165         return false;
12166 
12167       // TODO: others?
12168     }
12169 
12170     // Sort everything else by location.
12171     SourceLocation LLoc = GetLocationForCandidate(L);
12172     SourceLocation RLoc = GetLocationForCandidate(R);
12173 
12174     // Put candidates without locations (e.g. builtins) at the end.
12175     if (LLoc.isValid() && RLoc.isValid())
12176       return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12177     if (LLoc.isValid() && !RLoc.isValid())
12178       return true;
12179     if (RLoc.isValid() && !LLoc.isValid())
12180       return false;
12181     assert(!LLoc.isValid() && !RLoc.isValid());
12182     // For builtins and other functions without locations, fallback to the order
12183     // in which they were added into the candidate set.
12184     return L < R;
12185   }
12186 
12187 private:
12188   struct ConversionSignals {
12189     unsigned KindRank = 0;
12190     ImplicitConversionRank Rank = ICR_Exact_Match;
12191 
12192     static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
12193       ConversionSignals Sig;
12194       Sig.KindRank = Seq.getKindRank();
12195       if (Seq.isStandard())
12196         Sig.Rank = Seq.Standard.getRank();
12197       else if (Seq.isUserDefined())
12198         Sig.Rank = Seq.UserDefined.After.getRank();
12199       // We intend StaticObjectArgumentConversion to compare the same as
12200       // StandardConversion with ICR_ExactMatch rank.
12201       return Sig;
12202     }
12203 
12204     static ConversionSignals ForObjectArgument() {
12205       // We intend StaticObjectArgumentConversion to compare the same as
12206       // StandardConversion with ICR_ExactMatch rank. Default give us that.
12207       return {};
12208     }
12209   };
12210 
12211   // Returns -1 if conversions in L are considered better.
12212   //          0 if they are considered indistinguishable.
12213   //          1 if conversions in R are better.
12214   int CompareConversions(const OverloadCandidate &L,
12215                          const OverloadCandidate &R) {
12216     // We cannot use `isBetterOverloadCandidate` because it is defined
12217     // according to the C++ standard and provides a partial order, but we need
12218     // a total order as this function is used in sort.
12219     assert(L.Conversions.size() == R.Conversions.size());
12220     for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
12221       auto LS = L.IgnoreObjectArgument && I == 0
12222                     ? ConversionSignals::ForObjectArgument()
12223                     : ConversionSignals::ForSequence(L.Conversions[I]);
12224       auto RS = R.IgnoreObjectArgument
12225                     ? ConversionSignals::ForObjectArgument()
12226                     : ConversionSignals::ForSequence(R.Conversions[I]);
12227       if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
12228         return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
12229                    ? -1
12230                    : 1;
12231     }
12232     // FIXME: find a way to compare templates for being more or less
12233     // specialized that provides a strict weak ordering.
12234     return 0;
12235   }
12236 };
12237 }
12238 
12239 /// CompleteNonViableCandidate - Normally, overload resolution only
12240 /// computes up to the first bad conversion. Produces the FixIt set if
12241 /// possible.
12242 static void
12243 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
12244                            ArrayRef<Expr *> Args,
12245                            OverloadCandidateSet::CandidateSetKind CSK) {
12246   assert(!Cand->Viable);
12247 
12248   // Don't do anything on failures other than bad conversion.
12249   if (Cand->FailureKind != ovl_fail_bad_conversion)
12250     return;
12251 
12252   // We only want the FixIts if all the arguments can be corrected.
12253   bool Unfixable = false;
12254   // Use a implicit copy initialization to check conversion fixes.
12255   Cand->Fix.setConversionChecker(TryCopyInitialization);
12256 
12257   // Attempt to fix the bad conversion.
12258   unsigned ConvCount = Cand->Conversions.size();
12259   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
12260        ++ConvIdx) {
12261     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
12262     if (Cand->Conversions[ConvIdx].isInitialized() &&
12263         Cand->Conversions[ConvIdx].isBad()) {
12264       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
12265       break;
12266     }
12267   }
12268 
12269   // FIXME: this should probably be preserved from the overload
12270   // operation somehow.
12271   bool SuppressUserConversions = false;
12272 
12273   unsigned ConvIdx = 0;
12274   unsigned ArgIdx = 0;
12275   ArrayRef<QualType> ParamTypes;
12276   bool Reversed = Cand->isReversed();
12277 
12278   if (Cand->IsSurrogate) {
12279     QualType ConvType
12280       = Cand->Surrogate->getConversionType().getNonReferenceType();
12281     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12282       ConvType = ConvPtrType->getPointeeType();
12283     ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
12284     // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12285     ConvIdx = 1;
12286   } else if (Cand->Function) {
12287     ParamTypes =
12288         Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
12289     if (isa<CXXMethodDecl>(Cand->Function) &&
12290         !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
12291       // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12292       ConvIdx = 1;
12293       if (CSK == OverloadCandidateSet::CSK_Operator &&
12294           Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
12295           Cand->Function->getDeclName().getCXXOverloadedOperator() !=
12296               OO_Subscript)
12297         // Argument 0 is 'this', which doesn't have a corresponding parameter.
12298         ArgIdx = 1;
12299     }
12300   } else {
12301     // Builtin operator.
12302     assert(ConvCount <= 3);
12303     ParamTypes = Cand->BuiltinParamTypes;
12304   }
12305 
12306   // Fill in the rest of the conversions.
12307   for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
12308        ConvIdx != ConvCount;
12309        ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
12310     assert(ArgIdx < Args.size() && "no argument for this arg conversion");
12311     if (Cand->Conversions[ConvIdx].isInitialized()) {
12312       // We've already checked this conversion.
12313     } else if (ParamIdx < ParamTypes.size()) {
12314       if (ParamTypes[ParamIdx]->isDependentType())
12315         Cand->Conversions[ConvIdx].setAsIdentityConversion(
12316             Args[ArgIdx]->getType());
12317       else {
12318         Cand->Conversions[ConvIdx] =
12319             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
12320                                   SuppressUserConversions,
12321                                   /*InOverloadResolution=*/true,
12322                                   /*AllowObjCWritebackConversion=*/
12323                                   S.getLangOpts().ObjCAutoRefCount);
12324         // Store the FixIt in the candidate if it exists.
12325         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
12326           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
12327       }
12328     } else
12329       Cand->Conversions[ConvIdx].setEllipsis();
12330   }
12331 }
12332 
12333 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
12334     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
12335     SourceLocation OpLoc,
12336     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12337   // Sort the candidates by viability and position.  Sorting directly would
12338   // be prohibitive, so we make a set of pointers and sort those.
12339   SmallVector<OverloadCandidate*, 32> Cands;
12340   if (OCD == OCD_AllCandidates) Cands.reserve(size());
12341   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12342     if (!Filter(*Cand))
12343       continue;
12344     switch (OCD) {
12345     case OCD_AllCandidates:
12346       if (!Cand->Viable) {
12347         if (!Cand->Function && !Cand->IsSurrogate) {
12348           // This a non-viable builtin candidate.  We do not, in general,
12349           // want to list every possible builtin candidate.
12350           continue;
12351         }
12352         CompleteNonViableCandidate(S, Cand, Args, Kind);
12353       }
12354       break;
12355 
12356     case OCD_ViableCandidates:
12357       if (!Cand->Viable)
12358         continue;
12359       break;
12360 
12361     case OCD_AmbiguousCandidates:
12362       if (!Cand->Best)
12363         continue;
12364       break;
12365     }
12366 
12367     Cands.push_back(Cand);
12368   }
12369 
12370   llvm::stable_sort(
12371       Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
12372 
12373   return Cands;
12374 }
12375 
12376 bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
12377                                             SourceLocation OpLoc) {
12378   bool DeferHint = false;
12379   if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
12380     // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
12381     // host device candidates.
12382     auto WrongSidedCands =
12383         CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
12384           return (Cand.Viable == false &&
12385                   Cand.FailureKind == ovl_fail_bad_target) ||
12386                  (Cand.Function &&
12387                   Cand.Function->template hasAttr<CUDAHostAttr>() &&
12388                   Cand.Function->template hasAttr<CUDADeviceAttr>());
12389         });
12390     DeferHint = !WrongSidedCands.empty();
12391   }
12392   return DeferHint;
12393 }
12394 
12395 /// When overload resolution fails, prints diagnostic messages containing the
12396 /// candidates in the candidate set.
12397 void OverloadCandidateSet::NoteCandidates(
12398     PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
12399     ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
12400     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12401 
12402   auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
12403 
12404   S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
12405 
12406   // In WebAssembly we don't want to emit further diagnostics if a table is
12407   // passed as an argument to a function.
12408   bool NoteCands = true;
12409   for (const Expr *Arg : Args) {
12410     if (Arg->getType()->isWebAssemblyTableType())
12411       NoteCands = false;
12412   }
12413 
12414   if (NoteCands)
12415     NoteCandidates(S, Args, Cands, Opc, OpLoc);
12416 
12417   if (OCD == OCD_AmbiguousCandidates)
12418     MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
12419 }
12420 
12421 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
12422                                           ArrayRef<OverloadCandidate *> Cands,
12423                                           StringRef Opc, SourceLocation OpLoc) {
12424   bool ReportedAmbiguousConversions = false;
12425 
12426   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12427   unsigned CandsShown = 0;
12428   auto I = Cands.begin(), E = Cands.end();
12429   for (; I != E; ++I) {
12430     OverloadCandidate *Cand = *I;
12431 
12432     if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
12433         ShowOverloads == Ovl_Best) {
12434       break;
12435     }
12436     ++CandsShown;
12437 
12438     if (Cand->Function)
12439       NoteFunctionCandidate(S, Cand, Args.size(),
12440                             /*TakingCandidateAddress=*/false, DestAS);
12441     else if (Cand->IsSurrogate)
12442       NoteSurrogateCandidate(S, Cand);
12443     else {
12444       assert(Cand->Viable &&
12445              "Non-viable built-in candidates are not added to Cands.");
12446       // Generally we only see ambiguities including viable builtin
12447       // operators if overload resolution got screwed up by an
12448       // ambiguous user-defined conversion.
12449       //
12450       // FIXME: It's quite possible for different conversions to see
12451       // different ambiguities, though.
12452       if (!ReportedAmbiguousConversions) {
12453         NoteAmbiguousUserConversions(S, OpLoc, Cand);
12454         ReportedAmbiguousConversions = true;
12455       }
12456 
12457       // If this is a viable builtin, print it.
12458       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
12459     }
12460   }
12461 
12462   // Inform S.Diags that we've shown an overload set with N elements.  This may
12463   // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
12464   S.Diags.overloadCandidatesShown(CandsShown);
12465 
12466   if (I != E)
12467     S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
12468            shouldDeferDiags(S, Args, OpLoc))
12469         << int(E - I);
12470 }
12471 
12472 static SourceLocation
12473 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
12474   return Cand->Specialization ? Cand->Specialization->getLocation()
12475                               : SourceLocation();
12476 }
12477 
12478 namespace {
12479 struct CompareTemplateSpecCandidatesForDisplay {
12480   Sema &S;
12481   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
12482 
12483   bool operator()(const TemplateSpecCandidate *L,
12484                   const TemplateSpecCandidate *R) {
12485     // Fast-path this check.
12486     if (L == R)
12487       return false;
12488 
12489     // Assuming that both candidates are not matches...
12490 
12491     // Sort by the ranking of deduction failures.
12492     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
12493       return RankDeductionFailure(L->DeductionFailure) <
12494              RankDeductionFailure(R->DeductionFailure);
12495 
12496     // Sort everything else by location.
12497     SourceLocation LLoc = GetLocationForCandidate(L);
12498     SourceLocation RLoc = GetLocationForCandidate(R);
12499 
12500     // Put candidates without locations (e.g. builtins) at the end.
12501     if (LLoc.isInvalid())
12502       return false;
12503     if (RLoc.isInvalid())
12504       return true;
12505 
12506     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12507   }
12508 };
12509 }
12510 
12511 /// Diagnose a template argument deduction failure.
12512 /// We are treating these failures as overload failures due to bad
12513 /// deductions.
12514 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
12515                                                  bool ForTakingAddress) {
12516   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
12517                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
12518 }
12519 
12520 void TemplateSpecCandidateSet::destroyCandidates() {
12521   for (iterator i = begin(), e = end(); i != e; ++i) {
12522     i->DeductionFailure.Destroy();
12523   }
12524 }
12525 
12526 void TemplateSpecCandidateSet::clear() {
12527   destroyCandidates();
12528   Candidates.clear();
12529 }
12530 
12531 /// NoteCandidates - When no template specialization match is found, prints
12532 /// diagnostic messages containing the non-matching specializations that form
12533 /// the candidate set.
12534 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
12535 /// OCD == OCD_AllCandidates and Cand->Viable == false.
12536 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
12537   // Sort the candidates by position (assuming no candidate is a match).
12538   // Sorting directly would be prohibitive, so we make a set of pointers
12539   // and sort those.
12540   SmallVector<TemplateSpecCandidate *, 32> Cands;
12541   Cands.reserve(size());
12542   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12543     if (Cand->Specialization)
12544       Cands.push_back(Cand);
12545     // Otherwise, this is a non-matching builtin candidate.  We do not,
12546     // in general, want to list every possible builtin candidate.
12547   }
12548 
12549   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
12550 
12551   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
12552   // for generalization purposes (?).
12553   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12554 
12555   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
12556   unsigned CandsShown = 0;
12557   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
12558     TemplateSpecCandidate *Cand = *I;
12559 
12560     // Set an arbitrary limit on the number of candidates we'll spam
12561     // the user with.  FIXME: This limit should depend on details of the
12562     // candidate list.
12563     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
12564       break;
12565     ++CandsShown;
12566 
12567     assert(Cand->Specialization &&
12568            "Non-matching built-in candidates are not added to Cands.");
12569     Cand->NoteDeductionFailure(S, ForTakingAddress);
12570   }
12571 
12572   if (I != E)
12573     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
12574 }
12575 
12576 // [PossiblyAFunctionType]  -->   [Return]
12577 // NonFunctionType --> NonFunctionType
12578 // R (A) --> R(A)
12579 // R (*)(A) --> R (A)
12580 // R (&)(A) --> R (A)
12581 // R (S::*)(A) --> R (A)
12582 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
12583   QualType Ret = PossiblyAFunctionType;
12584   if (const PointerType *ToTypePtr =
12585     PossiblyAFunctionType->getAs<PointerType>())
12586     Ret = ToTypePtr->getPointeeType();
12587   else if (const ReferenceType *ToTypeRef =
12588     PossiblyAFunctionType->getAs<ReferenceType>())
12589     Ret = ToTypeRef->getPointeeType();
12590   else if (const MemberPointerType *MemTypePtr =
12591     PossiblyAFunctionType->getAs<MemberPointerType>())
12592     Ret = MemTypePtr->getPointeeType();
12593   Ret =
12594     Context.getCanonicalType(Ret).getUnqualifiedType();
12595   return Ret;
12596 }
12597 
12598 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
12599                                  bool Complain = true) {
12600   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
12601       S.DeduceReturnType(FD, Loc, Complain))
12602     return true;
12603 
12604   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
12605   if (S.getLangOpts().CPlusPlus17 &&
12606       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
12607       !S.ResolveExceptionSpec(Loc, FPT))
12608     return true;
12609 
12610   return false;
12611 }
12612 
12613 namespace {
12614 // A helper class to help with address of function resolution
12615 // - allows us to avoid passing around all those ugly parameters
12616 class AddressOfFunctionResolver {
12617   Sema& S;
12618   Expr* SourceExpr;
12619   const QualType& TargetType;
12620   QualType TargetFunctionType; // Extracted function type from target type
12621 
12622   bool Complain;
12623   //DeclAccessPair& ResultFunctionAccessPair;
12624   ASTContext& Context;
12625 
12626   bool TargetTypeIsNonStaticMemberFunction;
12627   bool FoundNonTemplateFunction;
12628   bool StaticMemberFunctionFromBoundPointer;
12629   bool HasComplained;
12630 
12631   OverloadExpr::FindResult OvlExprInfo;
12632   OverloadExpr *OvlExpr;
12633   TemplateArgumentListInfo OvlExplicitTemplateArgs;
12634   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
12635   TemplateSpecCandidateSet FailedCandidates;
12636 
12637 public:
12638   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
12639                             const QualType &TargetType, bool Complain)
12640       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
12641         Complain(Complain), Context(S.getASTContext()),
12642         TargetTypeIsNonStaticMemberFunction(
12643             !!TargetType->getAs<MemberPointerType>()),
12644         FoundNonTemplateFunction(false),
12645         StaticMemberFunctionFromBoundPointer(false),
12646         HasComplained(false),
12647         OvlExprInfo(OverloadExpr::find(SourceExpr)),
12648         OvlExpr(OvlExprInfo.Expression),
12649         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
12650     ExtractUnqualifiedFunctionTypeFromTargetType();
12651 
12652     if (TargetFunctionType->isFunctionType()) {
12653       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
12654         if (!UME->isImplicitAccess() &&
12655             !S.ResolveSingleFunctionTemplateSpecialization(UME))
12656           StaticMemberFunctionFromBoundPointer = true;
12657     } else if (OvlExpr->hasExplicitTemplateArgs()) {
12658       DeclAccessPair dap;
12659       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
12660               OvlExpr, false, &dap)) {
12661         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
12662           if (!Method->isStatic()) {
12663             // If the target type is a non-function type and the function found
12664             // is a non-static member function, pretend as if that was the
12665             // target, it's the only possible type to end up with.
12666             TargetTypeIsNonStaticMemberFunction = true;
12667 
12668             // And skip adding the function if its not in the proper form.
12669             // We'll diagnose this due to an empty set of functions.
12670             if (!OvlExprInfo.HasFormOfMemberPointer)
12671               return;
12672           }
12673 
12674         Matches.push_back(std::make_pair(dap, Fn));
12675       }
12676       return;
12677     }
12678 
12679     if (OvlExpr->hasExplicitTemplateArgs())
12680       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
12681 
12682     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
12683       // C++ [over.over]p4:
12684       //   If more than one function is selected, [...]
12685       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
12686         if (FoundNonTemplateFunction)
12687           EliminateAllTemplateMatches();
12688         else
12689           EliminateAllExceptMostSpecializedTemplate();
12690       }
12691     }
12692 
12693     if (S.getLangOpts().CUDA && Matches.size() > 1)
12694       EliminateSuboptimalCudaMatches();
12695   }
12696 
12697   bool hasComplained() const { return HasComplained; }
12698 
12699 private:
12700   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
12701     QualType Discard;
12702     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
12703            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
12704   }
12705 
12706   /// \return true if A is considered a better overload candidate for the
12707   /// desired type than B.
12708   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
12709     // If A doesn't have exactly the correct type, we don't want to classify it
12710     // as "better" than anything else. This way, the user is required to
12711     // disambiguate for us if there are multiple candidates and no exact match.
12712     return candidateHasExactlyCorrectType(A) &&
12713            (!candidateHasExactlyCorrectType(B) ||
12714             compareEnableIfAttrs(S, A, B) == Comparison::Better);
12715   }
12716 
12717   /// \return true if we were able to eliminate all but one overload candidate,
12718   /// false otherwise.
12719   bool eliminiateSuboptimalOverloadCandidates() {
12720     // Same algorithm as overload resolution -- one pass to pick the "best",
12721     // another pass to be sure that nothing is better than the best.
12722     auto Best = Matches.begin();
12723     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
12724       if (isBetterCandidate(I->second, Best->second))
12725         Best = I;
12726 
12727     const FunctionDecl *BestFn = Best->second;
12728     auto IsBestOrInferiorToBest = [this, BestFn](
12729         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
12730       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
12731     };
12732 
12733     // Note: We explicitly leave Matches unmodified if there isn't a clear best
12734     // option, so we can potentially give the user a better error
12735     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
12736       return false;
12737     Matches[0] = *Best;
12738     Matches.resize(1);
12739     return true;
12740   }
12741 
12742   bool isTargetTypeAFunction() const {
12743     return TargetFunctionType->isFunctionType();
12744   }
12745 
12746   // [ToType]     [Return]
12747 
12748   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
12749   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
12750   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
12751   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
12752     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
12753   }
12754 
12755   // return true if any matching specializations were found
12756   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
12757                                    const DeclAccessPair& CurAccessFunPair) {
12758     if (CXXMethodDecl *Method
12759               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
12760       // Skip non-static function templates when converting to pointer, and
12761       // static when converting to member pointer.
12762       bool CanConvertToFunctionPointer =
12763           Method->isStatic() || Method->isExplicitObjectMemberFunction();
12764       if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
12765         return false;
12766     }
12767     else if (TargetTypeIsNonStaticMemberFunction)
12768       return false;
12769 
12770     // C++ [over.over]p2:
12771     //   If the name is a function template, template argument deduction is
12772     //   done (14.8.2.2), and if the argument deduction succeeds, the
12773     //   resulting template argument list is used to generate a single
12774     //   function template specialization, which is added to the set of
12775     //   overloaded functions considered.
12776     FunctionDecl *Specialization = nullptr;
12777     TemplateDeductionInfo Info(FailedCandidates.getLocation());
12778     if (Sema::TemplateDeductionResult Result
12779           = S.DeduceTemplateArguments(FunctionTemplate,
12780                                       &OvlExplicitTemplateArgs,
12781                                       TargetFunctionType, Specialization,
12782                                       Info, /*IsAddressOfFunction*/true)) {
12783       // Make a note of the failed deduction for diagnostics.
12784       FailedCandidates.addCandidate()
12785           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
12786                MakeDeductionFailureInfo(Context, Result, Info));
12787       return false;
12788     }
12789 
12790     // Template argument deduction ensures that we have an exact match or
12791     // compatible pointer-to-function arguments that would be adjusted by ICS.
12792     // This function template specicalization works.
12793     assert(S.isSameOrCompatibleFunctionType(
12794               Context.getCanonicalType(Specialization->getType()),
12795               Context.getCanonicalType(TargetFunctionType)));
12796 
12797     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
12798       return false;
12799 
12800     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
12801     return true;
12802   }
12803 
12804   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
12805                                       const DeclAccessPair& CurAccessFunPair) {
12806     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12807       // Skip non-static functions when converting to pointer, and static
12808       // when converting to member pointer.
12809       bool CanConvertToFunctionPointer =
12810           Method->isStatic() || Method->isExplicitObjectMemberFunction();
12811       if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
12812         return false;
12813     }
12814     else if (TargetTypeIsNonStaticMemberFunction)
12815       return false;
12816 
12817     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
12818       if (S.getLangOpts().CUDA) {
12819         FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12820         if (!(Caller && Caller->isImplicit()) &&
12821             !S.IsAllowedCUDACall(Caller, FunDecl))
12822           return false;
12823       }
12824       if (FunDecl->isMultiVersion()) {
12825         const auto *TA = FunDecl->getAttr<TargetAttr>();
12826         if (TA && !TA->isDefaultVersion())
12827           return false;
12828         const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
12829         if (TVA && !TVA->isDefaultVersion())
12830           return false;
12831       }
12832 
12833       // If any candidate has a placeholder return type, trigger its deduction
12834       // now.
12835       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
12836                                Complain)) {
12837         HasComplained |= Complain;
12838         return false;
12839       }
12840 
12841       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
12842         return false;
12843 
12844       // If we're in C, we need to support types that aren't exactly identical.
12845       if (!S.getLangOpts().CPlusPlus ||
12846           candidateHasExactlyCorrectType(FunDecl)) {
12847         Matches.push_back(std::make_pair(
12848             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
12849         FoundNonTemplateFunction = true;
12850         return true;
12851       }
12852     }
12853 
12854     return false;
12855   }
12856 
12857   bool FindAllFunctionsThatMatchTargetTypeExactly() {
12858     bool Ret = false;
12859 
12860     // If the overload expression doesn't have the form of a pointer to
12861     // member, don't try to convert it to a pointer-to-member type.
12862     if (IsInvalidFormOfPointerToMemberFunction())
12863       return false;
12864 
12865     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12866                                E = OvlExpr->decls_end();
12867          I != E; ++I) {
12868       // Look through any using declarations to find the underlying function.
12869       NamedDecl *Fn = (*I)->getUnderlyingDecl();
12870 
12871       // C++ [over.over]p3:
12872       //   Non-member functions and static member functions match
12873       //   targets of type "pointer-to-function" or "reference-to-function."
12874       //   Nonstatic member functions match targets of
12875       //   type "pointer-to-member-function."
12876       // Note that according to DR 247, the containing class does not matter.
12877       if (FunctionTemplateDecl *FunctionTemplate
12878                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
12879         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
12880           Ret = true;
12881       }
12882       // If we have explicit template arguments supplied, skip non-templates.
12883       else if (!OvlExpr->hasExplicitTemplateArgs() &&
12884                AddMatchingNonTemplateFunction(Fn, I.getPair()))
12885         Ret = true;
12886     }
12887     assert(Ret || Matches.empty());
12888     return Ret;
12889   }
12890 
12891   void EliminateAllExceptMostSpecializedTemplate() {
12892     //   [...] and any given function template specialization F1 is
12893     //   eliminated if the set contains a second function template
12894     //   specialization whose function template is more specialized
12895     //   than the function template of F1 according to the partial
12896     //   ordering rules of 14.5.5.2.
12897 
12898     // The algorithm specified above is quadratic. We instead use a
12899     // two-pass algorithm (similar to the one used to identify the
12900     // best viable function in an overload set) that identifies the
12901     // best function template (if it exists).
12902 
12903     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
12904     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
12905       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
12906 
12907     // TODO: It looks like FailedCandidates does not serve much purpose
12908     // here, since the no_viable diagnostic has index 0.
12909     UnresolvedSetIterator Result = S.getMostSpecialized(
12910         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
12911         SourceExpr->getBeginLoc(), S.PDiag(),
12912         S.PDiag(diag::err_addr_ovl_ambiguous)
12913             << Matches[0].second->getDeclName(),
12914         S.PDiag(diag::note_ovl_candidate)
12915             << (unsigned)oc_function << (unsigned)ocs_described_template,
12916         Complain, TargetFunctionType);
12917 
12918     if (Result != MatchesCopy.end()) {
12919       // Make it the first and only element
12920       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
12921       Matches[0].second = cast<FunctionDecl>(*Result);
12922       Matches.resize(1);
12923     } else
12924       HasComplained |= Complain;
12925   }
12926 
12927   void EliminateAllTemplateMatches() {
12928     //   [...] any function template specializations in the set are
12929     //   eliminated if the set also contains a non-template function, [...]
12930     for (unsigned I = 0, N = Matches.size(); I != N; ) {
12931       if (Matches[I].second->getPrimaryTemplate() == nullptr)
12932         ++I;
12933       else {
12934         Matches[I] = Matches[--N];
12935         Matches.resize(N);
12936       }
12937     }
12938   }
12939 
12940   void EliminateSuboptimalCudaMatches() {
12941     S.EraseUnwantedCUDAMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
12942                                Matches);
12943   }
12944 
12945 public:
12946   void ComplainNoMatchesFound() const {
12947     assert(Matches.empty());
12948     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
12949         << OvlExpr->getName() << TargetFunctionType
12950         << OvlExpr->getSourceRange();
12951     if (FailedCandidates.empty())
12952       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12953                                   /*TakingAddress=*/true);
12954     else {
12955       // We have some deduction failure messages. Use them to diagnose
12956       // the function templates, and diagnose the non-template candidates
12957       // normally.
12958       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12959                                  IEnd = OvlExpr->decls_end();
12960            I != IEnd; ++I)
12961         if (FunctionDecl *Fun =
12962                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
12963           if (!functionHasPassObjectSizeParams(Fun))
12964             S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
12965                                     /*TakingAddress=*/true);
12966       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
12967     }
12968   }
12969 
12970   bool IsInvalidFormOfPointerToMemberFunction() const {
12971     return TargetTypeIsNonStaticMemberFunction &&
12972       !OvlExprInfo.HasFormOfMemberPointer;
12973   }
12974 
12975   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
12976       // TODO: Should we condition this on whether any functions might
12977       // have matched, or is it more appropriate to do that in callers?
12978       // TODO: a fixit wouldn't hurt.
12979       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
12980         << TargetType << OvlExpr->getSourceRange();
12981   }
12982 
12983   bool IsStaticMemberFunctionFromBoundPointer() const {
12984     return StaticMemberFunctionFromBoundPointer;
12985   }
12986 
12987   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
12988     S.Diag(OvlExpr->getBeginLoc(),
12989            diag::err_invalid_form_pointer_member_function)
12990         << OvlExpr->getSourceRange();
12991   }
12992 
12993   void ComplainOfInvalidConversion() const {
12994     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
12995         << OvlExpr->getName() << TargetType;
12996   }
12997 
12998   void ComplainMultipleMatchesFound() const {
12999     assert(Matches.size() > 1);
13000     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
13001         << OvlExpr->getName() << OvlExpr->getSourceRange();
13002     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13003                                 /*TakingAddress=*/true);
13004   }
13005 
13006   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
13007 
13008   int getNumMatches() const { return Matches.size(); }
13009 
13010   FunctionDecl* getMatchingFunctionDecl() const {
13011     if (Matches.size() != 1) return nullptr;
13012     return Matches[0].second;
13013   }
13014 
13015   const DeclAccessPair* getMatchingFunctionAccessPair() const {
13016     if (Matches.size() != 1) return nullptr;
13017     return &Matches[0].first;
13018   }
13019 };
13020 }
13021 
13022 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
13023 /// an overloaded function (C++ [over.over]), where @p From is an
13024 /// expression with overloaded function type and @p ToType is the type
13025 /// we're trying to resolve to. For example:
13026 ///
13027 /// @code
13028 /// int f(double);
13029 /// int f(int);
13030 ///
13031 /// int (*pfd)(double) = f; // selects f(double)
13032 /// @endcode
13033 ///
13034 /// This routine returns the resulting FunctionDecl if it could be
13035 /// resolved, and NULL otherwise. When @p Complain is true, this
13036 /// routine will emit diagnostics if there is an error.
13037 FunctionDecl *
13038 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
13039                                          QualType TargetType,
13040                                          bool Complain,
13041                                          DeclAccessPair &FoundResult,
13042                                          bool *pHadMultipleCandidates) {
13043   assert(AddressOfExpr->getType() == Context.OverloadTy);
13044 
13045   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
13046                                      Complain);
13047   int NumMatches = Resolver.getNumMatches();
13048   FunctionDecl *Fn = nullptr;
13049   bool ShouldComplain = Complain && !Resolver.hasComplained();
13050   if (NumMatches == 0 && ShouldComplain) {
13051     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
13052       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
13053     else
13054       Resolver.ComplainNoMatchesFound();
13055   }
13056   else if (NumMatches > 1 && ShouldComplain)
13057     Resolver.ComplainMultipleMatchesFound();
13058   else if (NumMatches == 1) {
13059     Fn = Resolver.getMatchingFunctionDecl();
13060     assert(Fn);
13061     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13062       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
13063     FoundResult = *Resolver.getMatchingFunctionAccessPair();
13064     if (Complain) {
13065       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
13066         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
13067       else
13068         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
13069     }
13070   }
13071 
13072   if (pHadMultipleCandidates)
13073     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
13074   return Fn;
13075 }
13076 
13077 /// Given an expression that refers to an overloaded function, try to
13078 /// resolve that function to a single function that can have its address taken.
13079 /// This will modify `Pair` iff it returns non-null.
13080 ///
13081 /// This routine can only succeed if from all of the candidates in the overload
13082 /// set for SrcExpr that can have their addresses taken, there is one candidate
13083 /// that is more constrained than the rest.
13084 FunctionDecl *
13085 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
13086   OverloadExpr::FindResult R = OverloadExpr::find(E);
13087   OverloadExpr *Ovl = R.Expression;
13088   bool IsResultAmbiguous = false;
13089   FunctionDecl *Result = nullptr;
13090   DeclAccessPair DAP;
13091   SmallVector<FunctionDecl *, 2> AmbiguousDecls;
13092 
13093   // Return positive for better, negative for worse, 0 for equal preference.
13094   auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
13095     FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
13096     return static_cast<int>(IdentifyCUDAPreference(Caller, FD1)) -
13097            static_cast<int>(IdentifyCUDAPreference(Caller, FD2));
13098   };
13099 
13100   auto CheckMoreConstrained = [&](FunctionDecl *FD1,
13101                                   FunctionDecl *FD2) -> std::optional<bool> {
13102     if (FunctionDecl *MF = FD1->getInstantiatedFromMemberFunction())
13103       FD1 = MF;
13104     if (FunctionDecl *MF = FD2->getInstantiatedFromMemberFunction())
13105       FD2 = MF;
13106     SmallVector<const Expr *, 1> AC1, AC2;
13107     FD1->getAssociatedConstraints(AC1);
13108     FD2->getAssociatedConstraints(AC2);
13109     bool AtLeastAsConstrained1, AtLeastAsConstrained2;
13110     if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
13111       return std::nullopt;
13112     if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
13113       return std::nullopt;
13114     if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
13115       return std::nullopt;
13116     return AtLeastAsConstrained1;
13117   };
13118 
13119   // Don't use the AddressOfResolver because we're specifically looking for
13120   // cases where we have one overload candidate that lacks
13121   // enable_if/pass_object_size/...
13122   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
13123     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
13124     if (!FD)
13125       return nullptr;
13126 
13127     if (!checkAddressOfFunctionIsAvailable(FD))
13128       continue;
13129 
13130     // If we found a better result, update Result.
13131     auto FoundBetter = [&]() {
13132       IsResultAmbiguous = false;
13133       DAP = I.getPair();
13134       Result = FD;
13135     };
13136 
13137     // We have more than one result - see if it is more constrained than the
13138     // previous one.
13139     if (Result) {
13140       // Check CUDA preference first. If the candidates have differennt CUDA
13141       // preference, choose the one with higher CUDA preference. Otherwise,
13142       // choose the one with more constraints.
13143       if (getLangOpts().CUDA) {
13144         int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
13145         // FD has different preference than Result.
13146         if (PreferenceByCUDA != 0) {
13147           // FD is more preferable than Result.
13148           if (PreferenceByCUDA > 0)
13149             FoundBetter();
13150           continue;
13151         }
13152       }
13153       // FD has the same CUDA prefernece than Result. Continue check
13154       // constraints.
13155       std::optional<bool> MoreConstrainedThanPrevious =
13156           CheckMoreConstrained(FD, Result);
13157       if (!MoreConstrainedThanPrevious) {
13158         IsResultAmbiguous = true;
13159         AmbiguousDecls.push_back(FD);
13160         continue;
13161       }
13162       if (!*MoreConstrainedThanPrevious)
13163         continue;
13164       // FD is more constrained - replace Result with it.
13165     }
13166     FoundBetter();
13167   }
13168 
13169   if (IsResultAmbiguous)
13170     return nullptr;
13171 
13172   if (Result) {
13173     SmallVector<const Expr *, 1> ResultAC;
13174     // We skipped over some ambiguous declarations which might be ambiguous with
13175     // the selected result.
13176     for (FunctionDecl *Skipped : AmbiguousDecls) {
13177       // If skipped candidate has different CUDA preference than the result,
13178       // there is no ambiguity. Otherwise check whether they have different
13179       // constraints.
13180       if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
13181         continue;
13182       if (!CheckMoreConstrained(Skipped, Result))
13183         return nullptr;
13184     }
13185     Pair = DAP;
13186   }
13187   return Result;
13188 }
13189 
13190 /// Given an overloaded function, tries to turn it into a non-overloaded
13191 /// function reference using resolveAddressOfSingleOverloadCandidate. This
13192 /// will perform access checks, diagnose the use of the resultant decl, and, if
13193 /// requested, potentially perform a function-to-pointer decay.
13194 ///
13195 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
13196 /// Otherwise, returns true. This may emit diagnostics and return true.
13197 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
13198     ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
13199   Expr *E = SrcExpr.get();
13200   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
13201 
13202   DeclAccessPair DAP;
13203   FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
13204   if (!Found || Found->isCPUDispatchMultiVersion() ||
13205       Found->isCPUSpecificMultiVersion())
13206     return false;
13207 
13208   // Emitting multiple diagnostics for a function that is both inaccessible and
13209   // unavailable is consistent with our behavior elsewhere. So, always check
13210   // for both.
13211   DiagnoseUseOfDecl(Found, E->getExprLoc());
13212   CheckAddressOfMemberAccess(E, DAP);
13213   ExprResult Res = FixOverloadedFunctionReference(E, DAP, Found);
13214   if (Res.isInvalid())
13215     return false;
13216   Expr *Fixed = Res.get();
13217   if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
13218     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
13219   else
13220     SrcExpr = Fixed;
13221   return true;
13222 }
13223 
13224 /// Given an expression that refers to an overloaded function, try to
13225 /// resolve that overloaded function expression down to a single function.
13226 ///
13227 /// This routine can only resolve template-ids that refer to a single function
13228 /// template, where that template-id refers to a single template whose template
13229 /// arguments are either provided by the template-id or have defaults,
13230 /// as described in C++0x [temp.arg.explicit]p3.
13231 ///
13232 /// If no template-ids are found, no diagnostics are emitted and NULL is
13233 /// returned.
13234 FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(
13235     OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
13236     TemplateSpecCandidateSet *FailedTSC) {
13237   // C++ [over.over]p1:
13238   //   [...] [Note: any redundant set of parentheses surrounding the
13239   //   overloaded function name is ignored (5.1). ]
13240   // C++ [over.over]p1:
13241   //   [...] The overloaded function name can be preceded by the &
13242   //   operator.
13243 
13244   // If we didn't actually find any template-ids, we're done.
13245   if (!ovl->hasExplicitTemplateArgs())
13246     return nullptr;
13247 
13248   TemplateArgumentListInfo ExplicitTemplateArgs;
13249   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
13250 
13251   // Look through all of the overloaded functions, searching for one
13252   // whose type matches exactly.
13253   FunctionDecl *Matched = nullptr;
13254   for (UnresolvedSetIterator I = ovl->decls_begin(),
13255          E = ovl->decls_end(); I != E; ++I) {
13256     // C++0x [temp.arg.explicit]p3:
13257     //   [...] In contexts where deduction is done and fails, or in contexts
13258     //   where deduction is not done, if a template argument list is
13259     //   specified and it, along with any default template arguments,
13260     //   identifies a single function template specialization, then the
13261     //   template-id is an lvalue for the function template specialization.
13262     FunctionTemplateDecl *FunctionTemplate
13263       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
13264 
13265     // C++ [over.over]p2:
13266     //   If the name is a function template, template argument deduction is
13267     //   done (14.8.2.2), and if the argument deduction succeeds, the
13268     //   resulting template argument list is used to generate a single
13269     //   function template specialization, which is added to the set of
13270     //   overloaded functions considered.
13271     FunctionDecl *Specialization = nullptr;
13272     TemplateDeductionInfo Info(ovl->getNameLoc());
13273     if (TemplateDeductionResult Result
13274           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
13275                                     Specialization, Info,
13276                                     /*IsAddressOfFunction*/true)) {
13277       // Make a note of the failed deduction for diagnostics.
13278       if (FailedTSC)
13279         FailedTSC->addCandidate().set(
13280             I.getPair(), FunctionTemplate->getTemplatedDecl(),
13281             MakeDeductionFailureInfo(Context, Result, Info));
13282       continue;
13283     }
13284 
13285     assert(Specialization && "no specialization and no error?");
13286 
13287     // Multiple matches; we can't resolve to a single declaration.
13288     if (Matched) {
13289       if (Complain) {
13290         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
13291           << ovl->getName();
13292         NoteAllOverloadCandidates(ovl);
13293       }
13294       return nullptr;
13295     }
13296 
13297     Matched = Specialization;
13298     if (FoundResult) *FoundResult = I.getPair();
13299   }
13300 
13301   if (Matched &&
13302       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
13303     return nullptr;
13304 
13305   return Matched;
13306 }
13307 
13308 // Resolve and fix an overloaded expression that can be resolved
13309 // because it identifies a single function template specialization.
13310 //
13311 // Last three arguments should only be supplied if Complain = true
13312 //
13313 // Return true if it was logically possible to so resolve the
13314 // expression, regardless of whether or not it succeeded.  Always
13315 // returns true if 'complain' is set.
13316 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
13317     ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
13318     SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
13319     unsigned DiagIDForComplaining) {
13320   assert(SrcExpr.get()->getType() == Context.OverloadTy);
13321 
13322   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
13323 
13324   DeclAccessPair found;
13325   ExprResult SingleFunctionExpression;
13326   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
13327                            ovl.Expression, /*complain*/ false, &found)) {
13328     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
13329       SrcExpr = ExprError();
13330       return true;
13331     }
13332 
13333     // It is only correct to resolve to an instance method if we're
13334     // resolving a form that's permitted to be a pointer to member.
13335     // Otherwise we'll end up making a bound member expression, which
13336     // is illegal in all the contexts we resolve like this.
13337     if (!ovl.HasFormOfMemberPointer &&
13338         isa<CXXMethodDecl>(fn) &&
13339         cast<CXXMethodDecl>(fn)->isInstance()) {
13340       if (!complain) return false;
13341 
13342       Diag(ovl.Expression->getExprLoc(),
13343            diag::err_bound_member_function)
13344         << 0 << ovl.Expression->getSourceRange();
13345 
13346       // TODO: I believe we only end up here if there's a mix of
13347       // static and non-static candidates (otherwise the expression
13348       // would have 'bound member' type, not 'overload' type).
13349       // Ideally we would note which candidate was chosen and why
13350       // the static candidates were rejected.
13351       SrcExpr = ExprError();
13352       return true;
13353     }
13354 
13355     // Fix the expression to refer to 'fn'.
13356     SingleFunctionExpression =
13357         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
13358 
13359     // If desired, do function-to-pointer decay.
13360     if (doFunctionPointerConversion) {
13361       SingleFunctionExpression =
13362         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
13363       if (SingleFunctionExpression.isInvalid()) {
13364         SrcExpr = ExprError();
13365         return true;
13366       }
13367     }
13368   }
13369 
13370   if (!SingleFunctionExpression.isUsable()) {
13371     if (complain) {
13372       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
13373         << ovl.Expression->getName()
13374         << DestTypeForComplaining
13375         << OpRangeForComplaining
13376         << ovl.Expression->getQualifierLoc().getSourceRange();
13377       NoteAllOverloadCandidates(SrcExpr.get());
13378 
13379       SrcExpr = ExprError();
13380       return true;
13381     }
13382 
13383     return false;
13384   }
13385 
13386   SrcExpr = SingleFunctionExpression;
13387   return true;
13388 }
13389 
13390 /// Add a single candidate to the overload set.
13391 static void AddOverloadedCallCandidate(Sema &S,
13392                                        DeclAccessPair FoundDecl,
13393                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
13394                                        ArrayRef<Expr *> Args,
13395                                        OverloadCandidateSet &CandidateSet,
13396                                        bool PartialOverloading,
13397                                        bool KnownValid) {
13398   NamedDecl *Callee = FoundDecl.getDecl();
13399   if (isa<UsingShadowDecl>(Callee))
13400     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
13401 
13402   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
13403     if (ExplicitTemplateArgs) {
13404       assert(!KnownValid && "Explicit template arguments?");
13405       return;
13406     }
13407     // Prevent ill-formed function decls to be added as overload candidates.
13408     if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
13409       return;
13410 
13411     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
13412                            /*SuppressUserConversions=*/false,
13413                            PartialOverloading);
13414     return;
13415   }
13416 
13417   if (FunctionTemplateDecl *FuncTemplate
13418       = dyn_cast<FunctionTemplateDecl>(Callee)) {
13419     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
13420                                    ExplicitTemplateArgs, Args, CandidateSet,
13421                                    /*SuppressUserConversions=*/false,
13422                                    PartialOverloading);
13423     return;
13424   }
13425 
13426   assert(!KnownValid && "unhandled case in overloaded call candidate");
13427 }
13428 
13429 /// Add the overload candidates named by callee and/or found by argument
13430 /// dependent lookup to the given overload set.
13431 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
13432                                        ArrayRef<Expr *> Args,
13433                                        OverloadCandidateSet &CandidateSet,
13434                                        bool PartialOverloading) {
13435 
13436 #ifndef NDEBUG
13437   // Verify that ArgumentDependentLookup is consistent with the rules
13438   // in C++0x [basic.lookup.argdep]p3:
13439   //
13440   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
13441   //   and let Y be the lookup set produced by argument dependent
13442   //   lookup (defined as follows). If X contains
13443   //
13444   //     -- a declaration of a class member, or
13445   //
13446   //     -- a block-scope function declaration that is not a
13447   //        using-declaration, or
13448   //
13449   //     -- a declaration that is neither a function or a function
13450   //        template
13451   //
13452   //   then Y is empty.
13453 
13454   if (ULE->requiresADL()) {
13455     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
13456            E = ULE->decls_end(); I != E; ++I) {
13457       assert(!(*I)->getDeclContext()->isRecord());
13458       assert(isa<UsingShadowDecl>(*I) ||
13459              !(*I)->getDeclContext()->isFunctionOrMethod());
13460       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
13461     }
13462   }
13463 #endif
13464 
13465   // It would be nice to avoid this copy.
13466   TemplateArgumentListInfo TABuffer;
13467   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13468   if (ULE->hasExplicitTemplateArgs()) {
13469     ULE->copyTemplateArgumentsInto(TABuffer);
13470     ExplicitTemplateArgs = &TABuffer;
13471   }
13472 
13473   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
13474          E = ULE->decls_end(); I != E; ++I)
13475     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13476                                CandidateSet, PartialOverloading,
13477                                /*KnownValid*/ true);
13478 
13479   if (ULE->requiresADL())
13480     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
13481                                          Args, ExplicitTemplateArgs,
13482                                          CandidateSet, PartialOverloading);
13483 }
13484 
13485 /// Add the call candidates from the given set of lookup results to the given
13486 /// overload set. Non-function lookup results are ignored.
13487 void Sema::AddOverloadedCallCandidates(
13488     LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
13489     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
13490   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
13491     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13492                                CandidateSet, false, /*KnownValid*/ false);
13493 }
13494 
13495 /// Determine whether a declaration with the specified name could be moved into
13496 /// a different namespace.
13497 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
13498   switch (Name.getCXXOverloadedOperator()) {
13499   case OO_New: case OO_Array_New:
13500   case OO_Delete: case OO_Array_Delete:
13501     return false;
13502 
13503   default:
13504     return true;
13505   }
13506 }
13507 
13508 /// Attempt to recover from an ill-formed use of a non-dependent name in a
13509 /// template, where the non-dependent name was declared after the template
13510 /// was defined. This is common in code written for a compilers which do not
13511 /// correctly implement two-stage name lookup.
13512 ///
13513 /// Returns true if a viable candidate was found and a diagnostic was issued.
13514 static bool DiagnoseTwoPhaseLookup(
13515     Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
13516     LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
13517     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
13518     CXXRecordDecl **FoundInClass = nullptr) {
13519   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
13520     return false;
13521 
13522   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
13523     if (DC->isTransparentContext())
13524       continue;
13525 
13526     SemaRef.LookupQualifiedName(R, DC);
13527 
13528     if (!R.empty()) {
13529       R.suppressDiagnostics();
13530 
13531       OverloadCandidateSet Candidates(FnLoc, CSK);
13532       SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
13533                                           Candidates);
13534 
13535       OverloadCandidateSet::iterator Best;
13536       OverloadingResult OR =
13537           Candidates.BestViableFunction(SemaRef, FnLoc, Best);
13538 
13539       if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
13540         // We either found non-function declarations or a best viable function
13541         // at class scope. A class-scope lookup result disables ADL. Don't
13542         // look past this, but let the caller know that we found something that
13543         // either is, or might be, usable in this class.
13544         if (FoundInClass) {
13545           *FoundInClass = RD;
13546           if (OR == OR_Success) {
13547             R.clear();
13548             R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
13549             R.resolveKind();
13550           }
13551         }
13552         return false;
13553       }
13554 
13555       if (OR != OR_Success) {
13556         // There wasn't a unique best function or function template.
13557         return false;
13558       }
13559 
13560       // Find the namespaces where ADL would have looked, and suggest
13561       // declaring the function there instead.
13562       Sema::AssociatedNamespaceSet AssociatedNamespaces;
13563       Sema::AssociatedClassSet AssociatedClasses;
13564       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
13565                                                  AssociatedNamespaces,
13566                                                  AssociatedClasses);
13567       Sema::AssociatedNamespaceSet SuggestedNamespaces;
13568       if (canBeDeclaredInNamespace(R.getLookupName())) {
13569         DeclContext *Std = SemaRef.getStdNamespace();
13570         for (Sema::AssociatedNamespaceSet::iterator
13571                it = AssociatedNamespaces.begin(),
13572                end = AssociatedNamespaces.end(); it != end; ++it) {
13573           // Never suggest declaring a function within namespace 'std'.
13574           if (Std && Std->Encloses(*it))
13575             continue;
13576 
13577           // Never suggest declaring a function within a namespace with a
13578           // reserved name, like __gnu_cxx.
13579           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
13580           if (NS &&
13581               NS->getQualifiedNameAsString().find("__") != std::string::npos)
13582             continue;
13583 
13584           SuggestedNamespaces.insert(*it);
13585         }
13586       }
13587 
13588       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
13589         << R.getLookupName();
13590       if (SuggestedNamespaces.empty()) {
13591         SemaRef.Diag(Best->Function->getLocation(),
13592                      diag::note_not_found_by_two_phase_lookup)
13593           << R.getLookupName() << 0;
13594       } else if (SuggestedNamespaces.size() == 1) {
13595         SemaRef.Diag(Best->Function->getLocation(),
13596                      diag::note_not_found_by_two_phase_lookup)
13597           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
13598       } else {
13599         // FIXME: It would be useful to list the associated namespaces here,
13600         // but the diagnostics infrastructure doesn't provide a way to produce
13601         // a localized representation of a list of items.
13602         SemaRef.Diag(Best->Function->getLocation(),
13603                      diag::note_not_found_by_two_phase_lookup)
13604           << R.getLookupName() << 2;
13605       }
13606 
13607       // Try to recover by calling this function.
13608       return true;
13609     }
13610 
13611     R.clear();
13612   }
13613 
13614   return false;
13615 }
13616 
13617 /// Attempt to recover from ill-formed use of a non-dependent operator in a
13618 /// template, where the non-dependent operator was declared after the template
13619 /// was defined.
13620 ///
13621 /// Returns true if a viable candidate was found and a diagnostic was issued.
13622 static bool
13623 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
13624                                SourceLocation OpLoc,
13625                                ArrayRef<Expr *> Args) {
13626   DeclarationName OpName =
13627     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
13628   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
13629   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
13630                                 OverloadCandidateSet::CSK_Operator,
13631                                 /*ExplicitTemplateArgs=*/nullptr, Args);
13632 }
13633 
13634 namespace {
13635 class BuildRecoveryCallExprRAII {
13636   Sema &SemaRef;
13637   Sema::SatisfactionStackResetRAII SatStack;
13638 
13639 public:
13640   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
13641     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
13642     SemaRef.IsBuildingRecoveryCallExpr = true;
13643   }
13644 
13645   ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
13646 };
13647 }
13648 
13649 /// Attempts to recover from a call where no functions were found.
13650 ///
13651 /// This function will do one of three things:
13652 ///  * Diagnose, recover, and return a recovery expression.
13653 ///  * Diagnose, fail to recover, and return ExprError().
13654 ///  * Do not diagnose, do not recover, and return ExprResult(). The caller is
13655 ///    expected to diagnose as appropriate.
13656 static ExprResult
13657 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
13658                       UnresolvedLookupExpr *ULE,
13659                       SourceLocation LParenLoc,
13660                       MutableArrayRef<Expr *> Args,
13661                       SourceLocation RParenLoc,
13662                       bool EmptyLookup, bool AllowTypoCorrection) {
13663   // Do not try to recover if it is already building a recovery call.
13664   // This stops infinite loops for template instantiations like
13665   //
13666   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
13667   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
13668   if (SemaRef.IsBuildingRecoveryCallExpr)
13669     return ExprResult();
13670   BuildRecoveryCallExprRAII RCE(SemaRef);
13671 
13672   CXXScopeSpec SS;
13673   SS.Adopt(ULE->getQualifierLoc());
13674   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
13675 
13676   TemplateArgumentListInfo TABuffer;
13677   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13678   if (ULE->hasExplicitTemplateArgs()) {
13679     ULE->copyTemplateArgumentsInto(TABuffer);
13680     ExplicitTemplateArgs = &TABuffer;
13681   }
13682 
13683   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
13684                  Sema::LookupOrdinaryName);
13685   CXXRecordDecl *FoundInClass = nullptr;
13686   if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
13687                              OverloadCandidateSet::CSK_Normal,
13688                              ExplicitTemplateArgs, Args, &FoundInClass)) {
13689     // OK, diagnosed a two-phase lookup issue.
13690   } else if (EmptyLookup) {
13691     // Try to recover from an empty lookup with typo correction.
13692     R.clear();
13693     NoTypoCorrectionCCC NoTypoValidator{};
13694     FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
13695                                                 ExplicitTemplateArgs != nullptr,
13696                                                 dyn_cast<MemberExpr>(Fn));
13697     CorrectionCandidateCallback &Validator =
13698         AllowTypoCorrection
13699             ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
13700             : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
13701     if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
13702                                     Args))
13703       return ExprError();
13704   } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
13705     // We found a usable declaration of the name in a dependent base of some
13706     // enclosing class.
13707     // FIXME: We should also explain why the candidates found by name lookup
13708     // were not viable.
13709     if (SemaRef.DiagnoseDependentMemberLookup(R))
13710       return ExprError();
13711   } else {
13712     // We had viable candidates and couldn't recover; let the caller diagnose
13713     // this.
13714     return ExprResult();
13715   }
13716 
13717   // If we get here, we should have issued a diagnostic and formed a recovery
13718   // lookup result.
13719   assert(!R.empty() && "lookup results empty despite recovery");
13720 
13721   // If recovery created an ambiguity, just bail out.
13722   if (R.isAmbiguous()) {
13723     R.suppressDiagnostics();
13724     return ExprError();
13725   }
13726 
13727   // Build an implicit member call if appropriate.  Just drop the
13728   // casts and such from the call, we don't really care.
13729   ExprResult NewFn = ExprError();
13730   if ((*R.begin())->isCXXClassMember())
13731     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
13732                                                     ExplicitTemplateArgs, S);
13733   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
13734     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
13735                                         ExplicitTemplateArgs);
13736   else
13737     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
13738 
13739   if (NewFn.isInvalid())
13740     return ExprError();
13741 
13742   // This shouldn't cause an infinite loop because we're giving it
13743   // an expression with viable lookup results, which should never
13744   // end up here.
13745   return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
13746                                MultiExprArg(Args.data(), Args.size()),
13747                                RParenLoc);
13748 }
13749 
13750 /// Constructs and populates an OverloadedCandidateSet from
13751 /// the given function.
13752 /// \returns true when an the ExprResult output parameter has been set.
13753 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
13754                                   UnresolvedLookupExpr *ULE,
13755                                   MultiExprArg Args,
13756                                   SourceLocation RParenLoc,
13757                                   OverloadCandidateSet *CandidateSet,
13758                                   ExprResult *Result) {
13759 #ifndef NDEBUG
13760   if (ULE->requiresADL()) {
13761     // To do ADL, we must have found an unqualified name.
13762     assert(!ULE->getQualifier() && "qualified name with ADL");
13763 
13764     // We don't perform ADL for implicit declarations of builtins.
13765     // Verify that this was correctly set up.
13766     FunctionDecl *F;
13767     if (ULE->decls_begin() != ULE->decls_end() &&
13768         ULE->decls_begin() + 1 == ULE->decls_end() &&
13769         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
13770         F->getBuiltinID() && F->isImplicit())
13771       llvm_unreachable("performing ADL for builtin");
13772 
13773     // We don't perform ADL in C.
13774     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
13775   }
13776 #endif
13777 
13778   UnbridgedCastsSet UnbridgedCasts;
13779   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
13780     *Result = ExprError();
13781     return true;
13782   }
13783 
13784   // Add the functions denoted by the callee to the set of candidate
13785   // functions, including those from argument-dependent lookup.
13786   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
13787 
13788   if (getLangOpts().MSVCCompat &&
13789       CurContext->isDependentContext() && !isSFINAEContext() &&
13790       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
13791 
13792     OverloadCandidateSet::iterator Best;
13793     if (CandidateSet->empty() ||
13794         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
13795             OR_No_Viable_Function) {
13796       // In Microsoft mode, if we are inside a template class member function
13797       // then create a type dependent CallExpr. The goal is to postpone name
13798       // lookup to instantiation time to be able to search into type dependent
13799       // base classes.
13800       CallExpr *CE =
13801           CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
13802                            RParenLoc, CurFPFeatureOverrides());
13803       CE->markDependentForPostponedNameLookup();
13804       *Result = CE;
13805       return true;
13806     }
13807   }
13808 
13809   if (CandidateSet->empty())
13810     return false;
13811 
13812   UnbridgedCasts.restore();
13813   return false;
13814 }
13815 
13816 // Guess at what the return type for an unresolvable overload should be.
13817 static QualType chooseRecoveryType(OverloadCandidateSet &CS,
13818                                    OverloadCandidateSet::iterator *Best) {
13819   std::optional<QualType> Result;
13820   // Adjust Type after seeing a candidate.
13821   auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
13822     if (!Candidate.Function)
13823       return;
13824     if (Candidate.Function->isInvalidDecl())
13825       return;
13826     QualType T = Candidate.Function->getReturnType();
13827     if (T.isNull())
13828       return;
13829     if (!Result)
13830       Result = T;
13831     else if (Result != T)
13832       Result = QualType();
13833   };
13834 
13835   // Look for an unambiguous type from a progressively larger subset.
13836   // e.g. if types disagree, but all *viable* overloads return int, choose int.
13837   //
13838   // First, consider only the best candidate.
13839   if (Best && *Best != CS.end())
13840     ConsiderCandidate(**Best);
13841   // Next, consider only viable candidates.
13842   if (!Result)
13843     for (const auto &C : CS)
13844       if (C.Viable)
13845         ConsiderCandidate(C);
13846   // Finally, consider all candidates.
13847   if (!Result)
13848     for (const auto &C : CS)
13849       ConsiderCandidate(C);
13850 
13851   if (!Result)
13852     return QualType();
13853   auto Value = *Result;
13854   if (Value.isNull() || Value->isUndeducedType())
13855     return QualType();
13856   return Value;
13857 }
13858 
13859 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
13860 /// the completed call expression. If overload resolution fails, emits
13861 /// diagnostics and returns ExprError()
13862 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
13863                                            UnresolvedLookupExpr *ULE,
13864                                            SourceLocation LParenLoc,
13865                                            MultiExprArg Args,
13866                                            SourceLocation RParenLoc,
13867                                            Expr *ExecConfig,
13868                                            OverloadCandidateSet *CandidateSet,
13869                                            OverloadCandidateSet::iterator *Best,
13870                                            OverloadingResult OverloadResult,
13871                                            bool AllowTypoCorrection) {
13872   switch (OverloadResult) {
13873   case OR_Success: {
13874     FunctionDecl *FDecl = (*Best)->Function;
13875     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
13876     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
13877       return ExprError();
13878     ExprResult Res =
13879         SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13880     if (Res.isInvalid())
13881       return ExprError();
13882     return SemaRef.BuildResolvedCallExpr(
13883         Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
13884         /*IsExecConfig=*/false, (*Best)->IsADLCandidate);
13885   }
13886 
13887   case OR_No_Viable_Function: {
13888     // Try to recover by looking for viable functions which the user might
13889     // have meant to call.
13890     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
13891                                                 Args, RParenLoc,
13892                                                 CandidateSet->empty(),
13893                                                 AllowTypoCorrection);
13894     if (Recovery.isInvalid() || Recovery.isUsable())
13895       return Recovery;
13896 
13897     // If the user passes in a function that we can't take the address of, we
13898     // generally end up emitting really bad error messages. Here, we attempt to
13899     // emit better ones.
13900     for (const Expr *Arg : Args) {
13901       if (!Arg->getType()->isFunctionType())
13902         continue;
13903       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
13904         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13905         if (FD &&
13906             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13907                                                        Arg->getExprLoc()))
13908           return ExprError();
13909       }
13910     }
13911 
13912     CandidateSet->NoteCandidates(
13913         PartialDiagnosticAt(
13914             Fn->getBeginLoc(),
13915             SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
13916                 << ULE->getName() << Fn->getSourceRange()),
13917         SemaRef, OCD_AllCandidates, Args);
13918     break;
13919   }
13920 
13921   case OR_Ambiguous:
13922     CandidateSet->NoteCandidates(
13923         PartialDiagnosticAt(Fn->getBeginLoc(),
13924                             SemaRef.PDiag(diag::err_ovl_ambiguous_call)
13925                                 << ULE->getName() << Fn->getSourceRange()),
13926         SemaRef, OCD_AmbiguousCandidates, Args);
13927     break;
13928 
13929   case OR_Deleted: {
13930     CandidateSet->NoteCandidates(
13931         PartialDiagnosticAt(Fn->getBeginLoc(),
13932                             SemaRef.PDiag(diag::err_ovl_deleted_call)
13933                                 << ULE->getName() << Fn->getSourceRange()),
13934         SemaRef, OCD_AllCandidates, Args);
13935 
13936     // We emitted an error for the unavailable/deleted function call but keep
13937     // the call in the AST.
13938     FunctionDecl *FDecl = (*Best)->Function;
13939     ExprResult Res =
13940         SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13941     if (Res.isInvalid())
13942       return ExprError();
13943     return SemaRef.BuildResolvedCallExpr(
13944         Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
13945         /*IsExecConfig=*/false, (*Best)->IsADLCandidate);
13946   }
13947   }
13948 
13949   // Overload resolution failed, try to recover.
13950   SmallVector<Expr *, 8> SubExprs = {Fn};
13951   SubExprs.append(Args.begin(), Args.end());
13952   return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
13953                                     chooseRecoveryType(*CandidateSet, Best));
13954 }
13955 
13956 static void markUnaddressableCandidatesUnviable(Sema &S,
13957                                                 OverloadCandidateSet &CS) {
13958   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
13959     if (I->Viable &&
13960         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
13961       I->Viable = false;
13962       I->FailureKind = ovl_fail_addr_not_available;
13963     }
13964   }
13965 }
13966 
13967 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
13968 /// (which eventually refers to the declaration Func) and the call
13969 /// arguments Args/NumArgs, attempt to resolve the function call down
13970 /// to a specific function. If overload resolution succeeds, returns
13971 /// the call expression produced by overload resolution.
13972 /// Otherwise, emits diagnostics and returns ExprError.
13973 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
13974                                          UnresolvedLookupExpr *ULE,
13975                                          SourceLocation LParenLoc,
13976                                          MultiExprArg Args,
13977                                          SourceLocation RParenLoc,
13978                                          Expr *ExecConfig,
13979                                          bool AllowTypoCorrection,
13980                                          bool CalleesAddressIsTaken) {
13981   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
13982                                     OverloadCandidateSet::CSK_Normal);
13983   ExprResult result;
13984 
13985   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
13986                              &result))
13987     return result;
13988 
13989   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
13990   // functions that aren't addressible are considered unviable.
13991   if (CalleesAddressIsTaken)
13992     markUnaddressableCandidatesUnviable(*this, CandidateSet);
13993 
13994   OverloadCandidateSet::iterator Best;
13995   OverloadingResult OverloadResult =
13996       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
13997 
13998   // Model the case with a call to a templated function whose definition
13999   // encloses the call and whose return type contains a placeholder type as if
14000   // the UnresolvedLookupExpr was type-dependent.
14001   if (OverloadResult == OR_Success) {
14002     const FunctionDecl *FDecl = Best->Function;
14003     if (FDecl && FDecl->isTemplateInstantiation() &&
14004         FDecl->getReturnType()->isUndeducedType()) {
14005       if (const auto *TP =
14006               FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
14007           TP && TP->willHaveBody()) {
14008         return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
14009                                 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
14010       }
14011     }
14012   }
14013 
14014   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
14015                                   ExecConfig, &CandidateSet, &Best,
14016                                   OverloadResult, AllowTypoCorrection);
14017 }
14018 
14019 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
14020   return Functions.size() > 1 ||
14021          (Functions.size() == 1 &&
14022           isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl()));
14023 }
14024 
14025 ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
14026                                             NestedNameSpecifierLoc NNSLoc,
14027                                             DeclarationNameInfo DNI,
14028                                             const UnresolvedSetImpl &Fns,
14029                                             bool PerformADL) {
14030   return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI,
14031                                       PerformADL, IsOverloaded(Fns),
14032                                       Fns.begin(), Fns.end());
14033 }
14034 
14035 ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
14036                                         CXXConversionDecl *Method,
14037                                         bool HadMultipleCandidates) {
14038   // Convert the expression to match the conversion function's implicit object
14039   // parameter.
14040   ExprResult Exp;
14041   if (Method->isExplicitObjectMemberFunction())
14042     Exp = InitializeExplicitObjectArgument(*this, E, Method);
14043   else
14044     Exp = PerformImplicitObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
14045                                                       FoundDecl, Method);
14046   if (Exp.isInvalid())
14047     return true;
14048 
14049   if (Method->getParent()->isLambda() &&
14050       Method->getConversionType()->isBlockPointerType()) {
14051     // This is a lambda conversion to block pointer; check if the argument
14052     // was a LambdaExpr.
14053     Expr *SubE = E;
14054     auto *CE = dyn_cast<CastExpr>(SubE);
14055     if (CE && CE->getCastKind() == CK_NoOp)
14056       SubE = CE->getSubExpr();
14057     SubE = SubE->IgnoreParens();
14058     if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
14059       SubE = BE->getSubExpr();
14060     if (isa<LambdaExpr>(SubE)) {
14061       // For the conversion to block pointer on a lambda expression, we
14062       // construct a special BlockLiteral instead; this doesn't really make
14063       // a difference in ARC, but outside of ARC the resulting block literal
14064       // follows the normal lifetime rules for block literals instead of being
14065       // autoreleased.
14066       PushExpressionEvaluationContext(
14067           ExpressionEvaluationContext::PotentiallyEvaluated);
14068       ExprResult BlockExp = BuildBlockForLambdaConversion(
14069           Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
14070       PopExpressionEvaluationContext();
14071 
14072       // FIXME: This note should be produced by a CodeSynthesisContext.
14073       if (BlockExp.isInvalid())
14074         Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
14075       return BlockExp;
14076     }
14077   }
14078   CallExpr *CE;
14079   QualType ResultType = Method->getReturnType();
14080   ExprValueKind VK = Expr::getValueKindForType(ResultType);
14081   ResultType = ResultType.getNonLValueExprType(Context);
14082   if (Method->isExplicitObjectMemberFunction()) {
14083     ExprResult FnExpr =
14084         CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
14085                               HadMultipleCandidates, E->getBeginLoc());
14086     if (FnExpr.isInvalid())
14087       return ExprError();
14088     Expr *ObjectParam = Exp.get();
14089     CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
14090                           ResultType, VK, Exp.get()->getEndLoc(),
14091                           CurFPFeatureOverrides());
14092   } else {
14093     MemberExpr *ME =
14094         BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
14095                         NestedNameSpecifierLoc(), SourceLocation(), Method,
14096                         DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
14097                         HadMultipleCandidates, DeclarationNameInfo(),
14098                         Context.BoundMemberTy, VK_PRValue, OK_Ordinary);
14099 
14100     CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
14101                                    Exp.get()->getEndLoc(),
14102                                    CurFPFeatureOverrides());
14103   }
14104 
14105   if (CheckFunctionCall(Method, CE,
14106                         Method->getType()->castAs<FunctionProtoType>()))
14107     return ExprError();
14108 
14109   return CheckForImmediateInvocation(CE, CE->getDirectCallee());
14110 }
14111 
14112 /// Create a unary operation that may resolve to an overloaded
14113 /// operator.
14114 ///
14115 /// \param OpLoc The location of the operator itself (e.g., '*').
14116 ///
14117 /// \param Opc The UnaryOperatorKind that describes this operator.
14118 ///
14119 /// \param Fns The set of non-member functions that will be
14120 /// considered by overload resolution. The caller needs to build this
14121 /// set based on the context using, e.g.,
14122 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
14123 /// set should not contain any member functions; those will be added
14124 /// by CreateOverloadedUnaryOp().
14125 ///
14126 /// \param Input The input argument.
14127 ExprResult
14128 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
14129                               const UnresolvedSetImpl &Fns,
14130                               Expr *Input, bool PerformADL) {
14131   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
14132   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
14133   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
14134   // TODO: provide better source location info.
14135   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14136 
14137   if (checkPlaceholderForOverload(*this, Input))
14138     return ExprError();
14139 
14140   Expr *Args[2] = { Input, nullptr };
14141   unsigned NumArgs = 1;
14142 
14143   // For post-increment and post-decrement, add the implicit '0' as
14144   // the second argument, so that we know this is a post-increment or
14145   // post-decrement.
14146   if (Opc == UO_PostInc || Opc == UO_PostDec) {
14147     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14148     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
14149                                      SourceLocation());
14150     NumArgs = 2;
14151   }
14152 
14153   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
14154 
14155   if (Input->isTypeDependent()) {
14156     if (Fns.empty())
14157       return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy,
14158                                    VK_PRValue, OK_Ordinary, OpLoc, false,
14159                                    CurFPFeatureOverrides());
14160 
14161     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14162     ExprResult Fn = CreateUnresolvedLookupExpr(
14163         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
14164     if (Fn.isInvalid())
14165       return ExprError();
14166     return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
14167                                        Context.DependentTy, VK_PRValue, OpLoc,
14168                                        CurFPFeatureOverrides());
14169   }
14170 
14171   // Build an empty overload set.
14172   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
14173 
14174   // Add the candidates from the given function set.
14175   AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
14176 
14177   // Add operator candidates that are member functions.
14178   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
14179 
14180   // Add candidates from ADL.
14181   if (PerformADL) {
14182     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
14183                                          /*ExplicitTemplateArgs*/nullptr,
14184                                          CandidateSet);
14185   }
14186 
14187   // Add builtin operator candidates.
14188   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
14189 
14190   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14191 
14192   // Perform overload resolution.
14193   OverloadCandidateSet::iterator Best;
14194   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14195   case OR_Success: {
14196     // We found a built-in operator or an overloaded operator.
14197     FunctionDecl *FnDecl = Best->Function;
14198 
14199     if (FnDecl) {
14200       Expr *Base = nullptr;
14201       // We matched an overloaded operator. Build a call to that
14202       // operator.
14203 
14204       // Convert the arguments.
14205       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
14206         CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
14207 
14208         ExprResult InputInit;
14209         if (Method->isExplicitObjectMemberFunction())
14210           InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
14211         else
14212           InputInit = PerformImplicitObjectArgumentInitialization(
14213               Input, /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14214         if (InputInit.isInvalid())
14215           return ExprError();
14216         Base = Input = InputInit.get();
14217       } else {
14218         // Convert the arguments.
14219         ExprResult InputInit
14220           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14221                                                       Context,
14222                                                       FnDecl->getParamDecl(0)),
14223                                       SourceLocation(),
14224                                       Input);
14225         if (InputInit.isInvalid())
14226           return ExprError();
14227         Input = InputInit.get();
14228       }
14229 
14230       // Build the actual expression node.
14231       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
14232                                                 Base, HadMultipleCandidates,
14233                                                 OpLoc);
14234       if (FnExpr.isInvalid())
14235         return ExprError();
14236 
14237       // Determine the result type.
14238       QualType ResultTy = FnDecl->getReturnType();
14239       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14240       ResultTy = ResultTy.getNonLValueExprType(Context);
14241 
14242       Args[0] = Input;
14243       CallExpr *TheCall = CXXOperatorCallExpr::Create(
14244           Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
14245           CurFPFeatureOverrides(), Best->IsADLCandidate);
14246 
14247       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
14248         return ExprError();
14249 
14250       if (CheckFunctionCall(FnDecl, TheCall,
14251                             FnDecl->getType()->castAs<FunctionProtoType>()))
14252         return ExprError();
14253       return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
14254     } else {
14255       // We matched a built-in operator. Convert the arguments, then
14256       // break out so that we will build the appropriate built-in
14257       // operator node.
14258       ExprResult InputRes = PerformImplicitConversion(
14259           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
14260           CCK_ForBuiltinOverloadedOp);
14261       if (InputRes.isInvalid())
14262         return ExprError();
14263       Input = InputRes.get();
14264       break;
14265     }
14266   }
14267 
14268   case OR_No_Viable_Function:
14269     // This is an erroneous use of an operator which can be overloaded by
14270     // a non-member function. Check for non-member operators which were
14271     // defined too late to be candidates.
14272     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
14273       // FIXME: Recover by calling the found function.
14274       return ExprError();
14275 
14276     // No viable function; fall through to handling this as a
14277     // built-in operator, which will produce an error message for us.
14278     break;
14279 
14280   case OR_Ambiguous:
14281     CandidateSet.NoteCandidates(
14282         PartialDiagnosticAt(OpLoc,
14283                             PDiag(diag::err_ovl_ambiguous_oper_unary)
14284                                 << UnaryOperator::getOpcodeStr(Opc)
14285                                 << Input->getType() << Input->getSourceRange()),
14286         *this, OCD_AmbiguousCandidates, ArgsArray,
14287         UnaryOperator::getOpcodeStr(Opc), OpLoc);
14288     return ExprError();
14289 
14290   case OR_Deleted:
14291     CandidateSet.NoteCandidates(
14292         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14293                                        << UnaryOperator::getOpcodeStr(Opc)
14294                                        << Input->getSourceRange()),
14295         *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
14296         OpLoc);
14297     return ExprError();
14298   }
14299 
14300   // Either we found no viable overloaded operator or we matched a
14301   // built-in operator. In either case, fall through to trying to
14302   // build a built-in operation.
14303   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14304 }
14305 
14306 /// Perform lookup for an overloaded binary operator.
14307 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
14308                                  OverloadedOperatorKind Op,
14309                                  const UnresolvedSetImpl &Fns,
14310                                  ArrayRef<Expr *> Args, bool PerformADL) {
14311   SourceLocation OpLoc = CandidateSet.getLocation();
14312 
14313   OverloadedOperatorKind ExtraOp =
14314       CandidateSet.getRewriteInfo().AllowRewrittenCandidates
14315           ? getRewrittenOverloadedOperator(Op)
14316           : OO_None;
14317 
14318   // Add the candidates from the given function set. This also adds the
14319   // rewritten candidates using these functions if necessary.
14320   AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
14321 
14322   // Add operator candidates that are member functions.
14323   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
14324   if (CandidateSet.getRewriteInfo().allowsReversed(Op))
14325     AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
14326                                 OverloadCandidateParamOrder::Reversed);
14327 
14328   // In C++20, also add any rewritten member candidates.
14329   if (ExtraOp) {
14330     AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
14331     if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
14332       AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
14333                                   CandidateSet,
14334                                   OverloadCandidateParamOrder::Reversed);
14335   }
14336 
14337   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
14338   // performed for an assignment operator (nor for operator[] nor operator->,
14339   // which don't get here).
14340   if (Op != OO_Equal && PerformADL) {
14341     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
14342     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
14343                                          /*ExplicitTemplateArgs*/ nullptr,
14344                                          CandidateSet);
14345     if (ExtraOp) {
14346       DeclarationName ExtraOpName =
14347           Context.DeclarationNames.getCXXOperatorName(ExtraOp);
14348       AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
14349                                            /*ExplicitTemplateArgs*/ nullptr,
14350                                            CandidateSet);
14351     }
14352   }
14353 
14354   // Add builtin operator candidates.
14355   //
14356   // FIXME: We don't add any rewritten candidates here. This is strictly
14357   // incorrect; a builtin candidate could be hidden by a non-viable candidate,
14358   // resulting in our selecting a rewritten builtin candidate. For example:
14359   //
14360   //   enum class E { e };
14361   //   bool operator!=(E, E) requires false;
14362   //   bool k = E::e != E::e;
14363   //
14364   // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
14365   // it seems unreasonable to consider rewritten builtin candidates. A core
14366   // issue has been filed proposing to removed this requirement.
14367   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
14368 }
14369 
14370 /// Create a binary operation that may resolve to an overloaded
14371 /// operator.
14372 ///
14373 /// \param OpLoc The location of the operator itself (e.g., '+').
14374 ///
14375 /// \param Opc The BinaryOperatorKind that describes this operator.
14376 ///
14377 /// \param Fns The set of non-member functions that will be
14378 /// considered by overload resolution. The caller needs to build this
14379 /// set based on the context using, e.g.,
14380 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
14381 /// set should not contain any member functions; those will be added
14382 /// by CreateOverloadedBinOp().
14383 ///
14384 /// \param LHS Left-hand argument.
14385 /// \param RHS Right-hand argument.
14386 /// \param PerformADL Whether to consider operator candidates found by ADL.
14387 /// \param AllowRewrittenCandidates Whether to consider candidates found by
14388 ///        C++20 operator rewrites.
14389 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
14390 ///        the function in question. Such a function is never a candidate in
14391 ///        our overload resolution. This also enables synthesizing a three-way
14392 ///        comparison from < and == as described in C++20 [class.spaceship]p1.
14393 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
14394                                        BinaryOperatorKind Opc,
14395                                        const UnresolvedSetImpl &Fns, Expr *LHS,
14396                                        Expr *RHS, bool PerformADL,
14397                                        bool AllowRewrittenCandidates,
14398                                        FunctionDecl *DefaultedFn) {
14399   Expr *Args[2] = { LHS, RHS };
14400   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
14401 
14402   if (!getLangOpts().CPlusPlus20)
14403     AllowRewrittenCandidates = false;
14404 
14405   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
14406 
14407   // If either side is type-dependent, create an appropriate dependent
14408   // expression.
14409   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
14410     if (Fns.empty()) {
14411       // If there are no functions to store, just build a dependent
14412       // BinaryOperator or CompoundAssignment.
14413       if (BinaryOperator::isCompoundAssignmentOp(Opc))
14414         return CompoundAssignOperator::Create(
14415             Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
14416             OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
14417             Context.DependentTy);
14418       return BinaryOperator::Create(
14419           Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
14420           OK_Ordinary, OpLoc, CurFPFeatureOverrides());
14421     }
14422 
14423     // FIXME: save results of ADL from here?
14424     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14425     // TODO: provide better source location info in DNLoc component.
14426     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
14427     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14428     ExprResult Fn = CreateUnresolvedLookupExpr(
14429         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
14430     if (Fn.isInvalid())
14431       return ExprError();
14432     return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
14433                                        Context.DependentTy, VK_PRValue, OpLoc,
14434                                        CurFPFeatureOverrides());
14435   }
14436 
14437   // Always do placeholder-like conversions on the RHS.
14438   if (checkPlaceholderForOverload(*this, Args[1]))
14439     return ExprError();
14440 
14441   // Do placeholder-like conversion on the LHS; note that we should
14442   // not get here with a PseudoObject LHS.
14443   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
14444   if (checkPlaceholderForOverload(*this, Args[0]))
14445     return ExprError();
14446 
14447   // If this is the assignment operator, we only perform overload resolution
14448   // if the left-hand side is a class or enumeration type. This is actually
14449   // a hack. The standard requires that we do overload resolution between the
14450   // various built-in candidates, but as DR507 points out, this can lead to
14451   // problems. So we do it this way, which pretty much follows what GCC does.
14452   // Note that we go the traditional code path for compound assignment forms.
14453   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
14454     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14455 
14456   // If this is the .* operator, which is not overloadable, just
14457   // create a built-in binary operator.
14458   if (Opc == BO_PtrMemD)
14459     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14460 
14461   // Build the overload set.
14462   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator,
14463                                     OverloadCandidateSet::OperatorRewriteInfo(
14464                                         Op, OpLoc, AllowRewrittenCandidates));
14465   if (DefaultedFn)
14466     CandidateSet.exclude(DefaultedFn);
14467   LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
14468 
14469   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14470 
14471   // Perform overload resolution.
14472   OverloadCandidateSet::iterator Best;
14473   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14474     case OR_Success: {
14475       // We found a built-in operator or an overloaded operator.
14476       FunctionDecl *FnDecl = Best->Function;
14477 
14478       bool IsReversed = Best->isReversed();
14479       if (IsReversed)
14480         std::swap(Args[0], Args[1]);
14481 
14482       if (FnDecl) {
14483 
14484         if (FnDecl->isInvalidDecl())
14485           return ExprError();
14486 
14487         Expr *Base = nullptr;
14488         // We matched an overloaded operator. Build a call to that
14489         // operator.
14490 
14491         OverloadedOperatorKind ChosenOp =
14492             FnDecl->getDeclName().getCXXOverloadedOperator();
14493 
14494         // C++2a [over.match.oper]p9:
14495         //   If a rewritten operator== candidate is selected by overload
14496         //   resolution for an operator@, its return type shall be cv bool
14497         if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
14498             !FnDecl->getReturnType()->isBooleanType()) {
14499           bool IsExtension =
14500               FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
14501           Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
14502                                   : diag::err_ovl_rewrite_equalequal_not_bool)
14503               << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
14504               << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14505           Diag(FnDecl->getLocation(), diag::note_declared_at);
14506           if (!IsExtension)
14507             return ExprError();
14508         }
14509 
14510         if (AllowRewrittenCandidates && !IsReversed &&
14511             CandidateSet.getRewriteInfo().isReversible()) {
14512           // We could have reversed this operator, but didn't. Check if some
14513           // reversed form was a viable candidate, and if so, if it had a
14514           // better conversion for either parameter. If so, this call is
14515           // formally ambiguous, and allowing it is an extension.
14516           llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
14517           for (OverloadCandidate &Cand : CandidateSet) {
14518             if (Cand.Viable && Cand.Function && Cand.isReversed() &&
14519                 haveSameParameterTypes(Context, Cand.Function, FnDecl)) {
14520               for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
14521                 if (CompareImplicitConversionSequences(
14522                         *this, OpLoc, Cand.Conversions[ArgIdx],
14523                         Best->Conversions[ArgIdx]) ==
14524                     ImplicitConversionSequence::Better) {
14525                   AmbiguousWith.push_back(Cand.Function);
14526                   break;
14527                 }
14528               }
14529             }
14530           }
14531 
14532           if (!AmbiguousWith.empty()) {
14533             bool AmbiguousWithSelf =
14534                 AmbiguousWith.size() == 1 &&
14535                 declaresSameEntity(AmbiguousWith.front(), FnDecl);
14536             Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
14537                 << BinaryOperator::getOpcodeStr(Opc)
14538                 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
14539                 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14540             if (AmbiguousWithSelf) {
14541               Diag(FnDecl->getLocation(),
14542                    diag::note_ovl_ambiguous_oper_binary_reversed_self);
14543               // Mark member== const or provide matching != to disallow reversed
14544               // args. Eg.
14545               // struct S { bool operator==(const S&); };
14546               // S()==S();
14547               if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
14548                 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
14549                     !MD->isConst() &&
14550                     !MD->hasCXXExplicitFunctionObjectParameter() &&
14551                     Context.hasSameUnqualifiedType(
14552                         MD->getFunctionObjectParameterType(),
14553                         MD->getParamDecl(0)->getType().getNonReferenceType()) &&
14554                     Context.hasSameUnqualifiedType(
14555                         MD->getFunctionObjectParameterType(),
14556                         Args[0]->getType()) &&
14557                     Context.hasSameUnqualifiedType(
14558                         MD->getFunctionObjectParameterType(),
14559                         Args[1]->getType()))
14560                   Diag(FnDecl->getLocation(),
14561                        diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
14562             } else {
14563               Diag(FnDecl->getLocation(),
14564                    diag::note_ovl_ambiguous_oper_binary_selected_candidate);
14565               for (auto *F : AmbiguousWith)
14566                 Diag(F->getLocation(),
14567                      diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
14568             }
14569           }
14570         }
14571 
14572         // Convert the arguments.
14573         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
14574           // Best->Access is only meaningful for class members.
14575           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
14576 
14577           ExprResult Arg0, Arg1;
14578           unsigned ParamIdx = 0;
14579           if (Method->isExplicitObjectMemberFunction()) {
14580             Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
14581             ParamIdx = 1;
14582           } else {
14583             Arg0 = PerformImplicitObjectArgumentInitialization(
14584                 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14585           }
14586           Arg1 = PerformCopyInitialization(
14587               InitializedEntity::InitializeParameter(
14588                   Context, FnDecl->getParamDecl(ParamIdx)),
14589               SourceLocation(), Args[1]);
14590           if (Arg0.isInvalid() || Arg1.isInvalid())
14591             return ExprError();
14592 
14593           Base = Args[0] = Arg0.getAs<Expr>();
14594           Args[1] = RHS = Arg1.getAs<Expr>();
14595         } else {
14596           // Convert the arguments.
14597           ExprResult Arg0 = PerformCopyInitialization(
14598             InitializedEntity::InitializeParameter(Context,
14599                                                    FnDecl->getParamDecl(0)),
14600             SourceLocation(), Args[0]);
14601           if (Arg0.isInvalid())
14602             return ExprError();
14603 
14604           ExprResult Arg1 =
14605             PerformCopyInitialization(
14606               InitializedEntity::InitializeParameter(Context,
14607                                                      FnDecl->getParamDecl(1)),
14608               SourceLocation(), Args[1]);
14609           if (Arg1.isInvalid())
14610             return ExprError();
14611           Args[0] = LHS = Arg0.getAs<Expr>();
14612           Args[1] = RHS = Arg1.getAs<Expr>();
14613         }
14614 
14615         // Build the actual expression node.
14616         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
14617                                                   Best->FoundDecl, Base,
14618                                                   HadMultipleCandidates, OpLoc);
14619         if (FnExpr.isInvalid())
14620           return ExprError();
14621 
14622         // Determine the result type.
14623         QualType ResultTy = FnDecl->getReturnType();
14624         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14625         ResultTy = ResultTy.getNonLValueExprType(Context);
14626 
14627         CallExpr *TheCall;
14628         ArrayRef<const Expr *> ArgsArray(Args, 2);
14629         const Expr *ImplicitThis = nullptr;
14630 
14631         // We always create a CXXOperatorCallExpr, even for explicit object
14632         // members; CodeGen should take care not to emit the this pointer.
14633         TheCall = CXXOperatorCallExpr::Create(
14634             Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
14635             CurFPFeatureOverrides(), Best->IsADLCandidate);
14636 
14637         if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
14638             Method && Method->isImplicitObjectMemberFunction()) {
14639           // Cut off the implicit 'this'.
14640           ImplicitThis = ArgsArray[0];
14641           ArgsArray = ArgsArray.slice(1);
14642         }
14643 
14644         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
14645                                 FnDecl))
14646           return ExprError();
14647 
14648         // Check for a self move.
14649         if (Op == OO_Equal)
14650           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
14651 
14652         if (ImplicitThis) {
14653           QualType ThisType = Context.getPointerType(ImplicitThis->getType());
14654           QualType ThisTypeFromDecl = Context.getPointerType(
14655               cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
14656 
14657           CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
14658                             ThisTypeFromDecl);
14659         }
14660 
14661         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
14662                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
14663                   VariadicDoesNotApply);
14664 
14665         ExprResult R = MaybeBindToTemporary(TheCall);
14666         if (R.isInvalid())
14667           return ExprError();
14668 
14669         R = CheckForImmediateInvocation(R, FnDecl);
14670         if (R.isInvalid())
14671           return ExprError();
14672 
14673         // For a rewritten candidate, we've already reversed the arguments
14674         // if needed. Perform the rest of the rewrite now.
14675         if ((Best->RewriteKind & CRK_DifferentOperator) ||
14676             (Op == OO_Spaceship && IsReversed)) {
14677           if (Op == OO_ExclaimEqual) {
14678             assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
14679             R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
14680           } else {
14681             assert(ChosenOp == OO_Spaceship && "unexpected operator name");
14682             llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14683             Expr *ZeroLiteral =
14684                 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
14685 
14686             Sema::CodeSynthesisContext Ctx;
14687             Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
14688             Ctx.Entity = FnDecl;
14689             pushCodeSynthesisContext(Ctx);
14690 
14691             R = CreateOverloadedBinOp(
14692                 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
14693                 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
14694                 /*AllowRewrittenCandidates=*/false);
14695 
14696             popCodeSynthesisContext();
14697           }
14698           if (R.isInvalid())
14699             return ExprError();
14700         } else {
14701           assert(ChosenOp == Op && "unexpected operator name");
14702         }
14703 
14704         // Make a note in the AST if we did any rewriting.
14705         if (Best->RewriteKind != CRK_None)
14706           R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
14707 
14708         return R;
14709       } else {
14710         // We matched a built-in operator. Convert the arguments, then
14711         // break out so that we will build the appropriate built-in
14712         // operator node.
14713         ExprResult ArgsRes0 = PerformImplicitConversion(
14714             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
14715             AA_Passing, CCK_ForBuiltinOverloadedOp);
14716         if (ArgsRes0.isInvalid())
14717           return ExprError();
14718         Args[0] = ArgsRes0.get();
14719 
14720         ExprResult ArgsRes1 = PerformImplicitConversion(
14721             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
14722             AA_Passing, CCK_ForBuiltinOverloadedOp);
14723         if (ArgsRes1.isInvalid())
14724           return ExprError();
14725         Args[1] = ArgsRes1.get();
14726         break;
14727       }
14728     }
14729 
14730     case OR_No_Viable_Function: {
14731       // C++ [over.match.oper]p9:
14732       //   If the operator is the operator , [...] and there are no
14733       //   viable functions, then the operator is assumed to be the
14734       //   built-in operator and interpreted according to clause 5.
14735       if (Opc == BO_Comma)
14736         break;
14737 
14738       // When defaulting an 'operator<=>', we can try to synthesize a three-way
14739       // compare result using '==' and '<'.
14740       if (DefaultedFn && Opc == BO_Cmp) {
14741         ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
14742                                                           Args[1], DefaultedFn);
14743         if (E.isInvalid() || E.isUsable())
14744           return E;
14745       }
14746 
14747       // For class as left operand for assignment or compound assignment
14748       // operator do not fall through to handling in built-in, but report that
14749       // no overloaded assignment operator found
14750       ExprResult Result = ExprError();
14751       StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
14752       auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
14753                                                    Args, OpLoc);
14754       DeferDiagsRAII DDR(*this,
14755                          CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
14756       if (Args[0]->getType()->isRecordType() &&
14757           Opc >= BO_Assign && Opc <= BO_OrAssign) {
14758         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
14759              << BinaryOperator::getOpcodeStr(Opc)
14760              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14761         if (Args[0]->getType()->isIncompleteType()) {
14762           Diag(OpLoc, diag::note_assign_lhs_incomplete)
14763             << Args[0]->getType()
14764             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14765         }
14766       } else {
14767         // This is an erroneous use of an operator which can be overloaded by
14768         // a non-member function. Check for non-member operators which were
14769         // defined too late to be candidates.
14770         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
14771           // FIXME: Recover by calling the found function.
14772           return ExprError();
14773 
14774         // No viable function; try to create a built-in operation, which will
14775         // produce an error. Then, show the non-viable candidates.
14776         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14777       }
14778       assert(Result.isInvalid() &&
14779              "C++ binary operator overloading is missing candidates!");
14780       CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
14781       return Result;
14782     }
14783 
14784     case OR_Ambiguous:
14785       CandidateSet.NoteCandidates(
14786           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
14787                                          << BinaryOperator::getOpcodeStr(Opc)
14788                                          << Args[0]->getType()
14789                                          << Args[1]->getType()
14790                                          << Args[0]->getSourceRange()
14791                                          << Args[1]->getSourceRange()),
14792           *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
14793           OpLoc);
14794       return ExprError();
14795 
14796     case OR_Deleted:
14797       if (isImplicitlyDeleted(Best->Function)) {
14798         FunctionDecl *DeletedFD = Best->Function;
14799         DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
14800         if (DFK.isSpecialMember()) {
14801           Diag(OpLoc, diag::err_ovl_deleted_special_oper)
14802             << Args[0]->getType() << DFK.asSpecialMember();
14803         } else {
14804           assert(DFK.isComparison());
14805           Diag(OpLoc, diag::err_ovl_deleted_comparison)
14806             << Args[0]->getType() << DeletedFD;
14807         }
14808 
14809         // The user probably meant to call this special member. Just
14810         // explain why it's deleted.
14811         NoteDeletedFunction(DeletedFD);
14812         return ExprError();
14813       }
14814       CandidateSet.NoteCandidates(
14815           PartialDiagnosticAt(
14816               OpLoc, PDiag(diag::err_ovl_deleted_oper)
14817                          << getOperatorSpelling(Best->Function->getDeclName()
14818                                                     .getCXXOverloadedOperator())
14819                          << Args[0]->getSourceRange()
14820                          << Args[1]->getSourceRange()),
14821           *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
14822           OpLoc);
14823       return ExprError();
14824   }
14825 
14826   // We matched a built-in operator; build it.
14827   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14828 }
14829 
14830 ExprResult Sema::BuildSynthesizedThreeWayComparison(
14831     SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
14832     FunctionDecl *DefaultedFn) {
14833   const ComparisonCategoryInfo *Info =
14834       Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
14835   // If we're not producing a known comparison category type, we can't
14836   // synthesize a three-way comparison. Let the caller diagnose this.
14837   if (!Info)
14838     return ExprResult((Expr*)nullptr);
14839 
14840   // If we ever want to perform this synthesis more generally, we will need to
14841   // apply the temporary materialization conversion to the operands.
14842   assert(LHS->isGLValue() && RHS->isGLValue() &&
14843          "cannot use prvalue expressions more than once");
14844   Expr *OrigLHS = LHS;
14845   Expr *OrigRHS = RHS;
14846 
14847   // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
14848   // each of them multiple times below.
14849   LHS = new (Context)
14850       OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
14851                       LHS->getObjectKind(), LHS);
14852   RHS = new (Context)
14853       OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
14854                       RHS->getObjectKind(), RHS);
14855 
14856   ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
14857                                         DefaultedFn);
14858   if (Eq.isInvalid())
14859     return ExprError();
14860 
14861   ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
14862                                           true, DefaultedFn);
14863   if (Less.isInvalid())
14864     return ExprError();
14865 
14866   ExprResult Greater;
14867   if (Info->isPartial()) {
14868     Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
14869                                     DefaultedFn);
14870     if (Greater.isInvalid())
14871       return ExprError();
14872   }
14873 
14874   // Form the list of comparisons we're going to perform.
14875   struct Comparison {
14876     ExprResult Cmp;
14877     ComparisonCategoryResult Result;
14878   } Comparisons[4] =
14879   { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
14880                           : ComparisonCategoryResult::Equivalent},
14881     {Less, ComparisonCategoryResult::Less},
14882     {Greater, ComparisonCategoryResult::Greater},
14883     {ExprResult(), ComparisonCategoryResult::Unordered},
14884   };
14885 
14886   int I = Info->isPartial() ? 3 : 2;
14887 
14888   // Combine the comparisons with suitable conditional expressions.
14889   ExprResult Result;
14890   for (; I >= 0; --I) {
14891     // Build a reference to the comparison category constant.
14892     auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
14893     // FIXME: Missing a constant for a comparison category. Diagnose this?
14894     if (!VI)
14895       return ExprResult((Expr*)nullptr);
14896     ExprResult ThisResult =
14897         BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
14898     if (ThisResult.isInvalid())
14899       return ExprError();
14900 
14901     // Build a conditional unless this is the final case.
14902     if (Result.get()) {
14903       Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
14904                                   ThisResult.get(), Result.get());
14905       if (Result.isInvalid())
14906         return ExprError();
14907     } else {
14908       Result = ThisResult;
14909     }
14910   }
14911 
14912   // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
14913   // bind the OpaqueValueExprs before they're (repeatedly) used.
14914   Expr *SyntacticForm = BinaryOperator::Create(
14915       Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
14916       Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
14917       CurFPFeatureOverrides());
14918   Expr *SemanticForm[] = {LHS, RHS, Result.get()};
14919   return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
14920 }
14921 
14922 static bool PrepareArgumentsForCallToObjectOfClassType(
14923     Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
14924     MultiExprArg Args, SourceLocation LParenLoc) {
14925 
14926   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14927   unsigned NumParams = Proto->getNumParams();
14928   unsigned NumArgsSlots =
14929       MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
14930   // Build the full argument list for the method call (the implicit object
14931   // parameter is placed at the beginning of the list).
14932   MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
14933   bool IsError = false;
14934   // Initialize the implicit object parameter.
14935   // Check the argument types.
14936   for (unsigned i = 0; i != NumParams; i++) {
14937     Expr *Arg;
14938     if (i < Args.size()) {
14939       Arg = Args[i];
14940       ExprResult InputInit =
14941           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
14942                                           S.Context, Method->getParamDecl(i)),
14943                                       SourceLocation(), Arg);
14944       IsError |= InputInit.isInvalid();
14945       Arg = InputInit.getAs<Expr>();
14946     } else {
14947       ExprResult DefArg =
14948           S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14949       if (DefArg.isInvalid()) {
14950         IsError = true;
14951         break;
14952       }
14953       Arg = DefArg.getAs<Expr>();
14954     }
14955 
14956     MethodArgs.push_back(Arg);
14957   }
14958   return IsError;
14959 }
14960 
14961 ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
14962                                                     SourceLocation RLoc,
14963                                                     Expr *Base,
14964                                                     MultiExprArg ArgExpr) {
14965   SmallVector<Expr *, 2> Args;
14966   Args.push_back(Base);
14967   for (auto *e : ArgExpr) {
14968     Args.push_back(e);
14969   }
14970   DeclarationName OpName =
14971       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
14972 
14973   SourceRange Range = ArgExpr.empty()
14974                           ? SourceRange{}
14975                           : SourceRange(ArgExpr.front()->getBeginLoc(),
14976                                         ArgExpr.back()->getEndLoc());
14977 
14978   // If either side is type-dependent, create an appropriate dependent
14979   // expression.
14980   if (Expr::hasAnyTypeDependentArguments(Args)) {
14981 
14982     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14983     // CHECKME: no 'operator' keyword?
14984     DeclarationNameInfo OpNameInfo(OpName, LLoc);
14985     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
14986     ExprResult Fn = CreateUnresolvedLookupExpr(
14987         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
14988     if (Fn.isInvalid())
14989       return ExprError();
14990     // Can't add any actual overloads yet
14991 
14992     return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
14993                                        Context.DependentTy, VK_PRValue, RLoc,
14994                                        CurFPFeatureOverrides());
14995   }
14996 
14997   // Handle placeholders
14998   UnbridgedCastsSet UnbridgedCasts;
14999   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
15000     return ExprError();
15001   }
15002   // Build an empty overload set.
15003   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
15004 
15005   // Subscript can only be overloaded as a member function.
15006 
15007   // Add operator candidates that are member functions.
15008   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15009 
15010   // Add builtin operator candidates.
15011   if (Args.size() == 2)
15012     AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15013 
15014   bool HadMultipleCandidates = (CandidateSet.size() > 1);
15015 
15016   // Perform overload resolution.
15017   OverloadCandidateSet::iterator Best;
15018   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
15019     case OR_Success: {
15020       // We found a built-in operator or an overloaded operator.
15021       FunctionDecl *FnDecl = Best->Function;
15022 
15023       if (FnDecl) {
15024         // We matched an overloaded operator. Build a call to that
15025         // operator.
15026 
15027         CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
15028 
15029         // Convert the arguments.
15030         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
15031         SmallVector<Expr *, 2> MethodArgs;
15032 
15033         // Handle 'this' parameter if the selected function is not static.
15034         if (Method->isExplicitObjectMemberFunction()) {
15035           ExprResult Res =
15036               InitializeExplicitObjectArgument(*this, Args[0], Method);
15037           if (Res.isInvalid())
15038             return ExprError();
15039           Args[0] = Res.get();
15040           ArgExpr = Args;
15041         } else if (Method->isInstance()) {
15042           ExprResult Arg0 = PerformImplicitObjectArgumentInitialization(
15043               Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15044           if (Arg0.isInvalid())
15045             return ExprError();
15046 
15047           MethodArgs.push_back(Arg0.get());
15048         }
15049 
15050         bool IsError = PrepareArgumentsForCallToObjectOfClassType(
15051             *this, MethodArgs, Method, ArgExpr, LLoc);
15052         if (IsError)
15053           return ExprError();
15054 
15055         // Build the actual expression node.
15056         DeclarationNameInfo OpLocInfo(OpName, LLoc);
15057         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15058         ExprResult FnExpr = CreateFunctionRefExpr(
15059             *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
15060             OpLocInfo.getLoc(), OpLocInfo.getInfo());
15061         if (FnExpr.isInvalid())
15062           return ExprError();
15063 
15064         // Determine the result type
15065         QualType ResultTy = FnDecl->getReturnType();
15066         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15067         ResultTy = ResultTy.getNonLValueExprType(Context);
15068 
15069         CallExpr *TheCall;
15070         if (Method->isInstance())
15071           TheCall = CXXOperatorCallExpr::Create(
15072               Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK,
15073               RLoc, CurFPFeatureOverrides());
15074         else
15075           TheCall =
15076               CallExpr::Create(Context, FnExpr.get(), MethodArgs, ResultTy, VK,
15077                                RLoc, CurFPFeatureOverrides());
15078 
15079         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
15080           return ExprError();
15081 
15082         if (CheckFunctionCall(Method, TheCall,
15083                               Method->getType()->castAs<FunctionProtoType>()))
15084           return ExprError();
15085 
15086         return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
15087                                            FnDecl);
15088       } else {
15089         // We matched a built-in operator. Convert the arguments, then
15090         // break out so that we will build the appropriate built-in
15091         // operator node.
15092         ExprResult ArgsRes0 = PerformImplicitConversion(
15093             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15094             AA_Passing, CCK_ForBuiltinOverloadedOp);
15095         if (ArgsRes0.isInvalid())
15096           return ExprError();
15097         Args[0] = ArgsRes0.get();
15098 
15099         ExprResult ArgsRes1 = PerformImplicitConversion(
15100             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15101             AA_Passing, CCK_ForBuiltinOverloadedOp);
15102         if (ArgsRes1.isInvalid())
15103           return ExprError();
15104         Args[1] = ArgsRes1.get();
15105 
15106         break;
15107       }
15108     }
15109 
15110     case OR_No_Viable_Function: {
15111       PartialDiagnostic PD =
15112           CandidateSet.empty()
15113               ? (PDiag(diag::err_ovl_no_oper)
15114                  << Args[0]->getType() << /*subscript*/ 0
15115                  << Args[0]->getSourceRange() << Range)
15116               : (PDiag(diag::err_ovl_no_viable_subscript)
15117                  << Args[0]->getType() << Args[0]->getSourceRange() << Range);
15118       CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
15119                                   OCD_AllCandidates, ArgExpr, "[]", LLoc);
15120       return ExprError();
15121     }
15122 
15123     case OR_Ambiguous:
15124       if (Args.size() == 2) {
15125         CandidateSet.NoteCandidates(
15126             PartialDiagnosticAt(
15127                 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15128                           << "[]" << Args[0]->getType() << Args[1]->getType()
15129                           << Args[0]->getSourceRange() << Range),
15130             *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15131       } else {
15132         CandidateSet.NoteCandidates(
15133             PartialDiagnosticAt(LLoc,
15134                                 PDiag(diag::err_ovl_ambiguous_subscript_call)
15135                                     << Args[0]->getType()
15136                                     << Args[0]->getSourceRange() << Range),
15137             *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15138       }
15139       return ExprError();
15140 
15141     case OR_Deleted:
15142       CandidateSet.NoteCandidates(
15143           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
15144                                         << "[]" << Args[0]->getSourceRange()
15145                                         << Range),
15146           *this, OCD_AllCandidates, Args, "[]", LLoc);
15147       return ExprError();
15148     }
15149 
15150   // We matched a built-in operator; build it.
15151   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
15152 }
15153 
15154 /// BuildCallToMemberFunction - Build a call to a member
15155 /// function. MemExpr is the expression that refers to the member
15156 /// function (and includes the object parameter), Args/NumArgs are the
15157 /// arguments to the function call (not including the object
15158 /// parameter). The caller needs to validate that the member
15159 /// expression refers to a non-static member function or an overloaded
15160 /// member function.
15161 ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
15162                                            SourceLocation LParenLoc,
15163                                            MultiExprArg Args,
15164                                            SourceLocation RParenLoc,
15165                                            Expr *ExecConfig, bool IsExecConfig,
15166                                            bool AllowRecovery) {
15167   assert(MemExprE->getType() == Context.BoundMemberTy ||
15168          MemExprE->getType() == Context.OverloadTy);
15169 
15170   // Dig out the member expression. This holds both the object
15171   // argument and the member function we're referring to.
15172   Expr *NakedMemExpr = MemExprE->IgnoreParens();
15173 
15174   // Determine whether this is a call to a pointer-to-member function.
15175   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
15176     assert(op->getType() == Context.BoundMemberTy);
15177     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
15178 
15179     QualType fnType =
15180       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
15181 
15182     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
15183     QualType resultType = proto->getCallResultType(Context);
15184     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
15185 
15186     // Check that the object type isn't more qualified than the
15187     // member function we're calling.
15188     Qualifiers funcQuals = proto->getMethodQuals();
15189 
15190     QualType objectType = op->getLHS()->getType();
15191     if (op->getOpcode() == BO_PtrMemI)
15192       objectType = objectType->castAs<PointerType>()->getPointeeType();
15193     Qualifiers objectQuals = objectType.getQualifiers();
15194 
15195     Qualifiers difference = objectQuals - funcQuals;
15196     difference.removeObjCGCAttr();
15197     difference.removeAddressSpace();
15198     if (difference) {
15199       std::string qualsString = difference.getAsString();
15200       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
15201         << fnType.getUnqualifiedType()
15202         << qualsString
15203         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
15204     }
15205 
15206     CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
15207         Context, MemExprE, Args, resultType, valueKind, RParenLoc,
15208         CurFPFeatureOverrides(), proto->getNumParams());
15209 
15210     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
15211                             call, nullptr))
15212       return ExprError();
15213 
15214     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
15215       return ExprError();
15216 
15217     if (CheckOtherCall(call, proto))
15218       return ExprError();
15219 
15220     return MaybeBindToTemporary(call);
15221   }
15222 
15223   // We only try to build a recovery expr at this level if we can preserve
15224   // the return type, otherwise we return ExprError() and let the caller
15225   // recover.
15226   auto BuildRecoveryExpr = [&](QualType Type) {
15227     if (!AllowRecovery)
15228       return ExprError();
15229     std::vector<Expr *> SubExprs = {MemExprE};
15230     llvm::append_range(SubExprs, Args);
15231     return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
15232                               Type);
15233   };
15234   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
15235     return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
15236                             RParenLoc, CurFPFeatureOverrides());
15237 
15238   UnbridgedCastsSet UnbridgedCasts;
15239   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
15240     return ExprError();
15241 
15242   MemberExpr *MemExpr;
15243   CXXMethodDecl *Method = nullptr;
15244   bool HadMultipleCandidates = false;
15245   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
15246   NestedNameSpecifier *Qualifier = nullptr;
15247   if (isa<MemberExpr>(NakedMemExpr)) {
15248     MemExpr = cast<MemberExpr>(NakedMemExpr);
15249     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
15250     FoundDecl = MemExpr->getFoundDecl();
15251     Qualifier = MemExpr->getQualifier();
15252     UnbridgedCasts.restore();
15253   } else {
15254     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
15255     Qualifier = UnresExpr->getQualifier();
15256 
15257     QualType ObjectType = UnresExpr->getBaseType();
15258     Expr::Classification ObjectClassification
15259       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
15260                             : UnresExpr->getBase()->Classify(Context);
15261 
15262     // Add overload candidates
15263     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
15264                                       OverloadCandidateSet::CSK_Normal);
15265 
15266     // FIXME: avoid copy.
15267     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15268     if (UnresExpr->hasExplicitTemplateArgs()) {
15269       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
15270       TemplateArgs = &TemplateArgsBuffer;
15271     }
15272 
15273     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
15274            E = UnresExpr->decls_end(); I != E; ++I) {
15275 
15276       QualType ExplicitObjectType = ObjectType;
15277 
15278       NamedDecl *Func = *I;
15279       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
15280       if (isa<UsingShadowDecl>(Func))
15281         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
15282 
15283       bool HasExplicitParameter = false;
15284       if (const auto *M = dyn_cast<FunctionDecl>(Func);
15285           M && M->hasCXXExplicitFunctionObjectParameter())
15286         HasExplicitParameter = true;
15287       else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
15288                M &&
15289                M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
15290         HasExplicitParameter = true;
15291 
15292       if (HasExplicitParameter)
15293         ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
15294 
15295       // Microsoft supports direct constructor calls.
15296       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
15297         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
15298                              CandidateSet,
15299                              /*SuppressUserConversions*/ false);
15300       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
15301         // If explicit template arguments were provided, we can't call a
15302         // non-template member function.
15303         if (TemplateArgs)
15304           continue;
15305 
15306         AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
15307                            ObjectClassification, Args, CandidateSet,
15308                            /*SuppressUserConversions=*/false);
15309       } else {
15310         AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
15311                                    I.getPair(), ActingDC, TemplateArgs,
15312                                    ExplicitObjectType, ObjectClassification,
15313                                    Args, CandidateSet,
15314                                    /*SuppressUserConversions=*/false);
15315       }
15316     }
15317 
15318     HadMultipleCandidates = (CandidateSet.size() > 1);
15319 
15320     DeclarationName DeclName = UnresExpr->getMemberName();
15321 
15322     UnbridgedCasts.restore();
15323 
15324     OverloadCandidateSet::iterator Best;
15325     bool Succeeded = false;
15326     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
15327                                             Best)) {
15328     case OR_Success:
15329       Method = cast<CXXMethodDecl>(Best->Function);
15330       FoundDecl = Best->FoundDecl;
15331       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
15332       if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
15333         break;
15334       // If FoundDecl is different from Method (such as if one is a template
15335       // and the other a specialization), make sure DiagnoseUseOfDecl is
15336       // called on both.
15337       // FIXME: This would be more comprehensively addressed by modifying
15338       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
15339       // being used.
15340       if (Method != FoundDecl.getDecl() &&
15341           DiagnoseUseOfOverloadedDecl(Method, UnresExpr->getNameLoc()))
15342         break;
15343       Succeeded = true;
15344       break;
15345 
15346     case OR_No_Viable_Function:
15347       CandidateSet.NoteCandidates(
15348           PartialDiagnosticAt(
15349               UnresExpr->getMemberLoc(),
15350               PDiag(diag::err_ovl_no_viable_member_function_in_call)
15351                   << DeclName << MemExprE->getSourceRange()),
15352           *this, OCD_AllCandidates, Args);
15353       break;
15354     case OR_Ambiguous:
15355       CandidateSet.NoteCandidates(
15356           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
15357                               PDiag(diag::err_ovl_ambiguous_member_call)
15358                                   << DeclName << MemExprE->getSourceRange()),
15359           *this, OCD_AmbiguousCandidates, Args);
15360       break;
15361     case OR_Deleted:
15362       CandidateSet.NoteCandidates(
15363           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
15364                               PDiag(diag::err_ovl_deleted_member_call)
15365                                   << DeclName << MemExprE->getSourceRange()),
15366           *this, OCD_AllCandidates, Args);
15367       break;
15368     }
15369     // Overload resolution fails, try to recover.
15370     if (!Succeeded)
15371       return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
15372 
15373     ExprResult Res =
15374         FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
15375     if (Res.isInvalid())
15376       return ExprError();
15377     MemExprE = Res.get();
15378 
15379     // If overload resolution picked a static member
15380     // build a non-member call based on that function.
15381     if (Method->isStatic()) {
15382       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
15383                                    ExecConfig, IsExecConfig);
15384     }
15385 
15386     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
15387   }
15388 
15389   QualType ResultType = Method->getReturnType();
15390   ExprValueKind VK = Expr::getValueKindForType(ResultType);
15391   ResultType = ResultType.getNonLValueExprType(Context);
15392 
15393   assert(Method && "Member call to something that isn't a method?");
15394   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15395 
15396   CallExpr *TheCall = nullptr;
15397   llvm::SmallVector<Expr *, 8> NewArgs;
15398   if (Method->isExplicitObjectMemberFunction()) {
15399     PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
15400                                   NewArgs);
15401     // Build the actual expression node.
15402     ExprResult FnExpr =
15403         CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
15404                               HadMultipleCandidates, MemExpr->getExprLoc());
15405     if (FnExpr.isInvalid())
15406       return ExprError();
15407 
15408     TheCall =
15409         CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
15410                          CurFPFeatureOverrides(), Proto->getNumParams());
15411   } else {
15412     // Convert the object argument (for a non-static member function call).
15413     // We only need to do this if there was actually an overload; otherwise
15414     // it was done at lookup.
15415     ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization(
15416         MemExpr->getBase(), Qualifier, FoundDecl, Method);
15417     if (ObjectArg.isInvalid())
15418       return ExprError();
15419     MemExpr->setBase(ObjectArg.get());
15420     TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
15421                                         RParenLoc, CurFPFeatureOverrides(),
15422                                         Proto->getNumParams());
15423   }
15424 
15425   // Check for a valid return type.
15426   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
15427                           TheCall, Method))
15428     return BuildRecoveryExpr(ResultType);
15429 
15430   // Convert the rest of the arguments
15431   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
15432                               RParenLoc))
15433     return BuildRecoveryExpr(ResultType);
15434 
15435   DiagnoseSentinelCalls(Method, LParenLoc, Args);
15436 
15437   if (CheckFunctionCall(Method, TheCall, Proto))
15438     return ExprError();
15439 
15440   // In the case the method to call was not selected by the overloading
15441   // resolution process, we still need to handle the enable_if attribute. Do
15442   // that here, so it will not hide previous -- and more relevant -- errors.
15443   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
15444     if (const EnableIfAttr *Attr =
15445             CheckEnableIf(Method, LParenLoc, Args, true)) {
15446       Diag(MemE->getMemberLoc(),
15447            diag::err_ovl_no_viable_member_function_in_call)
15448           << Method << Method->getSourceRange();
15449       Diag(Method->getLocation(),
15450            diag::note_ovl_candidate_disabled_by_function_cond_attr)
15451           << Attr->getCond()->getSourceRange() << Attr->getMessage();
15452       return ExprError();
15453     }
15454   }
15455 
15456   if (isa<CXXConstructorDecl, CXXDestructorDecl>(CurContext) &&
15457       TheCall->getDirectCallee()->isPure()) {
15458     const FunctionDecl *MD = TheCall->getDirectCallee();
15459 
15460     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
15461         MemExpr->performsVirtualDispatch(getLangOpts())) {
15462       Diag(MemExpr->getBeginLoc(),
15463            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
15464           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
15465           << MD->getParent();
15466 
15467       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
15468       if (getLangOpts().AppleKext)
15469         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
15470             << MD->getParent() << MD->getDeclName();
15471     }
15472   }
15473 
15474   if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
15475     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
15476     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
15477     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
15478                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
15479                          MemExpr->getMemberLoc());
15480   }
15481 
15482   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
15483                                      TheCall->getDirectCallee());
15484 }
15485 
15486 /// BuildCallToObjectOfClassType - Build a call to an object of class
15487 /// type (C++ [over.call.object]), which can end up invoking an
15488 /// overloaded function call operator (@c operator()) or performing a
15489 /// user-defined conversion on the object argument.
15490 ExprResult
15491 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
15492                                    SourceLocation LParenLoc,
15493                                    MultiExprArg Args,
15494                                    SourceLocation RParenLoc) {
15495   if (checkPlaceholderForOverload(*this, Obj))
15496     return ExprError();
15497   ExprResult Object = Obj;
15498 
15499   UnbridgedCastsSet UnbridgedCasts;
15500   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
15501     return ExprError();
15502 
15503   assert(Object.get()->getType()->isRecordType() &&
15504          "Requires object type argument");
15505 
15506   // C++ [over.call.object]p1:
15507   //  If the primary-expression E in the function call syntax
15508   //  evaluates to a class object of type "cv T", then the set of
15509   //  candidate functions includes at least the function call
15510   //  operators of T. The function call operators of T are obtained by
15511   //  ordinary lookup of the name operator() in the context of
15512   //  (E).operator().
15513   OverloadCandidateSet CandidateSet(LParenLoc,
15514                                     OverloadCandidateSet::CSK_Operator);
15515   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
15516 
15517   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
15518                           diag::err_incomplete_object_call, Object.get()))
15519     return true;
15520 
15521   const auto *Record = Object.get()->getType()->castAs<RecordType>();
15522   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
15523   LookupQualifiedName(R, Record->getDecl());
15524   R.suppressAccessDiagnostics();
15525 
15526   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
15527        Oper != OperEnd; ++Oper) {
15528     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
15529                        Object.get()->Classify(Context), Args, CandidateSet,
15530                        /*SuppressUserConversion=*/false);
15531   }
15532 
15533   // When calling a lambda, both the call operator, and
15534   // the conversion operator to function pointer
15535   // are considered. But when constraint checking
15536   // on the call operator fails, it will also fail on the
15537   // conversion operator as the constraints are always the same.
15538   // As the user probably does not intend to perform a surrogate call,
15539   // we filter them out to produce better error diagnostics, ie to avoid
15540   // showing 2 failed overloads instead of one.
15541   bool IgnoreSurrogateFunctions = false;
15542   if (CandidateSet.size() == 1 && Record->getAsCXXRecordDecl()->isLambda()) {
15543     const OverloadCandidate &Candidate = *CandidateSet.begin();
15544     if (!Candidate.Viable &&
15545         Candidate.FailureKind == ovl_fail_constraints_not_satisfied)
15546       IgnoreSurrogateFunctions = true;
15547   }
15548 
15549   // C++ [over.call.object]p2:
15550   //   In addition, for each (non-explicit in C++0x) conversion function
15551   //   declared in T of the form
15552   //
15553   //        operator conversion-type-id () cv-qualifier;
15554   //
15555   //   where cv-qualifier is the same cv-qualification as, or a
15556   //   greater cv-qualification than, cv, and where conversion-type-id
15557   //   denotes the type "pointer to function of (P1,...,Pn) returning
15558   //   R", or the type "reference to pointer to function of
15559   //   (P1,...,Pn) returning R", or the type "reference to function
15560   //   of (P1,...,Pn) returning R", a surrogate call function [...]
15561   //   is also considered as a candidate function. Similarly,
15562   //   surrogate call functions are added to the set of candidate
15563   //   functions for each conversion function declared in an
15564   //   accessible base class provided the function is not hidden
15565   //   within T by another intervening declaration.
15566   const auto &Conversions =
15567       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
15568   for (auto I = Conversions.begin(), E = Conversions.end();
15569        !IgnoreSurrogateFunctions && I != E; ++I) {
15570     NamedDecl *D = *I;
15571     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
15572     if (isa<UsingShadowDecl>(D))
15573       D = cast<UsingShadowDecl>(D)->getTargetDecl();
15574 
15575     // Skip over templated conversion functions; they aren't
15576     // surrogates.
15577     if (isa<FunctionTemplateDecl>(D))
15578       continue;
15579 
15580     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
15581     if (!Conv->isExplicit()) {
15582       // Strip the reference type (if any) and then the pointer type (if
15583       // any) to get down to what might be a function type.
15584       QualType ConvType = Conv->getConversionType().getNonReferenceType();
15585       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
15586         ConvType = ConvPtrType->getPointeeType();
15587 
15588       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
15589       {
15590         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
15591                               Object.get(), Args, CandidateSet);
15592       }
15593     }
15594   }
15595 
15596   bool HadMultipleCandidates = (CandidateSet.size() > 1);
15597 
15598   // Perform overload resolution.
15599   OverloadCandidateSet::iterator Best;
15600   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
15601                                           Best)) {
15602   case OR_Success:
15603     // Overload resolution succeeded; we'll build the appropriate call
15604     // below.
15605     break;
15606 
15607   case OR_No_Viable_Function: {
15608     PartialDiagnostic PD =
15609         CandidateSet.empty()
15610             ? (PDiag(diag::err_ovl_no_oper)
15611                << Object.get()->getType() << /*call*/ 1
15612                << Object.get()->getSourceRange())
15613             : (PDiag(diag::err_ovl_no_viable_object_call)
15614                << Object.get()->getType() << Object.get()->getSourceRange());
15615     CandidateSet.NoteCandidates(
15616         PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
15617         OCD_AllCandidates, Args);
15618     break;
15619   }
15620   case OR_Ambiguous:
15621     if (!R.isAmbiguous())
15622       CandidateSet.NoteCandidates(
15623           PartialDiagnosticAt(Object.get()->getBeginLoc(),
15624                               PDiag(diag::err_ovl_ambiguous_object_call)
15625                                   << Object.get()->getType()
15626                                   << Object.get()->getSourceRange()),
15627           *this, OCD_AmbiguousCandidates, Args);
15628     break;
15629 
15630   case OR_Deleted:
15631     CandidateSet.NoteCandidates(
15632         PartialDiagnosticAt(Object.get()->getBeginLoc(),
15633                             PDiag(diag::err_ovl_deleted_object_call)
15634                                 << Object.get()->getType()
15635                                 << Object.get()->getSourceRange()),
15636         *this, OCD_AllCandidates, Args);
15637     break;
15638   }
15639 
15640   if (Best == CandidateSet.end())
15641     return true;
15642 
15643   UnbridgedCasts.restore();
15644 
15645   if (Best->Function == nullptr) {
15646     // Since there is no function declaration, this is one of the
15647     // surrogate candidates. Dig out the conversion function.
15648     CXXConversionDecl *Conv
15649       = cast<CXXConversionDecl>(
15650                          Best->Conversions[0].UserDefined.ConversionFunction);
15651 
15652     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
15653                               Best->FoundDecl);
15654     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
15655       return ExprError();
15656     assert(Conv == Best->FoundDecl.getDecl() &&
15657              "Found Decl & conversion-to-functionptr should be same, right?!");
15658     // We selected one of the surrogate functions that converts the
15659     // object parameter to a function pointer. Perform the conversion
15660     // on the object argument, then let BuildCallExpr finish the job.
15661 
15662     // Create an implicit member expr to refer to the conversion operator.
15663     // and then call it.
15664     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
15665                                              Conv, HadMultipleCandidates);
15666     if (Call.isInvalid())
15667       return ExprError();
15668     // Record usage of conversion in an implicit cast.
15669     Call = ImplicitCastExpr::Create(
15670         Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
15671         nullptr, VK_PRValue, CurFPFeatureOverrides());
15672 
15673     return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
15674   }
15675 
15676   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
15677 
15678   // We found an overloaded operator(). Build a CXXOperatorCallExpr
15679   // that calls this method, using Object for the implicit object
15680   // parameter and passing along the remaining arguments.
15681   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
15682 
15683   // An error diagnostic has already been printed when parsing the declaration.
15684   if (Method->isInvalidDecl())
15685     return ExprError();
15686 
15687   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15688   unsigned NumParams = Proto->getNumParams();
15689 
15690   DeclarationNameInfo OpLocInfo(
15691                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
15692   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
15693   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
15694                                            Obj, HadMultipleCandidates,
15695                                            OpLocInfo.getLoc(),
15696                                            OpLocInfo.getInfo());
15697   if (NewFn.isInvalid())
15698     return true;
15699 
15700   SmallVector<Expr *, 8> MethodArgs;
15701   MethodArgs.reserve(NumParams + 1);
15702 
15703   bool IsError = false;
15704 
15705   // Initialize the implicit object parameter if needed.
15706   // Since C++23, this could also be a call to a static call operator
15707   // which we emit as a regular CallExpr.
15708   llvm::SmallVector<Expr *, 8> NewArgs;
15709   if (Method->isExplicitObjectMemberFunction()) {
15710     // FIXME: we should do that during the definition of the lambda when we can.
15711     DiagnoseInvalidExplicitObjectParameterInLambda(Method);
15712     PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
15713   } else if (Method->isInstance()) {
15714     ExprResult ObjRes = PerformImplicitObjectArgumentInitialization(
15715         Object.get(), /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15716     if (ObjRes.isInvalid())
15717       IsError = true;
15718     else
15719       Object = ObjRes;
15720     MethodArgs.push_back(Object.get());
15721   }
15722 
15723   IsError |= PrepareArgumentsForCallToObjectOfClassType(
15724       *this, MethodArgs, Method, Args, LParenLoc);
15725 
15726   // If this is a variadic call, handle args passed through "...".
15727   if (Proto->isVariadic()) {
15728     // Promote the arguments (C99 6.5.2.2p7).
15729     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
15730       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
15731                                                         nullptr);
15732       IsError |= Arg.isInvalid();
15733       MethodArgs.push_back(Arg.get());
15734     }
15735   }
15736 
15737   if (IsError)
15738     return true;
15739 
15740   DiagnoseSentinelCalls(Method, LParenLoc, Args);
15741 
15742   // Once we've built TheCall, all of the expressions are properly owned.
15743   QualType ResultTy = Method->getReturnType();
15744   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15745   ResultTy = ResultTy.getNonLValueExprType(Context);
15746 
15747   CallExpr *TheCall;
15748   if (Method->isInstance())
15749     TheCall = CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(),
15750                                           MethodArgs, ResultTy, VK, RParenLoc,
15751                                           CurFPFeatureOverrides());
15752   else
15753     TheCall = CallExpr::Create(Context, NewFn.get(), MethodArgs, ResultTy, VK,
15754                                RParenLoc, CurFPFeatureOverrides());
15755 
15756   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
15757     return true;
15758 
15759   if (CheckFunctionCall(Method, TheCall, Proto))
15760     return true;
15761 
15762   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
15763 }
15764 
15765 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
15766 ///  (if one exists), where @c Base is an expression of class type and
15767 /// @c Member is the name of the member we're trying to find.
15768 ExprResult
15769 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
15770                                bool *NoArrowOperatorFound) {
15771   assert(Base->getType()->isRecordType() &&
15772          "left-hand side must have class type");
15773 
15774   if (checkPlaceholderForOverload(*this, Base))
15775     return ExprError();
15776 
15777   SourceLocation Loc = Base->getExprLoc();
15778 
15779   // C++ [over.ref]p1:
15780   //
15781   //   [...] An expression x->m is interpreted as (x.operator->())->m
15782   //   for a class object x of type T if T::operator->() exists and if
15783   //   the operator is selected as the best match function by the
15784   //   overload resolution mechanism (13.3).
15785   DeclarationName OpName =
15786     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
15787   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
15788 
15789   if (RequireCompleteType(Loc, Base->getType(),
15790                           diag::err_typecheck_incomplete_tag, Base))
15791     return ExprError();
15792 
15793   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
15794   LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
15795   R.suppressAccessDiagnostics();
15796 
15797   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
15798        Oper != OperEnd; ++Oper) {
15799     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
15800                        std::nullopt, CandidateSet,
15801                        /*SuppressUserConversion=*/false);
15802   }
15803 
15804   bool HadMultipleCandidates = (CandidateSet.size() > 1);
15805 
15806   // Perform overload resolution.
15807   OverloadCandidateSet::iterator Best;
15808   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15809   case OR_Success:
15810     // Overload resolution succeeded; we'll build the call below.
15811     break;
15812 
15813   case OR_No_Viable_Function: {
15814     auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
15815     if (CandidateSet.empty()) {
15816       QualType BaseType = Base->getType();
15817       if (NoArrowOperatorFound) {
15818         // Report this specific error to the caller instead of emitting a
15819         // diagnostic, as requested.
15820         *NoArrowOperatorFound = true;
15821         return ExprError();
15822       }
15823       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
15824         << BaseType << Base->getSourceRange();
15825       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
15826         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
15827           << FixItHint::CreateReplacement(OpLoc, ".");
15828       }
15829     } else
15830       Diag(OpLoc, diag::err_ovl_no_viable_oper)
15831         << "operator->" << Base->getSourceRange();
15832     CandidateSet.NoteCandidates(*this, Base, Cands);
15833     return ExprError();
15834   }
15835   case OR_Ambiguous:
15836     if (!R.isAmbiguous())
15837       CandidateSet.NoteCandidates(
15838           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
15839                                          << "->" << Base->getType()
15840                                          << Base->getSourceRange()),
15841           *this, OCD_AmbiguousCandidates, Base);
15842     return ExprError();
15843 
15844   case OR_Deleted:
15845     CandidateSet.NoteCandidates(
15846         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15847                                        << "->" << Base->getSourceRange()),
15848         *this, OCD_AllCandidates, Base);
15849     return ExprError();
15850   }
15851 
15852   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
15853 
15854   // Convert the object parameter.
15855   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
15856 
15857   if (Method->isExplicitObjectMemberFunction()) {
15858     ExprResult R = InitializeExplicitObjectArgument(*this, Base, Method);
15859     if (R.isInvalid())
15860       return ExprError();
15861     Base = R.get();
15862   } else {
15863     ExprResult BaseResult = PerformImplicitObjectArgumentInitialization(
15864         Base, /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15865     if (BaseResult.isInvalid())
15866       return ExprError();
15867     Base = BaseResult.get();
15868   }
15869 
15870   // Build the operator call.
15871   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
15872                                             Base, HadMultipleCandidates, OpLoc);
15873   if (FnExpr.isInvalid())
15874     return ExprError();
15875 
15876   QualType ResultTy = Method->getReturnType();
15877   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15878   ResultTy = ResultTy.getNonLValueExprType(Context);
15879 
15880   CallExpr *TheCall =
15881       CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
15882                                   ResultTy, VK, OpLoc, CurFPFeatureOverrides());
15883 
15884   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
15885     return ExprError();
15886 
15887   if (CheckFunctionCall(Method, TheCall,
15888                         Method->getType()->castAs<FunctionProtoType>()))
15889     return ExprError();
15890 
15891   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
15892 }
15893 
15894 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
15895 /// a literal operator described by the provided lookup results.
15896 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
15897                                           DeclarationNameInfo &SuffixInfo,
15898                                           ArrayRef<Expr*> Args,
15899                                           SourceLocation LitEndLoc,
15900                                        TemplateArgumentListInfo *TemplateArgs) {
15901   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
15902 
15903   OverloadCandidateSet CandidateSet(UDSuffixLoc,
15904                                     OverloadCandidateSet::CSK_Normal);
15905   AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
15906                                  TemplateArgs);
15907 
15908   bool HadMultipleCandidates = (CandidateSet.size() > 1);
15909 
15910   // Perform overload resolution. This will usually be trivial, but might need
15911   // to perform substitutions for a literal operator template.
15912   OverloadCandidateSet::iterator Best;
15913   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
15914   case OR_Success:
15915   case OR_Deleted:
15916     break;
15917 
15918   case OR_No_Viable_Function:
15919     CandidateSet.NoteCandidates(
15920         PartialDiagnosticAt(UDSuffixLoc,
15921                             PDiag(diag::err_ovl_no_viable_function_in_call)
15922                                 << R.getLookupName()),
15923         *this, OCD_AllCandidates, Args);
15924     return ExprError();
15925 
15926   case OR_Ambiguous:
15927     CandidateSet.NoteCandidates(
15928         PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
15929                                                 << R.getLookupName()),
15930         *this, OCD_AmbiguousCandidates, Args);
15931     return ExprError();
15932   }
15933 
15934   FunctionDecl *FD = Best->Function;
15935   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
15936                                         nullptr, HadMultipleCandidates,
15937                                         SuffixInfo.getLoc(),
15938                                         SuffixInfo.getInfo());
15939   if (Fn.isInvalid())
15940     return true;
15941 
15942   // Check the argument types. This should almost always be a no-op, except
15943   // that array-to-pointer decay is applied to string literals.
15944   Expr *ConvArgs[2];
15945   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
15946     ExprResult InputInit = PerformCopyInitialization(
15947       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
15948       SourceLocation(), Args[ArgIdx]);
15949     if (InputInit.isInvalid())
15950       return true;
15951     ConvArgs[ArgIdx] = InputInit.get();
15952   }
15953 
15954   QualType ResultTy = FD->getReturnType();
15955   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15956   ResultTy = ResultTy.getNonLValueExprType(Context);
15957 
15958   UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
15959       Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
15960       LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
15961 
15962   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
15963     return ExprError();
15964 
15965   if (CheckFunctionCall(FD, UDL, nullptr))
15966     return ExprError();
15967 
15968   return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
15969 }
15970 
15971 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
15972 /// given LookupResult is non-empty, it is assumed to describe a member which
15973 /// will be invoked. Otherwise, the function will be found via argument
15974 /// dependent lookup.
15975 /// CallExpr is set to a valid expression and FRS_Success returned on success,
15976 /// otherwise CallExpr is set to ExprError() and some non-success value
15977 /// is returned.
15978 Sema::ForRangeStatus
15979 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
15980                                 SourceLocation RangeLoc,
15981                                 const DeclarationNameInfo &NameInfo,
15982                                 LookupResult &MemberLookup,
15983                                 OverloadCandidateSet *CandidateSet,
15984                                 Expr *Range, ExprResult *CallExpr) {
15985   Scope *S = nullptr;
15986 
15987   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
15988   if (!MemberLookup.empty()) {
15989     ExprResult MemberRef =
15990         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
15991                                  /*IsPtr=*/false, CXXScopeSpec(),
15992                                  /*TemplateKWLoc=*/SourceLocation(),
15993                                  /*FirstQualifierInScope=*/nullptr,
15994                                  MemberLookup,
15995                                  /*TemplateArgs=*/nullptr, S);
15996     if (MemberRef.isInvalid()) {
15997       *CallExpr = ExprError();
15998       return FRS_DiagnosticIssued;
15999     }
16000     *CallExpr =
16001         BuildCallExpr(S, MemberRef.get(), Loc, std::nullopt, Loc, nullptr);
16002     if (CallExpr->isInvalid()) {
16003       *CallExpr = ExprError();
16004       return FRS_DiagnosticIssued;
16005     }
16006   } else {
16007     ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
16008                                                 NestedNameSpecifierLoc(),
16009                                                 NameInfo, UnresolvedSet<0>());
16010     if (FnR.isInvalid())
16011       return FRS_DiagnosticIssued;
16012     UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
16013 
16014     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
16015                                                     CandidateSet, CallExpr);
16016     if (CandidateSet->empty() || CandidateSetError) {
16017       *CallExpr = ExprError();
16018       return FRS_NoViableFunction;
16019     }
16020     OverloadCandidateSet::iterator Best;
16021     OverloadingResult OverloadResult =
16022         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
16023 
16024     if (OverloadResult == OR_No_Viable_Function) {
16025       *CallExpr = ExprError();
16026       return FRS_NoViableFunction;
16027     }
16028     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
16029                                          Loc, nullptr, CandidateSet, &Best,
16030                                          OverloadResult,
16031                                          /*AllowTypoCorrection=*/false);
16032     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
16033       *CallExpr = ExprError();
16034       return FRS_DiagnosticIssued;
16035     }
16036   }
16037   return FRS_Success;
16038 }
16039 
16040 
16041 /// FixOverloadedFunctionReference - E is an expression that refers to
16042 /// a C++ overloaded function (possibly with some parentheses and
16043 /// perhaps a '&' around it). We have resolved the overloaded function
16044 /// to the function declaration Fn, so patch up the expression E to
16045 /// refer (possibly indirectly) to Fn. Returns the new expr.
16046 ExprResult Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
16047                                                 FunctionDecl *Fn) {
16048   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
16049     ExprResult SubExpr =
16050         FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
16051     if (SubExpr.isInvalid())
16052       return ExprError();
16053     if (SubExpr.get() == PE->getSubExpr())
16054       return PE;
16055 
16056     return new (Context)
16057         ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
16058   }
16059 
16060   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
16061     ExprResult SubExpr =
16062         FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
16063     if (SubExpr.isInvalid())
16064       return ExprError();
16065     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
16066                                SubExpr.get()->getType()) &&
16067            "Implicit cast type cannot be determined from overload");
16068     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
16069     if (SubExpr.get() == ICE->getSubExpr())
16070       return ICE;
16071 
16072     return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
16073                                     SubExpr.get(), nullptr, ICE->getValueKind(),
16074                                     CurFPFeatureOverrides());
16075   }
16076 
16077   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
16078     if (!GSE->isResultDependent()) {
16079       ExprResult SubExpr =
16080           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
16081       if (SubExpr.isInvalid())
16082         return ExprError();
16083       if (SubExpr.get() == GSE->getResultExpr())
16084         return GSE;
16085 
16086       // Replace the resulting type information before rebuilding the generic
16087       // selection expression.
16088       ArrayRef<Expr *> A = GSE->getAssocExprs();
16089       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
16090       unsigned ResultIdx = GSE->getResultIndex();
16091       AssocExprs[ResultIdx] = SubExpr.get();
16092 
16093       if (GSE->isExprPredicate())
16094         return GenericSelectionExpr::Create(
16095             Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
16096             GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16097             GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16098             ResultIdx);
16099       return GenericSelectionExpr::Create(
16100           Context, GSE->getGenericLoc(), GSE->getControllingType(),
16101           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16102           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16103           ResultIdx);
16104     }
16105     // Rather than fall through to the unreachable, return the original generic
16106     // selection expression.
16107     return GSE;
16108   }
16109 
16110   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
16111     assert(UnOp->getOpcode() == UO_AddrOf &&
16112            "Can only take the address of an overloaded function");
16113     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
16114       if (Method->isStatic()) {
16115         // Do nothing: static member functions aren't any different
16116         // from non-member functions.
16117       } else {
16118         // Fix the subexpression, which really has to be an
16119         // UnresolvedLookupExpr holding an overloaded member function
16120         // or template.
16121         ExprResult SubExpr =
16122             FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16123         if (SubExpr.isInvalid())
16124           return ExprError();
16125         if (SubExpr.get() == UnOp->getSubExpr())
16126           return UnOp;
16127 
16128         if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
16129                                                   SubExpr.get(), Method))
16130           return ExprError();
16131 
16132         assert(isa<DeclRefExpr>(SubExpr.get()) &&
16133                "fixed to something other than a decl ref");
16134         assert(cast<DeclRefExpr>(SubExpr.get())->getQualifier() &&
16135                "fixed to a member ref with no nested name qualifier");
16136 
16137         // We have taken the address of a pointer to member
16138         // function. Perform the computation here so that we get the
16139         // appropriate pointer to member type.
16140         QualType ClassType
16141           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
16142         QualType MemPtrType
16143           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
16144         // Under the MS ABI, lock down the inheritance model now.
16145         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
16146           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
16147 
16148         return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
16149                                      MemPtrType, VK_PRValue, OK_Ordinary,
16150                                      UnOp->getOperatorLoc(), false,
16151                                      CurFPFeatureOverrides());
16152       }
16153     }
16154     ExprResult SubExpr =
16155         FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16156     if (SubExpr.isInvalid())
16157       return ExprError();
16158     if (SubExpr.get() == UnOp->getSubExpr())
16159       return UnOp;
16160 
16161     return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
16162                                 SubExpr.get());
16163   }
16164 
16165   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16166     // FIXME: avoid copy.
16167     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16168     if (ULE->hasExplicitTemplateArgs()) {
16169       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
16170       TemplateArgs = &TemplateArgsBuffer;
16171     }
16172 
16173     QualType Type = Fn->getType();
16174     ExprValueKind ValueKind = getLangOpts().CPlusPlus ? VK_LValue : VK_PRValue;
16175 
16176     // FIXME: Duplicated from BuildDeclarationNameExpr.
16177     if (unsigned BID = Fn->getBuiltinID()) {
16178       if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
16179         Type = Context.BuiltinFnTy;
16180         ValueKind = VK_PRValue;
16181       }
16182     }
16183 
16184     DeclRefExpr *DRE = BuildDeclRefExpr(
16185         Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
16186         Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
16187     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
16188     return DRE;
16189   }
16190 
16191   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
16192     // FIXME: avoid copy.
16193     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16194     if (MemExpr->hasExplicitTemplateArgs()) {
16195       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16196       TemplateArgs = &TemplateArgsBuffer;
16197     }
16198 
16199     Expr *Base;
16200 
16201     // If we're filling in a static method where we used to have an
16202     // implicit member access, rewrite to a simple decl ref.
16203     if (MemExpr->isImplicitAccess()) {
16204       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
16205         DeclRefExpr *DRE = BuildDeclRefExpr(
16206             Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
16207             MemExpr->getQualifierLoc(), Found.getDecl(),
16208             MemExpr->getTemplateKeywordLoc(), TemplateArgs);
16209         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
16210         return DRE;
16211       } else {
16212         SourceLocation Loc = MemExpr->getMemberLoc();
16213         if (MemExpr->getQualifier())
16214           Loc = MemExpr->getQualifierLoc().getBeginLoc();
16215         Base =
16216             BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
16217       }
16218     } else
16219       Base = MemExpr->getBase();
16220 
16221     ExprValueKind valueKind;
16222     QualType type;
16223     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
16224       valueKind = VK_LValue;
16225       type = Fn->getType();
16226     } else {
16227       valueKind = VK_PRValue;
16228       type = Context.BoundMemberTy;
16229     }
16230 
16231     return BuildMemberExpr(
16232         Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
16233         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
16234         /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
16235         type, valueKind, OK_Ordinary, TemplateArgs);
16236   }
16237 
16238   llvm_unreachable("Invalid reference to overloaded function");
16239 }
16240 
16241 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
16242                                                 DeclAccessPair Found,
16243                                                 FunctionDecl *Fn) {
16244   return FixOverloadedFunctionReference(E.get(), Found, Fn);
16245 }
16246 
16247 bool clang::shouldEnforceArgLimit(bool PartialOverloading,
16248                                   FunctionDecl *Function) {
16249   if (!PartialOverloading || !Function)
16250     return true;
16251   if (Function->isVariadic())
16252     return false;
16253   if (const auto *Proto =
16254           dyn_cast<FunctionProtoType>(Function->getFunctionType()))
16255     if (Proto->isTemplateVariadic())
16256       return false;
16257   if (auto *Pattern = Function->getTemplateInstantiationPattern())
16258     if (const auto *Proto =
16259             dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
16260       if (Proto->isTemplateVariadic())
16261         return false;
16262   return true;
16263 }
16264