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/CXXInheritance.h"
15 #include "clang/AST/DeclObjC.h"
16 #include "clang/AST/DependenceFlags.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/ExprObjC.h"
20 #include "clang/AST/TypeOrdering.h"
21 #include "clang/Basic/Diagnostic.h"
22 #include "clang/Basic/DiagnosticOptions.h"
23 #include "clang/Basic/PartialDiagnostic.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/Overload.h"
29 #include "clang/Sema/SemaInternal.h"
30 #include "clang/Sema/Template.h"
31 #include "clang/Sema/TemplateDeduction.h"
32 #include "llvm/ADT/DenseSet.h"
33 #include "llvm/ADT/Optional.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/SmallString.h"
37 #include <algorithm>
38 #include <cstdlib>
39 
40 using namespace clang;
41 using namespace sema;
42 
43 using AllowedExplicit = Sema::AllowedExplicit;
44 
45 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
46   return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
47     return P->hasAttr<PassObjectSizeAttr>();
48   });
49 }
50 
51 /// A convenience routine for creating a decayed reference to a function.
52 static ExprResult CreateFunctionRefExpr(
53     Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
54     bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
55     const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
56   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
57     return ExprError();
58   // If FoundDecl is different from Fn (such as if one is a template
59   // and the other a specialization), make sure DiagnoseUseOfDecl is
60   // called on both.
61   // FIXME: This would be more comprehensively addressed by modifying
62   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
63   // being used.
64   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
65     return ExprError();
66   DeclRefExpr *DRE = new (S.Context)
67       DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
68   if (HadMultipleCandidates)
69     DRE->setHadMultipleCandidates(true);
70 
71   S.MarkDeclRefReferenced(DRE, Base);
72   if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
73     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
74       S.ResolveExceptionSpec(Loc, FPT);
75       DRE->setType(Fn->getType());
76     }
77   }
78   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
79                              CK_FunctionToPointerDecay);
80 }
81 
82 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
83                                  bool InOverloadResolution,
84                                  StandardConversionSequence &SCS,
85                                  bool CStyle,
86                                  bool AllowObjCWritebackConversion);
87 
88 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
89                                                  QualType &ToType,
90                                                  bool InOverloadResolution,
91                                                  StandardConversionSequence &SCS,
92                                                  bool CStyle);
93 static OverloadingResult
94 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
95                         UserDefinedConversionSequence& User,
96                         OverloadCandidateSet& Conversions,
97                         AllowedExplicit AllowExplicit,
98                         bool AllowObjCConversionOnExplicit);
99 
100 static ImplicitConversionSequence::CompareKind
101 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
102                                    const StandardConversionSequence& SCS1,
103                                    const StandardConversionSequence& SCS2);
104 
105 static ImplicitConversionSequence::CompareKind
106 CompareQualificationConversions(Sema &S,
107                                 const StandardConversionSequence& SCS1,
108                                 const StandardConversionSequence& SCS2);
109 
110 static ImplicitConversionSequence::CompareKind
111 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
112                                 const StandardConversionSequence& SCS1,
113                                 const StandardConversionSequence& SCS2);
114 
115 /// GetConversionRank - Retrieve the implicit conversion rank
116 /// corresponding to the given implicit conversion kind.
117 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
118   static const ImplicitConversionRank
119     Rank[(int)ICK_Num_Conversion_Kinds] = {
120     ICR_Exact_Match,
121     ICR_Exact_Match,
122     ICR_Exact_Match,
123     ICR_Exact_Match,
124     ICR_Exact_Match,
125     ICR_Exact_Match,
126     ICR_Promotion,
127     ICR_Promotion,
128     ICR_Promotion,
129     ICR_Conversion,
130     ICR_Conversion,
131     ICR_Conversion,
132     ICR_Conversion,
133     ICR_Conversion,
134     ICR_Conversion,
135     ICR_Conversion,
136     ICR_Conversion,
137     ICR_Conversion,
138     ICR_Conversion,
139     ICR_Conversion,
140     ICR_OCL_Scalar_Widening,
141     ICR_Complex_Real_Conversion,
142     ICR_Conversion,
143     ICR_Conversion,
144     ICR_Writeback_Conversion,
145     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
146                      // it was omitted by the patch that added
147                      // ICK_Zero_Event_Conversion
148     ICR_C_Conversion,
149     ICR_C_Conversion_Extension
150   };
151   return Rank[(int)Kind];
152 }
153 
154 /// GetImplicitConversionName - Return the name of this kind of
155 /// implicit conversion.
156 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
157   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
158     "No conversion",
159     "Lvalue-to-rvalue",
160     "Array-to-pointer",
161     "Function-to-pointer",
162     "Function pointer conversion",
163     "Qualification",
164     "Integral promotion",
165     "Floating point promotion",
166     "Complex promotion",
167     "Integral conversion",
168     "Floating conversion",
169     "Complex conversion",
170     "Floating-integral conversion",
171     "Pointer conversion",
172     "Pointer-to-member conversion",
173     "Boolean conversion",
174     "Compatible-types conversion",
175     "Derived-to-base conversion",
176     "Vector conversion",
177     "SVE Vector conversion",
178     "Vector splat",
179     "Complex-real conversion",
180     "Block Pointer conversion",
181     "Transparent Union Conversion",
182     "Writeback conversion",
183     "OpenCL Zero Event Conversion",
184     "C specific type conversion",
185     "Incompatible pointer conversion"
186   };
187   return Name[Kind];
188 }
189 
190 /// StandardConversionSequence - Set the standard conversion
191 /// sequence to the identity conversion.
192 void StandardConversionSequence::setAsIdentityConversion() {
193   First = ICK_Identity;
194   Second = ICK_Identity;
195   Third = ICK_Identity;
196   DeprecatedStringLiteralToCharPtr = false;
197   QualificationIncludesObjCLifetime = false;
198   ReferenceBinding = false;
199   DirectBinding = false;
200   IsLvalueReference = true;
201   BindsToFunctionLvalue = false;
202   BindsToRvalue = false;
203   BindsImplicitObjectArgumentWithoutRefQualifier = false;
204   ObjCLifetimeConversionBinding = false;
205   CopyConstructor = nullptr;
206 }
207 
208 /// getRank - Retrieve the rank of this standard conversion sequence
209 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
210 /// implicit conversions.
211 ImplicitConversionRank StandardConversionSequence::getRank() const {
212   ImplicitConversionRank Rank = ICR_Exact_Match;
213   if  (GetConversionRank(First) > Rank)
214     Rank = GetConversionRank(First);
215   if  (GetConversionRank(Second) > Rank)
216     Rank = GetConversionRank(Second);
217   if  (GetConversionRank(Third) > Rank)
218     Rank = GetConversionRank(Third);
219   return Rank;
220 }
221 
222 /// isPointerConversionToBool - Determines whether this conversion is
223 /// a conversion of a pointer or pointer-to-member to bool. This is
224 /// used as part of the ranking of standard conversion sequences
225 /// (C++ 13.3.3.2p4).
226 bool StandardConversionSequence::isPointerConversionToBool() const {
227   // Note that FromType has not necessarily been transformed by the
228   // array-to-pointer or function-to-pointer implicit conversions, so
229   // check for their presence as well as checking whether FromType is
230   // a pointer.
231   if (getToType(1)->isBooleanType() &&
232       (getFromType()->isPointerType() ||
233        getFromType()->isMemberPointerType() ||
234        getFromType()->isObjCObjectPointerType() ||
235        getFromType()->isBlockPointerType() ||
236        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
237     return true;
238 
239   return false;
240 }
241 
242 /// isPointerConversionToVoidPointer - Determines whether this
243 /// conversion is a conversion of a pointer to a void pointer. This is
244 /// used as part of the ranking of standard conversion sequences (C++
245 /// 13.3.3.2p4).
246 bool
247 StandardConversionSequence::
248 isPointerConversionToVoidPointer(ASTContext& Context) const {
249   QualType FromType = getFromType();
250   QualType ToType = getToType(1);
251 
252   // Note that FromType has not necessarily been transformed by the
253   // array-to-pointer implicit conversion, so check for its presence
254   // and redo the conversion to get a pointer.
255   if (First == ICK_Array_To_Pointer)
256     FromType = Context.getArrayDecayedType(FromType);
257 
258   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
259     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
260       return ToPtrType->getPointeeType()->isVoidType();
261 
262   return false;
263 }
264 
265 /// Skip any implicit casts which could be either part of a narrowing conversion
266 /// or after one in an implicit conversion.
267 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
268                                              const Expr *Converted) {
269   // We can have cleanups wrapping the converted expression; these need to be
270   // preserved so that destructors run if necessary.
271   if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
272     Expr *Inner =
273         const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
274     return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
275                                     EWC->getObjects());
276   }
277 
278   while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
279     switch (ICE->getCastKind()) {
280     case CK_NoOp:
281     case CK_IntegralCast:
282     case CK_IntegralToBoolean:
283     case CK_IntegralToFloating:
284     case CK_BooleanToSignedIntegral:
285     case CK_FloatingToIntegral:
286     case CK_FloatingToBoolean:
287     case CK_FloatingCast:
288       Converted = ICE->getSubExpr();
289       continue;
290 
291     default:
292       return Converted;
293     }
294   }
295 
296   return Converted;
297 }
298 
299 /// Check if this standard conversion sequence represents a narrowing
300 /// conversion, according to C++11 [dcl.init.list]p7.
301 ///
302 /// \param Ctx  The AST context.
303 /// \param Converted  The result of applying this standard conversion sequence.
304 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
305 ///        value of the expression prior to the narrowing conversion.
306 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
307 ///        type of the expression prior to the narrowing conversion.
308 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
309 ///        from floating point types to integral types should be ignored.
310 NarrowingKind StandardConversionSequence::getNarrowingKind(
311     ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
312     QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
313   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
314 
315   // C++11 [dcl.init.list]p7:
316   //   A narrowing conversion is an implicit conversion ...
317   QualType FromType = getToType(0);
318   QualType ToType = getToType(1);
319 
320   // A conversion to an enumeration type is narrowing if the conversion to
321   // the underlying type is narrowing. This only arises for expressions of
322   // the form 'Enum{init}'.
323   if (auto *ET = ToType->getAs<EnumType>())
324     ToType = ET->getDecl()->getIntegerType();
325 
326   switch (Second) {
327   // 'bool' is an integral type; dispatch to the right place to handle it.
328   case ICK_Boolean_Conversion:
329     if (FromType->isRealFloatingType())
330       goto FloatingIntegralConversion;
331     if (FromType->isIntegralOrUnscopedEnumerationType())
332       goto IntegralConversion;
333     // -- from a pointer type or pointer-to-member type to bool, or
334     return NK_Type_Narrowing;
335 
336   // -- from a floating-point type to an integer type, or
337   //
338   // -- from an integer type or unscoped enumeration type to a floating-point
339   //    type, except where the source is a constant expression and the actual
340   //    value after conversion will fit into the target type and will produce
341   //    the original value when converted back to the original type, or
342   case ICK_Floating_Integral:
343   FloatingIntegralConversion:
344     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
345       return NK_Type_Narrowing;
346     } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
347                ToType->isRealFloatingType()) {
348       if (IgnoreFloatToIntegralConversion)
349         return NK_Not_Narrowing;
350       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
351       assert(Initializer && "Unknown conversion expression");
352 
353       // If it's value-dependent, we can't tell whether it's narrowing.
354       if (Initializer->isValueDependent())
355         return NK_Dependent_Narrowing;
356 
357       if (Optional<llvm::APSInt> IntConstantValue =
358               Initializer->getIntegerConstantExpr(Ctx)) {
359         // Convert the integer to the floating type.
360         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
361         Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
362                                 llvm::APFloat::rmNearestTiesToEven);
363         // And back.
364         llvm::APSInt ConvertedValue = *IntConstantValue;
365         bool ignored;
366         Result.convertToInteger(ConvertedValue,
367                                 llvm::APFloat::rmTowardZero, &ignored);
368         // If the resulting value is different, this was a narrowing conversion.
369         if (*IntConstantValue != ConvertedValue) {
370           ConstantValue = APValue(*IntConstantValue);
371           ConstantType = Initializer->getType();
372           return NK_Constant_Narrowing;
373         }
374       } else {
375         // Variables are always narrowings.
376         return NK_Variable_Narrowing;
377       }
378     }
379     return NK_Not_Narrowing;
380 
381   // -- from long double to double or float, or from double to float, except
382   //    where the source is a constant expression and the actual value after
383   //    conversion is within the range of values that can be represented (even
384   //    if it cannot be represented exactly), or
385   case ICK_Floating_Conversion:
386     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
387         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
388       // FromType is larger than ToType.
389       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
390 
391       // If it's value-dependent, we can't tell whether it's narrowing.
392       if (Initializer->isValueDependent())
393         return NK_Dependent_Narrowing;
394 
395       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
396         // Constant!
397         assert(ConstantValue.isFloat());
398         llvm::APFloat FloatVal = ConstantValue.getFloat();
399         // Convert the source value into the target type.
400         bool ignored;
401         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
402           Ctx.getFloatTypeSemantics(ToType),
403           llvm::APFloat::rmNearestTiesToEven, &ignored);
404         // If there was no overflow, the source value is within the range of
405         // values that can be represented.
406         if (ConvertStatus & llvm::APFloat::opOverflow) {
407           ConstantType = Initializer->getType();
408           return NK_Constant_Narrowing;
409         }
410       } else {
411         return NK_Variable_Narrowing;
412       }
413     }
414     return NK_Not_Narrowing;
415 
416   // -- from an integer type or unscoped enumeration type to an integer type
417   //    that cannot represent all the values of the original type, except where
418   //    the source is a constant expression and the actual value after
419   //    conversion will fit into the target type and will produce the original
420   //    value when converted back to the original type.
421   case ICK_Integral_Conversion:
422   IntegralConversion: {
423     assert(FromType->isIntegralOrUnscopedEnumerationType());
424     assert(ToType->isIntegralOrUnscopedEnumerationType());
425     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
426     const unsigned FromWidth = Ctx.getIntWidth(FromType);
427     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
428     const unsigned ToWidth = Ctx.getIntWidth(ToType);
429 
430     if (FromWidth > ToWidth ||
431         (FromWidth == ToWidth && FromSigned != ToSigned) ||
432         (FromSigned && !ToSigned)) {
433       // Not all values of FromType can be represented in ToType.
434       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
435 
436       // If it's value-dependent, we can't tell whether it's narrowing.
437       if (Initializer->isValueDependent())
438         return NK_Dependent_Narrowing;
439 
440       Optional<llvm::APSInt> OptInitializerValue;
441       if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) {
442         // Such conversions on variables are always narrowing.
443         return NK_Variable_Narrowing;
444       }
445       llvm::APSInt &InitializerValue = *OptInitializerValue;
446       bool Narrowing = false;
447       if (FromWidth < ToWidth) {
448         // Negative -> unsigned is narrowing. Otherwise, more bits is never
449         // narrowing.
450         if (InitializerValue.isSigned() && InitializerValue.isNegative())
451           Narrowing = true;
452       } else {
453         // Add a bit to the InitializerValue so we don't have to worry about
454         // signed vs. unsigned comparisons.
455         InitializerValue = InitializerValue.extend(
456           InitializerValue.getBitWidth() + 1);
457         // Convert the initializer to and from the target width and signed-ness.
458         llvm::APSInt ConvertedValue = InitializerValue;
459         ConvertedValue = ConvertedValue.trunc(ToWidth);
460         ConvertedValue.setIsSigned(ToSigned);
461         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
462         ConvertedValue.setIsSigned(InitializerValue.isSigned());
463         // If the result is different, this was a narrowing conversion.
464         if (ConvertedValue != InitializerValue)
465           Narrowing = true;
466       }
467       if (Narrowing) {
468         ConstantType = Initializer->getType();
469         ConstantValue = APValue(InitializerValue);
470         return NK_Constant_Narrowing;
471       }
472     }
473     return NK_Not_Narrowing;
474   }
475 
476   default:
477     // Other kinds of conversions are not narrowings.
478     return NK_Not_Narrowing;
479   }
480 }
481 
482 /// dump - Print this standard conversion sequence to standard
483 /// error. Useful for debugging overloading issues.
484 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
485   raw_ostream &OS = llvm::errs();
486   bool PrintedSomething = false;
487   if (First != ICK_Identity) {
488     OS << GetImplicitConversionName(First);
489     PrintedSomething = true;
490   }
491 
492   if (Second != ICK_Identity) {
493     if (PrintedSomething) {
494       OS << " -> ";
495     }
496     OS << GetImplicitConversionName(Second);
497 
498     if (CopyConstructor) {
499       OS << " (by copy constructor)";
500     } else if (DirectBinding) {
501       OS << " (direct reference binding)";
502     } else if (ReferenceBinding) {
503       OS << " (reference binding)";
504     }
505     PrintedSomething = true;
506   }
507 
508   if (Third != ICK_Identity) {
509     if (PrintedSomething) {
510       OS << " -> ";
511     }
512     OS << GetImplicitConversionName(Third);
513     PrintedSomething = true;
514   }
515 
516   if (!PrintedSomething) {
517     OS << "No conversions required";
518   }
519 }
520 
521 /// dump - Print this user-defined conversion sequence to standard
522 /// error. Useful for debugging overloading issues.
523 void UserDefinedConversionSequence::dump() const {
524   raw_ostream &OS = llvm::errs();
525   if (Before.First || Before.Second || Before.Third) {
526     Before.dump();
527     OS << " -> ";
528   }
529   if (ConversionFunction)
530     OS << '\'' << *ConversionFunction << '\'';
531   else
532     OS << "aggregate initialization";
533   if (After.First || After.Second || After.Third) {
534     OS << " -> ";
535     After.dump();
536   }
537 }
538 
539 /// dump - Print this implicit conversion sequence to standard
540 /// error. Useful for debugging overloading issues.
541 void ImplicitConversionSequence::dump() const {
542   raw_ostream &OS = llvm::errs();
543   if (hasInitializerListContainerType())
544     OS << "Worst list element conversion: ";
545   switch (ConversionKind) {
546   case StandardConversion:
547     OS << "Standard conversion: ";
548     Standard.dump();
549     break;
550   case UserDefinedConversion:
551     OS << "User-defined conversion: ";
552     UserDefined.dump();
553     break;
554   case EllipsisConversion:
555     OS << "Ellipsis conversion";
556     break;
557   case AmbiguousConversion:
558     OS << "Ambiguous conversion";
559     break;
560   case BadConversion:
561     OS << "Bad conversion";
562     break;
563   }
564 
565   OS << "\n";
566 }
567 
568 void AmbiguousConversionSequence::construct() {
569   new (&conversions()) ConversionSet();
570 }
571 
572 void AmbiguousConversionSequence::destruct() {
573   conversions().~ConversionSet();
574 }
575 
576 void
577 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
578   FromTypePtr = O.FromTypePtr;
579   ToTypePtr = O.ToTypePtr;
580   new (&conversions()) ConversionSet(O.conversions());
581 }
582 
583 namespace {
584   // Structure used by DeductionFailureInfo to store
585   // template argument information.
586   struct DFIArguments {
587     TemplateArgument FirstArg;
588     TemplateArgument SecondArg;
589   };
590   // Structure used by DeductionFailureInfo to store
591   // template parameter and template argument information.
592   struct DFIParamWithArguments : DFIArguments {
593     TemplateParameter Param;
594   };
595   // Structure used by DeductionFailureInfo to store template argument
596   // information and the index of the problematic call argument.
597   struct DFIDeducedMismatchArgs : DFIArguments {
598     TemplateArgumentList *TemplateArgs;
599     unsigned CallArgIndex;
600   };
601   // Structure used by DeductionFailureInfo to store information about
602   // unsatisfied constraints.
603   struct CNSInfo {
604     TemplateArgumentList *TemplateArgs;
605     ConstraintSatisfaction Satisfaction;
606   };
607 }
608 
609 /// Convert from Sema's representation of template deduction information
610 /// to the form used in overload-candidate information.
611 DeductionFailureInfo
612 clang::MakeDeductionFailureInfo(ASTContext &Context,
613                                 Sema::TemplateDeductionResult TDK,
614                                 TemplateDeductionInfo &Info) {
615   DeductionFailureInfo Result;
616   Result.Result = static_cast<unsigned>(TDK);
617   Result.HasDiagnostic = false;
618   switch (TDK) {
619   case Sema::TDK_Invalid:
620   case Sema::TDK_InstantiationDepth:
621   case Sema::TDK_TooManyArguments:
622   case Sema::TDK_TooFewArguments:
623   case Sema::TDK_MiscellaneousDeductionFailure:
624   case Sema::TDK_CUDATargetMismatch:
625     Result.Data = nullptr;
626     break;
627 
628   case Sema::TDK_Incomplete:
629   case Sema::TDK_InvalidExplicitArguments:
630     Result.Data = Info.Param.getOpaqueValue();
631     break;
632 
633   case Sema::TDK_DeducedMismatch:
634   case Sema::TDK_DeducedMismatchNested: {
635     // FIXME: Should allocate from normal heap so that we can free this later.
636     auto *Saved = new (Context) DFIDeducedMismatchArgs;
637     Saved->FirstArg = Info.FirstArg;
638     Saved->SecondArg = Info.SecondArg;
639     Saved->TemplateArgs = Info.take();
640     Saved->CallArgIndex = Info.CallArgIndex;
641     Result.Data = Saved;
642     break;
643   }
644 
645   case Sema::TDK_NonDeducedMismatch: {
646     // FIXME: Should allocate from normal heap so that we can free this later.
647     DFIArguments *Saved = new (Context) DFIArguments;
648     Saved->FirstArg = Info.FirstArg;
649     Saved->SecondArg = Info.SecondArg;
650     Result.Data = Saved;
651     break;
652   }
653 
654   case Sema::TDK_IncompletePack:
655     // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
656   case Sema::TDK_Inconsistent:
657   case Sema::TDK_Underqualified: {
658     // FIXME: Should allocate from normal heap so that we can free this later.
659     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
660     Saved->Param = Info.Param;
661     Saved->FirstArg = Info.FirstArg;
662     Saved->SecondArg = Info.SecondArg;
663     Result.Data = Saved;
664     break;
665   }
666 
667   case Sema::TDK_SubstitutionFailure:
668     Result.Data = Info.take();
669     if (Info.hasSFINAEDiagnostic()) {
670       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
671           SourceLocation(), PartialDiagnostic::NullDiagnostic());
672       Info.takeSFINAEDiagnostic(*Diag);
673       Result.HasDiagnostic = true;
674     }
675     break;
676 
677   case Sema::TDK_ConstraintsNotSatisfied: {
678     CNSInfo *Saved = new (Context) CNSInfo;
679     Saved->TemplateArgs = Info.take();
680     Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
681     Result.Data = Saved;
682     break;
683   }
684 
685   case Sema::TDK_Success:
686   case Sema::TDK_NonDependentConversionFailure:
687     llvm_unreachable("not a deduction failure");
688   }
689 
690   return Result;
691 }
692 
693 void DeductionFailureInfo::Destroy() {
694   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
695   case Sema::TDK_Success:
696   case Sema::TDK_Invalid:
697   case Sema::TDK_InstantiationDepth:
698   case Sema::TDK_Incomplete:
699   case Sema::TDK_TooManyArguments:
700   case Sema::TDK_TooFewArguments:
701   case Sema::TDK_InvalidExplicitArguments:
702   case Sema::TDK_CUDATargetMismatch:
703   case Sema::TDK_NonDependentConversionFailure:
704     break;
705 
706   case Sema::TDK_IncompletePack:
707   case Sema::TDK_Inconsistent:
708   case Sema::TDK_Underqualified:
709   case Sema::TDK_DeducedMismatch:
710   case Sema::TDK_DeducedMismatchNested:
711   case Sema::TDK_NonDeducedMismatch:
712     // FIXME: Destroy the data?
713     Data = nullptr;
714     break;
715 
716   case Sema::TDK_SubstitutionFailure:
717     // FIXME: Destroy the template argument list?
718     Data = nullptr;
719     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
720       Diag->~PartialDiagnosticAt();
721       HasDiagnostic = false;
722     }
723     break;
724 
725   case Sema::TDK_ConstraintsNotSatisfied:
726     // FIXME: Destroy the template argument list?
727     Data = nullptr;
728     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
729       Diag->~PartialDiagnosticAt();
730       HasDiagnostic = false;
731     }
732     break;
733 
734   // Unhandled
735   case Sema::TDK_MiscellaneousDeductionFailure:
736     break;
737   }
738 }
739 
740 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
741   if (HasDiagnostic)
742     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
743   return nullptr;
744 }
745 
746 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
747   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
748   case Sema::TDK_Success:
749   case Sema::TDK_Invalid:
750   case Sema::TDK_InstantiationDepth:
751   case Sema::TDK_TooManyArguments:
752   case Sema::TDK_TooFewArguments:
753   case Sema::TDK_SubstitutionFailure:
754   case Sema::TDK_DeducedMismatch:
755   case Sema::TDK_DeducedMismatchNested:
756   case Sema::TDK_NonDeducedMismatch:
757   case Sema::TDK_CUDATargetMismatch:
758   case Sema::TDK_NonDependentConversionFailure:
759   case Sema::TDK_ConstraintsNotSatisfied:
760     return TemplateParameter();
761 
762   case Sema::TDK_Incomplete:
763   case Sema::TDK_InvalidExplicitArguments:
764     return TemplateParameter::getFromOpaqueValue(Data);
765 
766   case Sema::TDK_IncompletePack:
767   case Sema::TDK_Inconsistent:
768   case Sema::TDK_Underqualified:
769     return static_cast<DFIParamWithArguments*>(Data)->Param;
770 
771   // Unhandled
772   case Sema::TDK_MiscellaneousDeductionFailure:
773     break;
774   }
775 
776   return TemplateParameter();
777 }
778 
779 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
780   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
781   case Sema::TDK_Success:
782   case Sema::TDK_Invalid:
783   case Sema::TDK_InstantiationDepth:
784   case Sema::TDK_TooManyArguments:
785   case Sema::TDK_TooFewArguments:
786   case Sema::TDK_Incomplete:
787   case Sema::TDK_IncompletePack:
788   case Sema::TDK_InvalidExplicitArguments:
789   case Sema::TDK_Inconsistent:
790   case Sema::TDK_Underqualified:
791   case Sema::TDK_NonDeducedMismatch:
792   case Sema::TDK_CUDATargetMismatch:
793   case Sema::TDK_NonDependentConversionFailure:
794     return nullptr;
795 
796   case Sema::TDK_DeducedMismatch:
797   case Sema::TDK_DeducedMismatchNested:
798     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
799 
800   case Sema::TDK_SubstitutionFailure:
801     return static_cast<TemplateArgumentList*>(Data);
802 
803   case Sema::TDK_ConstraintsNotSatisfied:
804     return static_cast<CNSInfo*>(Data)->TemplateArgs;
805 
806   // Unhandled
807   case Sema::TDK_MiscellaneousDeductionFailure:
808     break;
809   }
810 
811   return nullptr;
812 }
813 
814 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
815   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
816   case Sema::TDK_Success:
817   case Sema::TDK_Invalid:
818   case Sema::TDK_InstantiationDepth:
819   case Sema::TDK_Incomplete:
820   case Sema::TDK_TooManyArguments:
821   case Sema::TDK_TooFewArguments:
822   case Sema::TDK_InvalidExplicitArguments:
823   case Sema::TDK_SubstitutionFailure:
824   case Sema::TDK_CUDATargetMismatch:
825   case Sema::TDK_NonDependentConversionFailure:
826   case Sema::TDK_ConstraintsNotSatisfied:
827     return nullptr;
828 
829   case Sema::TDK_IncompletePack:
830   case Sema::TDK_Inconsistent:
831   case Sema::TDK_Underqualified:
832   case Sema::TDK_DeducedMismatch:
833   case Sema::TDK_DeducedMismatchNested:
834   case Sema::TDK_NonDeducedMismatch:
835     return &static_cast<DFIArguments*>(Data)->FirstArg;
836 
837   // Unhandled
838   case Sema::TDK_MiscellaneousDeductionFailure:
839     break;
840   }
841 
842   return nullptr;
843 }
844 
845 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
846   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
847   case Sema::TDK_Success:
848   case Sema::TDK_Invalid:
849   case Sema::TDK_InstantiationDepth:
850   case Sema::TDK_Incomplete:
851   case Sema::TDK_IncompletePack:
852   case Sema::TDK_TooManyArguments:
853   case Sema::TDK_TooFewArguments:
854   case Sema::TDK_InvalidExplicitArguments:
855   case Sema::TDK_SubstitutionFailure:
856   case Sema::TDK_CUDATargetMismatch:
857   case Sema::TDK_NonDependentConversionFailure:
858   case Sema::TDK_ConstraintsNotSatisfied:
859     return nullptr;
860 
861   case Sema::TDK_Inconsistent:
862   case Sema::TDK_Underqualified:
863   case Sema::TDK_DeducedMismatch:
864   case Sema::TDK_DeducedMismatchNested:
865   case Sema::TDK_NonDeducedMismatch:
866     return &static_cast<DFIArguments*>(Data)->SecondArg;
867 
868   // Unhandled
869   case Sema::TDK_MiscellaneousDeductionFailure:
870     break;
871   }
872 
873   return nullptr;
874 }
875 
876 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
877   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
878   case Sema::TDK_DeducedMismatch:
879   case Sema::TDK_DeducedMismatchNested:
880     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
881 
882   default:
883     return llvm::None;
884   }
885 }
886 
887 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
888     OverloadedOperatorKind Op) {
889   if (!AllowRewrittenCandidates)
890     return false;
891   return Op == OO_EqualEqual || Op == OO_Spaceship;
892 }
893 
894 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
895     ASTContext &Ctx, const FunctionDecl *FD) {
896   if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator()))
897     return false;
898   // Don't bother adding a reversed candidate that can never be a better
899   // match than the non-reversed version.
900   return FD->getNumParams() != 2 ||
901          !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
902                                      FD->getParamDecl(1)->getType()) ||
903          FD->hasAttr<EnableIfAttr>();
904 }
905 
906 void OverloadCandidateSet::destroyCandidates() {
907   for (iterator i = begin(), e = end(); i != e; ++i) {
908     for (auto &C : i->Conversions)
909       C.~ImplicitConversionSequence();
910     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
911       i->DeductionFailure.Destroy();
912   }
913 }
914 
915 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
916   destroyCandidates();
917   SlabAllocator.Reset();
918   NumInlineBytesUsed = 0;
919   Candidates.clear();
920   Functions.clear();
921   Kind = CSK;
922 }
923 
924 namespace {
925   class UnbridgedCastsSet {
926     struct Entry {
927       Expr **Addr;
928       Expr *Saved;
929     };
930     SmallVector<Entry, 2> Entries;
931 
932   public:
933     void save(Sema &S, Expr *&E) {
934       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
935       Entry entry = { &E, E };
936       Entries.push_back(entry);
937       E = S.stripARCUnbridgedCast(E);
938     }
939 
940     void restore() {
941       for (SmallVectorImpl<Entry>::iterator
942              i = Entries.begin(), e = Entries.end(); i != e; ++i)
943         *i->Addr = i->Saved;
944     }
945   };
946 }
947 
948 /// checkPlaceholderForOverload - Do any interesting placeholder-like
949 /// preprocessing on the given expression.
950 ///
951 /// \param unbridgedCasts a collection to which to add unbridged casts;
952 ///   without this, they will be immediately diagnosed as errors
953 ///
954 /// Return true on unrecoverable error.
955 static bool
956 checkPlaceholderForOverload(Sema &S, Expr *&E,
957                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
958   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
959     // We can't handle overloaded expressions here because overload
960     // resolution might reasonably tweak them.
961     if (placeholder->getKind() == BuiltinType::Overload) return false;
962 
963     // If the context potentially accepts unbridged ARC casts, strip
964     // the unbridged cast and add it to the collection for later restoration.
965     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
966         unbridgedCasts) {
967       unbridgedCasts->save(S, E);
968       return false;
969     }
970 
971     // Go ahead and check everything else.
972     ExprResult result = S.CheckPlaceholderExpr(E);
973     if (result.isInvalid())
974       return true;
975 
976     E = result.get();
977     return false;
978   }
979 
980   // Nothing to do.
981   return false;
982 }
983 
984 /// checkArgPlaceholdersForOverload - Check a set of call operands for
985 /// placeholders.
986 static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args,
987                                             UnbridgedCastsSet &unbridged) {
988   for (unsigned i = 0, e = Args.size(); i != e; ++i)
989     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
990       return true;
991 
992   return false;
993 }
994 
995 /// Determine whether the given New declaration is an overload of the
996 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
997 /// New and Old cannot be overloaded, e.g., if New has the same signature as
998 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
999 /// functions (or function templates) at all. When it does return Ovl_Match or
1000 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1001 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1002 /// declaration.
1003 ///
1004 /// Example: Given the following input:
1005 ///
1006 ///   void f(int, float); // #1
1007 ///   void f(int, int); // #2
1008 ///   int f(int, int); // #3
1009 ///
1010 /// When we process #1, there is no previous declaration of "f", so IsOverload
1011 /// will not be used.
1012 ///
1013 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1014 /// the parameter types, we see that #1 and #2 are overloaded (since they have
1015 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1016 /// unchanged.
1017 ///
1018 /// When we process #3, Old is an overload set containing #1 and #2. We compare
1019 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1020 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1021 /// functions are not part of the signature), IsOverload returns Ovl_Match and
1022 /// MatchedDecl will be set to point to the FunctionDecl for #2.
1023 ///
1024 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1025 /// by a using declaration. The rules for whether to hide shadow declarations
1026 /// ignore some properties which otherwise figure into a function template's
1027 /// signature.
1028 Sema::OverloadKind
1029 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1030                     NamedDecl *&Match, bool NewIsUsingDecl) {
1031   for (LookupResult::iterator I = Old.begin(), E = Old.end();
1032          I != E; ++I) {
1033     NamedDecl *OldD = *I;
1034 
1035     bool OldIsUsingDecl = false;
1036     if (isa<UsingShadowDecl>(OldD)) {
1037       OldIsUsingDecl = true;
1038 
1039       // We can always introduce two using declarations into the same
1040       // context, even if they have identical signatures.
1041       if (NewIsUsingDecl) continue;
1042 
1043       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1044     }
1045 
1046     // A using-declaration does not conflict with another declaration
1047     // if one of them is hidden.
1048     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1049       continue;
1050 
1051     // If either declaration was introduced by a using declaration,
1052     // we'll need to use slightly different rules for matching.
1053     // Essentially, these rules are the normal rules, except that
1054     // function templates hide function templates with different
1055     // return types or template parameter lists.
1056     bool UseMemberUsingDeclRules =
1057       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1058       !New->getFriendObjectKind();
1059 
1060     if (FunctionDecl *OldF = OldD->getAsFunction()) {
1061       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1062         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1063           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1064           continue;
1065         }
1066 
1067         if (!isa<FunctionTemplateDecl>(OldD) &&
1068             !shouldLinkPossiblyHiddenDecl(*I, New))
1069           continue;
1070 
1071         Match = *I;
1072         return Ovl_Match;
1073       }
1074 
1075       // Builtins that have custom typechecking or have a reference should
1076       // not be overloadable or redeclarable.
1077       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1078         Match = *I;
1079         return Ovl_NonFunction;
1080       }
1081     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1082       // We can overload with these, which can show up when doing
1083       // redeclaration checks for UsingDecls.
1084       assert(Old.getLookupKind() == LookupUsingDeclName);
1085     } else if (isa<TagDecl>(OldD)) {
1086       // We can always overload with tags by hiding them.
1087     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1088       // Optimistically assume that an unresolved using decl will
1089       // overload; if it doesn't, we'll have to diagnose during
1090       // template instantiation.
1091       //
1092       // Exception: if the scope is dependent and this is not a class
1093       // member, the using declaration can only introduce an enumerator.
1094       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1095         Match = *I;
1096         return Ovl_NonFunction;
1097       }
1098     } else {
1099       // (C++ 13p1):
1100       //   Only function declarations can be overloaded; object and type
1101       //   declarations cannot be overloaded.
1102       Match = *I;
1103       return Ovl_NonFunction;
1104     }
1105   }
1106 
1107   // C++ [temp.friend]p1:
1108   //   For a friend function declaration that is not a template declaration:
1109   //    -- if the name of the friend is a qualified or unqualified template-id,
1110   //       [...], otherwise
1111   //    -- if the name of the friend is a qualified-id and a matching
1112   //       non-template function is found in the specified class or namespace,
1113   //       the friend declaration refers to that function, otherwise,
1114   //    -- if the name of the friend is a qualified-id and a matching function
1115   //       template is found in the specified class or namespace, the friend
1116   //       declaration refers to the deduced specialization of that function
1117   //       template, otherwise
1118   //    -- the name shall be an unqualified-id [...]
1119   // If we get here for a qualified friend declaration, we've just reached the
1120   // third bullet. If the type of the friend is dependent, skip this lookup
1121   // until instantiation.
1122   if (New->getFriendObjectKind() && New->getQualifier() &&
1123       !New->getDescribedFunctionTemplate() &&
1124       !New->getDependentSpecializationInfo() &&
1125       !New->getType()->isDependentType()) {
1126     LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1127     TemplateSpecResult.addAllDecls(Old);
1128     if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1129                                             /*QualifiedFriend*/true)) {
1130       New->setInvalidDecl();
1131       return Ovl_Overload;
1132     }
1133 
1134     Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1135     return Ovl_Match;
1136   }
1137 
1138   return Ovl_Overload;
1139 }
1140 
1141 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1142                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs,
1143                       bool ConsiderRequiresClauses) {
1144   // C++ [basic.start.main]p2: This function shall not be overloaded.
1145   if (New->isMain())
1146     return false;
1147 
1148   // MSVCRT user defined entry points cannot be overloaded.
1149   if (New->isMSVCRTEntryPoint())
1150     return false;
1151 
1152   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1153   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1154 
1155   // C++ [temp.fct]p2:
1156   //   A function template can be overloaded with other function templates
1157   //   and with normal (non-template) functions.
1158   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1159     return true;
1160 
1161   // Is the function New an overload of the function Old?
1162   QualType OldQType = Context.getCanonicalType(Old->getType());
1163   QualType NewQType = Context.getCanonicalType(New->getType());
1164 
1165   // Compare the signatures (C++ 1.3.10) of the two functions to
1166   // determine whether they are overloads. If we find any mismatch
1167   // in the signature, they are overloads.
1168 
1169   // If either of these functions is a K&R-style function (no
1170   // prototype), then we consider them to have matching signatures.
1171   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1172       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1173     return false;
1174 
1175   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1176   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1177 
1178   // The signature of a function includes the types of its
1179   // parameters (C++ 1.3.10), which includes the presence or absence
1180   // of the ellipsis; see C++ DR 357).
1181   if (OldQType != NewQType &&
1182       (OldType->getNumParams() != NewType->getNumParams() ||
1183        OldType->isVariadic() != NewType->isVariadic() ||
1184        !FunctionParamTypesAreEqual(OldType, NewType)))
1185     return true;
1186 
1187   // C++ [temp.over.link]p4:
1188   //   The signature of a function template consists of its function
1189   //   signature, its return type and its template parameter list. The names
1190   //   of the template parameters are significant only for establishing the
1191   //   relationship between the template parameters and the rest of the
1192   //   signature.
1193   //
1194   // We check the return type and template parameter lists for function
1195   // templates first; the remaining checks follow.
1196   //
1197   // However, we don't consider either of these when deciding whether
1198   // a member introduced by a shadow declaration is hidden.
1199   if (!UseMemberUsingDeclRules && NewTemplate &&
1200       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1201                                        OldTemplate->getTemplateParameters(),
1202                                        false, TPL_TemplateMatch) ||
1203        !Context.hasSameType(Old->getDeclaredReturnType(),
1204                             New->getDeclaredReturnType())))
1205     return true;
1206 
1207   // If the function is a class member, its signature includes the
1208   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1209   //
1210   // As part of this, also check whether one of the member functions
1211   // is static, in which case they are not overloads (C++
1212   // 13.1p2). While not part of the definition of the signature,
1213   // this check is important to determine whether these functions
1214   // can be overloaded.
1215   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1216   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1217   if (OldMethod && NewMethod &&
1218       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1219     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1220       if (!UseMemberUsingDeclRules &&
1221           (OldMethod->getRefQualifier() == RQ_None ||
1222            NewMethod->getRefQualifier() == RQ_None)) {
1223         // C++0x [over.load]p2:
1224         //   - Member function declarations with the same name and the same
1225         //     parameter-type-list as well as member function template
1226         //     declarations with the same name, the same parameter-type-list, and
1227         //     the same template parameter lists cannot be overloaded if any of
1228         //     them, but not all, have a ref-qualifier (8.3.5).
1229         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1230           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1231         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1232       }
1233       return true;
1234     }
1235 
1236     // We may not have applied the implicit const for a constexpr member
1237     // function yet (because we haven't yet resolved whether this is a static
1238     // or non-static member function). Add it now, on the assumption that this
1239     // is a redeclaration of OldMethod.
1240     auto OldQuals = OldMethod->getMethodQualifiers();
1241     auto NewQuals = NewMethod->getMethodQualifiers();
1242     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1243         !isa<CXXConstructorDecl>(NewMethod))
1244       NewQuals.addConst();
1245     // We do not allow overloading based off of '__restrict'.
1246     OldQuals.removeRestrict();
1247     NewQuals.removeRestrict();
1248     if (OldQuals != NewQuals)
1249       return true;
1250   }
1251 
1252   // Though pass_object_size is placed on parameters and takes an argument, we
1253   // consider it to be a function-level modifier for the sake of function
1254   // identity. Either the function has one or more parameters with
1255   // pass_object_size or it doesn't.
1256   if (functionHasPassObjectSizeParams(New) !=
1257       functionHasPassObjectSizeParams(Old))
1258     return true;
1259 
1260   // enable_if attributes are an order-sensitive part of the signature.
1261   for (specific_attr_iterator<EnableIfAttr>
1262          NewI = New->specific_attr_begin<EnableIfAttr>(),
1263          NewE = New->specific_attr_end<EnableIfAttr>(),
1264          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1265          OldE = Old->specific_attr_end<EnableIfAttr>();
1266        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1267     if (NewI == NewE || OldI == OldE)
1268       return true;
1269     llvm::FoldingSetNodeID NewID, OldID;
1270     NewI->getCond()->Profile(NewID, Context, true);
1271     OldI->getCond()->Profile(OldID, Context, true);
1272     if (NewID != OldID)
1273       return true;
1274   }
1275 
1276   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1277     // Don't allow overloading of destructors.  (In theory we could, but it
1278     // would be a giant change to clang.)
1279     if (!isa<CXXDestructorDecl>(New)) {
1280       CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1281                          OldTarget = IdentifyCUDATarget(Old);
1282       if (NewTarget != CFT_InvalidTarget) {
1283         assert((OldTarget != CFT_InvalidTarget) &&
1284                "Unexpected invalid target.");
1285 
1286         // Allow overloading of functions with same signature and different CUDA
1287         // target attributes.
1288         if (NewTarget != OldTarget)
1289           return true;
1290       }
1291     }
1292   }
1293 
1294   if (ConsiderRequiresClauses) {
1295     Expr *NewRC = New->getTrailingRequiresClause(),
1296          *OldRC = Old->getTrailingRequiresClause();
1297     if ((NewRC != nullptr) != (OldRC != nullptr))
1298       // RC are most certainly different - these are overloads.
1299       return true;
1300 
1301     if (NewRC) {
1302       llvm::FoldingSetNodeID NewID, OldID;
1303       NewRC->Profile(NewID, Context, /*Canonical=*/true);
1304       OldRC->Profile(OldID, Context, /*Canonical=*/true);
1305       if (NewID != OldID)
1306         // RCs are not equivalent - these are overloads.
1307         return true;
1308     }
1309   }
1310 
1311   // The signatures match; this is not an overload.
1312   return false;
1313 }
1314 
1315 /// Tries a user-defined conversion from From to ToType.
1316 ///
1317 /// Produces an implicit conversion sequence for when a standard conversion
1318 /// is not an option. See TryImplicitConversion for more information.
1319 static ImplicitConversionSequence
1320 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1321                          bool SuppressUserConversions,
1322                          AllowedExplicit AllowExplicit,
1323                          bool InOverloadResolution,
1324                          bool CStyle,
1325                          bool AllowObjCWritebackConversion,
1326                          bool AllowObjCConversionOnExplicit) {
1327   ImplicitConversionSequence ICS;
1328 
1329   if (SuppressUserConversions) {
1330     // We're not in the case above, so there is no conversion that
1331     // we can perform.
1332     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1333     return ICS;
1334   }
1335 
1336   // Attempt user-defined conversion.
1337   OverloadCandidateSet Conversions(From->getExprLoc(),
1338                                    OverloadCandidateSet::CSK_Normal);
1339   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1340                                   Conversions, AllowExplicit,
1341                                   AllowObjCConversionOnExplicit)) {
1342   case OR_Success:
1343   case OR_Deleted:
1344     ICS.setUserDefined();
1345     // C++ [over.ics.user]p4:
1346     //   A conversion of an expression of class type to the same class
1347     //   type is given Exact Match rank, and a conversion of an
1348     //   expression of class type to a base class of that type is
1349     //   given Conversion rank, in spite of the fact that a copy
1350     //   constructor (i.e., a user-defined conversion function) is
1351     //   called for those cases.
1352     if (CXXConstructorDecl *Constructor
1353           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1354       QualType FromCanon
1355         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1356       QualType ToCanon
1357         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1358       if (Constructor->isCopyConstructor() &&
1359           (FromCanon == ToCanon ||
1360            S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1361         // Turn this into a "standard" conversion sequence, so that it
1362         // gets ranked with standard conversion sequences.
1363         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1364         ICS.setStandard();
1365         ICS.Standard.setAsIdentityConversion();
1366         ICS.Standard.setFromType(From->getType());
1367         ICS.Standard.setAllToTypes(ToType);
1368         ICS.Standard.CopyConstructor = Constructor;
1369         ICS.Standard.FoundCopyConstructor = Found;
1370         if (ToCanon != FromCanon)
1371           ICS.Standard.Second = ICK_Derived_To_Base;
1372       }
1373     }
1374     break;
1375 
1376   case OR_Ambiguous:
1377     ICS.setAmbiguous();
1378     ICS.Ambiguous.setFromType(From->getType());
1379     ICS.Ambiguous.setToType(ToType);
1380     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1381          Cand != Conversions.end(); ++Cand)
1382       if (Cand->Best)
1383         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1384     break;
1385 
1386     // Fall through.
1387   case OR_No_Viable_Function:
1388     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1389     break;
1390   }
1391 
1392   return ICS;
1393 }
1394 
1395 /// TryImplicitConversion - Attempt to perform an implicit conversion
1396 /// from the given expression (Expr) to the given type (ToType). This
1397 /// function returns an implicit conversion sequence that can be used
1398 /// to perform the initialization. Given
1399 ///
1400 ///   void f(float f);
1401 ///   void g(int i) { f(i); }
1402 ///
1403 /// this routine would produce an implicit conversion sequence to
1404 /// describe the initialization of f from i, which will be a standard
1405 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1406 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1407 //
1408 /// Note that this routine only determines how the conversion can be
1409 /// performed; it does not actually perform the conversion. As such,
1410 /// it will not produce any diagnostics if no conversion is available,
1411 /// but will instead return an implicit conversion sequence of kind
1412 /// "BadConversion".
1413 ///
1414 /// If @p SuppressUserConversions, then user-defined conversions are
1415 /// not permitted.
1416 /// If @p AllowExplicit, then explicit user-defined conversions are
1417 /// permitted.
1418 ///
1419 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1420 /// writeback conversion, which allows __autoreleasing id* parameters to
1421 /// be initialized with __strong id* or __weak id* arguments.
1422 static ImplicitConversionSequence
1423 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1424                       bool SuppressUserConversions,
1425                       AllowedExplicit AllowExplicit,
1426                       bool InOverloadResolution,
1427                       bool CStyle,
1428                       bool AllowObjCWritebackConversion,
1429                       bool AllowObjCConversionOnExplicit) {
1430   ImplicitConversionSequence ICS;
1431   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1432                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1433     ICS.setStandard();
1434     return ICS;
1435   }
1436 
1437   if (!S.getLangOpts().CPlusPlus) {
1438     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1439     return ICS;
1440   }
1441 
1442   // C++ [over.ics.user]p4:
1443   //   A conversion of an expression of class type to the same class
1444   //   type is given Exact Match rank, and a conversion of an
1445   //   expression of class type to a base class of that type is
1446   //   given Conversion rank, in spite of the fact that a copy/move
1447   //   constructor (i.e., a user-defined conversion function) is
1448   //   called for those cases.
1449   QualType FromType = From->getType();
1450   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1451       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1452        S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1453     ICS.setStandard();
1454     ICS.Standard.setAsIdentityConversion();
1455     ICS.Standard.setFromType(FromType);
1456     ICS.Standard.setAllToTypes(ToType);
1457 
1458     // We don't actually check at this point whether there is a valid
1459     // copy/move constructor, since overloading just assumes that it
1460     // exists. When we actually perform initialization, we'll find the
1461     // appropriate constructor to copy the returned object, if needed.
1462     ICS.Standard.CopyConstructor = nullptr;
1463 
1464     // Determine whether this is considered a derived-to-base conversion.
1465     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1466       ICS.Standard.Second = ICK_Derived_To_Base;
1467 
1468     return ICS;
1469   }
1470 
1471   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1472                                   AllowExplicit, InOverloadResolution, CStyle,
1473                                   AllowObjCWritebackConversion,
1474                                   AllowObjCConversionOnExplicit);
1475 }
1476 
1477 ImplicitConversionSequence
1478 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1479                             bool SuppressUserConversions,
1480                             AllowedExplicit AllowExplicit,
1481                             bool InOverloadResolution,
1482                             bool CStyle,
1483                             bool AllowObjCWritebackConversion) {
1484   return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1485                                  AllowExplicit, InOverloadResolution, CStyle,
1486                                  AllowObjCWritebackConversion,
1487                                  /*AllowObjCConversionOnExplicit=*/false);
1488 }
1489 
1490 /// PerformImplicitConversion - Perform an implicit conversion of the
1491 /// expression From to the type ToType. Returns the
1492 /// converted expression. Flavor is the kind of conversion we're
1493 /// performing, used in the error message. If @p AllowExplicit,
1494 /// explicit user-defined conversions are permitted.
1495 ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1496                                            AssignmentAction Action,
1497                                            bool AllowExplicit) {
1498   if (checkPlaceholderForOverload(*this, From))
1499     return ExprError();
1500 
1501   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1502   bool AllowObjCWritebackConversion
1503     = getLangOpts().ObjCAutoRefCount &&
1504       (Action == AA_Passing || Action == AA_Sending);
1505   if (getLangOpts().ObjC)
1506     CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1507                                       From->getType(), From);
1508   ImplicitConversionSequence ICS = ::TryImplicitConversion(
1509       *this, From, ToType,
1510       /*SuppressUserConversions=*/false,
1511       AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1512       /*InOverloadResolution=*/false,
1513       /*CStyle=*/false, AllowObjCWritebackConversion,
1514       /*AllowObjCConversionOnExplicit=*/false);
1515   return PerformImplicitConversion(From, ToType, ICS, Action);
1516 }
1517 
1518 /// Determine whether the conversion from FromType to ToType is a valid
1519 /// conversion that strips "noexcept" or "noreturn" off the nested function
1520 /// type.
1521 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1522                                 QualType &ResultTy) {
1523   if (Context.hasSameUnqualifiedType(FromType, ToType))
1524     return false;
1525 
1526   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1527   //                    or F(t noexcept) -> F(t)
1528   // where F adds one of the following at most once:
1529   //   - a pointer
1530   //   - a member pointer
1531   //   - a block pointer
1532   // Changes here need matching changes in FindCompositePointerType.
1533   CanQualType CanTo = Context.getCanonicalType(ToType);
1534   CanQualType CanFrom = Context.getCanonicalType(FromType);
1535   Type::TypeClass TyClass = CanTo->getTypeClass();
1536   if (TyClass != CanFrom->getTypeClass()) return false;
1537   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1538     if (TyClass == Type::Pointer) {
1539       CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1540       CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1541     } else if (TyClass == Type::BlockPointer) {
1542       CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1543       CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1544     } else if (TyClass == Type::MemberPointer) {
1545       auto ToMPT = CanTo.castAs<MemberPointerType>();
1546       auto FromMPT = CanFrom.castAs<MemberPointerType>();
1547       // A function pointer conversion cannot change the class of the function.
1548       if (ToMPT->getClass() != FromMPT->getClass())
1549         return false;
1550       CanTo = ToMPT->getPointeeType();
1551       CanFrom = FromMPT->getPointeeType();
1552     } else {
1553       return false;
1554     }
1555 
1556     TyClass = CanTo->getTypeClass();
1557     if (TyClass != CanFrom->getTypeClass()) return false;
1558     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1559       return false;
1560   }
1561 
1562   const auto *FromFn = cast<FunctionType>(CanFrom);
1563   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1564 
1565   const auto *ToFn = cast<FunctionType>(CanTo);
1566   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1567 
1568   bool Changed = false;
1569 
1570   // Drop 'noreturn' if not present in target type.
1571   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1572     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1573     Changed = true;
1574   }
1575 
1576   // Drop 'noexcept' if not present in target type.
1577   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1578     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1579     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1580       FromFn = cast<FunctionType>(
1581           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1582                                                    EST_None)
1583                  .getTypePtr());
1584       Changed = true;
1585     }
1586 
1587     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1588     // only if the ExtParameterInfo lists of the two function prototypes can be
1589     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1590     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1591     bool CanUseToFPT, CanUseFromFPT;
1592     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1593                                       CanUseFromFPT, NewParamInfos) &&
1594         CanUseToFPT && !CanUseFromFPT) {
1595       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1596       ExtInfo.ExtParameterInfos =
1597           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1598       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1599                                             FromFPT->getParamTypes(), ExtInfo);
1600       FromFn = QT->getAs<FunctionType>();
1601       Changed = true;
1602     }
1603   }
1604 
1605   if (!Changed)
1606     return false;
1607 
1608   assert(QualType(FromFn, 0).isCanonical());
1609   if (QualType(FromFn, 0) != CanTo) return false;
1610 
1611   ResultTy = ToType;
1612   return true;
1613 }
1614 
1615 /// Determine whether the conversion from FromType to ToType is a valid
1616 /// vector conversion.
1617 ///
1618 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1619 /// conversion.
1620 static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
1621                                ImplicitConversionKind &ICK, Expr *From,
1622                                bool InOverloadResolution) {
1623   // We need at least one of these types to be a vector type to have a vector
1624   // conversion.
1625   if (!ToType->isVectorType() && !FromType->isVectorType())
1626     return false;
1627 
1628   // Identical types require no conversions.
1629   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1630     return false;
1631 
1632   // There are no conversions between extended vector types, only identity.
1633   if (ToType->isExtVectorType()) {
1634     // There are no conversions between extended vector types other than the
1635     // identity conversion.
1636     if (FromType->isExtVectorType())
1637       return false;
1638 
1639     // Vector splat from any arithmetic type to a vector.
1640     if (FromType->isArithmeticType()) {
1641       ICK = ICK_Vector_Splat;
1642       return true;
1643     }
1644   }
1645 
1646   if (ToType->isSizelessBuiltinType() || FromType->isSizelessBuiltinType())
1647     if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
1648         S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
1649       ICK = ICK_SVE_Vector_Conversion;
1650       return true;
1651     }
1652 
1653   // We can perform the conversion between vector types in the following cases:
1654   // 1)vector types are equivalent AltiVec and GCC vector types
1655   // 2)lax vector conversions are permitted and the vector types are of the
1656   //   same size
1657   // 3)the destination type does not have the ARM MVE strict-polymorphism
1658   //   attribute, which inhibits lax vector conversion for overload resolution
1659   //   only
1660   if (ToType->isVectorType() && FromType->isVectorType()) {
1661     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1662         (S.isLaxVectorConversion(FromType, ToType) &&
1663          !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
1664       if (S.isLaxVectorConversion(FromType, ToType) &&
1665           S.anyAltivecTypes(FromType, ToType) &&
1666           !S.areSameVectorElemTypes(FromType, ToType) &&
1667           !InOverloadResolution) {
1668         S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
1669             << FromType << ToType;
1670       }
1671       ICK = ICK_Vector_Conversion;
1672       return true;
1673     }
1674   }
1675 
1676   return false;
1677 }
1678 
1679 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1680                                 bool InOverloadResolution,
1681                                 StandardConversionSequence &SCS,
1682                                 bool CStyle);
1683 
1684 /// IsStandardConversion - Determines whether there is a standard
1685 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1686 /// expression From to the type ToType. Standard conversion sequences
1687 /// only consider non-class types; for conversions that involve class
1688 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1689 /// contain the standard conversion sequence required to perform this
1690 /// conversion and this routine will return true. Otherwise, this
1691 /// routine will return false and the value of SCS is unspecified.
1692 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1693                                  bool InOverloadResolution,
1694                                  StandardConversionSequence &SCS,
1695                                  bool CStyle,
1696                                  bool AllowObjCWritebackConversion) {
1697   QualType FromType = From->getType();
1698 
1699   // Standard conversions (C++ [conv])
1700   SCS.setAsIdentityConversion();
1701   SCS.IncompatibleObjC = false;
1702   SCS.setFromType(FromType);
1703   SCS.CopyConstructor = nullptr;
1704 
1705   // There are no standard conversions for class types in C++, so
1706   // abort early. When overloading in C, however, we do permit them.
1707   if (S.getLangOpts().CPlusPlus &&
1708       (FromType->isRecordType() || ToType->isRecordType()))
1709     return false;
1710 
1711   // The first conversion can be an lvalue-to-rvalue conversion,
1712   // array-to-pointer conversion, or function-to-pointer conversion
1713   // (C++ 4p1).
1714 
1715   if (FromType == S.Context.OverloadTy) {
1716     DeclAccessPair AccessPair;
1717     if (FunctionDecl *Fn
1718           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1719                                                  AccessPair)) {
1720       // We were able to resolve the address of the overloaded function,
1721       // so we can convert to the type of that function.
1722       FromType = Fn->getType();
1723       SCS.setFromType(FromType);
1724 
1725       // we can sometimes resolve &foo<int> regardless of ToType, so check
1726       // if the type matches (identity) or we are converting to bool
1727       if (!S.Context.hasSameUnqualifiedType(
1728                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1729         QualType resultTy;
1730         // if the function type matches except for [[noreturn]], it's ok
1731         if (!S.IsFunctionConversion(FromType,
1732               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1733           // otherwise, only a boolean conversion is standard
1734           if (!ToType->isBooleanType())
1735             return false;
1736       }
1737 
1738       // Check if the "from" expression is taking the address of an overloaded
1739       // function and recompute the FromType accordingly. Take advantage of the
1740       // fact that non-static member functions *must* have such an address-of
1741       // expression.
1742       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1743       if (Method && !Method->isStatic()) {
1744         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1745                "Non-unary operator on non-static member address");
1746         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1747                == UO_AddrOf &&
1748                "Non-address-of operator on non-static member address");
1749         const Type *ClassType
1750           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1751         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1752       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1753         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1754                UO_AddrOf &&
1755                "Non-address-of operator for overloaded function expression");
1756         FromType = S.Context.getPointerType(FromType);
1757       }
1758     } else {
1759       return false;
1760     }
1761   }
1762   // Lvalue-to-rvalue conversion (C++11 4.1):
1763   //   A glvalue (3.10) of a non-function, non-array type T can
1764   //   be converted to a prvalue.
1765   bool argIsLValue = From->isGLValue();
1766   if (argIsLValue &&
1767       !FromType->isFunctionType() && !FromType->isArrayType() &&
1768       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1769     SCS.First = ICK_Lvalue_To_Rvalue;
1770 
1771     // C11 6.3.2.1p2:
1772     //   ... if the lvalue has atomic type, the value has the non-atomic version
1773     //   of the type of the lvalue ...
1774     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1775       FromType = Atomic->getValueType();
1776 
1777     // If T is a non-class type, the type of the rvalue is the
1778     // cv-unqualified version of T. Otherwise, the type of the rvalue
1779     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1780     // just strip the qualifiers because they don't matter.
1781     FromType = FromType.getUnqualifiedType();
1782   } else if (FromType->isArrayType()) {
1783     // Array-to-pointer conversion (C++ 4.2)
1784     SCS.First = ICK_Array_To_Pointer;
1785 
1786     // An lvalue or rvalue of type "array of N T" or "array of unknown
1787     // bound of T" can be converted to an rvalue of type "pointer to
1788     // T" (C++ 4.2p1).
1789     FromType = S.Context.getArrayDecayedType(FromType);
1790 
1791     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1792       // This conversion is deprecated in C++03 (D.4)
1793       SCS.DeprecatedStringLiteralToCharPtr = true;
1794 
1795       // For the purpose of ranking in overload resolution
1796       // (13.3.3.1.1), this conversion is considered an
1797       // array-to-pointer conversion followed by a qualification
1798       // conversion (4.4). (C++ 4.2p2)
1799       SCS.Second = ICK_Identity;
1800       SCS.Third = ICK_Qualification;
1801       SCS.QualificationIncludesObjCLifetime = false;
1802       SCS.setAllToTypes(FromType);
1803       return true;
1804     }
1805   } else if (FromType->isFunctionType() && argIsLValue) {
1806     // Function-to-pointer conversion (C++ 4.3).
1807     SCS.First = ICK_Function_To_Pointer;
1808 
1809     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1810       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1811         if (!S.checkAddressOfFunctionIsAvailable(FD))
1812           return false;
1813 
1814     // An lvalue of function type T can be converted to an rvalue of
1815     // type "pointer to T." The result is a pointer to the
1816     // function. (C++ 4.3p1).
1817     FromType = S.Context.getPointerType(FromType);
1818   } else {
1819     // We don't require any conversions for the first step.
1820     SCS.First = ICK_Identity;
1821   }
1822   SCS.setToType(0, FromType);
1823 
1824   // The second conversion can be an integral promotion, floating
1825   // point promotion, integral conversion, floating point conversion,
1826   // floating-integral conversion, pointer conversion,
1827   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1828   // For overloading in C, this can also be a "compatible-type"
1829   // conversion.
1830   bool IncompatibleObjC = false;
1831   ImplicitConversionKind SecondICK = ICK_Identity;
1832   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1833     // The unqualified versions of the types are the same: there's no
1834     // conversion to do.
1835     SCS.Second = ICK_Identity;
1836   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1837     // Integral promotion (C++ 4.5).
1838     SCS.Second = ICK_Integral_Promotion;
1839     FromType = ToType.getUnqualifiedType();
1840   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1841     // Floating point promotion (C++ 4.6).
1842     SCS.Second = ICK_Floating_Promotion;
1843     FromType = ToType.getUnqualifiedType();
1844   } else if (S.IsComplexPromotion(FromType, ToType)) {
1845     // Complex promotion (Clang extension)
1846     SCS.Second = ICK_Complex_Promotion;
1847     FromType = ToType.getUnqualifiedType();
1848   } else if (ToType->isBooleanType() &&
1849              (FromType->isArithmeticType() ||
1850               FromType->isAnyPointerType() ||
1851               FromType->isBlockPointerType() ||
1852               FromType->isMemberPointerType())) {
1853     // Boolean conversions (C++ 4.12).
1854     SCS.Second = ICK_Boolean_Conversion;
1855     FromType = S.Context.BoolTy;
1856   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1857              ToType->isIntegralType(S.Context)) {
1858     // Integral conversions (C++ 4.7).
1859     SCS.Second = ICK_Integral_Conversion;
1860     FromType = ToType.getUnqualifiedType();
1861   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1862     // Complex conversions (C99 6.3.1.6)
1863     SCS.Second = ICK_Complex_Conversion;
1864     FromType = ToType.getUnqualifiedType();
1865   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1866              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1867     // Complex-real conversions (C99 6.3.1.7)
1868     SCS.Second = ICK_Complex_Real;
1869     FromType = ToType.getUnqualifiedType();
1870   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1871     // FIXME: disable conversions between long double, __ibm128 and __float128
1872     // if their representation is different until there is back end support
1873     // We of course allow this conversion if long double is really double.
1874 
1875     // Conversions between bfloat and other floats are not permitted.
1876     if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty)
1877       return false;
1878 
1879     // Conversions between IEEE-quad and IBM-extended semantics are not
1880     // permitted.
1881     const llvm::fltSemantics &FromSem =
1882         S.Context.getFloatTypeSemantics(FromType);
1883     const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
1884     if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
1885          &ToSem == &llvm::APFloat::IEEEquad()) ||
1886         (&FromSem == &llvm::APFloat::IEEEquad() &&
1887          &ToSem == &llvm::APFloat::PPCDoubleDouble()))
1888       return false;
1889 
1890     // Floating point conversions (C++ 4.8).
1891     SCS.Second = ICK_Floating_Conversion;
1892     FromType = ToType.getUnqualifiedType();
1893   } else if ((FromType->isRealFloatingType() &&
1894               ToType->isIntegralType(S.Context)) ||
1895              (FromType->isIntegralOrUnscopedEnumerationType() &&
1896               ToType->isRealFloatingType())) {
1897     // Conversions between bfloat and int are not permitted.
1898     if (FromType->isBFloat16Type() || ToType->isBFloat16Type())
1899       return false;
1900 
1901     // Floating-integral conversions (C++ 4.9).
1902     SCS.Second = ICK_Floating_Integral;
1903     FromType = ToType.getUnqualifiedType();
1904   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1905     SCS.Second = ICK_Block_Pointer_Conversion;
1906   } else if (AllowObjCWritebackConversion &&
1907              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1908     SCS.Second = ICK_Writeback_Conversion;
1909   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1910                                    FromType, IncompatibleObjC)) {
1911     // Pointer conversions (C++ 4.10).
1912     SCS.Second = ICK_Pointer_Conversion;
1913     SCS.IncompatibleObjC = IncompatibleObjC;
1914     FromType = FromType.getUnqualifiedType();
1915   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1916                                          InOverloadResolution, FromType)) {
1917     // Pointer to member conversions (4.11).
1918     SCS.Second = ICK_Pointer_Member;
1919   } else if (IsVectorConversion(S, FromType, ToType, SecondICK, From,
1920                                 InOverloadResolution)) {
1921     SCS.Second = SecondICK;
1922     FromType = ToType.getUnqualifiedType();
1923   } else if (!S.getLangOpts().CPlusPlus &&
1924              S.Context.typesAreCompatible(ToType, FromType)) {
1925     // Compatible conversions (Clang extension for C function overloading)
1926     SCS.Second = ICK_Compatible_Conversion;
1927     FromType = ToType.getUnqualifiedType();
1928   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1929                                              InOverloadResolution,
1930                                              SCS, CStyle)) {
1931     SCS.Second = ICK_TransparentUnionConversion;
1932     FromType = ToType;
1933   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1934                                  CStyle)) {
1935     // tryAtomicConversion has updated the standard conversion sequence
1936     // appropriately.
1937     return true;
1938   } else if (ToType->isEventT() &&
1939              From->isIntegerConstantExpr(S.getASTContext()) &&
1940              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1941     SCS.Second = ICK_Zero_Event_Conversion;
1942     FromType = ToType;
1943   } else if (ToType->isQueueT() &&
1944              From->isIntegerConstantExpr(S.getASTContext()) &&
1945              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1946     SCS.Second = ICK_Zero_Queue_Conversion;
1947     FromType = ToType;
1948   } else if (ToType->isSamplerT() &&
1949              From->isIntegerConstantExpr(S.getASTContext())) {
1950     SCS.Second = ICK_Compatible_Conversion;
1951     FromType = ToType;
1952   } else {
1953     // No second conversion required.
1954     SCS.Second = ICK_Identity;
1955   }
1956   SCS.setToType(1, FromType);
1957 
1958   // The third conversion can be a function pointer conversion or a
1959   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1960   bool ObjCLifetimeConversion;
1961   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1962     // Function pointer conversions (removing 'noexcept') including removal of
1963     // 'noreturn' (Clang extension).
1964     SCS.Third = ICK_Function_Conversion;
1965   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1966                                          ObjCLifetimeConversion)) {
1967     SCS.Third = ICK_Qualification;
1968     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1969     FromType = ToType;
1970   } else {
1971     // No conversion required
1972     SCS.Third = ICK_Identity;
1973   }
1974 
1975   // C++ [over.best.ics]p6:
1976   //   [...] Any difference in top-level cv-qualification is
1977   //   subsumed by the initialization itself and does not constitute
1978   //   a conversion. [...]
1979   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1980   QualType CanonTo = S.Context.getCanonicalType(ToType);
1981   if (CanonFrom.getLocalUnqualifiedType()
1982                                      == CanonTo.getLocalUnqualifiedType() &&
1983       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1984     FromType = ToType;
1985     CanonFrom = CanonTo;
1986   }
1987 
1988   SCS.setToType(2, FromType);
1989 
1990   if (CanonFrom == CanonTo)
1991     return true;
1992 
1993   // If we have not converted the argument type to the parameter type,
1994   // this is a bad conversion sequence, unless we're resolving an overload in C.
1995   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1996     return false;
1997 
1998   ExprResult ER = ExprResult{From};
1999   Sema::AssignConvertType Conv =
2000       S.CheckSingleAssignmentConstraints(ToType, ER,
2001                                          /*Diagnose=*/false,
2002                                          /*DiagnoseCFAudited=*/false,
2003                                          /*ConvertRHS=*/false);
2004   ImplicitConversionKind SecondConv;
2005   switch (Conv) {
2006   case Sema::Compatible:
2007     SecondConv = ICK_C_Only_Conversion;
2008     break;
2009   // For our purposes, discarding qualifiers is just as bad as using an
2010   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2011   // qualifiers, as well.
2012   case Sema::CompatiblePointerDiscardsQualifiers:
2013   case Sema::IncompatiblePointer:
2014   case Sema::IncompatiblePointerSign:
2015     SecondConv = ICK_Incompatible_Pointer_Conversion;
2016     break;
2017   default:
2018     return false;
2019   }
2020 
2021   // First can only be an lvalue conversion, so we pretend that this was the
2022   // second conversion. First should already be valid from earlier in the
2023   // function.
2024   SCS.Second = SecondConv;
2025   SCS.setToType(1, ToType);
2026 
2027   // Third is Identity, because Second should rank us worse than any other
2028   // conversion. This could also be ICK_Qualification, but it's simpler to just
2029   // lump everything in with the second conversion, and we don't gain anything
2030   // from making this ICK_Qualification.
2031   SCS.Third = ICK_Identity;
2032   SCS.setToType(2, ToType);
2033   return true;
2034 }
2035 
2036 static bool
2037 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2038                                      QualType &ToType,
2039                                      bool InOverloadResolution,
2040                                      StandardConversionSequence &SCS,
2041                                      bool CStyle) {
2042 
2043   const RecordType *UT = ToType->getAsUnionType();
2044   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2045     return false;
2046   // The field to initialize within the transparent union.
2047   RecordDecl *UD = UT->getDecl();
2048   // It's compatible if the expression matches any of the fields.
2049   for (const auto *it : UD->fields()) {
2050     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2051                              CStyle, /*AllowObjCWritebackConversion=*/false)) {
2052       ToType = it->getType();
2053       return true;
2054     }
2055   }
2056   return false;
2057 }
2058 
2059 /// IsIntegralPromotion - Determines whether the conversion from the
2060 /// expression From (whose potentially-adjusted type is FromType) to
2061 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
2062 /// sets PromotedType to the promoted type.
2063 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2064   const BuiltinType *To = ToType->getAs<BuiltinType>();
2065   // All integers are built-in.
2066   if (!To) {
2067     return false;
2068   }
2069 
2070   // An rvalue of type char, signed char, unsigned char, short int, or
2071   // unsigned short int can be converted to an rvalue of type int if
2072   // int can represent all the values of the source type; otherwise,
2073   // the source rvalue can be converted to an rvalue of type unsigned
2074   // int (C++ 4.5p1).
2075   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
2076       !FromType->isEnumeralType()) {
2077     if (// We can promote any signed, promotable integer type to an int
2078         (FromType->isSignedIntegerType() ||
2079          // We can promote any unsigned integer type whose size is
2080          // less than int to an int.
2081          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2082       return To->getKind() == BuiltinType::Int;
2083     }
2084 
2085     return To->getKind() == BuiltinType::UInt;
2086   }
2087 
2088   // C++11 [conv.prom]p3:
2089   //   A prvalue of an unscoped enumeration type whose underlying type is not
2090   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2091   //   following types that can represent all the values of the enumeration
2092   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
2093   //   unsigned int, long int, unsigned long int, long long int, or unsigned
2094   //   long long int. If none of the types in that list can represent all the
2095   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2096   //   type can be converted to an rvalue a prvalue of the extended integer type
2097   //   with lowest integer conversion rank (4.13) greater than the rank of long
2098   //   long in which all the values of the enumeration can be represented. If
2099   //   there are two such extended types, the signed one is chosen.
2100   // C++11 [conv.prom]p4:
2101   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
2102   //   can be converted to a prvalue of its underlying type. Moreover, if
2103   //   integral promotion can be applied to its underlying type, a prvalue of an
2104   //   unscoped enumeration type whose underlying type is fixed can also be
2105   //   converted to a prvalue of the promoted underlying type.
2106   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2107     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2108     // provided for a scoped enumeration.
2109     if (FromEnumType->getDecl()->isScoped())
2110       return false;
2111 
2112     // We can perform an integral promotion to the underlying type of the enum,
2113     // even if that's not the promoted type. Note that the check for promoting
2114     // the underlying type is based on the type alone, and does not consider
2115     // the bitfield-ness of the actual source expression.
2116     if (FromEnumType->getDecl()->isFixed()) {
2117       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2118       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2119              IsIntegralPromotion(nullptr, Underlying, ToType);
2120     }
2121 
2122     // We have already pre-calculated the promotion type, so this is trivial.
2123     if (ToType->isIntegerType() &&
2124         isCompleteType(From->getBeginLoc(), FromType))
2125       return Context.hasSameUnqualifiedType(
2126           ToType, FromEnumType->getDecl()->getPromotionType());
2127 
2128     // C++ [conv.prom]p5:
2129     //   If the bit-field has an enumerated type, it is treated as any other
2130     //   value of that type for promotion purposes.
2131     //
2132     // ... so do not fall through into the bit-field checks below in C++.
2133     if (getLangOpts().CPlusPlus)
2134       return false;
2135   }
2136 
2137   // C++0x [conv.prom]p2:
2138   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2139   //   to an rvalue a prvalue of the first of the following types that can
2140   //   represent all the values of its underlying type: int, unsigned int,
2141   //   long int, unsigned long int, long long int, or unsigned long long int.
2142   //   If none of the types in that list can represent all the values of its
2143   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2144   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2145   //   type.
2146   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2147       ToType->isIntegerType()) {
2148     // Determine whether the type we're converting from is signed or
2149     // unsigned.
2150     bool FromIsSigned = FromType->isSignedIntegerType();
2151     uint64_t FromSize = Context.getTypeSize(FromType);
2152 
2153     // The types we'll try to promote to, in the appropriate
2154     // order. Try each of these types.
2155     QualType PromoteTypes[6] = {
2156       Context.IntTy, Context.UnsignedIntTy,
2157       Context.LongTy, Context.UnsignedLongTy ,
2158       Context.LongLongTy, Context.UnsignedLongLongTy
2159     };
2160     for (int Idx = 0; Idx < 6; ++Idx) {
2161       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2162       if (FromSize < ToSize ||
2163           (FromSize == ToSize &&
2164            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2165         // We found the type that we can promote to. If this is the
2166         // type we wanted, we have a promotion. Otherwise, no
2167         // promotion.
2168         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2169       }
2170     }
2171   }
2172 
2173   // An rvalue for an integral bit-field (9.6) can be converted to an
2174   // rvalue of type int if int can represent all the values of the
2175   // bit-field; otherwise, it can be converted to unsigned int if
2176   // unsigned int can represent all the values of the bit-field. If
2177   // the bit-field is larger yet, no integral promotion applies to
2178   // it. If the bit-field has an enumerated type, it is treated as any
2179   // other value of that type for promotion purposes (C++ 4.5p3).
2180   // FIXME: We should delay checking of bit-fields until we actually perform the
2181   // conversion.
2182   //
2183   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2184   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2185   // bit-fields and those whose underlying type is larger than int) for GCC
2186   // compatibility.
2187   if (From) {
2188     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2189       Optional<llvm::APSInt> BitWidth;
2190       if (FromType->isIntegralType(Context) &&
2191           (BitWidth =
2192                MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2193         llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2194         ToSize = Context.getTypeSize(ToType);
2195 
2196         // Are we promoting to an int from a bitfield that fits in an int?
2197         if (*BitWidth < ToSize ||
2198             (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2199           return To->getKind() == BuiltinType::Int;
2200         }
2201 
2202         // Are we promoting to an unsigned int from an unsigned bitfield
2203         // that fits into an unsigned int?
2204         if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2205           return To->getKind() == BuiltinType::UInt;
2206         }
2207 
2208         return false;
2209       }
2210     }
2211   }
2212 
2213   // An rvalue of type bool can be converted to an rvalue of type int,
2214   // with false becoming zero and true becoming one (C++ 4.5p4).
2215   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2216     return true;
2217   }
2218 
2219   return false;
2220 }
2221 
2222 /// IsFloatingPointPromotion - Determines whether the conversion from
2223 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2224 /// returns true and sets PromotedType to the promoted type.
2225 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2226   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2227     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2228       /// An rvalue of type float can be converted to an rvalue of type
2229       /// double. (C++ 4.6p1).
2230       if (FromBuiltin->getKind() == BuiltinType::Float &&
2231           ToBuiltin->getKind() == BuiltinType::Double)
2232         return true;
2233 
2234       // C99 6.3.1.5p1:
2235       //   When a float is promoted to double or long double, or a
2236       //   double is promoted to long double [...].
2237       if (!getLangOpts().CPlusPlus &&
2238           (FromBuiltin->getKind() == BuiltinType::Float ||
2239            FromBuiltin->getKind() == BuiltinType::Double) &&
2240           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2241            ToBuiltin->getKind() == BuiltinType::Float128 ||
2242            ToBuiltin->getKind() == BuiltinType::Ibm128))
2243         return true;
2244 
2245       // Half can be promoted to float.
2246       if (!getLangOpts().NativeHalfType &&
2247            FromBuiltin->getKind() == BuiltinType::Half &&
2248           ToBuiltin->getKind() == BuiltinType::Float)
2249         return true;
2250     }
2251 
2252   return false;
2253 }
2254 
2255 /// Determine if a conversion is a complex promotion.
2256 ///
2257 /// A complex promotion is defined as a complex -> complex conversion
2258 /// where the conversion between the underlying real types is a
2259 /// floating-point or integral promotion.
2260 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2261   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2262   if (!FromComplex)
2263     return false;
2264 
2265   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2266   if (!ToComplex)
2267     return false;
2268 
2269   return IsFloatingPointPromotion(FromComplex->getElementType(),
2270                                   ToComplex->getElementType()) ||
2271     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2272                         ToComplex->getElementType());
2273 }
2274 
2275 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2276 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2277 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2278 /// if non-empty, will be a pointer to ToType that may or may not have
2279 /// the right set of qualifiers on its pointee.
2280 ///
2281 static QualType
2282 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2283                                    QualType ToPointee, QualType ToType,
2284                                    ASTContext &Context,
2285                                    bool StripObjCLifetime = false) {
2286   assert((FromPtr->getTypeClass() == Type::Pointer ||
2287           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2288          "Invalid similarly-qualified pointer type");
2289 
2290   /// Conversions to 'id' subsume cv-qualifier conversions.
2291   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2292     return ToType.getUnqualifiedType();
2293 
2294   QualType CanonFromPointee
2295     = Context.getCanonicalType(FromPtr->getPointeeType());
2296   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2297   Qualifiers Quals = CanonFromPointee.getQualifiers();
2298 
2299   if (StripObjCLifetime)
2300     Quals.removeObjCLifetime();
2301 
2302   // Exact qualifier match -> return the pointer type we're converting to.
2303   if (CanonToPointee.getLocalQualifiers() == Quals) {
2304     // ToType is exactly what we need. Return it.
2305     if (!ToType.isNull())
2306       return ToType.getUnqualifiedType();
2307 
2308     // Build a pointer to ToPointee. It has the right qualifiers
2309     // already.
2310     if (isa<ObjCObjectPointerType>(ToType))
2311       return Context.getObjCObjectPointerType(ToPointee);
2312     return Context.getPointerType(ToPointee);
2313   }
2314 
2315   // Just build a canonical type that has the right qualifiers.
2316   QualType QualifiedCanonToPointee
2317     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2318 
2319   if (isa<ObjCObjectPointerType>(ToType))
2320     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2321   return Context.getPointerType(QualifiedCanonToPointee);
2322 }
2323 
2324 static bool isNullPointerConstantForConversion(Expr *Expr,
2325                                                bool InOverloadResolution,
2326                                                ASTContext &Context) {
2327   // Handle value-dependent integral null pointer constants correctly.
2328   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2329   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2330       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2331     return !InOverloadResolution;
2332 
2333   return Expr->isNullPointerConstant(Context,
2334                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2335                                         : Expr::NPC_ValueDependentIsNull);
2336 }
2337 
2338 /// IsPointerConversion - Determines whether the conversion of the
2339 /// expression From, which has the (possibly adjusted) type FromType,
2340 /// can be converted to the type ToType via a pointer conversion (C++
2341 /// 4.10). If so, returns true and places the converted type (that
2342 /// might differ from ToType in its cv-qualifiers at some level) into
2343 /// ConvertedType.
2344 ///
2345 /// This routine also supports conversions to and from block pointers
2346 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2347 /// pointers to interfaces. FIXME: Once we've determined the
2348 /// appropriate overloading rules for Objective-C, we may want to
2349 /// split the Objective-C checks into a different routine; however,
2350 /// GCC seems to consider all of these conversions to be pointer
2351 /// conversions, so for now they live here. IncompatibleObjC will be
2352 /// set if the conversion is an allowed Objective-C conversion that
2353 /// should result in a warning.
2354 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2355                                bool InOverloadResolution,
2356                                QualType& ConvertedType,
2357                                bool &IncompatibleObjC) {
2358   IncompatibleObjC = false;
2359   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2360                               IncompatibleObjC))
2361     return true;
2362 
2363   // Conversion from a null pointer constant to any Objective-C pointer type.
2364   if (ToType->isObjCObjectPointerType() &&
2365       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2366     ConvertedType = ToType;
2367     return true;
2368   }
2369 
2370   // Blocks: Block pointers can be converted to void*.
2371   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2372       ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2373     ConvertedType = ToType;
2374     return true;
2375   }
2376   // Blocks: A null pointer constant can be converted to a block
2377   // pointer type.
2378   if (ToType->isBlockPointerType() &&
2379       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2380     ConvertedType = ToType;
2381     return true;
2382   }
2383 
2384   // If the left-hand-side is nullptr_t, the right side can be a null
2385   // pointer constant.
2386   if (ToType->isNullPtrType() &&
2387       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2388     ConvertedType = ToType;
2389     return true;
2390   }
2391 
2392   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2393   if (!ToTypePtr)
2394     return false;
2395 
2396   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2397   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2398     ConvertedType = ToType;
2399     return true;
2400   }
2401 
2402   // Beyond this point, both types need to be pointers
2403   // , including objective-c pointers.
2404   QualType ToPointeeType = ToTypePtr->getPointeeType();
2405   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2406       !getLangOpts().ObjCAutoRefCount) {
2407     ConvertedType = BuildSimilarlyQualifiedPointerType(
2408         FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2409         Context);
2410     return true;
2411   }
2412   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2413   if (!FromTypePtr)
2414     return false;
2415 
2416   QualType FromPointeeType = FromTypePtr->getPointeeType();
2417 
2418   // If the unqualified pointee types are the same, this can't be a
2419   // pointer conversion, so don't do all of the work below.
2420   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2421     return false;
2422 
2423   // An rvalue of type "pointer to cv T," where T is an object type,
2424   // can be converted to an rvalue of type "pointer to cv void" (C++
2425   // 4.10p2).
2426   if (FromPointeeType->isIncompleteOrObjectType() &&
2427       ToPointeeType->isVoidType()) {
2428     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2429                                                        ToPointeeType,
2430                                                        ToType, Context,
2431                                                    /*StripObjCLifetime=*/true);
2432     return true;
2433   }
2434 
2435   // MSVC allows implicit function to void* type conversion.
2436   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2437       ToPointeeType->isVoidType()) {
2438     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2439                                                        ToPointeeType,
2440                                                        ToType, Context);
2441     return true;
2442   }
2443 
2444   // When we're overloading in C, we allow a special kind of pointer
2445   // conversion for compatible-but-not-identical pointee types.
2446   if (!getLangOpts().CPlusPlus &&
2447       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2448     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2449                                                        ToPointeeType,
2450                                                        ToType, Context);
2451     return true;
2452   }
2453 
2454   // C++ [conv.ptr]p3:
2455   //
2456   //   An rvalue of type "pointer to cv D," where D is a class type,
2457   //   can be converted to an rvalue of type "pointer to cv B," where
2458   //   B is a base class (clause 10) of D. If B is an inaccessible
2459   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2460   //   necessitates this conversion is ill-formed. The result of the
2461   //   conversion is a pointer to the base class sub-object of the
2462   //   derived class object. The null pointer value is converted to
2463   //   the null pointer value of the destination type.
2464   //
2465   // Note that we do not check for ambiguity or inaccessibility
2466   // here. That is handled by CheckPointerConversion.
2467   if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2468       ToPointeeType->isRecordType() &&
2469       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2470       IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2471     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2472                                                        ToPointeeType,
2473                                                        ToType, Context);
2474     return true;
2475   }
2476 
2477   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2478       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2479     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2480                                                        ToPointeeType,
2481                                                        ToType, Context);
2482     return true;
2483   }
2484 
2485   return false;
2486 }
2487 
2488 /// Adopt the given qualifiers for the given type.
2489 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2490   Qualifiers TQs = T.getQualifiers();
2491 
2492   // Check whether qualifiers already match.
2493   if (TQs == Qs)
2494     return T;
2495 
2496   if (Qs.compatiblyIncludes(TQs))
2497     return Context.getQualifiedType(T, Qs);
2498 
2499   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2500 }
2501 
2502 /// isObjCPointerConversion - Determines whether this is an
2503 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2504 /// with the same arguments and return values.
2505 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2506                                    QualType& ConvertedType,
2507                                    bool &IncompatibleObjC) {
2508   if (!getLangOpts().ObjC)
2509     return false;
2510 
2511   // The set of qualifiers on the type we're converting from.
2512   Qualifiers FromQualifiers = FromType.getQualifiers();
2513 
2514   // First, we handle all conversions on ObjC object pointer types.
2515   const ObjCObjectPointerType* ToObjCPtr =
2516     ToType->getAs<ObjCObjectPointerType>();
2517   const ObjCObjectPointerType *FromObjCPtr =
2518     FromType->getAs<ObjCObjectPointerType>();
2519 
2520   if (ToObjCPtr && FromObjCPtr) {
2521     // If the pointee types are the same (ignoring qualifications),
2522     // then this is not a pointer conversion.
2523     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2524                                        FromObjCPtr->getPointeeType()))
2525       return false;
2526 
2527     // Conversion between Objective-C pointers.
2528     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2529       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2530       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2531       if (getLangOpts().CPlusPlus && LHS && RHS &&
2532           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2533                                                 FromObjCPtr->getPointeeType()))
2534         return false;
2535       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2536                                                    ToObjCPtr->getPointeeType(),
2537                                                          ToType, Context);
2538       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2539       return true;
2540     }
2541 
2542     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2543       // Okay: this is some kind of implicit downcast of Objective-C
2544       // interfaces, which is permitted. However, we're going to
2545       // complain about it.
2546       IncompatibleObjC = true;
2547       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2548                                                    ToObjCPtr->getPointeeType(),
2549                                                          ToType, Context);
2550       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2551       return true;
2552     }
2553   }
2554   // Beyond this point, both types need to be C pointers or block pointers.
2555   QualType ToPointeeType;
2556   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2557     ToPointeeType = ToCPtr->getPointeeType();
2558   else if (const BlockPointerType *ToBlockPtr =
2559             ToType->getAs<BlockPointerType>()) {
2560     // Objective C++: We're able to convert from a pointer to any object
2561     // to a block pointer type.
2562     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2563       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2564       return true;
2565     }
2566     ToPointeeType = ToBlockPtr->getPointeeType();
2567   }
2568   else if (FromType->getAs<BlockPointerType>() &&
2569            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2570     // Objective C++: We're able to convert from a block pointer type to a
2571     // pointer to any object.
2572     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2573     return true;
2574   }
2575   else
2576     return false;
2577 
2578   QualType FromPointeeType;
2579   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2580     FromPointeeType = FromCPtr->getPointeeType();
2581   else if (const BlockPointerType *FromBlockPtr =
2582            FromType->getAs<BlockPointerType>())
2583     FromPointeeType = FromBlockPtr->getPointeeType();
2584   else
2585     return false;
2586 
2587   // If we have pointers to pointers, recursively check whether this
2588   // is an Objective-C conversion.
2589   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2590       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2591                               IncompatibleObjC)) {
2592     // We always complain about this conversion.
2593     IncompatibleObjC = true;
2594     ConvertedType = Context.getPointerType(ConvertedType);
2595     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2596     return true;
2597   }
2598   // Allow conversion of pointee being objective-c pointer to another one;
2599   // as in I* to id.
2600   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2601       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2602       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2603                               IncompatibleObjC)) {
2604 
2605     ConvertedType = Context.getPointerType(ConvertedType);
2606     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2607     return true;
2608   }
2609 
2610   // If we have pointers to functions or blocks, check whether the only
2611   // differences in the argument and result types are in Objective-C
2612   // pointer conversions. If so, we permit the conversion (but
2613   // complain about it).
2614   const FunctionProtoType *FromFunctionType
2615     = FromPointeeType->getAs<FunctionProtoType>();
2616   const FunctionProtoType *ToFunctionType
2617     = ToPointeeType->getAs<FunctionProtoType>();
2618   if (FromFunctionType && ToFunctionType) {
2619     // If the function types are exactly the same, this isn't an
2620     // Objective-C pointer conversion.
2621     if (Context.getCanonicalType(FromPointeeType)
2622           == Context.getCanonicalType(ToPointeeType))
2623       return false;
2624 
2625     // Perform the quick checks that will tell us whether these
2626     // function types are obviously different.
2627     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2628         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2629         FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2630       return false;
2631 
2632     bool HasObjCConversion = false;
2633     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2634         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2635       // Okay, the types match exactly. Nothing to do.
2636     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2637                                        ToFunctionType->getReturnType(),
2638                                        ConvertedType, IncompatibleObjC)) {
2639       // Okay, we have an Objective-C pointer conversion.
2640       HasObjCConversion = true;
2641     } else {
2642       // Function types are too different. Abort.
2643       return false;
2644     }
2645 
2646     // Check argument types.
2647     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2648          ArgIdx != NumArgs; ++ArgIdx) {
2649       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2650       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2651       if (Context.getCanonicalType(FromArgType)
2652             == Context.getCanonicalType(ToArgType)) {
2653         // Okay, the types match exactly. Nothing to do.
2654       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2655                                          ConvertedType, IncompatibleObjC)) {
2656         // Okay, we have an Objective-C pointer conversion.
2657         HasObjCConversion = true;
2658       } else {
2659         // Argument types are too different. Abort.
2660         return false;
2661       }
2662     }
2663 
2664     if (HasObjCConversion) {
2665       // We had an Objective-C conversion. Allow this pointer
2666       // conversion, but complain about it.
2667       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2668       IncompatibleObjC = true;
2669       return true;
2670     }
2671   }
2672 
2673   return false;
2674 }
2675 
2676 /// Determine whether this is an Objective-C writeback conversion,
2677 /// used for parameter passing when performing automatic reference counting.
2678 ///
2679 /// \param FromType The type we're converting form.
2680 ///
2681 /// \param ToType The type we're converting to.
2682 ///
2683 /// \param ConvertedType The type that will be produced after applying
2684 /// this conversion.
2685 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2686                                      QualType &ConvertedType) {
2687   if (!getLangOpts().ObjCAutoRefCount ||
2688       Context.hasSameUnqualifiedType(FromType, ToType))
2689     return false;
2690 
2691   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2692   QualType ToPointee;
2693   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2694     ToPointee = ToPointer->getPointeeType();
2695   else
2696     return false;
2697 
2698   Qualifiers ToQuals = ToPointee.getQualifiers();
2699   if (!ToPointee->isObjCLifetimeType() ||
2700       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2701       !ToQuals.withoutObjCLifetime().empty())
2702     return false;
2703 
2704   // Argument must be a pointer to __strong to __weak.
2705   QualType FromPointee;
2706   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2707     FromPointee = FromPointer->getPointeeType();
2708   else
2709     return false;
2710 
2711   Qualifiers FromQuals = FromPointee.getQualifiers();
2712   if (!FromPointee->isObjCLifetimeType() ||
2713       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2714        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2715     return false;
2716 
2717   // Make sure that we have compatible qualifiers.
2718   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2719   if (!ToQuals.compatiblyIncludes(FromQuals))
2720     return false;
2721 
2722   // Remove qualifiers from the pointee type we're converting from; they
2723   // aren't used in the compatibility check belong, and we'll be adding back
2724   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2725   FromPointee = FromPointee.getUnqualifiedType();
2726 
2727   // The unqualified form of the pointee types must be compatible.
2728   ToPointee = ToPointee.getUnqualifiedType();
2729   bool IncompatibleObjC;
2730   if (Context.typesAreCompatible(FromPointee, ToPointee))
2731     FromPointee = ToPointee;
2732   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2733                                     IncompatibleObjC))
2734     return false;
2735 
2736   /// Construct the type we're converting to, which is a pointer to
2737   /// __autoreleasing pointee.
2738   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2739   ConvertedType = Context.getPointerType(FromPointee);
2740   return true;
2741 }
2742 
2743 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2744                                     QualType& ConvertedType) {
2745   QualType ToPointeeType;
2746   if (const BlockPointerType *ToBlockPtr =
2747         ToType->getAs<BlockPointerType>())
2748     ToPointeeType = ToBlockPtr->getPointeeType();
2749   else
2750     return false;
2751 
2752   QualType FromPointeeType;
2753   if (const BlockPointerType *FromBlockPtr =
2754       FromType->getAs<BlockPointerType>())
2755     FromPointeeType = FromBlockPtr->getPointeeType();
2756   else
2757     return false;
2758   // We have pointer to blocks, check whether the only
2759   // differences in the argument and result types are in Objective-C
2760   // pointer conversions. If so, we permit the conversion.
2761 
2762   const FunctionProtoType *FromFunctionType
2763     = FromPointeeType->getAs<FunctionProtoType>();
2764   const FunctionProtoType *ToFunctionType
2765     = ToPointeeType->getAs<FunctionProtoType>();
2766 
2767   if (!FromFunctionType || !ToFunctionType)
2768     return false;
2769 
2770   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2771     return true;
2772 
2773   // Perform the quick checks that will tell us whether these
2774   // function types are obviously different.
2775   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2776       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2777     return false;
2778 
2779   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2780   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2781   if (FromEInfo != ToEInfo)
2782     return false;
2783 
2784   bool IncompatibleObjC = false;
2785   if (Context.hasSameType(FromFunctionType->getReturnType(),
2786                           ToFunctionType->getReturnType())) {
2787     // Okay, the types match exactly. Nothing to do.
2788   } else {
2789     QualType RHS = FromFunctionType->getReturnType();
2790     QualType LHS = ToFunctionType->getReturnType();
2791     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2792         !RHS.hasQualifiers() && LHS.hasQualifiers())
2793        LHS = LHS.getUnqualifiedType();
2794 
2795      if (Context.hasSameType(RHS,LHS)) {
2796        // OK exact match.
2797      } else if (isObjCPointerConversion(RHS, LHS,
2798                                         ConvertedType, IncompatibleObjC)) {
2799      if (IncompatibleObjC)
2800        return false;
2801      // Okay, we have an Objective-C pointer conversion.
2802      }
2803      else
2804        return false;
2805    }
2806 
2807    // Check argument types.
2808    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2809         ArgIdx != NumArgs; ++ArgIdx) {
2810      IncompatibleObjC = false;
2811      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2812      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2813      if (Context.hasSameType(FromArgType, ToArgType)) {
2814        // Okay, the types match exactly. Nothing to do.
2815      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2816                                         ConvertedType, IncompatibleObjC)) {
2817        if (IncompatibleObjC)
2818          return false;
2819        // Okay, we have an Objective-C pointer conversion.
2820      } else
2821        // Argument types are too different. Abort.
2822        return false;
2823    }
2824 
2825    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2826    bool CanUseToFPT, CanUseFromFPT;
2827    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2828                                       CanUseToFPT, CanUseFromFPT,
2829                                       NewParamInfos))
2830      return false;
2831 
2832    ConvertedType = ToType;
2833    return true;
2834 }
2835 
2836 enum {
2837   ft_default,
2838   ft_different_class,
2839   ft_parameter_arity,
2840   ft_parameter_mismatch,
2841   ft_return_type,
2842   ft_qualifer_mismatch,
2843   ft_noexcept
2844 };
2845 
2846 /// Attempts to get the FunctionProtoType from a Type. Handles
2847 /// MemberFunctionPointers properly.
2848 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2849   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2850     return FPT;
2851 
2852   if (auto *MPT = FromType->getAs<MemberPointerType>())
2853     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2854 
2855   return nullptr;
2856 }
2857 
2858 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2859 /// function types.  Catches different number of parameter, mismatch in
2860 /// parameter types, and different return types.
2861 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2862                                       QualType FromType, QualType ToType) {
2863   // If either type is not valid, include no extra info.
2864   if (FromType.isNull() || ToType.isNull()) {
2865     PDiag << ft_default;
2866     return;
2867   }
2868 
2869   // Get the function type from the pointers.
2870   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2871     const auto *FromMember = FromType->castAs<MemberPointerType>(),
2872                *ToMember = ToType->castAs<MemberPointerType>();
2873     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2874       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2875             << QualType(FromMember->getClass(), 0);
2876       return;
2877     }
2878     FromType = FromMember->getPointeeType();
2879     ToType = ToMember->getPointeeType();
2880   }
2881 
2882   if (FromType->isPointerType())
2883     FromType = FromType->getPointeeType();
2884   if (ToType->isPointerType())
2885     ToType = ToType->getPointeeType();
2886 
2887   // Remove references.
2888   FromType = FromType.getNonReferenceType();
2889   ToType = ToType.getNonReferenceType();
2890 
2891   // Don't print extra info for non-specialized template functions.
2892   if (FromType->isInstantiationDependentType() &&
2893       !FromType->getAs<TemplateSpecializationType>()) {
2894     PDiag << ft_default;
2895     return;
2896   }
2897 
2898   // No extra info for same types.
2899   if (Context.hasSameType(FromType, ToType)) {
2900     PDiag << ft_default;
2901     return;
2902   }
2903 
2904   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2905                           *ToFunction = tryGetFunctionProtoType(ToType);
2906 
2907   // Both types need to be function types.
2908   if (!FromFunction || !ToFunction) {
2909     PDiag << ft_default;
2910     return;
2911   }
2912 
2913   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2914     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2915           << FromFunction->getNumParams();
2916     return;
2917   }
2918 
2919   // Handle different parameter types.
2920   unsigned ArgPos;
2921   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2922     PDiag << ft_parameter_mismatch << ArgPos + 1
2923           << ToFunction->getParamType(ArgPos)
2924           << FromFunction->getParamType(ArgPos);
2925     return;
2926   }
2927 
2928   // Handle different return type.
2929   if (!Context.hasSameType(FromFunction->getReturnType(),
2930                            ToFunction->getReturnType())) {
2931     PDiag << ft_return_type << ToFunction->getReturnType()
2932           << FromFunction->getReturnType();
2933     return;
2934   }
2935 
2936   if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2937     PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2938           << FromFunction->getMethodQuals();
2939     return;
2940   }
2941 
2942   // Handle exception specification differences on canonical type (in C++17
2943   // onwards).
2944   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2945           ->isNothrow() !=
2946       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2947           ->isNothrow()) {
2948     PDiag << ft_noexcept;
2949     return;
2950   }
2951 
2952   // Unable to find a difference, so add no extra info.
2953   PDiag << ft_default;
2954 }
2955 
2956 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2957 /// for equality of their parameter types. Caller has already checked that
2958 /// they have same number of parameters.  If the parameters are different,
2959 /// ArgPos will have the parameter index of the first different parameter.
2960 /// If `Reversed` is true, the parameters of `NewType` will be compared in
2961 /// reverse order. That's useful if one of the functions is being used as a C++20
2962 /// synthesized operator overload with a reversed parameter order.
2963 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2964                                       const FunctionProtoType *NewType,
2965                                       unsigned *ArgPos, bool Reversed) {
2966   assert(OldType->getNumParams() == NewType->getNumParams() &&
2967          "Can't compare parameters of functions with different number of "
2968          "parameters!");
2969   for (size_t I = 0; I < OldType->getNumParams(); I++) {
2970     // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
2971     size_t J = Reversed ? (OldType->getNumParams() - I - 1) : I;
2972 
2973     // Ignore address spaces in pointee type. This is to disallow overloading
2974     // on __ptr32/__ptr64 address spaces.
2975     QualType Old = Context.removePtrSizeAddrSpace(OldType->getParamType(I).getUnqualifiedType());
2976     QualType New = Context.removePtrSizeAddrSpace(NewType->getParamType(J).getUnqualifiedType());
2977 
2978     if (!Context.hasSameType(Old, New)) {
2979       if (ArgPos)
2980         *ArgPos = I;
2981       return false;
2982     }
2983   }
2984   return true;
2985 }
2986 
2987 /// CheckPointerConversion - Check the pointer conversion from the
2988 /// expression From to the type ToType. This routine checks for
2989 /// ambiguous or inaccessible derived-to-base pointer
2990 /// conversions for which IsPointerConversion has already returned
2991 /// true. It returns true and produces a diagnostic if there was an
2992 /// error, or returns false otherwise.
2993 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2994                                   CastKind &Kind,
2995                                   CXXCastPath& BasePath,
2996                                   bool IgnoreBaseAccess,
2997                                   bool Diagnose) {
2998   QualType FromType = From->getType();
2999   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3000 
3001   Kind = CK_BitCast;
3002 
3003   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3004       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
3005           Expr::NPCK_ZeroExpression) {
3006     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3007       DiagRuntimeBehavior(From->getExprLoc(), From,
3008                           PDiag(diag::warn_impcast_bool_to_null_pointer)
3009                             << ToType << From->getSourceRange());
3010     else if (!isUnevaluatedContext())
3011       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3012         << ToType << From->getSourceRange();
3013   }
3014   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3015     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3016       QualType FromPointeeType = FromPtrType->getPointeeType(),
3017                ToPointeeType   = ToPtrType->getPointeeType();
3018 
3019       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3020           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3021         // We must have a derived-to-base conversion. Check an
3022         // ambiguous or inaccessible conversion.
3023         unsigned InaccessibleID = 0;
3024         unsigned AmbiguousID = 0;
3025         if (Diagnose) {
3026           InaccessibleID = diag::err_upcast_to_inaccessible_base;
3027           AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3028         }
3029         if (CheckDerivedToBaseConversion(
3030                 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3031                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3032                 &BasePath, IgnoreBaseAccess))
3033           return true;
3034 
3035         // The conversion was successful.
3036         Kind = CK_DerivedToBase;
3037       }
3038 
3039       if (Diagnose && !IsCStyleOrFunctionalCast &&
3040           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3041         assert(getLangOpts().MSVCCompat &&
3042                "this should only be possible with MSVCCompat!");
3043         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3044             << From->getSourceRange();
3045       }
3046     }
3047   } else if (const ObjCObjectPointerType *ToPtrType =
3048                ToType->getAs<ObjCObjectPointerType>()) {
3049     if (const ObjCObjectPointerType *FromPtrType =
3050           FromType->getAs<ObjCObjectPointerType>()) {
3051       // Objective-C++ conversions are always okay.
3052       // FIXME: We should have a different class of conversions for the
3053       // Objective-C++ implicit conversions.
3054       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3055         return false;
3056     } else if (FromType->isBlockPointerType()) {
3057       Kind = CK_BlockPointerToObjCPointerCast;
3058     } else {
3059       Kind = CK_CPointerToObjCPointerCast;
3060     }
3061   } else if (ToType->isBlockPointerType()) {
3062     if (!FromType->isBlockPointerType())
3063       Kind = CK_AnyPointerToBlockPointerCast;
3064   }
3065 
3066   // We shouldn't fall into this case unless it's valid for other
3067   // reasons.
3068   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3069     Kind = CK_NullToPointer;
3070 
3071   return false;
3072 }
3073 
3074 /// IsMemberPointerConversion - Determines whether the conversion of the
3075 /// expression From, which has the (possibly adjusted) type FromType, can be
3076 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
3077 /// If so, returns true and places the converted type (that might differ from
3078 /// ToType in its cv-qualifiers at some level) into ConvertedType.
3079 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3080                                      QualType ToType,
3081                                      bool InOverloadResolution,
3082                                      QualType &ConvertedType) {
3083   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3084   if (!ToTypePtr)
3085     return false;
3086 
3087   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3088   if (From->isNullPointerConstant(Context,
3089                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3090                                         : Expr::NPC_ValueDependentIsNull)) {
3091     ConvertedType = ToType;
3092     return true;
3093   }
3094 
3095   // Otherwise, both types have to be member pointers.
3096   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3097   if (!FromTypePtr)
3098     return false;
3099 
3100   // A pointer to member of B can be converted to a pointer to member of D,
3101   // where D is derived from B (C++ 4.11p2).
3102   QualType FromClass(FromTypePtr->getClass(), 0);
3103   QualType ToClass(ToTypePtr->getClass(), 0);
3104 
3105   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3106       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3107     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3108                                                  ToClass.getTypePtr());
3109     return true;
3110   }
3111 
3112   return false;
3113 }
3114 
3115 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3116 /// expression From to the type ToType. This routine checks for ambiguous or
3117 /// virtual or inaccessible base-to-derived member pointer conversions
3118 /// for which IsMemberPointerConversion has already returned true. It returns
3119 /// true and produces a diagnostic if there was an error, or returns false
3120 /// otherwise.
3121 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3122                                         CastKind &Kind,
3123                                         CXXCastPath &BasePath,
3124                                         bool IgnoreBaseAccess) {
3125   QualType FromType = From->getType();
3126   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3127   if (!FromPtrType) {
3128     // This must be a null pointer to member pointer conversion
3129     assert(From->isNullPointerConstant(Context,
3130                                        Expr::NPC_ValueDependentIsNull) &&
3131            "Expr must be null pointer constant!");
3132     Kind = CK_NullToMemberPointer;
3133     return false;
3134   }
3135 
3136   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3137   assert(ToPtrType && "No member pointer cast has a target type "
3138                       "that is not a member pointer.");
3139 
3140   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3141   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3142 
3143   // FIXME: What about dependent types?
3144   assert(FromClass->isRecordType() && "Pointer into non-class.");
3145   assert(ToClass->isRecordType() && "Pointer into non-class.");
3146 
3147   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3148                      /*DetectVirtual=*/true);
3149   bool DerivationOkay =
3150       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3151   assert(DerivationOkay &&
3152          "Should not have been called if derivation isn't OK.");
3153   (void)DerivationOkay;
3154 
3155   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3156                                   getUnqualifiedType())) {
3157     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3158     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3159       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3160     return true;
3161   }
3162 
3163   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3164     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3165       << FromClass << ToClass << QualType(VBase, 0)
3166       << From->getSourceRange();
3167     return true;
3168   }
3169 
3170   if (!IgnoreBaseAccess)
3171     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3172                          Paths.front(),
3173                          diag::err_downcast_from_inaccessible_base);
3174 
3175   // Must be a base to derived member conversion.
3176   BuildBasePathArray(Paths, BasePath);
3177   Kind = CK_BaseToDerivedMemberPointer;
3178   return false;
3179 }
3180 
3181 /// Determine whether the lifetime conversion between the two given
3182 /// qualifiers sets is nontrivial.
3183 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3184                                                Qualifiers ToQuals) {
3185   // Converting anything to const __unsafe_unretained is trivial.
3186   if (ToQuals.hasConst() &&
3187       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3188     return false;
3189 
3190   return true;
3191 }
3192 
3193 /// Perform a single iteration of the loop for checking if a qualification
3194 /// conversion is valid.
3195 ///
3196 /// Specifically, check whether any change between the qualifiers of \p
3197 /// FromType and \p ToType is permissible, given knowledge about whether every
3198 /// outer layer is const-qualified.
3199 static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3200                                           bool CStyle, bool IsTopLevel,
3201                                           bool &PreviousToQualsIncludeConst,
3202                                           bool &ObjCLifetimeConversion) {
3203   Qualifiers FromQuals = FromType.getQualifiers();
3204   Qualifiers ToQuals = ToType.getQualifiers();
3205 
3206   // Ignore __unaligned qualifier.
3207   FromQuals.removeUnaligned();
3208 
3209   // Objective-C ARC:
3210   //   Check Objective-C lifetime conversions.
3211   if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3212     if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3213       if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3214         ObjCLifetimeConversion = true;
3215       FromQuals.removeObjCLifetime();
3216       ToQuals.removeObjCLifetime();
3217     } else {
3218       // Qualification conversions cannot cast between different
3219       // Objective-C lifetime qualifiers.
3220       return false;
3221     }
3222   }
3223 
3224   // Allow addition/removal of GC attributes but not changing GC attributes.
3225   if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3226       (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3227     FromQuals.removeObjCGCAttr();
3228     ToQuals.removeObjCGCAttr();
3229   }
3230 
3231   //   -- for every j > 0, if const is in cv 1,j then const is in cv
3232   //      2,j, and similarly for volatile.
3233   if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3234     return false;
3235 
3236   // If address spaces mismatch:
3237   //  - in top level it is only valid to convert to addr space that is a
3238   //    superset in all cases apart from C-style casts where we allow
3239   //    conversions between overlapping address spaces.
3240   //  - in non-top levels it is not a valid conversion.
3241   if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3242       (!IsTopLevel ||
3243        !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3244          (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3245     return false;
3246 
3247   //   -- if the cv 1,j and cv 2,j are different, then const is in
3248   //      every cv for 0 < k < j.
3249   if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3250       !PreviousToQualsIncludeConst)
3251     return false;
3252 
3253   // The following wording is from C++20, where the result of the conversion
3254   // is T3, not T2.
3255   //   -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3256   //      "array of unknown bound of"
3257   if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3258     return false;
3259 
3260   //   -- if the resulting P3,i is different from P1,i [...], then const is
3261   //      added to every cv 3_k for 0 < k < i.
3262   if (!CStyle && FromType->isConstantArrayType() &&
3263       ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3264     return false;
3265 
3266   // Keep track of whether all prior cv-qualifiers in the "to" type
3267   // include const.
3268   PreviousToQualsIncludeConst =
3269       PreviousToQualsIncludeConst && ToQuals.hasConst();
3270   return true;
3271 }
3272 
3273 /// IsQualificationConversion - Determines whether the conversion from
3274 /// an rvalue of type FromType to ToType is a qualification conversion
3275 /// (C++ 4.4).
3276 ///
3277 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3278 /// when the qualification conversion involves a change in the Objective-C
3279 /// object lifetime.
3280 bool
3281 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3282                                 bool CStyle, bool &ObjCLifetimeConversion) {
3283   FromType = Context.getCanonicalType(FromType);
3284   ToType = Context.getCanonicalType(ToType);
3285   ObjCLifetimeConversion = false;
3286 
3287   // If FromType and ToType are the same type, this is not a
3288   // qualification conversion.
3289   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3290     return false;
3291 
3292   // (C++ 4.4p4):
3293   //   A conversion can add cv-qualifiers at levels other than the first
3294   //   in multi-level pointers, subject to the following rules: [...]
3295   bool PreviousToQualsIncludeConst = true;
3296   bool UnwrappedAnyPointer = false;
3297   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3298     if (!isQualificationConversionStep(
3299             FromType, ToType, CStyle, !UnwrappedAnyPointer,
3300             PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3301       return false;
3302     UnwrappedAnyPointer = true;
3303   }
3304 
3305   // We are left with FromType and ToType being the pointee types
3306   // after unwrapping the original FromType and ToType the same number
3307   // of times. If we unwrapped any pointers, and if FromType and
3308   // ToType have the same unqualified type (since we checked
3309   // qualifiers above), then this is a qualification conversion.
3310   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3311 }
3312 
3313 /// - Determine whether this is a conversion from a scalar type to an
3314 /// atomic type.
3315 ///
3316 /// If successful, updates \c SCS's second and third steps in the conversion
3317 /// sequence to finish the conversion.
3318 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3319                                 bool InOverloadResolution,
3320                                 StandardConversionSequence &SCS,
3321                                 bool CStyle) {
3322   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3323   if (!ToAtomic)
3324     return false;
3325 
3326   StandardConversionSequence InnerSCS;
3327   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3328                             InOverloadResolution, InnerSCS,
3329                             CStyle, /*AllowObjCWritebackConversion=*/false))
3330     return false;
3331 
3332   SCS.Second = InnerSCS.Second;
3333   SCS.setToType(1, InnerSCS.getToType(1));
3334   SCS.Third = InnerSCS.Third;
3335   SCS.QualificationIncludesObjCLifetime
3336     = InnerSCS.QualificationIncludesObjCLifetime;
3337   SCS.setToType(2, InnerSCS.getToType(2));
3338   return true;
3339 }
3340 
3341 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3342                                               CXXConstructorDecl *Constructor,
3343                                               QualType Type) {
3344   const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3345   if (CtorType->getNumParams() > 0) {
3346     QualType FirstArg = CtorType->getParamType(0);
3347     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3348       return true;
3349   }
3350   return false;
3351 }
3352 
3353 static OverloadingResult
3354 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3355                                        CXXRecordDecl *To,
3356                                        UserDefinedConversionSequence &User,
3357                                        OverloadCandidateSet &CandidateSet,
3358                                        bool AllowExplicit) {
3359   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3360   for (auto *D : S.LookupConstructors(To)) {
3361     auto Info = getConstructorInfo(D);
3362     if (!Info)
3363       continue;
3364 
3365     bool Usable = !Info.Constructor->isInvalidDecl() &&
3366                   S.isInitListConstructor(Info.Constructor);
3367     if (Usable) {
3368       bool SuppressUserConversions = false;
3369       if (Info.ConstructorTmpl)
3370         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3371                                        /*ExplicitArgs*/ nullptr, From,
3372                                        CandidateSet, SuppressUserConversions,
3373                                        /*PartialOverloading*/ false,
3374                                        AllowExplicit);
3375       else
3376         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3377                                CandidateSet, SuppressUserConversions,
3378                                /*PartialOverloading*/ false, AllowExplicit);
3379     }
3380   }
3381 
3382   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3383 
3384   OverloadCandidateSet::iterator Best;
3385   switch (auto Result =
3386               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3387   case OR_Deleted:
3388   case OR_Success: {
3389     // Record the standard conversion we used and the conversion function.
3390     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3391     QualType ThisType = Constructor->getThisType();
3392     // Initializer lists don't have conversions as such.
3393     User.Before.setAsIdentityConversion();
3394     User.HadMultipleCandidates = HadMultipleCandidates;
3395     User.ConversionFunction = Constructor;
3396     User.FoundConversionFunction = Best->FoundDecl;
3397     User.After.setAsIdentityConversion();
3398     User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3399     User.After.setAllToTypes(ToType);
3400     return Result;
3401   }
3402 
3403   case OR_No_Viable_Function:
3404     return OR_No_Viable_Function;
3405   case OR_Ambiguous:
3406     return OR_Ambiguous;
3407   }
3408 
3409   llvm_unreachable("Invalid OverloadResult!");
3410 }
3411 
3412 /// Determines whether there is a user-defined conversion sequence
3413 /// (C++ [over.ics.user]) that converts expression From to the type
3414 /// ToType. If such a conversion exists, User will contain the
3415 /// user-defined conversion sequence that performs such a conversion
3416 /// and this routine will return true. Otherwise, this routine returns
3417 /// false and User is unspecified.
3418 ///
3419 /// \param AllowExplicit  true if the conversion should consider C++0x
3420 /// "explicit" conversion functions as well as non-explicit conversion
3421 /// functions (C++0x [class.conv.fct]p2).
3422 ///
3423 /// \param AllowObjCConversionOnExplicit true if the conversion should
3424 /// allow an extra Objective-C pointer conversion on uses of explicit
3425 /// constructors. Requires \c AllowExplicit to also be set.
3426 static OverloadingResult
3427 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3428                         UserDefinedConversionSequence &User,
3429                         OverloadCandidateSet &CandidateSet,
3430                         AllowedExplicit AllowExplicit,
3431                         bool AllowObjCConversionOnExplicit) {
3432   assert(AllowExplicit != AllowedExplicit::None ||
3433          !AllowObjCConversionOnExplicit);
3434   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3435 
3436   // Whether we will only visit constructors.
3437   bool ConstructorsOnly = false;
3438 
3439   // If the type we are conversion to is a class type, enumerate its
3440   // constructors.
3441   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3442     // C++ [over.match.ctor]p1:
3443     //   When objects of class type are direct-initialized (8.5), or
3444     //   copy-initialized from an expression of the same or a
3445     //   derived class type (8.5), overload resolution selects the
3446     //   constructor. [...] For copy-initialization, the candidate
3447     //   functions are all the converting constructors (12.3.1) of
3448     //   that class. The argument list is the expression-list within
3449     //   the parentheses of the initializer.
3450     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3451         (From->getType()->getAs<RecordType>() &&
3452          S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3453       ConstructorsOnly = true;
3454 
3455     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3456       // We're not going to find any constructors.
3457     } else if (CXXRecordDecl *ToRecordDecl
3458                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3459 
3460       Expr **Args = &From;
3461       unsigned NumArgs = 1;
3462       bool ListInitializing = false;
3463       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3464         // But first, see if there is an init-list-constructor that will work.
3465         OverloadingResult Result = IsInitializerListConstructorConversion(
3466             S, From, ToType, ToRecordDecl, User, CandidateSet,
3467             AllowExplicit == AllowedExplicit::All);
3468         if (Result != OR_No_Viable_Function)
3469           return Result;
3470         // Never mind.
3471         CandidateSet.clear(
3472             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3473 
3474         // If we're list-initializing, we pass the individual elements as
3475         // arguments, not the entire list.
3476         Args = InitList->getInits();
3477         NumArgs = InitList->getNumInits();
3478         ListInitializing = true;
3479       }
3480 
3481       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3482         auto Info = getConstructorInfo(D);
3483         if (!Info)
3484           continue;
3485 
3486         bool Usable = !Info.Constructor->isInvalidDecl();
3487         if (!ListInitializing)
3488           Usable = Usable && Info.Constructor->isConvertingConstructor(
3489                                  /*AllowExplicit*/ true);
3490         if (Usable) {
3491           bool SuppressUserConversions = !ConstructorsOnly;
3492           // C++20 [over.best.ics.general]/4.5:
3493           //   if the target is the first parameter of a constructor [of class
3494           //   X] and the constructor [...] is a candidate by [...] the second
3495           //   phase of [over.match.list] when the initializer list has exactly
3496           //   one element that is itself an initializer list, [...] and the
3497           //   conversion is to X or reference to cv X, user-defined conversion
3498           //   sequences are not cnosidered.
3499           if (SuppressUserConversions && ListInitializing) {
3500             SuppressUserConversions =
3501                 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
3502                 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3503                                                   ToType);
3504           }
3505           if (Info.ConstructorTmpl)
3506             S.AddTemplateOverloadCandidate(
3507                 Info.ConstructorTmpl, Info.FoundDecl,
3508                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3509                 CandidateSet, SuppressUserConversions,
3510                 /*PartialOverloading*/ false,
3511                 AllowExplicit == AllowedExplicit::All);
3512           else
3513             // Allow one user-defined conversion when user specifies a
3514             // From->ToType conversion via an static cast (c-style, etc).
3515             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3516                                    llvm::makeArrayRef(Args, NumArgs),
3517                                    CandidateSet, SuppressUserConversions,
3518                                    /*PartialOverloading*/ false,
3519                                    AllowExplicit == AllowedExplicit::All);
3520         }
3521       }
3522     }
3523   }
3524 
3525   // Enumerate conversion functions, if we're allowed to.
3526   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3527   } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3528     // No conversion functions from incomplete types.
3529   } else if (const RecordType *FromRecordType =
3530                  From->getType()->getAs<RecordType>()) {
3531     if (CXXRecordDecl *FromRecordDecl
3532          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3533       // Add all of the conversion functions as candidates.
3534       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3535       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3536         DeclAccessPair FoundDecl = I.getPair();
3537         NamedDecl *D = FoundDecl.getDecl();
3538         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3539         if (isa<UsingShadowDecl>(D))
3540           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3541 
3542         CXXConversionDecl *Conv;
3543         FunctionTemplateDecl *ConvTemplate;
3544         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3545           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3546         else
3547           Conv = cast<CXXConversionDecl>(D);
3548 
3549         if (ConvTemplate)
3550           S.AddTemplateConversionCandidate(
3551               ConvTemplate, FoundDecl, ActingContext, From, ToType,
3552               CandidateSet, AllowObjCConversionOnExplicit,
3553               AllowExplicit != AllowedExplicit::None);
3554         else
3555           S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3556                                    CandidateSet, AllowObjCConversionOnExplicit,
3557                                    AllowExplicit != AllowedExplicit::None);
3558       }
3559     }
3560   }
3561 
3562   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3563 
3564   OverloadCandidateSet::iterator Best;
3565   switch (auto Result =
3566               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3567   case OR_Success:
3568   case OR_Deleted:
3569     // Record the standard conversion we used and the conversion function.
3570     if (CXXConstructorDecl *Constructor
3571           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3572       // C++ [over.ics.user]p1:
3573       //   If the user-defined conversion is specified by a
3574       //   constructor (12.3.1), the initial standard conversion
3575       //   sequence converts the source type to the type required by
3576       //   the argument of the constructor.
3577       //
3578       QualType ThisType = Constructor->getThisType();
3579       if (isa<InitListExpr>(From)) {
3580         // Initializer lists don't have conversions as such.
3581         User.Before.setAsIdentityConversion();
3582       } else {
3583         if (Best->Conversions[0].isEllipsis())
3584           User.EllipsisConversion = true;
3585         else {
3586           User.Before = Best->Conversions[0].Standard;
3587           User.EllipsisConversion = false;
3588         }
3589       }
3590       User.HadMultipleCandidates = HadMultipleCandidates;
3591       User.ConversionFunction = Constructor;
3592       User.FoundConversionFunction = Best->FoundDecl;
3593       User.After.setAsIdentityConversion();
3594       User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3595       User.After.setAllToTypes(ToType);
3596       return Result;
3597     }
3598     if (CXXConversionDecl *Conversion
3599                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3600       // C++ [over.ics.user]p1:
3601       //
3602       //   [...] If the user-defined conversion is specified by a
3603       //   conversion function (12.3.2), the initial standard
3604       //   conversion sequence converts the source type to the
3605       //   implicit object parameter of the conversion function.
3606       User.Before = Best->Conversions[0].Standard;
3607       User.HadMultipleCandidates = HadMultipleCandidates;
3608       User.ConversionFunction = Conversion;
3609       User.FoundConversionFunction = Best->FoundDecl;
3610       User.EllipsisConversion = false;
3611 
3612       // C++ [over.ics.user]p2:
3613       //   The second standard conversion sequence converts the
3614       //   result of the user-defined conversion to the target type
3615       //   for the sequence. Since an implicit conversion sequence
3616       //   is an initialization, the special rules for
3617       //   initialization by user-defined conversion apply when
3618       //   selecting the best user-defined conversion for a
3619       //   user-defined conversion sequence (see 13.3.3 and
3620       //   13.3.3.1).
3621       User.After = Best->FinalConversion;
3622       return Result;
3623     }
3624     llvm_unreachable("Not a constructor or conversion function?");
3625 
3626   case OR_No_Viable_Function:
3627     return OR_No_Viable_Function;
3628 
3629   case OR_Ambiguous:
3630     return OR_Ambiguous;
3631   }
3632 
3633   llvm_unreachable("Invalid OverloadResult!");
3634 }
3635 
3636 bool
3637 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3638   ImplicitConversionSequence ICS;
3639   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3640                                     OverloadCandidateSet::CSK_Normal);
3641   OverloadingResult OvResult =
3642     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3643                             CandidateSet, AllowedExplicit::None, false);
3644 
3645   if (!(OvResult == OR_Ambiguous ||
3646         (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3647     return false;
3648 
3649   auto Cands = CandidateSet.CompleteCandidates(
3650       *this,
3651       OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3652       From);
3653   if (OvResult == OR_Ambiguous)
3654     Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3655         << From->getType() << ToType << From->getSourceRange();
3656   else { // OR_No_Viable_Function && !CandidateSet.empty()
3657     if (!RequireCompleteType(From->getBeginLoc(), ToType,
3658                              diag::err_typecheck_nonviable_condition_incomplete,
3659                              From->getType(), From->getSourceRange()))
3660       Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3661           << false << From->getType() << From->getSourceRange() << ToType;
3662   }
3663 
3664   CandidateSet.NoteCandidates(
3665                               *this, From, Cands);
3666   return true;
3667 }
3668 
3669 // Helper for compareConversionFunctions that gets the FunctionType that the
3670 // conversion-operator return  value 'points' to, or nullptr.
3671 static const FunctionType *
3672 getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
3673   const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
3674   const PointerType *RetPtrTy =
3675       ConvFuncTy->getReturnType()->getAs<PointerType>();
3676 
3677   if (!RetPtrTy)
3678     return nullptr;
3679 
3680   return RetPtrTy->getPointeeType()->getAs<FunctionType>();
3681 }
3682 
3683 /// Compare the user-defined conversion functions or constructors
3684 /// of two user-defined conversion sequences to determine whether any ordering
3685 /// is possible.
3686 static ImplicitConversionSequence::CompareKind
3687 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3688                            FunctionDecl *Function2) {
3689   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3690   CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
3691   if (!Conv1 || !Conv2)
3692     return ImplicitConversionSequence::Indistinguishable;
3693 
3694   if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
3695     return ImplicitConversionSequence::Indistinguishable;
3696 
3697   // Objective-C++:
3698   //   If both conversion functions are implicitly-declared conversions from
3699   //   a lambda closure type to a function pointer and a block pointer,
3700   //   respectively, always prefer the conversion to a function pointer,
3701   //   because the function pointer is more lightweight and is more likely
3702   //   to keep code working.
3703   if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
3704     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3705     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3706     if (Block1 != Block2)
3707       return Block1 ? ImplicitConversionSequence::Worse
3708                     : ImplicitConversionSequence::Better;
3709   }
3710 
3711   // In order to support multiple calling conventions for the lambda conversion
3712   // operator (such as when the free and member function calling convention is
3713   // different), prefer the 'free' mechanism, followed by the calling-convention
3714   // of operator(). The latter is in place to support the MSVC-like solution of
3715   // defining ALL of the possible conversions in regards to calling-convention.
3716   const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
3717   const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
3718 
3719   if (Conv1FuncRet && Conv2FuncRet &&
3720       Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
3721     CallingConv Conv1CC = Conv1FuncRet->getCallConv();
3722     CallingConv Conv2CC = Conv2FuncRet->getCallConv();
3723 
3724     CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
3725     const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
3726 
3727     CallingConv CallOpCC =
3728         CallOp->getType()->castAs<FunctionType>()->getCallConv();
3729     CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
3730         CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
3731     CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
3732         CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
3733 
3734     CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
3735     for (CallingConv CC : PrefOrder) {
3736       if (Conv1CC == CC)
3737         return ImplicitConversionSequence::Better;
3738       if (Conv2CC == CC)
3739         return ImplicitConversionSequence::Worse;
3740     }
3741   }
3742 
3743   return ImplicitConversionSequence::Indistinguishable;
3744 }
3745 
3746 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3747     const ImplicitConversionSequence &ICS) {
3748   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3749          (ICS.isUserDefined() &&
3750           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3751 }
3752 
3753 /// CompareImplicitConversionSequences - Compare two implicit
3754 /// conversion sequences to determine whether one is better than the
3755 /// other or if they are indistinguishable (C++ 13.3.3.2).
3756 static ImplicitConversionSequence::CompareKind
3757 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3758                                    const ImplicitConversionSequence& ICS1,
3759                                    const ImplicitConversionSequence& ICS2)
3760 {
3761   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3762   // conversion sequences (as defined in 13.3.3.1)
3763   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3764   //      conversion sequence than a user-defined conversion sequence or
3765   //      an ellipsis conversion sequence, and
3766   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3767   //      conversion sequence than an ellipsis conversion sequence
3768   //      (13.3.3.1.3).
3769   //
3770   // C++0x [over.best.ics]p10:
3771   //   For the purpose of ranking implicit conversion sequences as
3772   //   described in 13.3.3.2, the ambiguous conversion sequence is
3773   //   treated as a user-defined sequence that is indistinguishable
3774   //   from any other user-defined conversion sequence.
3775 
3776   // String literal to 'char *' conversion has been deprecated in C++03. It has
3777   // been removed from C++11. We still accept this conversion, if it happens at
3778   // the best viable function. Otherwise, this conversion is considered worse
3779   // than ellipsis conversion. Consider this as an extension; this is not in the
3780   // standard. For example:
3781   //
3782   // int &f(...);    // #1
3783   // void f(char*);  // #2
3784   // void g() { int &r = f("foo"); }
3785   //
3786   // In C++03, we pick #2 as the best viable function.
3787   // In C++11, we pick #1 as the best viable function, because ellipsis
3788   // conversion is better than string-literal to char* conversion (since there
3789   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3790   // convert arguments, #2 would be the best viable function in C++11.
3791   // If the best viable function has this conversion, a warning will be issued
3792   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3793 
3794   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3795       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3796           hasDeprecatedStringLiteralToCharPtrConversion(ICS2) &&
3797       // Ill-formedness must not differ
3798       ICS1.isBad() == ICS2.isBad())
3799     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3800                ? ImplicitConversionSequence::Worse
3801                : ImplicitConversionSequence::Better;
3802 
3803   if (ICS1.getKindRank() < ICS2.getKindRank())
3804     return ImplicitConversionSequence::Better;
3805   if (ICS2.getKindRank() < ICS1.getKindRank())
3806     return ImplicitConversionSequence::Worse;
3807 
3808   // The following checks require both conversion sequences to be of
3809   // the same kind.
3810   if (ICS1.getKind() != ICS2.getKind())
3811     return ImplicitConversionSequence::Indistinguishable;
3812 
3813   ImplicitConversionSequence::CompareKind Result =
3814       ImplicitConversionSequence::Indistinguishable;
3815 
3816   // Two implicit conversion sequences of the same form are
3817   // indistinguishable conversion sequences unless one of the
3818   // following rules apply: (C++ 13.3.3.2p3):
3819 
3820   // List-initialization sequence L1 is a better conversion sequence than
3821   // list-initialization sequence L2 if:
3822   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3823   //   if not that,
3824   // — L1 and L2 convert to arrays of the same element type, and either the
3825   //   number of elements n_1 initialized by L1 is less than the number of
3826   //   elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
3827   //   an array of unknown bound and L1 does not,
3828   // even if one of the other rules in this paragraph would otherwise apply.
3829   if (!ICS1.isBad()) {
3830     bool StdInit1 = false, StdInit2 = false;
3831     if (ICS1.hasInitializerListContainerType())
3832       StdInit1 = S.isStdInitializerList(ICS1.getInitializerListContainerType(),
3833                                         nullptr);
3834     if (ICS2.hasInitializerListContainerType())
3835       StdInit2 = S.isStdInitializerList(ICS2.getInitializerListContainerType(),
3836                                         nullptr);
3837     if (StdInit1 != StdInit2)
3838       return StdInit1 ? ImplicitConversionSequence::Better
3839                       : ImplicitConversionSequence::Worse;
3840 
3841     if (ICS1.hasInitializerListContainerType() &&
3842         ICS2.hasInitializerListContainerType())
3843       if (auto *CAT1 = S.Context.getAsConstantArrayType(
3844               ICS1.getInitializerListContainerType()))
3845         if (auto *CAT2 = S.Context.getAsConstantArrayType(
3846                 ICS2.getInitializerListContainerType())) {
3847           if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
3848                                                CAT2->getElementType())) {
3849             // Both to arrays of the same element type
3850             if (CAT1->getSize() != CAT2->getSize())
3851               // Different sized, the smaller wins
3852               return CAT1->getSize().ult(CAT2->getSize())
3853                          ? ImplicitConversionSequence::Better
3854                          : ImplicitConversionSequence::Worse;
3855             if (ICS1.isInitializerListOfIncompleteArray() !=
3856                 ICS2.isInitializerListOfIncompleteArray())
3857               // One is incomplete, it loses
3858               return ICS2.isInitializerListOfIncompleteArray()
3859                          ? ImplicitConversionSequence::Better
3860                          : ImplicitConversionSequence::Worse;
3861           }
3862         }
3863   }
3864 
3865   if (ICS1.isStandard())
3866     // Standard conversion sequence S1 is a better conversion sequence than
3867     // standard conversion sequence S2 if [...]
3868     Result = CompareStandardConversionSequences(S, Loc,
3869                                                 ICS1.Standard, ICS2.Standard);
3870   else if (ICS1.isUserDefined()) {
3871     // User-defined conversion sequence U1 is a better conversion
3872     // sequence than another user-defined conversion sequence U2 if
3873     // they contain the same user-defined conversion function or
3874     // constructor and if the second standard conversion sequence of
3875     // U1 is better than the second standard conversion sequence of
3876     // U2 (C++ 13.3.3.2p3).
3877     if (ICS1.UserDefined.ConversionFunction ==
3878           ICS2.UserDefined.ConversionFunction)
3879       Result = CompareStandardConversionSequences(S, Loc,
3880                                                   ICS1.UserDefined.After,
3881                                                   ICS2.UserDefined.After);
3882     else
3883       Result = compareConversionFunctions(S,
3884                                           ICS1.UserDefined.ConversionFunction,
3885                                           ICS2.UserDefined.ConversionFunction);
3886   }
3887 
3888   return Result;
3889 }
3890 
3891 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3892 // determine if one is a proper subset of the other.
3893 static ImplicitConversionSequence::CompareKind
3894 compareStandardConversionSubsets(ASTContext &Context,
3895                                  const StandardConversionSequence& SCS1,
3896                                  const StandardConversionSequence& SCS2) {
3897   ImplicitConversionSequence::CompareKind Result
3898     = ImplicitConversionSequence::Indistinguishable;
3899 
3900   // the identity conversion sequence is considered to be a subsequence of
3901   // any non-identity conversion sequence
3902   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3903     return ImplicitConversionSequence::Better;
3904   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3905     return ImplicitConversionSequence::Worse;
3906 
3907   if (SCS1.Second != SCS2.Second) {
3908     if (SCS1.Second == ICK_Identity)
3909       Result = ImplicitConversionSequence::Better;
3910     else if (SCS2.Second == ICK_Identity)
3911       Result = ImplicitConversionSequence::Worse;
3912     else
3913       return ImplicitConversionSequence::Indistinguishable;
3914   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3915     return ImplicitConversionSequence::Indistinguishable;
3916 
3917   if (SCS1.Third == SCS2.Third) {
3918     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3919                              : ImplicitConversionSequence::Indistinguishable;
3920   }
3921 
3922   if (SCS1.Third == ICK_Identity)
3923     return Result == ImplicitConversionSequence::Worse
3924              ? ImplicitConversionSequence::Indistinguishable
3925              : ImplicitConversionSequence::Better;
3926 
3927   if (SCS2.Third == ICK_Identity)
3928     return Result == ImplicitConversionSequence::Better
3929              ? ImplicitConversionSequence::Indistinguishable
3930              : ImplicitConversionSequence::Worse;
3931 
3932   return ImplicitConversionSequence::Indistinguishable;
3933 }
3934 
3935 /// Determine whether one of the given reference bindings is better
3936 /// than the other based on what kind of bindings they are.
3937 static bool
3938 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3939                              const StandardConversionSequence &SCS2) {
3940   // C++0x [over.ics.rank]p3b4:
3941   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3942   //      implicit object parameter of a non-static member function declared
3943   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3944   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3945   //      lvalue reference to a function lvalue and S2 binds an rvalue
3946   //      reference*.
3947   //
3948   // FIXME: Rvalue references. We're going rogue with the above edits,
3949   // because the semantics in the current C++0x working paper (N3225 at the
3950   // time of this writing) break the standard definition of std::forward
3951   // and std::reference_wrapper when dealing with references to functions.
3952   // Proposed wording changes submitted to CWG for consideration.
3953   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3954       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3955     return false;
3956 
3957   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3958           SCS2.IsLvalueReference) ||
3959          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3960           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3961 }
3962 
3963 enum class FixedEnumPromotion {
3964   None,
3965   ToUnderlyingType,
3966   ToPromotedUnderlyingType
3967 };
3968 
3969 /// Returns kind of fixed enum promotion the \a SCS uses.
3970 static FixedEnumPromotion
3971 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
3972 
3973   if (SCS.Second != ICK_Integral_Promotion)
3974     return FixedEnumPromotion::None;
3975 
3976   QualType FromType = SCS.getFromType();
3977   if (!FromType->isEnumeralType())
3978     return FixedEnumPromotion::None;
3979 
3980   EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
3981   if (!Enum->isFixed())
3982     return FixedEnumPromotion::None;
3983 
3984   QualType UnderlyingType = Enum->getIntegerType();
3985   if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
3986     return FixedEnumPromotion::ToUnderlyingType;
3987 
3988   return FixedEnumPromotion::ToPromotedUnderlyingType;
3989 }
3990 
3991 /// CompareStandardConversionSequences - Compare two standard
3992 /// conversion sequences to determine whether one is better than the
3993 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3994 static ImplicitConversionSequence::CompareKind
3995 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3996                                    const StandardConversionSequence& SCS1,
3997                                    const StandardConversionSequence& SCS2)
3998 {
3999   // Standard conversion sequence S1 is a better conversion sequence
4000   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4001 
4002   //  -- S1 is a proper subsequence of S2 (comparing the conversion
4003   //     sequences in the canonical form defined by 13.3.3.1.1,
4004   //     excluding any Lvalue Transformation; the identity conversion
4005   //     sequence is considered to be a subsequence of any
4006   //     non-identity conversion sequence) or, if not that,
4007   if (ImplicitConversionSequence::CompareKind CK
4008         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
4009     return CK;
4010 
4011   //  -- the rank of S1 is better than the rank of S2 (by the rules
4012   //     defined below), or, if not that,
4013   ImplicitConversionRank Rank1 = SCS1.getRank();
4014   ImplicitConversionRank Rank2 = SCS2.getRank();
4015   if (Rank1 < Rank2)
4016     return ImplicitConversionSequence::Better;
4017   else if (Rank2 < Rank1)
4018     return ImplicitConversionSequence::Worse;
4019 
4020   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4021   // are indistinguishable unless one of the following rules
4022   // applies:
4023 
4024   //   A conversion that is not a conversion of a pointer, or
4025   //   pointer to member, to bool is better than another conversion
4026   //   that is such a conversion.
4027   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4028     return SCS2.isPointerConversionToBool()
4029              ? ImplicitConversionSequence::Better
4030              : ImplicitConversionSequence::Worse;
4031 
4032   // C++14 [over.ics.rank]p4b2:
4033   // This is retroactively applied to C++11 by CWG 1601.
4034   //
4035   //   A conversion that promotes an enumeration whose underlying type is fixed
4036   //   to its underlying type is better than one that promotes to the promoted
4037   //   underlying type, if the two are different.
4038   FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
4039   FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
4040   if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4041       FEP1 != FEP2)
4042     return FEP1 == FixedEnumPromotion::ToUnderlyingType
4043                ? ImplicitConversionSequence::Better
4044                : ImplicitConversionSequence::Worse;
4045 
4046   // C++ [over.ics.rank]p4b2:
4047   //
4048   //   If class B is derived directly or indirectly from class A,
4049   //   conversion of B* to A* is better than conversion of B* to
4050   //   void*, and conversion of A* to void* is better than conversion
4051   //   of B* to void*.
4052   bool SCS1ConvertsToVoid
4053     = SCS1.isPointerConversionToVoidPointer(S.Context);
4054   bool SCS2ConvertsToVoid
4055     = SCS2.isPointerConversionToVoidPointer(S.Context);
4056   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4057     // Exactly one of the conversion sequences is a conversion to
4058     // a void pointer; it's the worse conversion.
4059     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4060                               : ImplicitConversionSequence::Worse;
4061   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4062     // Neither conversion sequence converts to a void pointer; compare
4063     // their derived-to-base conversions.
4064     if (ImplicitConversionSequence::CompareKind DerivedCK
4065           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4066       return DerivedCK;
4067   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4068              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4069     // Both conversion sequences are conversions to void
4070     // pointers. Compare the source types to determine if there's an
4071     // inheritance relationship in their sources.
4072     QualType FromType1 = SCS1.getFromType();
4073     QualType FromType2 = SCS2.getFromType();
4074 
4075     // Adjust the types we're converting from via the array-to-pointer
4076     // conversion, if we need to.
4077     if (SCS1.First == ICK_Array_To_Pointer)
4078       FromType1 = S.Context.getArrayDecayedType(FromType1);
4079     if (SCS2.First == ICK_Array_To_Pointer)
4080       FromType2 = S.Context.getArrayDecayedType(FromType2);
4081 
4082     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4083     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4084 
4085     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4086       return ImplicitConversionSequence::Better;
4087     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4088       return ImplicitConversionSequence::Worse;
4089 
4090     // Objective-C++: If one interface is more specific than the
4091     // other, it is the better one.
4092     const ObjCObjectPointerType* FromObjCPtr1
4093       = FromType1->getAs<ObjCObjectPointerType>();
4094     const ObjCObjectPointerType* FromObjCPtr2
4095       = FromType2->getAs<ObjCObjectPointerType>();
4096     if (FromObjCPtr1 && FromObjCPtr2) {
4097       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4098                                                           FromObjCPtr2);
4099       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4100                                                            FromObjCPtr1);
4101       if (AssignLeft != AssignRight) {
4102         return AssignLeft? ImplicitConversionSequence::Better
4103                          : ImplicitConversionSequence::Worse;
4104       }
4105     }
4106   }
4107 
4108   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4109     // Check for a better reference binding based on the kind of bindings.
4110     if (isBetterReferenceBindingKind(SCS1, SCS2))
4111       return ImplicitConversionSequence::Better;
4112     else if (isBetterReferenceBindingKind(SCS2, SCS1))
4113       return ImplicitConversionSequence::Worse;
4114   }
4115 
4116   // Compare based on qualification conversions (C++ 13.3.3.2p3,
4117   // bullet 3).
4118   if (ImplicitConversionSequence::CompareKind QualCK
4119         = CompareQualificationConversions(S, SCS1, SCS2))
4120     return QualCK;
4121 
4122   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4123     // C++ [over.ics.rank]p3b4:
4124     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
4125     //      which the references refer are the same type except for
4126     //      top-level cv-qualifiers, and the type to which the reference
4127     //      initialized by S2 refers is more cv-qualified than the type
4128     //      to which the reference initialized by S1 refers.
4129     QualType T1 = SCS1.getToType(2);
4130     QualType T2 = SCS2.getToType(2);
4131     T1 = S.Context.getCanonicalType(T1);
4132     T2 = S.Context.getCanonicalType(T2);
4133     Qualifiers T1Quals, T2Quals;
4134     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4135     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4136     if (UnqualT1 == UnqualT2) {
4137       // Objective-C++ ARC: If the references refer to objects with different
4138       // lifetimes, prefer bindings that don't change lifetime.
4139       if (SCS1.ObjCLifetimeConversionBinding !=
4140                                           SCS2.ObjCLifetimeConversionBinding) {
4141         return SCS1.ObjCLifetimeConversionBinding
4142                                            ? ImplicitConversionSequence::Worse
4143                                            : ImplicitConversionSequence::Better;
4144       }
4145 
4146       // If the type is an array type, promote the element qualifiers to the
4147       // type for comparison.
4148       if (isa<ArrayType>(T1) && T1Quals)
4149         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4150       if (isa<ArrayType>(T2) && T2Quals)
4151         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4152       if (T2.isMoreQualifiedThan(T1))
4153         return ImplicitConversionSequence::Better;
4154       if (T1.isMoreQualifiedThan(T2))
4155         return ImplicitConversionSequence::Worse;
4156     }
4157   }
4158 
4159   // In Microsoft mode (below 19.28), prefer an integral conversion to a
4160   // floating-to-integral conversion if the integral conversion
4161   // is between types of the same size.
4162   // For example:
4163   // void f(float);
4164   // void f(int);
4165   // int main {
4166   //    long a;
4167   //    f(a);
4168   // }
4169   // Here, MSVC will call f(int) instead of generating a compile error
4170   // as clang will do in standard mode.
4171   if (S.getLangOpts().MSVCCompat &&
4172       !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) &&
4173       SCS1.Second == ICK_Integral_Conversion &&
4174       SCS2.Second == ICK_Floating_Integral &&
4175       S.Context.getTypeSize(SCS1.getFromType()) ==
4176           S.Context.getTypeSize(SCS1.getToType(2)))
4177     return ImplicitConversionSequence::Better;
4178 
4179   // Prefer a compatible vector conversion over a lax vector conversion
4180   // For example:
4181   //
4182   // typedef float __v4sf __attribute__((__vector_size__(16)));
4183   // void f(vector float);
4184   // void f(vector signed int);
4185   // int main() {
4186   //   __v4sf a;
4187   //   f(a);
4188   // }
4189   // Here, we'd like to choose f(vector float) and not
4190   // report an ambiguous call error
4191   if (SCS1.Second == ICK_Vector_Conversion &&
4192       SCS2.Second == ICK_Vector_Conversion) {
4193     bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4194         SCS1.getFromType(), SCS1.getToType(2));
4195     bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4196         SCS2.getFromType(), SCS2.getToType(2));
4197 
4198     if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4199       return SCS1IsCompatibleVectorConversion
4200                  ? ImplicitConversionSequence::Better
4201                  : ImplicitConversionSequence::Worse;
4202   }
4203 
4204   if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4205       SCS2.Second == ICK_SVE_Vector_Conversion) {
4206     bool SCS1IsCompatibleSVEVectorConversion =
4207         S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4208     bool SCS2IsCompatibleSVEVectorConversion =
4209         S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4210 
4211     if (SCS1IsCompatibleSVEVectorConversion !=
4212         SCS2IsCompatibleSVEVectorConversion)
4213       return SCS1IsCompatibleSVEVectorConversion
4214                  ? ImplicitConversionSequence::Better
4215                  : ImplicitConversionSequence::Worse;
4216   }
4217 
4218   return ImplicitConversionSequence::Indistinguishable;
4219 }
4220 
4221 /// CompareQualificationConversions - Compares two standard conversion
4222 /// sequences to determine whether they can be ranked based on their
4223 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4224 static ImplicitConversionSequence::CompareKind
4225 CompareQualificationConversions(Sema &S,
4226                                 const StandardConversionSequence& SCS1,
4227                                 const StandardConversionSequence& SCS2) {
4228   // C++ [over.ics.rank]p3:
4229   //  -- S1 and S2 differ only in their qualification conversion and
4230   //     yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4231   // [C++98]
4232   //     [...] and the cv-qualification signature of type T1 is a proper subset
4233   //     of the cv-qualification signature of type T2, and S1 is not the
4234   //     deprecated string literal array-to-pointer conversion (4.2).
4235   // [C++2a]
4236   //     [...] where T1 can be converted to T2 by a qualification conversion.
4237   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4238       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4239     return ImplicitConversionSequence::Indistinguishable;
4240 
4241   // FIXME: the example in the standard doesn't use a qualification
4242   // conversion (!)
4243   QualType T1 = SCS1.getToType(2);
4244   QualType T2 = SCS2.getToType(2);
4245   T1 = S.Context.getCanonicalType(T1);
4246   T2 = S.Context.getCanonicalType(T2);
4247   assert(!T1->isReferenceType() && !T2->isReferenceType());
4248   Qualifiers T1Quals, T2Quals;
4249   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4250   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4251 
4252   // If the types are the same, we won't learn anything by unwrapping
4253   // them.
4254   if (UnqualT1 == UnqualT2)
4255     return ImplicitConversionSequence::Indistinguishable;
4256 
4257   // Don't ever prefer a standard conversion sequence that uses the deprecated
4258   // string literal array to pointer conversion.
4259   bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4260   bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4261 
4262   // Objective-C++ ARC:
4263   //   Prefer qualification conversions not involving a change in lifetime
4264   //   to qualification conversions that do change lifetime.
4265   if (SCS1.QualificationIncludesObjCLifetime &&
4266       !SCS2.QualificationIncludesObjCLifetime)
4267     CanPick1 = false;
4268   if (SCS2.QualificationIncludesObjCLifetime &&
4269       !SCS1.QualificationIncludesObjCLifetime)
4270     CanPick2 = false;
4271 
4272   bool ObjCLifetimeConversion;
4273   if (CanPick1 &&
4274       !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4275     CanPick1 = false;
4276   // FIXME: In Objective-C ARC, we can have qualification conversions in both
4277   // directions, so we can't short-cut this second check in general.
4278   if (CanPick2 &&
4279       !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4280     CanPick2 = false;
4281 
4282   if (CanPick1 != CanPick2)
4283     return CanPick1 ? ImplicitConversionSequence::Better
4284                     : ImplicitConversionSequence::Worse;
4285   return ImplicitConversionSequence::Indistinguishable;
4286 }
4287 
4288 /// CompareDerivedToBaseConversions - Compares two standard conversion
4289 /// sequences to determine whether they can be ranked based on their
4290 /// various kinds of derived-to-base conversions (C++
4291 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4292 /// conversions between Objective-C interface types.
4293 static ImplicitConversionSequence::CompareKind
4294 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4295                                 const StandardConversionSequence& SCS1,
4296                                 const StandardConversionSequence& SCS2) {
4297   QualType FromType1 = SCS1.getFromType();
4298   QualType ToType1 = SCS1.getToType(1);
4299   QualType FromType2 = SCS2.getFromType();
4300   QualType ToType2 = SCS2.getToType(1);
4301 
4302   // Adjust the types we're converting from via the array-to-pointer
4303   // conversion, if we need to.
4304   if (SCS1.First == ICK_Array_To_Pointer)
4305     FromType1 = S.Context.getArrayDecayedType(FromType1);
4306   if (SCS2.First == ICK_Array_To_Pointer)
4307     FromType2 = S.Context.getArrayDecayedType(FromType2);
4308 
4309   // Canonicalize all of the types.
4310   FromType1 = S.Context.getCanonicalType(FromType1);
4311   ToType1 = S.Context.getCanonicalType(ToType1);
4312   FromType2 = S.Context.getCanonicalType(FromType2);
4313   ToType2 = S.Context.getCanonicalType(ToType2);
4314 
4315   // C++ [over.ics.rank]p4b3:
4316   //
4317   //   If class B is derived directly or indirectly from class A and
4318   //   class C is derived directly or indirectly from B,
4319   //
4320   // Compare based on pointer conversions.
4321   if (SCS1.Second == ICK_Pointer_Conversion &&
4322       SCS2.Second == ICK_Pointer_Conversion &&
4323       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4324       FromType1->isPointerType() && FromType2->isPointerType() &&
4325       ToType1->isPointerType() && ToType2->isPointerType()) {
4326     QualType FromPointee1 =
4327         FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4328     QualType ToPointee1 =
4329         ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4330     QualType FromPointee2 =
4331         FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4332     QualType ToPointee2 =
4333         ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4334 
4335     //   -- conversion of C* to B* is better than conversion of C* to A*,
4336     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4337       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4338         return ImplicitConversionSequence::Better;
4339       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4340         return ImplicitConversionSequence::Worse;
4341     }
4342 
4343     //   -- conversion of B* to A* is better than conversion of C* to A*,
4344     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4345       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4346         return ImplicitConversionSequence::Better;
4347       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4348         return ImplicitConversionSequence::Worse;
4349     }
4350   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4351              SCS2.Second == ICK_Pointer_Conversion) {
4352     const ObjCObjectPointerType *FromPtr1
4353       = FromType1->getAs<ObjCObjectPointerType>();
4354     const ObjCObjectPointerType *FromPtr2
4355       = FromType2->getAs<ObjCObjectPointerType>();
4356     const ObjCObjectPointerType *ToPtr1
4357       = ToType1->getAs<ObjCObjectPointerType>();
4358     const ObjCObjectPointerType *ToPtr2
4359       = ToType2->getAs<ObjCObjectPointerType>();
4360 
4361     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4362       // Apply the same conversion ranking rules for Objective-C pointer types
4363       // that we do for C++ pointers to class types. However, we employ the
4364       // Objective-C pseudo-subtyping relationship used for assignment of
4365       // Objective-C pointer types.
4366       bool FromAssignLeft
4367         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4368       bool FromAssignRight
4369         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4370       bool ToAssignLeft
4371         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4372       bool ToAssignRight
4373         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4374 
4375       // A conversion to an a non-id object pointer type or qualified 'id'
4376       // type is better than a conversion to 'id'.
4377       if (ToPtr1->isObjCIdType() &&
4378           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4379         return ImplicitConversionSequence::Worse;
4380       if (ToPtr2->isObjCIdType() &&
4381           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4382         return ImplicitConversionSequence::Better;
4383 
4384       // A conversion to a non-id object pointer type is better than a
4385       // conversion to a qualified 'id' type
4386       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4387         return ImplicitConversionSequence::Worse;
4388       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4389         return ImplicitConversionSequence::Better;
4390 
4391       // A conversion to an a non-Class object pointer type or qualified 'Class'
4392       // type is better than a conversion to 'Class'.
4393       if (ToPtr1->isObjCClassType() &&
4394           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4395         return ImplicitConversionSequence::Worse;
4396       if (ToPtr2->isObjCClassType() &&
4397           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4398         return ImplicitConversionSequence::Better;
4399 
4400       // A conversion to a non-Class object pointer type is better than a
4401       // conversion to a qualified 'Class' type.
4402       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4403         return ImplicitConversionSequence::Worse;
4404       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4405         return ImplicitConversionSequence::Better;
4406 
4407       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4408       if (S.Context.hasSameType(FromType1, FromType2) &&
4409           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4410           (ToAssignLeft != ToAssignRight)) {
4411         if (FromPtr1->isSpecialized()) {
4412           // "conversion of B<A> * to B * is better than conversion of B * to
4413           // C *.
4414           bool IsFirstSame =
4415               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4416           bool IsSecondSame =
4417               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4418           if (IsFirstSame) {
4419             if (!IsSecondSame)
4420               return ImplicitConversionSequence::Better;
4421           } else if (IsSecondSame)
4422             return ImplicitConversionSequence::Worse;
4423         }
4424         return ToAssignLeft? ImplicitConversionSequence::Worse
4425                            : ImplicitConversionSequence::Better;
4426       }
4427 
4428       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4429       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4430           (FromAssignLeft != FromAssignRight))
4431         return FromAssignLeft? ImplicitConversionSequence::Better
4432         : ImplicitConversionSequence::Worse;
4433     }
4434   }
4435 
4436   // Ranking of member-pointer types.
4437   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4438       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4439       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4440     const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4441     const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4442     const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4443     const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4444     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4445     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4446     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4447     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4448     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4449     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4450     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4451     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4452     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4453     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4454       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4455         return ImplicitConversionSequence::Worse;
4456       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4457         return ImplicitConversionSequence::Better;
4458     }
4459     // conversion of B::* to C::* is better than conversion of A::* to C::*
4460     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4461       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4462         return ImplicitConversionSequence::Better;
4463       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4464         return ImplicitConversionSequence::Worse;
4465     }
4466   }
4467 
4468   if (SCS1.Second == ICK_Derived_To_Base) {
4469     //   -- conversion of C to B is better than conversion of C to A,
4470     //   -- binding of an expression of type C to a reference of type
4471     //      B& is better than binding an expression of type C to a
4472     //      reference of type A&,
4473     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4474         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4475       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4476         return ImplicitConversionSequence::Better;
4477       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4478         return ImplicitConversionSequence::Worse;
4479     }
4480 
4481     //   -- conversion of B to A is better than conversion of C to A.
4482     //   -- binding of an expression of type B to a reference of type
4483     //      A& is better than binding an expression of type C to a
4484     //      reference of type A&,
4485     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4486         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4487       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4488         return ImplicitConversionSequence::Better;
4489       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4490         return ImplicitConversionSequence::Worse;
4491     }
4492   }
4493 
4494   return ImplicitConversionSequence::Indistinguishable;
4495 }
4496 
4497 /// Determine whether the given type is valid, e.g., it is not an invalid
4498 /// C++ class.
4499 static bool isTypeValid(QualType T) {
4500   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4501     return !Record->isInvalidDecl();
4502 
4503   return true;
4504 }
4505 
4506 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4507   if (!T.getQualifiers().hasUnaligned())
4508     return T;
4509 
4510   Qualifiers Q;
4511   T = Ctx.getUnqualifiedArrayType(T, Q);
4512   Q.removeUnaligned();
4513   return Ctx.getQualifiedType(T, Q);
4514 }
4515 
4516 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4517 /// determine whether they are reference-compatible,
4518 /// reference-related, or incompatible, for use in C++ initialization by
4519 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4520 /// type, and the first type (T1) is the pointee type of the reference
4521 /// type being initialized.
4522 Sema::ReferenceCompareResult
4523 Sema::CompareReferenceRelationship(SourceLocation Loc,
4524                                    QualType OrigT1, QualType OrigT2,
4525                                    ReferenceConversions *ConvOut) {
4526   assert(!OrigT1->isReferenceType() &&
4527     "T1 must be the pointee type of the reference type");
4528   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4529 
4530   QualType T1 = Context.getCanonicalType(OrigT1);
4531   QualType T2 = Context.getCanonicalType(OrigT2);
4532   Qualifiers T1Quals, T2Quals;
4533   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4534   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4535 
4536   ReferenceConversions ConvTmp;
4537   ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4538   Conv = ReferenceConversions();
4539 
4540   // C++2a [dcl.init.ref]p4:
4541   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4542   //   reference-related to "cv2 T2" if T1 is similar to T2, or
4543   //   T1 is a base class of T2.
4544   //   "cv1 T1" is reference-compatible with "cv2 T2" if
4545   //   a prvalue of type "pointer to cv2 T2" can be converted to the type
4546   //   "pointer to cv1 T1" via a standard conversion sequence.
4547 
4548   // Check for standard conversions we can apply to pointers: derived-to-base
4549   // conversions, ObjC pointer conversions, and function pointer conversions.
4550   // (Qualification conversions are checked last.)
4551   QualType ConvertedT2;
4552   if (UnqualT1 == UnqualT2) {
4553     // Nothing to do.
4554   } else if (isCompleteType(Loc, OrigT2) &&
4555              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4556              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4557     Conv |= ReferenceConversions::DerivedToBase;
4558   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4559            UnqualT2->isObjCObjectOrInterfaceType() &&
4560            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4561     Conv |= ReferenceConversions::ObjC;
4562   else if (UnqualT2->isFunctionType() &&
4563            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4564     Conv |= ReferenceConversions::Function;
4565     // No need to check qualifiers; function types don't have them.
4566     return Ref_Compatible;
4567   }
4568   bool ConvertedReferent = Conv != 0;
4569 
4570   // We can have a qualification conversion. Compute whether the types are
4571   // similar at the same time.
4572   bool PreviousToQualsIncludeConst = true;
4573   bool TopLevel = true;
4574   do {
4575     if (T1 == T2)
4576       break;
4577 
4578     // We will need a qualification conversion.
4579     Conv |= ReferenceConversions::Qualification;
4580 
4581     // Track whether we performed a qualification conversion anywhere other
4582     // than the top level. This matters for ranking reference bindings in
4583     // overload resolution.
4584     if (!TopLevel)
4585       Conv |= ReferenceConversions::NestedQualification;
4586 
4587     // MS compiler ignores __unaligned qualifier for references; do the same.
4588     T1 = withoutUnaligned(Context, T1);
4589     T2 = withoutUnaligned(Context, T2);
4590 
4591     // If we find a qualifier mismatch, the types are not reference-compatible,
4592     // but are still be reference-related if they're similar.
4593     bool ObjCLifetimeConversion = false;
4594     if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4595                                        PreviousToQualsIncludeConst,
4596                                        ObjCLifetimeConversion))
4597       return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4598                  ? Ref_Related
4599                  : Ref_Incompatible;
4600 
4601     // FIXME: Should we track this for any level other than the first?
4602     if (ObjCLifetimeConversion)
4603       Conv |= ReferenceConversions::ObjCLifetime;
4604 
4605     TopLevel = false;
4606   } while (Context.UnwrapSimilarTypes(T1, T2));
4607 
4608   // At this point, if the types are reference-related, we must either have the
4609   // same inner type (ignoring qualifiers), or must have already worked out how
4610   // to convert the referent.
4611   return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4612              ? Ref_Compatible
4613              : Ref_Incompatible;
4614 }
4615 
4616 /// Look for a user-defined conversion to a value reference-compatible
4617 ///        with DeclType. Return true if something definite is found.
4618 static bool
4619 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4620                          QualType DeclType, SourceLocation DeclLoc,
4621                          Expr *Init, QualType T2, bool AllowRvalues,
4622                          bool AllowExplicit) {
4623   assert(T2->isRecordType() && "Can only find conversions of record types.");
4624   auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4625 
4626   OverloadCandidateSet CandidateSet(
4627       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4628   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4629   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4630     NamedDecl *D = *I;
4631     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4632     if (isa<UsingShadowDecl>(D))
4633       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4634 
4635     FunctionTemplateDecl *ConvTemplate
4636       = dyn_cast<FunctionTemplateDecl>(D);
4637     CXXConversionDecl *Conv;
4638     if (ConvTemplate)
4639       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4640     else
4641       Conv = cast<CXXConversionDecl>(D);
4642 
4643     if (AllowRvalues) {
4644       // If we are initializing an rvalue reference, don't permit conversion
4645       // functions that return lvalues.
4646       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4647         const ReferenceType *RefType
4648           = Conv->getConversionType()->getAs<LValueReferenceType>();
4649         if (RefType && !RefType->getPointeeType()->isFunctionType())
4650           continue;
4651       }
4652 
4653       if (!ConvTemplate &&
4654           S.CompareReferenceRelationship(
4655               DeclLoc,
4656               Conv->getConversionType()
4657                   .getNonReferenceType()
4658                   .getUnqualifiedType(),
4659               DeclType.getNonReferenceType().getUnqualifiedType()) ==
4660               Sema::Ref_Incompatible)
4661         continue;
4662     } else {
4663       // If the conversion function doesn't return a reference type,
4664       // it can't be considered for this conversion. An rvalue reference
4665       // is only acceptable if its referencee is a function type.
4666 
4667       const ReferenceType *RefType =
4668         Conv->getConversionType()->getAs<ReferenceType>();
4669       if (!RefType ||
4670           (!RefType->isLValueReferenceType() &&
4671            !RefType->getPointeeType()->isFunctionType()))
4672         continue;
4673     }
4674 
4675     if (ConvTemplate)
4676       S.AddTemplateConversionCandidate(
4677           ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4678           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4679     else
4680       S.AddConversionCandidate(
4681           Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4682           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4683   }
4684 
4685   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4686 
4687   OverloadCandidateSet::iterator Best;
4688   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4689   case OR_Success:
4690     // C++ [over.ics.ref]p1:
4691     //
4692     //   [...] If the parameter binds directly to the result of
4693     //   applying a conversion function to the argument
4694     //   expression, the implicit conversion sequence is a
4695     //   user-defined conversion sequence (13.3.3.1.2), with the
4696     //   second standard conversion sequence either an identity
4697     //   conversion or, if the conversion function returns an
4698     //   entity of a type that is a derived class of the parameter
4699     //   type, a derived-to-base Conversion.
4700     if (!Best->FinalConversion.DirectBinding)
4701       return false;
4702 
4703     ICS.setUserDefined();
4704     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4705     ICS.UserDefined.After = Best->FinalConversion;
4706     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4707     ICS.UserDefined.ConversionFunction = Best->Function;
4708     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4709     ICS.UserDefined.EllipsisConversion = false;
4710     assert(ICS.UserDefined.After.ReferenceBinding &&
4711            ICS.UserDefined.After.DirectBinding &&
4712            "Expected a direct reference binding!");
4713     return true;
4714 
4715   case OR_Ambiguous:
4716     ICS.setAmbiguous();
4717     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4718          Cand != CandidateSet.end(); ++Cand)
4719       if (Cand->Best)
4720         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4721     return true;
4722 
4723   case OR_No_Viable_Function:
4724   case OR_Deleted:
4725     // There was no suitable conversion, or we found a deleted
4726     // conversion; continue with other checks.
4727     return false;
4728   }
4729 
4730   llvm_unreachable("Invalid OverloadResult!");
4731 }
4732 
4733 /// Compute an implicit conversion sequence for reference
4734 /// initialization.
4735 static ImplicitConversionSequence
4736 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4737                  SourceLocation DeclLoc,
4738                  bool SuppressUserConversions,
4739                  bool AllowExplicit) {
4740   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4741 
4742   // Most paths end in a failed conversion.
4743   ImplicitConversionSequence ICS;
4744   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4745 
4746   QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4747   QualType T2 = Init->getType();
4748 
4749   // If the initializer is the address of an overloaded function, try
4750   // to resolve the overloaded function. If all goes well, T2 is the
4751   // type of the resulting function.
4752   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4753     DeclAccessPair Found;
4754     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4755                                                                 false, Found))
4756       T2 = Fn->getType();
4757   }
4758 
4759   // Compute some basic properties of the types and the initializer.
4760   bool isRValRef = DeclType->isRValueReferenceType();
4761   Expr::Classification InitCategory = Init->Classify(S.Context);
4762 
4763   Sema::ReferenceConversions RefConv;
4764   Sema::ReferenceCompareResult RefRelationship =
4765       S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4766 
4767   auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4768     ICS.setStandard();
4769     ICS.Standard.First = ICK_Identity;
4770     // FIXME: A reference binding can be a function conversion too. We should
4771     // consider that when ordering reference-to-function bindings.
4772     ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4773                               ? ICK_Derived_To_Base
4774                               : (RefConv & Sema::ReferenceConversions::ObjC)
4775                                     ? ICK_Compatible_Conversion
4776                                     : ICK_Identity;
4777     // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4778     // a reference binding that performs a non-top-level qualification
4779     // conversion as a qualification conversion, not as an identity conversion.
4780     ICS.Standard.Third = (RefConv &
4781                               Sema::ReferenceConversions::NestedQualification)
4782                              ? ICK_Qualification
4783                              : ICK_Identity;
4784     ICS.Standard.setFromType(T2);
4785     ICS.Standard.setToType(0, T2);
4786     ICS.Standard.setToType(1, T1);
4787     ICS.Standard.setToType(2, T1);
4788     ICS.Standard.ReferenceBinding = true;
4789     ICS.Standard.DirectBinding = BindsDirectly;
4790     ICS.Standard.IsLvalueReference = !isRValRef;
4791     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4792     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4793     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4794     ICS.Standard.ObjCLifetimeConversionBinding =
4795         (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4796     ICS.Standard.CopyConstructor = nullptr;
4797     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4798   };
4799 
4800   // C++0x [dcl.init.ref]p5:
4801   //   A reference to type "cv1 T1" is initialized by an expression
4802   //   of type "cv2 T2" as follows:
4803 
4804   //     -- If reference is an lvalue reference and the initializer expression
4805   if (!isRValRef) {
4806     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4807     //        reference-compatible with "cv2 T2," or
4808     //
4809     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4810     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4811       // C++ [over.ics.ref]p1:
4812       //   When a parameter of reference type binds directly (8.5.3)
4813       //   to an argument expression, the implicit conversion sequence
4814       //   is the identity conversion, unless the argument expression
4815       //   has a type that is a derived class of the parameter type,
4816       //   in which case the implicit conversion sequence is a
4817       //   derived-to-base Conversion (13.3.3.1).
4818       SetAsReferenceBinding(/*BindsDirectly=*/true);
4819 
4820       // Nothing more to do: the inaccessibility/ambiguity check for
4821       // derived-to-base conversions is suppressed when we're
4822       // computing the implicit conversion sequence (C++
4823       // [over.best.ics]p2).
4824       return ICS;
4825     }
4826 
4827     //       -- has a class type (i.e., T2 is a class type), where T1 is
4828     //          not reference-related to T2, and can be implicitly
4829     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4830     //          is reference-compatible with "cv3 T3" 92) (this
4831     //          conversion is selected by enumerating the applicable
4832     //          conversion functions (13.3.1.6) and choosing the best
4833     //          one through overload resolution (13.3)),
4834     if (!SuppressUserConversions && T2->isRecordType() &&
4835         S.isCompleteType(DeclLoc, T2) &&
4836         RefRelationship == Sema::Ref_Incompatible) {
4837       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4838                                    Init, T2, /*AllowRvalues=*/false,
4839                                    AllowExplicit))
4840         return ICS;
4841     }
4842   }
4843 
4844   //     -- Otherwise, the reference shall be an lvalue reference to a
4845   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4846   //        shall be an rvalue reference.
4847   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
4848     if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
4849       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4850     return ICS;
4851   }
4852 
4853   //       -- If the initializer expression
4854   //
4855   //            -- is an xvalue, class prvalue, array prvalue or function
4856   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4857   if (RefRelationship == Sema::Ref_Compatible &&
4858       (InitCategory.isXValue() ||
4859        (InitCategory.isPRValue() &&
4860           (T2->isRecordType() || T2->isArrayType())) ||
4861        (InitCategory.isLValue() && T2->isFunctionType()))) {
4862     // In C++11, this is always a direct binding. In C++98/03, it's a direct
4863     // binding unless we're binding to a class prvalue.
4864     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4865     // allow the use of rvalue references in C++98/03 for the benefit of
4866     // standard library implementors; therefore, we need the xvalue check here.
4867     SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4868                           !(InitCategory.isPRValue() || T2->isRecordType()));
4869     return ICS;
4870   }
4871 
4872   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4873   //               reference-related to T2, and can be implicitly converted to
4874   //               an xvalue, class prvalue, or function lvalue of type
4875   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4876   //               "cv3 T3",
4877   //
4878   //          then the reference is bound to the value of the initializer
4879   //          expression in the first case and to the result of the conversion
4880   //          in the second case (or, in either case, to an appropriate base
4881   //          class subobject).
4882   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4883       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4884       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4885                                Init, T2, /*AllowRvalues=*/true,
4886                                AllowExplicit)) {
4887     // In the second case, if the reference is an rvalue reference
4888     // and the second standard conversion sequence of the
4889     // user-defined conversion sequence includes an lvalue-to-rvalue
4890     // conversion, the program is ill-formed.
4891     if (ICS.isUserDefined() && isRValRef &&
4892         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4893       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4894 
4895     return ICS;
4896   }
4897 
4898   // A temporary of function type cannot be created; don't even try.
4899   if (T1->isFunctionType())
4900     return ICS;
4901 
4902   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4903   //          initialized from the initializer expression using the
4904   //          rules for a non-reference copy initialization (8.5). The
4905   //          reference is then bound to the temporary. If T1 is
4906   //          reference-related to T2, cv1 must be the same
4907   //          cv-qualification as, or greater cv-qualification than,
4908   //          cv2; otherwise, the program is ill-formed.
4909   if (RefRelationship == Sema::Ref_Related) {
4910     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4911     // we would be reference-compatible or reference-compatible with
4912     // added qualification. But that wasn't the case, so the reference
4913     // initialization fails.
4914     //
4915     // Note that we only want to check address spaces and cvr-qualifiers here.
4916     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4917     Qualifiers T1Quals = T1.getQualifiers();
4918     Qualifiers T2Quals = T2.getQualifiers();
4919     T1Quals.removeObjCGCAttr();
4920     T1Quals.removeObjCLifetime();
4921     T2Quals.removeObjCGCAttr();
4922     T2Quals.removeObjCLifetime();
4923     // MS compiler ignores __unaligned qualifier for references; do the same.
4924     T1Quals.removeUnaligned();
4925     T2Quals.removeUnaligned();
4926     if (!T1Quals.compatiblyIncludes(T2Quals))
4927       return ICS;
4928   }
4929 
4930   // If at least one of the types is a class type, the types are not
4931   // related, and we aren't allowed any user conversions, the
4932   // reference binding fails. This case is important for breaking
4933   // recursion, since TryImplicitConversion below will attempt to
4934   // create a temporary through the use of a copy constructor.
4935   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4936       (T1->isRecordType() || T2->isRecordType()))
4937     return ICS;
4938 
4939   // If T1 is reference-related to T2 and the reference is an rvalue
4940   // reference, the initializer expression shall not be an lvalue.
4941   if (RefRelationship >= Sema::Ref_Related && isRValRef &&
4942       Init->Classify(S.Context).isLValue()) {
4943     ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType);
4944     return ICS;
4945   }
4946 
4947   // C++ [over.ics.ref]p2:
4948   //   When a parameter of reference type is not bound directly to
4949   //   an argument expression, the conversion sequence is the one
4950   //   required to convert the argument expression to the
4951   //   underlying type of the reference according to
4952   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4953   //   to copy-initializing a temporary of the underlying type with
4954   //   the argument expression. Any difference in top-level
4955   //   cv-qualification is subsumed by the initialization itself
4956   //   and does not constitute a conversion.
4957   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4958                               AllowedExplicit::None,
4959                               /*InOverloadResolution=*/false,
4960                               /*CStyle=*/false,
4961                               /*AllowObjCWritebackConversion=*/false,
4962                               /*AllowObjCConversionOnExplicit=*/false);
4963 
4964   // Of course, that's still a reference binding.
4965   if (ICS.isStandard()) {
4966     ICS.Standard.ReferenceBinding = true;
4967     ICS.Standard.IsLvalueReference = !isRValRef;
4968     ICS.Standard.BindsToFunctionLvalue = false;
4969     ICS.Standard.BindsToRvalue = true;
4970     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4971     ICS.Standard.ObjCLifetimeConversionBinding = false;
4972   } else if (ICS.isUserDefined()) {
4973     const ReferenceType *LValRefType =
4974         ICS.UserDefined.ConversionFunction->getReturnType()
4975             ->getAs<LValueReferenceType>();
4976 
4977     // C++ [over.ics.ref]p3:
4978     //   Except for an implicit object parameter, for which see 13.3.1, a
4979     //   standard conversion sequence cannot be formed if it requires [...]
4980     //   binding an rvalue reference to an lvalue other than a function
4981     //   lvalue.
4982     // Note that the function case is not possible here.
4983     if (isRValRef && LValRefType) {
4984       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4985       return ICS;
4986     }
4987 
4988     ICS.UserDefined.After.ReferenceBinding = true;
4989     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4990     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4991     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4992     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4993     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4994   }
4995 
4996   return ICS;
4997 }
4998 
4999 static ImplicitConversionSequence
5000 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5001                       bool SuppressUserConversions,
5002                       bool InOverloadResolution,
5003                       bool AllowObjCWritebackConversion,
5004                       bool AllowExplicit = false);
5005 
5006 /// TryListConversion - Try to copy-initialize a value of type ToType from the
5007 /// initializer list From.
5008 static ImplicitConversionSequence
5009 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5010                   bool SuppressUserConversions,
5011                   bool InOverloadResolution,
5012                   bool AllowObjCWritebackConversion) {
5013   // C++11 [over.ics.list]p1:
5014   //   When an argument is an initializer list, it is not an expression and
5015   //   special rules apply for converting it to a parameter type.
5016 
5017   ImplicitConversionSequence Result;
5018   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5019 
5020   // We need a complete type for what follows.  With one C++20 exception,
5021   // incomplete types can never be initialized from init lists.
5022   QualType InitTy = ToType;
5023   const ArrayType *AT = S.Context.getAsArrayType(ToType);
5024   if (AT && S.getLangOpts().CPlusPlus20)
5025     if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5026       // C++20 allows list initialization of an incomplete array type.
5027       InitTy = IAT->getElementType();
5028   if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5029     return Result;
5030 
5031   // Per DR1467:
5032   //   If the parameter type is a class X and the initializer list has a single
5033   //   element of type cv U, where U is X or a class derived from X, the
5034   //   implicit conversion sequence is the one required to convert the element
5035   //   to the parameter type.
5036   //
5037   //   Otherwise, if the parameter type is a character array [... ]
5038   //   and the initializer list has a single element that is an
5039   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5040   //   implicit conversion sequence is the identity conversion.
5041   if (From->getNumInits() == 1) {
5042     if (ToType->isRecordType()) {
5043       QualType InitType = From->getInit(0)->getType();
5044       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5045           S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5046         return TryCopyInitialization(S, From->getInit(0), ToType,
5047                                      SuppressUserConversions,
5048                                      InOverloadResolution,
5049                                      AllowObjCWritebackConversion);
5050     }
5051 
5052     if (AT && S.IsStringInit(From->getInit(0), AT)) {
5053       InitializedEntity Entity =
5054           InitializedEntity::InitializeParameter(S.Context, ToType,
5055                                                  /*Consumed=*/false);
5056       if (S.CanPerformCopyInitialization(Entity, From)) {
5057         Result.setStandard();
5058         Result.Standard.setAsIdentityConversion();
5059         Result.Standard.setFromType(ToType);
5060         Result.Standard.setAllToTypes(ToType);
5061         return Result;
5062       }
5063     }
5064   }
5065 
5066   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5067   // C++11 [over.ics.list]p2:
5068   //   If the parameter type is std::initializer_list<X> or "array of X" and
5069   //   all the elements can be implicitly converted to X, the implicit
5070   //   conversion sequence is the worst conversion necessary to convert an
5071   //   element of the list to X.
5072   //
5073   // C++14 [over.ics.list]p3:
5074   //   Otherwise, if the parameter type is "array of N X", if the initializer
5075   //   list has exactly N elements or if it has fewer than N elements and X is
5076   //   default-constructible, and if all the elements of the initializer list
5077   //   can be implicitly converted to X, the implicit conversion sequence is
5078   //   the worst conversion necessary to convert an element of the list to X.
5079   if (AT || S.isStdInitializerList(ToType, &InitTy)) {
5080     unsigned e = From->getNumInits();
5081     ImplicitConversionSequence DfltElt;
5082     DfltElt.setBad(BadConversionSequence::no_conversion, QualType(),
5083                    QualType());
5084     QualType ContTy = ToType;
5085     bool IsUnbounded = false;
5086     if (AT) {
5087       InitTy = AT->getElementType();
5088       if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5089         if (CT->getSize().ult(e)) {
5090           // Too many inits, fatally bad
5091           Result.setBad(BadConversionSequence::too_many_initializers, From,
5092                         ToType);
5093           Result.setInitializerListContainerType(ContTy, IsUnbounded);
5094           return Result;
5095         }
5096         if (CT->getSize().ugt(e)) {
5097           // Need an init from empty {}, is there one?
5098           InitListExpr EmptyList(S.Context, From->getEndLoc(), None,
5099                                  From->getEndLoc());
5100           EmptyList.setType(S.Context.VoidTy);
5101           DfltElt = TryListConversion(
5102               S, &EmptyList, InitTy, SuppressUserConversions,
5103               InOverloadResolution, AllowObjCWritebackConversion);
5104           if (DfltElt.isBad()) {
5105             // No {} init, fatally bad
5106             Result.setBad(BadConversionSequence::too_few_initializers, From,
5107                           ToType);
5108             Result.setInitializerListContainerType(ContTy, IsUnbounded);
5109             return Result;
5110           }
5111         }
5112       } else {
5113         assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5114         IsUnbounded = true;
5115         if (!e) {
5116           // Cannot convert to zero-sized.
5117           Result.setBad(BadConversionSequence::too_few_initializers, From,
5118                         ToType);
5119           Result.setInitializerListContainerType(ContTy, IsUnbounded);
5120           return Result;
5121         }
5122         llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5123         ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5124                                                 ArrayType::Normal, 0);
5125       }
5126     }
5127 
5128     Result.setStandard();
5129     Result.Standard.setAsIdentityConversion();
5130     Result.Standard.setFromType(InitTy);
5131     Result.Standard.setAllToTypes(InitTy);
5132     for (unsigned i = 0; i < e; ++i) {
5133       Expr *Init = From->getInit(i);
5134       ImplicitConversionSequence ICS = TryCopyInitialization(
5135           S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5136           AllowObjCWritebackConversion);
5137 
5138       // Keep the worse conversion seen so far.
5139       // FIXME: Sequences are not totally ordered, so 'worse' can be
5140       // ambiguous. CWG has been informed.
5141       if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS,
5142                                              Result) ==
5143           ImplicitConversionSequence::Worse) {
5144         Result = ICS;
5145         // Bail as soon as we find something unconvertible.
5146         if (Result.isBad()) {
5147           Result.setInitializerListContainerType(ContTy, IsUnbounded);
5148           return Result;
5149         }
5150       }
5151     }
5152 
5153     // If we needed any implicit {} initialization, compare that now.
5154     // over.ics.list/6 indicates we should compare that conversion.  Again CWG
5155     // has been informed that this might not be the best thing.
5156     if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5157                                 S, From->getEndLoc(), DfltElt, Result) ==
5158                                 ImplicitConversionSequence::Worse)
5159       Result = DfltElt;
5160     // Record the type being initialized so that we may compare sequences
5161     Result.setInitializerListContainerType(ContTy, IsUnbounded);
5162     return Result;
5163   }
5164 
5165   // C++14 [over.ics.list]p4:
5166   // C++11 [over.ics.list]p3:
5167   //   Otherwise, if the parameter is a non-aggregate class X and overload
5168   //   resolution chooses a single best constructor [...] the implicit
5169   //   conversion sequence is a user-defined conversion sequence. If multiple
5170   //   constructors are viable but none is better than the others, the
5171   //   implicit conversion sequence is a user-defined conversion sequence.
5172   if (ToType->isRecordType() && !ToType->isAggregateType()) {
5173     // This function can deal with initializer lists.
5174     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5175                                     AllowedExplicit::None,
5176                                     InOverloadResolution, /*CStyle=*/false,
5177                                     AllowObjCWritebackConversion,
5178                                     /*AllowObjCConversionOnExplicit=*/false);
5179   }
5180 
5181   // C++14 [over.ics.list]p5:
5182   // C++11 [over.ics.list]p4:
5183   //   Otherwise, if the parameter has an aggregate type which can be
5184   //   initialized from the initializer list [...] the implicit conversion
5185   //   sequence is a user-defined conversion sequence.
5186   if (ToType->isAggregateType()) {
5187     // Type is an aggregate, argument is an init list. At this point it comes
5188     // down to checking whether the initialization works.
5189     // FIXME: Find out whether this parameter is consumed or not.
5190     InitializedEntity Entity =
5191         InitializedEntity::InitializeParameter(S.Context, ToType,
5192                                                /*Consumed=*/false);
5193     if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5194                                                                  From)) {
5195       Result.setUserDefined();
5196       Result.UserDefined.Before.setAsIdentityConversion();
5197       // Initializer lists don't have a type.
5198       Result.UserDefined.Before.setFromType(QualType());
5199       Result.UserDefined.Before.setAllToTypes(QualType());
5200 
5201       Result.UserDefined.After.setAsIdentityConversion();
5202       Result.UserDefined.After.setFromType(ToType);
5203       Result.UserDefined.After.setAllToTypes(ToType);
5204       Result.UserDefined.ConversionFunction = nullptr;
5205     }
5206     return Result;
5207   }
5208 
5209   // C++14 [over.ics.list]p6:
5210   // C++11 [over.ics.list]p5:
5211   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5212   if (ToType->isReferenceType()) {
5213     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5214     // mention initializer lists in any way. So we go by what list-
5215     // initialization would do and try to extrapolate from that.
5216 
5217     QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5218 
5219     // If the initializer list has a single element that is reference-related
5220     // to the parameter type, we initialize the reference from that.
5221     if (From->getNumInits() == 1) {
5222       Expr *Init = From->getInit(0);
5223 
5224       QualType T2 = Init->getType();
5225 
5226       // If the initializer is the address of an overloaded function, try
5227       // to resolve the overloaded function. If all goes well, T2 is the
5228       // type of the resulting function.
5229       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5230         DeclAccessPair Found;
5231         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5232                                    Init, ToType, false, Found))
5233           T2 = Fn->getType();
5234       }
5235 
5236       // Compute some basic properties of the types and the initializer.
5237       Sema::ReferenceCompareResult RefRelationship =
5238           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5239 
5240       if (RefRelationship >= Sema::Ref_Related) {
5241         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5242                                 SuppressUserConversions,
5243                                 /*AllowExplicit=*/false);
5244       }
5245     }
5246 
5247     // Otherwise, we bind the reference to a temporary created from the
5248     // initializer list.
5249     Result = TryListConversion(S, From, T1, SuppressUserConversions,
5250                                InOverloadResolution,
5251                                AllowObjCWritebackConversion);
5252     if (Result.isFailure())
5253       return Result;
5254     assert(!Result.isEllipsis() &&
5255            "Sub-initialization cannot result in ellipsis conversion.");
5256 
5257     // Can we even bind to a temporary?
5258     if (ToType->isRValueReferenceType() ||
5259         (T1.isConstQualified() && !T1.isVolatileQualified())) {
5260       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5261                                             Result.UserDefined.After;
5262       SCS.ReferenceBinding = true;
5263       SCS.IsLvalueReference = ToType->isLValueReferenceType();
5264       SCS.BindsToRvalue = true;
5265       SCS.BindsToFunctionLvalue = false;
5266       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5267       SCS.ObjCLifetimeConversionBinding = false;
5268     } else
5269       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5270                     From, ToType);
5271     return Result;
5272   }
5273 
5274   // C++14 [over.ics.list]p7:
5275   // C++11 [over.ics.list]p6:
5276   //   Otherwise, if the parameter type is not a class:
5277   if (!ToType->isRecordType()) {
5278     //    - if the initializer list has one element that is not itself an
5279     //      initializer list, the implicit conversion sequence is the one
5280     //      required to convert the element to the parameter type.
5281     unsigned NumInits = From->getNumInits();
5282     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5283       Result = TryCopyInitialization(S, From->getInit(0), ToType,
5284                                      SuppressUserConversions,
5285                                      InOverloadResolution,
5286                                      AllowObjCWritebackConversion);
5287     //    - if the initializer list has no elements, the implicit conversion
5288     //      sequence is the identity conversion.
5289     else if (NumInits == 0) {
5290       Result.setStandard();
5291       Result.Standard.setAsIdentityConversion();
5292       Result.Standard.setFromType(ToType);
5293       Result.Standard.setAllToTypes(ToType);
5294     }
5295     return Result;
5296   }
5297 
5298   // C++14 [over.ics.list]p8:
5299   // C++11 [over.ics.list]p7:
5300   //   In all cases other than those enumerated above, no conversion is possible
5301   return Result;
5302 }
5303 
5304 /// TryCopyInitialization - Try to copy-initialize a value of type
5305 /// ToType from the expression From. Return the implicit conversion
5306 /// sequence required to pass this argument, which may be a bad
5307 /// conversion sequence (meaning that the argument cannot be passed to
5308 /// a parameter of this type). If @p SuppressUserConversions, then we
5309 /// do not permit any user-defined conversion sequences.
5310 static ImplicitConversionSequence
5311 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5312                       bool SuppressUserConversions,
5313                       bool InOverloadResolution,
5314                       bool AllowObjCWritebackConversion,
5315                       bool AllowExplicit) {
5316   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5317     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5318                              InOverloadResolution,AllowObjCWritebackConversion);
5319 
5320   if (ToType->isReferenceType())
5321     return TryReferenceInit(S, From, ToType,
5322                             /*FIXME:*/ From->getBeginLoc(),
5323                             SuppressUserConversions, AllowExplicit);
5324 
5325   return TryImplicitConversion(S, From, ToType,
5326                                SuppressUserConversions,
5327                                AllowedExplicit::None,
5328                                InOverloadResolution,
5329                                /*CStyle=*/false,
5330                                AllowObjCWritebackConversion,
5331                                /*AllowObjCConversionOnExplicit=*/false);
5332 }
5333 
5334 static bool TryCopyInitialization(const CanQualType FromQTy,
5335                                   const CanQualType ToQTy,
5336                                   Sema &S,
5337                                   SourceLocation Loc,
5338                                   ExprValueKind FromVK) {
5339   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5340   ImplicitConversionSequence ICS =
5341     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5342 
5343   return !ICS.isBad();
5344 }
5345 
5346 /// TryObjectArgumentInitialization - Try to initialize the object
5347 /// parameter of the given member function (@c Method) from the
5348 /// expression @p From.
5349 static ImplicitConversionSequence
5350 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5351                                 Expr::Classification FromClassification,
5352                                 CXXMethodDecl *Method,
5353                                 CXXRecordDecl *ActingContext) {
5354   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5355   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5356   //                 const volatile object.
5357   Qualifiers Quals = Method->getMethodQualifiers();
5358   if (isa<CXXDestructorDecl>(Method)) {
5359     Quals.addConst();
5360     Quals.addVolatile();
5361   }
5362 
5363   QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5364 
5365   // Set up the conversion sequence as a "bad" conversion, to allow us
5366   // to exit early.
5367   ImplicitConversionSequence ICS;
5368 
5369   // We need to have an object of class type.
5370   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5371     FromType = PT->getPointeeType();
5372 
5373     // When we had a pointer, it's implicitly dereferenced, so we
5374     // better have an lvalue.
5375     assert(FromClassification.isLValue());
5376   }
5377 
5378   assert(FromType->isRecordType());
5379 
5380   // C++0x [over.match.funcs]p4:
5381   //   For non-static member functions, the type of the implicit object
5382   //   parameter is
5383   //
5384   //     - "lvalue reference to cv X" for functions declared without a
5385   //        ref-qualifier or with the & ref-qualifier
5386   //     - "rvalue reference to cv X" for functions declared with the &&
5387   //        ref-qualifier
5388   //
5389   // where X is the class of which the function is a member and cv is the
5390   // cv-qualification on the member function declaration.
5391   //
5392   // However, when finding an implicit conversion sequence for the argument, we
5393   // are not allowed to perform user-defined conversions
5394   // (C++ [over.match.funcs]p5). We perform a simplified version of
5395   // reference binding here, that allows class rvalues to bind to
5396   // non-constant references.
5397 
5398   // First check the qualifiers.
5399   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5400   if (ImplicitParamType.getCVRQualifiers()
5401                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5402       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5403     ICS.setBad(BadConversionSequence::bad_qualifiers,
5404                FromType, ImplicitParamType);
5405     return ICS;
5406   }
5407 
5408   if (FromTypeCanon.hasAddressSpace()) {
5409     Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5410     Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5411     if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5412       ICS.setBad(BadConversionSequence::bad_qualifiers,
5413                  FromType, ImplicitParamType);
5414       return ICS;
5415     }
5416   }
5417 
5418   // Check that we have either the same type or a derived type. It
5419   // affects the conversion rank.
5420   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5421   ImplicitConversionKind SecondKind;
5422   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5423     SecondKind = ICK_Identity;
5424   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5425     SecondKind = ICK_Derived_To_Base;
5426   else {
5427     ICS.setBad(BadConversionSequence::unrelated_class,
5428                FromType, ImplicitParamType);
5429     return ICS;
5430   }
5431 
5432   // Check the ref-qualifier.
5433   switch (Method->getRefQualifier()) {
5434   case RQ_None:
5435     // Do nothing; we don't care about lvalueness or rvalueness.
5436     break;
5437 
5438   case RQ_LValue:
5439     if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5440       // non-const lvalue reference cannot bind to an rvalue
5441       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5442                  ImplicitParamType);
5443       return ICS;
5444     }
5445     break;
5446 
5447   case RQ_RValue:
5448     if (!FromClassification.isRValue()) {
5449       // rvalue reference cannot bind to an lvalue
5450       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5451                  ImplicitParamType);
5452       return ICS;
5453     }
5454     break;
5455   }
5456 
5457   // Success. Mark this as a reference binding.
5458   ICS.setStandard();
5459   ICS.Standard.setAsIdentityConversion();
5460   ICS.Standard.Second = SecondKind;
5461   ICS.Standard.setFromType(FromType);
5462   ICS.Standard.setAllToTypes(ImplicitParamType);
5463   ICS.Standard.ReferenceBinding = true;
5464   ICS.Standard.DirectBinding = true;
5465   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5466   ICS.Standard.BindsToFunctionLvalue = false;
5467   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5468   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5469     = (Method->getRefQualifier() == RQ_None);
5470   return ICS;
5471 }
5472 
5473 /// PerformObjectArgumentInitialization - Perform initialization of
5474 /// the implicit object parameter for the given Method with the given
5475 /// expression.
5476 ExprResult
5477 Sema::PerformObjectArgumentInitialization(Expr *From,
5478                                           NestedNameSpecifier *Qualifier,
5479                                           NamedDecl *FoundDecl,
5480                                           CXXMethodDecl *Method) {
5481   QualType FromRecordType, DestType;
5482   QualType ImplicitParamRecordType  =
5483     Method->getThisType()->castAs<PointerType>()->getPointeeType();
5484 
5485   Expr::Classification FromClassification;
5486   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5487     FromRecordType = PT->getPointeeType();
5488     DestType = Method->getThisType();
5489     FromClassification = Expr::Classification::makeSimpleLValue();
5490   } else {
5491     FromRecordType = From->getType();
5492     DestType = ImplicitParamRecordType;
5493     FromClassification = From->Classify(Context);
5494 
5495     // When performing member access on a prvalue, materialize a temporary.
5496     if (From->isPRValue()) {
5497       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5498                                             Method->getRefQualifier() !=
5499                                                 RefQualifierKind::RQ_RValue);
5500     }
5501   }
5502 
5503   // Note that we always use the true parent context when performing
5504   // the actual argument initialization.
5505   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5506       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5507       Method->getParent());
5508   if (ICS.isBad()) {
5509     switch (ICS.Bad.Kind) {
5510     case BadConversionSequence::bad_qualifiers: {
5511       Qualifiers FromQs = FromRecordType.getQualifiers();
5512       Qualifiers ToQs = DestType.getQualifiers();
5513       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5514       if (CVR) {
5515         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5516             << Method->getDeclName() << FromRecordType << (CVR - 1)
5517             << From->getSourceRange();
5518         Diag(Method->getLocation(), diag::note_previous_decl)
5519           << Method->getDeclName();
5520         return ExprError();
5521       }
5522       break;
5523     }
5524 
5525     case BadConversionSequence::lvalue_ref_to_rvalue:
5526     case BadConversionSequence::rvalue_ref_to_lvalue: {
5527       bool IsRValueQualified =
5528         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5529       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5530           << Method->getDeclName() << FromClassification.isRValue()
5531           << IsRValueQualified;
5532       Diag(Method->getLocation(), diag::note_previous_decl)
5533         << Method->getDeclName();
5534       return ExprError();
5535     }
5536 
5537     case BadConversionSequence::no_conversion:
5538     case BadConversionSequence::unrelated_class:
5539       break;
5540 
5541     case BadConversionSequence::too_few_initializers:
5542     case BadConversionSequence::too_many_initializers:
5543       llvm_unreachable("Lists are not objects");
5544     }
5545 
5546     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5547            << ImplicitParamRecordType << FromRecordType
5548            << From->getSourceRange();
5549   }
5550 
5551   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5552     ExprResult FromRes =
5553       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5554     if (FromRes.isInvalid())
5555       return ExprError();
5556     From = FromRes.get();
5557   }
5558 
5559   if (!Context.hasSameType(From->getType(), DestType)) {
5560     CastKind CK;
5561     QualType PteeTy = DestType->getPointeeType();
5562     LangAS DestAS =
5563         PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5564     if (FromRecordType.getAddressSpace() != DestAS)
5565       CK = CK_AddressSpaceConversion;
5566     else
5567       CK = CK_NoOp;
5568     From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5569   }
5570   return From;
5571 }
5572 
5573 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5574 /// expression From to bool (C++0x [conv]p3).
5575 static ImplicitConversionSequence
5576 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5577   // C++ [dcl.init]/17.8:
5578   //   - Otherwise, if the initialization is direct-initialization, the source
5579   //     type is std::nullptr_t, and the destination type is bool, the initial
5580   //     value of the object being initialized is false.
5581   if (From->getType()->isNullPtrType())
5582     return ImplicitConversionSequence::getNullptrToBool(From->getType(),
5583                                                         S.Context.BoolTy,
5584                                                         From->isGLValue());
5585 
5586   // All other direct-initialization of bool is equivalent to an implicit
5587   // conversion to bool in which explicit conversions are permitted.
5588   return TryImplicitConversion(S, From, S.Context.BoolTy,
5589                                /*SuppressUserConversions=*/false,
5590                                AllowedExplicit::Conversions,
5591                                /*InOverloadResolution=*/false,
5592                                /*CStyle=*/false,
5593                                /*AllowObjCWritebackConversion=*/false,
5594                                /*AllowObjCConversionOnExplicit=*/false);
5595 }
5596 
5597 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5598 /// of the expression From to bool (C++0x [conv]p3).
5599 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5600   if (checkPlaceholderForOverload(*this, From))
5601     return ExprError();
5602 
5603   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5604   if (!ICS.isBad())
5605     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5606 
5607   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5608     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5609            << From->getType() << From->getSourceRange();
5610   return ExprError();
5611 }
5612 
5613 /// Check that the specified conversion is permitted in a converted constant
5614 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5615 /// is acceptable.
5616 static bool CheckConvertedConstantConversions(Sema &S,
5617                                               StandardConversionSequence &SCS) {
5618   // Since we know that the target type is an integral or unscoped enumeration
5619   // type, most conversion kinds are impossible. All possible First and Third
5620   // conversions are fine.
5621   switch (SCS.Second) {
5622   case ICK_Identity:
5623   case ICK_Integral_Promotion:
5624   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5625   case ICK_Zero_Queue_Conversion:
5626     return true;
5627 
5628   case ICK_Boolean_Conversion:
5629     // Conversion from an integral or unscoped enumeration type to bool is
5630     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5631     // conversion, so we allow it in a converted constant expression.
5632     //
5633     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5634     // a lot of popular code. We should at least add a warning for this
5635     // (non-conforming) extension.
5636     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5637            SCS.getToType(2)->isBooleanType();
5638 
5639   case ICK_Pointer_Conversion:
5640   case ICK_Pointer_Member:
5641     // C++1z: null pointer conversions and null member pointer conversions are
5642     // only permitted if the source type is std::nullptr_t.
5643     return SCS.getFromType()->isNullPtrType();
5644 
5645   case ICK_Floating_Promotion:
5646   case ICK_Complex_Promotion:
5647   case ICK_Floating_Conversion:
5648   case ICK_Complex_Conversion:
5649   case ICK_Floating_Integral:
5650   case ICK_Compatible_Conversion:
5651   case ICK_Derived_To_Base:
5652   case ICK_Vector_Conversion:
5653   case ICK_SVE_Vector_Conversion:
5654   case ICK_Vector_Splat:
5655   case ICK_Complex_Real:
5656   case ICK_Block_Pointer_Conversion:
5657   case ICK_TransparentUnionConversion:
5658   case ICK_Writeback_Conversion:
5659   case ICK_Zero_Event_Conversion:
5660   case ICK_C_Only_Conversion:
5661   case ICK_Incompatible_Pointer_Conversion:
5662     return false;
5663 
5664   case ICK_Lvalue_To_Rvalue:
5665   case ICK_Array_To_Pointer:
5666   case ICK_Function_To_Pointer:
5667     llvm_unreachable("found a first conversion kind in Second");
5668 
5669   case ICK_Function_Conversion:
5670   case ICK_Qualification:
5671     llvm_unreachable("found a third conversion kind in Second");
5672 
5673   case ICK_Num_Conversion_Kinds:
5674     break;
5675   }
5676 
5677   llvm_unreachable("unknown conversion kind");
5678 }
5679 
5680 /// CheckConvertedConstantExpression - Check that the expression From is a
5681 /// converted constant expression of type T, perform the conversion and produce
5682 /// the converted expression, per C++11 [expr.const]p3.
5683 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5684                                                    QualType T, APValue &Value,
5685                                                    Sema::CCEKind CCE,
5686                                                    bool RequireInt,
5687                                                    NamedDecl *Dest) {
5688   assert(S.getLangOpts().CPlusPlus11 &&
5689          "converted constant expression outside C++11");
5690 
5691   if (checkPlaceholderForOverload(S, From))
5692     return ExprError();
5693 
5694   // C++1z [expr.const]p3:
5695   //  A converted constant expression of type T is an expression,
5696   //  implicitly converted to type T, where the converted
5697   //  expression is a constant expression and the implicit conversion
5698   //  sequence contains only [... list of conversions ...].
5699   ImplicitConversionSequence ICS =
5700       (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept)
5701           ? TryContextuallyConvertToBool(S, From)
5702           : TryCopyInitialization(S, From, T,
5703                                   /*SuppressUserConversions=*/false,
5704                                   /*InOverloadResolution=*/false,
5705                                   /*AllowObjCWritebackConversion=*/false,
5706                                   /*AllowExplicit=*/false);
5707   StandardConversionSequence *SCS = nullptr;
5708   switch (ICS.getKind()) {
5709   case ImplicitConversionSequence::StandardConversion:
5710     SCS = &ICS.Standard;
5711     break;
5712   case ImplicitConversionSequence::UserDefinedConversion:
5713     if (T->isRecordType())
5714       SCS = &ICS.UserDefined.Before;
5715     else
5716       SCS = &ICS.UserDefined.After;
5717     break;
5718   case ImplicitConversionSequence::AmbiguousConversion:
5719   case ImplicitConversionSequence::BadConversion:
5720     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5721       return S.Diag(From->getBeginLoc(),
5722                     diag::err_typecheck_converted_constant_expression)
5723              << From->getType() << From->getSourceRange() << T;
5724     return ExprError();
5725 
5726   case ImplicitConversionSequence::EllipsisConversion:
5727     llvm_unreachable("ellipsis conversion in converted constant expression");
5728   }
5729 
5730   // Check that we would only use permitted conversions.
5731   if (!CheckConvertedConstantConversions(S, *SCS)) {
5732     return S.Diag(From->getBeginLoc(),
5733                   diag::err_typecheck_converted_constant_expression_disallowed)
5734            << From->getType() << From->getSourceRange() << T;
5735   }
5736   // [...] and where the reference binding (if any) binds directly.
5737   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5738     return S.Diag(From->getBeginLoc(),
5739                   diag::err_typecheck_converted_constant_expression_indirect)
5740            << From->getType() << From->getSourceRange() << T;
5741   }
5742 
5743   // Usually we can simply apply the ImplicitConversionSequence we formed
5744   // earlier, but that's not guaranteed to work when initializing an object of
5745   // class type.
5746   ExprResult Result;
5747   if (T->isRecordType()) {
5748     assert(CCE == Sema::CCEK_TemplateArg &&
5749            "unexpected class type converted constant expr");
5750     Result = S.PerformCopyInitialization(
5751         InitializedEntity::InitializeTemplateParameter(
5752             T, cast<NonTypeTemplateParmDecl>(Dest)),
5753         SourceLocation(), From);
5754   } else {
5755     Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5756   }
5757   if (Result.isInvalid())
5758     return Result;
5759 
5760   // C++2a [intro.execution]p5:
5761   //   A full-expression is [...] a constant-expression [...]
5762   Result =
5763       S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5764                             /*DiscardedValue=*/false, /*IsConstexpr=*/true);
5765   if (Result.isInvalid())
5766     return Result;
5767 
5768   // Check for a narrowing implicit conversion.
5769   bool ReturnPreNarrowingValue = false;
5770   APValue PreNarrowingValue;
5771   QualType PreNarrowingType;
5772   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5773                                 PreNarrowingType)) {
5774   case NK_Dependent_Narrowing:
5775     // Implicit conversion to a narrower type, but the expression is
5776     // value-dependent so we can't tell whether it's actually narrowing.
5777   case NK_Variable_Narrowing:
5778     // Implicit conversion to a narrower type, and the value is not a constant
5779     // expression. We'll diagnose this in a moment.
5780   case NK_Not_Narrowing:
5781     break;
5782 
5783   case NK_Constant_Narrowing:
5784     if (CCE == Sema::CCEK_ArrayBound &&
5785         PreNarrowingType->isIntegralOrEnumerationType() &&
5786         PreNarrowingValue.isInt()) {
5787       // Don't diagnose array bound narrowing here; we produce more precise
5788       // errors by allowing the un-narrowed value through.
5789       ReturnPreNarrowingValue = true;
5790       break;
5791     }
5792     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5793         << CCE << /*Constant*/ 1
5794         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5795     break;
5796 
5797   case NK_Type_Narrowing:
5798     // FIXME: It would be better to diagnose that the expression is not a
5799     // constant expression.
5800     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5801         << CCE << /*Constant*/ 0 << From->getType() << T;
5802     break;
5803   }
5804 
5805   if (Result.get()->isValueDependent()) {
5806     Value = APValue();
5807     return Result;
5808   }
5809 
5810   // Check the expression is a constant expression.
5811   SmallVector<PartialDiagnosticAt, 8> Notes;
5812   Expr::EvalResult Eval;
5813   Eval.Diag = &Notes;
5814 
5815   ConstantExprKind Kind;
5816   if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
5817     Kind = ConstantExprKind::ClassTemplateArgument;
5818   else if (CCE == Sema::CCEK_TemplateArg)
5819     Kind = ConstantExprKind::NonClassTemplateArgument;
5820   else
5821     Kind = ConstantExprKind::Normal;
5822 
5823   if (!Result.get()->EvaluateAsConstantExpr(Eval, S.Context, Kind) ||
5824       (RequireInt && !Eval.Val.isInt())) {
5825     // The expression can't be folded, so we can't keep it at this position in
5826     // the AST.
5827     Result = ExprError();
5828   } else {
5829     Value = Eval.Val;
5830 
5831     if (Notes.empty()) {
5832       // It's a constant expression.
5833       Expr *E = ConstantExpr::Create(S.Context, Result.get(), Value);
5834       if (ReturnPreNarrowingValue)
5835         Value = std::move(PreNarrowingValue);
5836       return E;
5837     }
5838   }
5839 
5840   // It's not a constant expression. Produce an appropriate diagnostic.
5841   if (Notes.size() == 1 &&
5842       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
5843     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5844   } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
5845                                    diag::note_constexpr_invalid_template_arg) {
5846     Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
5847     for (unsigned I = 0; I < Notes.size(); ++I)
5848       S.Diag(Notes[I].first, Notes[I].second);
5849   } else {
5850     S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5851         << CCE << From->getSourceRange();
5852     for (unsigned I = 0; I < Notes.size(); ++I)
5853       S.Diag(Notes[I].first, Notes[I].second);
5854   }
5855   return ExprError();
5856 }
5857 
5858 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5859                                                   APValue &Value, CCEKind CCE,
5860                                                   NamedDecl *Dest) {
5861   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
5862                                             Dest);
5863 }
5864 
5865 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5866                                                   llvm::APSInt &Value,
5867                                                   CCEKind CCE) {
5868   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5869 
5870   APValue V;
5871   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
5872                                               /*Dest=*/nullptr);
5873   if (!R.isInvalid() && !R.get()->isValueDependent())
5874     Value = V.getInt();
5875   return R;
5876 }
5877 
5878 
5879 /// dropPointerConversions - If the given standard conversion sequence
5880 /// involves any pointer conversions, remove them.  This may change
5881 /// the result type of the conversion sequence.
5882 static void dropPointerConversion(StandardConversionSequence &SCS) {
5883   if (SCS.Second == ICK_Pointer_Conversion) {
5884     SCS.Second = ICK_Identity;
5885     SCS.Third = ICK_Identity;
5886     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5887   }
5888 }
5889 
5890 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5891 /// convert the expression From to an Objective-C pointer type.
5892 static ImplicitConversionSequence
5893 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5894   // Do an implicit conversion to 'id'.
5895   QualType Ty = S.Context.getObjCIdType();
5896   ImplicitConversionSequence ICS
5897     = TryImplicitConversion(S, From, Ty,
5898                             // FIXME: Are these flags correct?
5899                             /*SuppressUserConversions=*/false,
5900                             AllowedExplicit::Conversions,
5901                             /*InOverloadResolution=*/false,
5902                             /*CStyle=*/false,
5903                             /*AllowObjCWritebackConversion=*/false,
5904                             /*AllowObjCConversionOnExplicit=*/true);
5905 
5906   // Strip off any final conversions to 'id'.
5907   switch (ICS.getKind()) {
5908   case ImplicitConversionSequence::BadConversion:
5909   case ImplicitConversionSequence::AmbiguousConversion:
5910   case ImplicitConversionSequence::EllipsisConversion:
5911     break;
5912 
5913   case ImplicitConversionSequence::UserDefinedConversion:
5914     dropPointerConversion(ICS.UserDefined.After);
5915     break;
5916 
5917   case ImplicitConversionSequence::StandardConversion:
5918     dropPointerConversion(ICS.Standard);
5919     break;
5920   }
5921 
5922   return ICS;
5923 }
5924 
5925 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5926 /// conversion of the expression From to an Objective-C pointer type.
5927 /// Returns a valid but null ExprResult if no conversion sequence exists.
5928 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5929   if (checkPlaceholderForOverload(*this, From))
5930     return ExprError();
5931 
5932   QualType Ty = Context.getObjCIdType();
5933   ImplicitConversionSequence ICS =
5934     TryContextuallyConvertToObjCPointer(*this, From);
5935   if (!ICS.isBad())
5936     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5937   return ExprResult();
5938 }
5939 
5940 /// Determine whether the provided type is an integral type, or an enumeration
5941 /// type of a permitted flavor.
5942 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5943   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5944                                  : T->isIntegralOrUnscopedEnumerationType();
5945 }
5946 
5947 static ExprResult
5948 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5949                             Sema::ContextualImplicitConverter &Converter,
5950                             QualType T, UnresolvedSetImpl &ViableConversions) {
5951 
5952   if (Converter.Suppress)
5953     return ExprError();
5954 
5955   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5956   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5957     CXXConversionDecl *Conv =
5958         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5959     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5960     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5961   }
5962   return From;
5963 }
5964 
5965 static bool
5966 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5967                            Sema::ContextualImplicitConverter &Converter,
5968                            QualType T, bool HadMultipleCandidates,
5969                            UnresolvedSetImpl &ExplicitConversions) {
5970   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5971     DeclAccessPair Found = ExplicitConversions[0];
5972     CXXConversionDecl *Conversion =
5973         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5974 
5975     // The user probably meant to invoke the given explicit
5976     // conversion; use it.
5977     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5978     std::string TypeStr;
5979     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5980 
5981     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5982         << FixItHint::CreateInsertion(From->getBeginLoc(),
5983                                       "static_cast<" + TypeStr + ">(")
5984         << FixItHint::CreateInsertion(
5985                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5986     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5987 
5988     // If we aren't in a SFINAE context, build a call to the
5989     // explicit conversion function.
5990     if (SemaRef.isSFINAEContext())
5991       return true;
5992 
5993     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5994     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5995                                                        HadMultipleCandidates);
5996     if (Result.isInvalid())
5997       return true;
5998     // Record usage of conversion in an implicit cast.
5999     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6000                                     CK_UserDefinedConversion, Result.get(),
6001                                     nullptr, Result.get()->getValueKind(),
6002                                     SemaRef.CurFPFeatureOverrides());
6003   }
6004   return false;
6005 }
6006 
6007 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6008                              Sema::ContextualImplicitConverter &Converter,
6009                              QualType T, bool HadMultipleCandidates,
6010                              DeclAccessPair &Found) {
6011   CXXConversionDecl *Conversion =
6012       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6013   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6014 
6015   QualType ToType = Conversion->getConversionType().getNonReferenceType();
6016   if (!Converter.SuppressConversion) {
6017     if (SemaRef.isSFINAEContext())
6018       return true;
6019 
6020     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6021         << From->getSourceRange();
6022   }
6023 
6024   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6025                                                      HadMultipleCandidates);
6026   if (Result.isInvalid())
6027     return true;
6028   // Record usage of conversion in an implicit cast.
6029   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6030                                   CK_UserDefinedConversion, Result.get(),
6031                                   nullptr, Result.get()->getValueKind(),
6032                                   SemaRef.CurFPFeatureOverrides());
6033   return false;
6034 }
6035 
6036 static ExprResult finishContextualImplicitConversion(
6037     Sema &SemaRef, SourceLocation Loc, Expr *From,
6038     Sema::ContextualImplicitConverter &Converter) {
6039   if (!Converter.match(From->getType()) && !Converter.Suppress)
6040     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6041         << From->getSourceRange();
6042 
6043   return SemaRef.DefaultLvalueConversion(From);
6044 }
6045 
6046 static void
6047 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
6048                                   UnresolvedSetImpl &ViableConversions,
6049                                   OverloadCandidateSet &CandidateSet) {
6050   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6051     DeclAccessPair FoundDecl = ViableConversions[I];
6052     NamedDecl *D = FoundDecl.getDecl();
6053     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6054     if (isa<UsingShadowDecl>(D))
6055       D = cast<UsingShadowDecl>(D)->getTargetDecl();
6056 
6057     CXXConversionDecl *Conv;
6058     FunctionTemplateDecl *ConvTemplate;
6059     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
6060       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6061     else
6062       Conv = cast<CXXConversionDecl>(D);
6063 
6064     if (ConvTemplate)
6065       SemaRef.AddTemplateConversionCandidate(
6066           ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6067           /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
6068     else
6069       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
6070                                      ToType, CandidateSet,
6071                                      /*AllowObjCConversionOnExplicit=*/false,
6072                                      /*AllowExplicit*/ true);
6073   }
6074 }
6075 
6076 /// Attempt to convert the given expression to a type which is accepted
6077 /// by the given converter.
6078 ///
6079 /// This routine will attempt to convert an expression of class type to a
6080 /// type accepted by the specified converter. In C++11 and before, the class
6081 /// must have a single non-explicit conversion function converting to a matching
6082 /// type. In C++1y, there can be multiple such conversion functions, but only
6083 /// one target type.
6084 ///
6085 /// \param Loc The source location of the construct that requires the
6086 /// conversion.
6087 ///
6088 /// \param From The expression we're converting from.
6089 ///
6090 /// \param Converter Used to control and diagnose the conversion process.
6091 ///
6092 /// \returns The expression, converted to an integral or enumeration type if
6093 /// successful.
6094 ExprResult Sema::PerformContextualImplicitConversion(
6095     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6096   // We can't perform any more checking for type-dependent expressions.
6097   if (From->isTypeDependent())
6098     return From;
6099 
6100   // Process placeholders immediately.
6101   if (From->hasPlaceholderType()) {
6102     ExprResult result = CheckPlaceholderExpr(From);
6103     if (result.isInvalid())
6104       return result;
6105     From = result.get();
6106   }
6107 
6108   // If the expression already has a matching type, we're golden.
6109   QualType T = From->getType();
6110   if (Converter.match(T))
6111     return DefaultLvalueConversion(From);
6112 
6113   // FIXME: Check for missing '()' if T is a function type?
6114 
6115   // We can only perform contextual implicit conversions on objects of class
6116   // type.
6117   const RecordType *RecordTy = T->getAs<RecordType>();
6118   if (!RecordTy || !getLangOpts().CPlusPlus) {
6119     if (!Converter.Suppress)
6120       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6121     return From;
6122   }
6123 
6124   // We must have a complete class type.
6125   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6126     ContextualImplicitConverter &Converter;
6127     Expr *From;
6128 
6129     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6130         : Converter(Converter), From(From) {}
6131 
6132     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6133       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6134     }
6135   } IncompleteDiagnoser(Converter, From);
6136 
6137   if (Converter.Suppress ? !isCompleteType(Loc, T)
6138                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6139     return From;
6140 
6141   // Look for a conversion to an integral or enumeration type.
6142   UnresolvedSet<4>
6143       ViableConversions; // These are *potentially* viable in C++1y.
6144   UnresolvedSet<4> ExplicitConversions;
6145   const auto &Conversions =
6146       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
6147 
6148   bool HadMultipleCandidates =
6149       (std::distance(Conversions.begin(), Conversions.end()) > 1);
6150 
6151   // To check that there is only one target type, in C++1y:
6152   QualType ToType;
6153   bool HasUniqueTargetType = true;
6154 
6155   // Collect explicit or viable (potentially in C++1y) conversions.
6156   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6157     NamedDecl *D = (*I)->getUnderlyingDecl();
6158     CXXConversionDecl *Conversion;
6159     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6160     if (ConvTemplate) {
6161       if (getLangOpts().CPlusPlus14)
6162         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6163       else
6164         continue; // C++11 does not consider conversion operator templates(?).
6165     } else
6166       Conversion = cast<CXXConversionDecl>(D);
6167 
6168     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6169            "Conversion operator templates are considered potentially "
6170            "viable in C++1y");
6171 
6172     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6173     if (Converter.match(CurToType) || ConvTemplate) {
6174 
6175       if (Conversion->isExplicit()) {
6176         // FIXME: For C++1y, do we need this restriction?
6177         // cf. diagnoseNoViableConversion()
6178         if (!ConvTemplate)
6179           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6180       } else {
6181         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6182           if (ToType.isNull())
6183             ToType = CurToType.getUnqualifiedType();
6184           else if (HasUniqueTargetType &&
6185                    (CurToType.getUnqualifiedType() != ToType))
6186             HasUniqueTargetType = false;
6187         }
6188         ViableConversions.addDecl(I.getDecl(), I.getAccess());
6189       }
6190     }
6191   }
6192 
6193   if (getLangOpts().CPlusPlus14) {
6194     // C++1y [conv]p6:
6195     // ... An expression e of class type E appearing in such a context
6196     // is said to be contextually implicitly converted to a specified
6197     // type T and is well-formed if and only if e can be implicitly
6198     // converted to a type T that is determined as follows: E is searched
6199     // for conversion functions whose return type is cv T or reference to
6200     // cv T such that T is allowed by the context. There shall be
6201     // exactly one such T.
6202 
6203     // If no unique T is found:
6204     if (ToType.isNull()) {
6205       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6206                                      HadMultipleCandidates,
6207                                      ExplicitConversions))
6208         return ExprError();
6209       return finishContextualImplicitConversion(*this, Loc, From, Converter);
6210     }
6211 
6212     // If more than one unique Ts are found:
6213     if (!HasUniqueTargetType)
6214       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6215                                          ViableConversions);
6216 
6217     // If one unique T is found:
6218     // First, build a candidate set from the previously recorded
6219     // potentially viable conversions.
6220     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6221     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6222                                       CandidateSet);
6223 
6224     // Then, perform overload resolution over the candidate set.
6225     OverloadCandidateSet::iterator Best;
6226     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6227     case OR_Success: {
6228       // Apply this conversion.
6229       DeclAccessPair Found =
6230           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6231       if (recordConversion(*this, Loc, From, Converter, T,
6232                            HadMultipleCandidates, Found))
6233         return ExprError();
6234       break;
6235     }
6236     case OR_Ambiguous:
6237       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6238                                          ViableConversions);
6239     case OR_No_Viable_Function:
6240       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6241                                      HadMultipleCandidates,
6242                                      ExplicitConversions))
6243         return ExprError();
6244       LLVM_FALLTHROUGH;
6245     case OR_Deleted:
6246       // We'll complain below about a non-integral condition type.
6247       break;
6248     }
6249   } else {
6250     switch (ViableConversions.size()) {
6251     case 0: {
6252       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6253                                      HadMultipleCandidates,
6254                                      ExplicitConversions))
6255         return ExprError();
6256 
6257       // We'll complain below about a non-integral condition type.
6258       break;
6259     }
6260     case 1: {
6261       // Apply this conversion.
6262       DeclAccessPair Found = ViableConversions[0];
6263       if (recordConversion(*this, Loc, From, Converter, T,
6264                            HadMultipleCandidates, Found))
6265         return ExprError();
6266       break;
6267     }
6268     default:
6269       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6270                                          ViableConversions);
6271     }
6272   }
6273 
6274   return finishContextualImplicitConversion(*this, Loc, From, Converter);
6275 }
6276 
6277 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6278 /// an acceptable non-member overloaded operator for a call whose
6279 /// arguments have types T1 (and, if non-empty, T2). This routine
6280 /// implements the check in C++ [over.match.oper]p3b2 concerning
6281 /// enumeration types.
6282 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6283                                                    FunctionDecl *Fn,
6284                                                    ArrayRef<Expr *> Args) {
6285   QualType T1 = Args[0]->getType();
6286   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6287 
6288   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6289     return true;
6290 
6291   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6292     return true;
6293 
6294   const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6295   if (Proto->getNumParams() < 1)
6296     return false;
6297 
6298   if (T1->isEnumeralType()) {
6299     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6300     if (Context.hasSameUnqualifiedType(T1, ArgType))
6301       return true;
6302   }
6303 
6304   if (Proto->getNumParams() < 2)
6305     return false;
6306 
6307   if (!T2.isNull() && T2->isEnumeralType()) {
6308     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6309     if (Context.hasSameUnqualifiedType(T2, ArgType))
6310       return true;
6311   }
6312 
6313   return false;
6314 }
6315 
6316 /// AddOverloadCandidate - Adds the given function to the set of
6317 /// candidate functions, using the given function call arguments.  If
6318 /// @p SuppressUserConversions, then don't allow user-defined
6319 /// conversions via constructors or conversion operators.
6320 ///
6321 /// \param PartialOverloading true if we are performing "partial" overloading
6322 /// based on an incomplete set of function arguments. This feature is used by
6323 /// code completion.
6324 void Sema::AddOverloadCandidate(
6325     FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6326     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6327     bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6328     ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6329     OverloadCandidateParamOrder PO) {
6330   const FunctionProtoType *Proto
6331     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6332   assert(Proto && "Functions without a prototype cannot be overloaded");
6333   assert(!Function->getDescribedFunctionTemplate() &&
6334          "Use AddTemplateOverloadCandidate for function templates");
6335 
6336   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6337     if (!isa<CXXConstructorDecl>(Method)) {
6338       // If we get here, it's because we're calling a member function
6339       // that is named without a member access expression (e.g.,
6340       // "this->f") that was either written explicitly or created
6341       // implicitly. This can happen with a qualified call to a member
6342       // function, e.g., X::f(). We use an empty type for the implied
6343       // object argument (C++ [over.call.func]p3), and the acting context
6344       // is irrelevant.
6345       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6346                          Expr::Classification::makeSimpleLValue(), Args,
6347                          CandidateSet, SuppressUserConversions,
6348                          PartialOverloading, EarlyConversions, PO);
6349       return;
6350     }
6351     // We treat a constructor like a non-member function, since its object
6352     // argument doesn't participate in overload resolution.
6353   }
6354 
6355   if (!CandidateSet.isNewCandidate(Function, PO))
6356     return;
6357 
6358   // C++11 [class.copy]p11: [DR1402]
6359   //   A defaulted move constructor that is defined as deleted is ignored by
6360   //   overload resolution.
6361   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6362   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6363       Constructor->isMoveConstructor())
6364     return;
6365 
6366   // Overload resolution is always an unevaluated context.
6367   EnterExpressionEvaluationContext Unevaluated(
6368       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6369 
6370   // C++ [over.match.oper]p3:
6371   //   if no operand has a class type, only those non-member functions in the
6372   //   lookup set that have a first parameter of type T1 or "reference to
6373   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6374   //   is a right operand) a second parameter of type T2 or "reference to
6375   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
6376   //   candidate functions.
6377   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6378       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6379     return;
6380 
6381   // Add this candidate
6382   OverloadCandidate &Candidate =
6383       CandidateSet.addCandidate(Args.size(), EarlyConversions);
6384   Candidate.FoundDecl = FoundDecl;
6385   Candidate.Function = Function;
6386   Candidate.Viable = true;
6387   Candidate.RewriteKind =
6388       CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6389   Candidate.IsSurrogate = false;
6390   Candidate.IsADLCandidate = IsADLCandidate;
6391   Candidate.IgnoreObjectArgument = false;
6392   Candidate.ExplicitCallArguments = Args.size();
6393 
6394   // Explicit functions are not actually candidates at all if we're not
6395   // allowing them in this context, but keep them around so we can point
6396   // to them in diagnostics.
6397   if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6398     Candidate.Viable = false;
6399     Candidate.FailureKind = ovl_fail_explicit;
6400     return;
6401   }
6402 
6403   if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6404       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6405     Candidate.Viable = false;
6406     Candidate.FailureKind = ovl_non_default_multiversion_function;
6407     return;
6408   }
6409 
6410   if (Constructor) {
6411     // C++ [class.copy]p3:
6412     //   A member function template is never instantiated to perform the copy
6413     //   of a class object to an object of its class type.
6414     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6415     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6416         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6417          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6418                        ClassType))) {
6419       Candidate.Viable = false;
6420       Candidate.FailureKind = ovl_fail_illegal_constructor;
6421       return;
6422     }
6423 
6424     // C++ [over.match.funcs]p8: (proposed DR resolution)
6425     //   A constructor inherited from class type C that has a first parameter
6426     //   of type "reference to P" (including such a constructor instantiated
6427     //   from a template) is excluded from the set of candidate functions when
6428     //   constructing an object of type cv D if the argument list has exactly
6429     //   one argument and D is reference-related to P and P is reference-related
6430     //   to C.
6431     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6432     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6433         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6434       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6435       QualType C = Context.getRecordType(Constructor->getParent());
6436       QualType D = Context.getRecordType(Shadow->getParent());
6437       SourceLocation Loc = Args.front()->getExprLoc();
6438       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6439           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6440         Candidate.Viable = false;
6441         Candidate.FailureKind = ovl_fail_inhctor_slice;
6442         return;
6443       }
6444     }
6445 
6446     // Check that the constructor is capable of constructing an object in the
6447     // destination address space.
6448     if (!Qualifiers::isAddressSpaceSupersetOf(
6449             Constructor->getMethodQualifiers().getAddressSpace(),
6450             CandidateSet.getDestAS())) {
6451       Candidate.Viable = false;
6452       Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6453     }
6454   }
6455 
6456   unsigned NumParams = Proto->getNumParams();
6457 
6458   // (C++ 13.3.2p2): A candidate function having fewer than m
6459   // parameters is viable only if it has an ellipsis in its parameter
6460   // list (8.3.5).
6461   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6462       !Proto->isVariadic() &&
6463       shouldEnforceArgLimit(PartialOverloading, Function)) {
6464     Candidate.Viable = false;
6465     Candidate.FailureKind = ovl_fail_too_many_arguments;
6466     return;
6467   }
6468 
6469   // (C++ 13.3.2p2): A candidate function having more than m parameters
6470   // is viable only if the (m+1)st parameter has a default argument
6471   // (8.3.6). For the purposes of overload resolution, the
6472   // parameter list is truncated on the right, so that there are
6473   // exactly m parameters.
6474   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6475   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6476     // Not enough arguments.
6477     Candidate.Viable = false;
6478     Candidate.FailureKind = ovl_fail_too_few_arguments;
6479     return;
6480   }
6481 
6482   // (CUDA B.1): Check for invalid calls between targets.
6483   if (getLangOpts().CUDA)
6484     if (const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true))
6485       // Skip the check for callers that are implicit members, because in this
6486       // case we may not yet know what the member's target is; the target is
6487       // inferred for the member automatically, based on the bases and fields of
6488       // the class.
6489       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6490         Candidate.Viable = false;
6491         Candidate.FailureKind = ovl_fail_bad_target;
6492         return;
6493       }
6494 
6495   if (Function->getTrailingRequiresClause()) {
6496     ConstraintSatisfaction Satisfaction;
6497     if (CheckFunctionConstraints(Function, Satisfaction) ||
6498         !Satisfaction.IsSatisfied) {
6499       Candidate.Viable = false;
6500       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6501       return;
6502     }
6503   }
6504 
6505   // Determine the implicit conversion sequences for each of the
6506   // arguments.
6507   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6508     unsigned ConvIdx =
6509         PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6510     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6511       // We already formed a conversion sequence for this parameter during
6512       // template argument deduction.
6513     } else if (ArgIdx < NumParams) {
6514       // (C++ 13.3.2p3): for F to be a viable function, there shall
6515       // exist for each argument an implicit conversion sequence
6516       // (13.3.3.1) that converts that argument to the corresponding
6517       // parameter of F.
6518       QualType ParamType = Proto->getParamType(ArgIdx);
6519       Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6520           *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6521           /*InOverloadResolution=*/true,
6522           /*AllowObjCWritebackConversion=*/
6523           getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6524       if (Candidate.Conversions[ConvIdx].isBad()) {
6525         Candidate.Viable = false;
6526         Candidate.FailureKind = ovl_fail_bad_conversion;
6527         return;
6528       }
6529     } else {
6530       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6531       // argument for which there is no corresponding parameter is
6532       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6533       Candidate.Conversions[ConvIdx].setEllipsis();
6534     }
6535   }
6536 
6537   if (EnableIfAttr *FailedAttr =
6538           CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
6539     Candidate.Viable = false;
6540     Candidate.FailureKind = ovl_fail_enable_if;
6541     Candidate.DeductionFailure.Data = FailedAttr;
6542     return;
6543   }
6544 }
6545 
6546 ObjCMethodDecl *
6547 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6548                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6549   if (Methods.size() <= 1)
6550     return nullptr;
6551 
6552   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6553     bool Match = true;
6554     ObjCMethodDecl *Method = Methods[b];
6555     unsigned NumNamedArgs = Sel.getNumArgs();
6556     // Method might have more arguments than selector indicates. This is due
6557     // to addition of c-style arguments in method.
6558     if (Method->param_size() > NumNamedArgs)
6559       NumNamedArgs = Method->param_size();
6560     if (Args.size() < NumNamedArgs)
6561       continue;
6562 
6563     for (unsigned i = 0; i < NumNamedArgs; i++) {
6564       // We can't do any type-checking on a type-dependent argument.
6565       if (Args[i]->isTypeDependent()) {
6566         Match = false;
6567         break;
6568       }
6569 
6570       ParmVarDecl *param = Method->parameters()[i];
6571       Expr *argExpr = Args[i];
6572       assert(argExpr && "SelectBestMethod(): missing expression");
6573 
6574       // Strip the unbridged-cast placeholder expression off unless it's
6575       // a consumed argument.
6576       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6577           !param->hasAttr<CFConsumedAttr>())
6578         argExpr = stripARCUnbridgedCast(argExpr);
6579 
6580       // If the parameter is __unknown_anytype, move on to the next method.
6581       if (param->getType() == Context.UnknownAnyTy) {
6582         Match = false;
6583         break;
6584       }
6585 
6586       ImplicitConversionSequence ConversionState
6587         = TryCopyInitialization(*this, argExpr, param->getType(),
6588                                 /*SuppressUserConversions*/false,
6589                                 /*InOverloadResolution=*/true,
6590                                 /*AllowObjCWritebackConversion=*/
6591                                 getLangOpts().ObjCAutoRefCount,
6592                                 /*AllowExplicit*/false);
6593       // This function looks for a reasonably-exact match, so we consider
6594       // incompatible pointer conversions to be a failure here.
6595       if (ConversionState.isBad() ||
6596           (ConversionState.isStandard() &&
6597            ConversionState.Standard.Second ==
6598                ICK_Incompatible_Pointer_Conversion)) {
6599         Match = false;
6600         break;
6601       }
6602     }
6603     // Promote additional arguments to variadic methods.
6604     if (Match && Method->isVariadic()) {
6605       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6606         if (Args[i]->isTypeDependent()) {
6607           Match = false;
6608           break;
6609         }
6610         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6611                                                           nullptr);
6612         if (Arg.isInvalid()) {
6613           Match = false;
6614           break;
6615         }
6616       }
6617     } else {
6618       // Check for extra arguments to non-variadic methods.
6619       if (Args.size() != NumNamedArgs)
6620         Match = false;
6621       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6622         // Special case when selectors have no argument. In this case, select
6623         // one with the most general result type of 'id'.
6624         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6625           QualType ReturnT = Methods[b]->getReturnType();
6626           if (ReturnT->isObjCIdType())
6627             return Methods[b];
6628         }
6629       }
6630     }
6631 
6632     if (Match)
6633       return Method;
6634   }
6635   return nullptr;
6636 }
6637 
6638 static bool convertArgsForAvailabilityChecks(
6639     Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
6640     ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
6641     Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
6642   if (ThisArg) {
6643     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6644     assert(!isa<CXXConstructorDecl>(Method) &&
6645            "Shouldn't have `this` for ctors!");
6646     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6647     ExprResult R = S.PerformObjectArgumentInitialization(
6648         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6649     if (R.isInvalid())
6650       return false;
6651     ConvertedThis = R.get();
6652   } else {
6653     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6654       (void)MD;
6655       assert((MissingImplicitThis || MD->isStatic() ||
6656               isa<CXXConstructorDecl>(MD)) &&
6657              "Expected `this` for non-ctor instance methods");
6658     }
6659     ConvertedThis = nullptr;
6660   }
6661 
6662   // Ignore any variadic arguments. Converting them is pointless, since the
6663   // user can't refer to them in the function condition.
6664   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6665 
6666   // Convert the arguments.
6667   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6668     ExprResult R;
6669     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6670                                         S.Context, Function->getParamDecl(I)),
6671                                     SourceLocation(), Args[I]);
6672 
6673     if (R.isInvalid())
6674       return false;
6675 
6676     ConvertedArgs.push_back(R.get());
6677   }
6678 
6679   if (Trap.hasErrorOccurred())
6680     return false;
6681 
6682   // Push default arguments if needed.
6683   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6684     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6685       ParmVarDecl *P = Function->getParamDecl(i);
6686       if (!P->hasDefaultArg())
6687         return false;
6688       ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
6689       if (R.isInvalid())
6690         return false;
6691       ConvertedArgs.push_back(R.get());
6692     }
6693 
6694     if (Trap.hasErrorOccurred())
6695       return false;
6696   }
6697   return true;
6698 }
6699 
6700 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
6701                                   SourceLocation CallLoc,
6702                                   ArrayRef<Expr *> Args,
6703                                   bool MissingImplicitThis) {
6704   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6705   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6706     return nullptr;
6707 
6708   SFINAETrap Trap(*this);
6709   SmallVector<Expr *, 16> ConvertedArgs;
6710   // FIXME: We should look into making enable_if late-parsed.
6711   Expr *DiscardedThis;
6712   if (!convertArgsForAvailabilityChecks(
6713           *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
6714           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6715     return *EnableIfAttrs.begin();
6716 
6717   for (auto *EIA : EnableIfAttrs) {
6718     APValue Result;
6719     // FIXME: This doesn't consider value-dependent cases, because doing so is
6720     // very difficult. Ideally, we should handle them more gracefully.
6721     if (EIA->getCond()->isValueDependent() ||
6722         !EIA->getCond()->EvaluateWithSubstitution(
6723             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6724       return EIA;
6725 
6726     if (!Result.isInt() || !Result.getInt().getBoolValue())
6727       return EIA;
6728   }
6729   return nullptr;
6730 }
6731 
6732 template <typename CheckFn>
6733 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6734                                         bool ArgDependent, SourceLocation Loc,
6735                                         CheckFn &&IsSuccessful) {
6736   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6737   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6738     if (ArgDependent == DIA->getArgDependent())
6739       Attrs.push_back(DIA);
6740   }
6741 
6742   // Common case: No diagnose_if attributes, so we can quit early.
6743   if (Attrs.empty())
6744     return false;
6745 
6746   auto WarningBegin = std::stable_partition(
6747       Attrs.begin(), Attrs.end(),
6748       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6749 
6750   // Note that diagnose_if attributes are late-parsed, so they appear in the
6751   // correct order (unlike enable_if attributes).
6752   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6753                                IsSuccessful);
6754   if (ErrAttr != WarningBegin) {
6755     const DiagnoseIfAttr *DIA = *ErrAttr;
6756     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6757     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6758         << DIA->getParent() << DIA->getCond()->getSourceRange();
6759     return true;
6760   }
6761 
6762   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6763     if (IsSuccessful(DIA)) {
6764       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6765       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6766           << DIA->getParent() << DIA->getCond()->getSourceRange();
6767     }
6768 
6769   return false;
6770 }
6771 
6772 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6773                                                const Expr *ThisArg,
6774                                                ArrayRef<const Expr *> Args,
6775                                                SourceLocation Loc) {
6776   return diagnoseDiagnoseIfAttrsWith(
6777       *this, Function, /*ArgDependent=*/true, Loc,
6778       [&](const DiagnoseIfAttr *DIA) {
6779         APValue Result;
6780         // It's sane to use the same Args for any redecl of this function, since
6781         // EvaluateWithSubstitution only cares about the position of each
6782         // argument in the arg list, not the ParmVarDecl* it maps to.
6783         if (!DIA->getCond()->EvaluateWithSubstitution(
6784                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6785           return false;
6786         return Result.isInt() && Result.getInt().getBoolValue();
6787       });
6788 }
6789 
6790 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6791                                                  SourceLocation Loc) {
6792   return diagnoseDiagnoseIfAttrsWith(
6793       *this, ND, /*ArgDependent=*/false, Loc,
6794       [&](const DiagnoseIfAttr *DIA) {
6795         bool Result;
6796         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6797                Result;
6798       });
6799 }
6800 
6801 /// Add all of the function declarations in the given function set to
6802 /// the overload candidate set.
6803 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6804                                  ArrayRef<Expr *> Args,
6805                                  OverloadCandidateSet &CandidateSet,
6806                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6807                                  bool SuppressUserConversions,
6808                                  bool PartialOverloading,
6809                                  bool FirstArgumentIsBase) {
6810   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6811     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6812     ArrayRef<Expr *> FunctionArgs = Args;
6813 
6814     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6815     FunctionDecl *FD =
6816         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6817 
6818     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6819       QualType ObjectType;
6820       Expr::Classification ObjectClassification;
6821       if (Args.size() > 0) {
6822         if (Expr *E = Args[0]) {
6823           // Use the explicit base to restrict the lookup:
6824           ObjectType = E->getType();
6825           // Pointers in the object arguments are implicitly dereferenced, so we
6826           // always classify them as l-values.
6827           if (!ObjectType.isNull() && ObjectType->isPointerType())
6828             ObjectClassification = Expr::Classification::makeSimpleLValue();
6829           else
6830             ObjectClassification = E->Classify(Context);
6831         } // .. else there is an implicit base.
6832         FunctionArgs = Args.slice(1);
6833       }
6834       if (FunTmpl) {
6835         AddMethodTemplateCandidate(
6836             FunTmpl, F.getPair(),
6837             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6838             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6839             FunctionArgs, CandidateSet, SuppressUserConversions,
6840             PartialOverloading);
6841       } else {
6842         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6843                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6844                            ObjectClassification, FunctionArgs, CandidateSet,
6845                            SuppressUserConversions, PartialOverloading);
6846       }
6847     } else {
6848       // This branch handles both standalone functions and static methods.
6849 
6850       // Slice the first argument (which is the base) when we access
6851       // static method as non-static.
6852       if (Args.size() > 0 &&
6853           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6854                         !isa<CXXConstructorDecl>(FD)))) {
6855         assert(cast<CXXMethodDecl>(FD)->isStatic());
6856         FunctionArgs = Args.slice(1);
6857       }
6858       if (FunTmpl) {
6859         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6860                                      ExplicitTemplateArgs, FunctionArgs,
6861                                      CandidateSet, SuppressUserConversions,
6862                                      PartialOverloading);
6863       } else {
6864         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6865                              SuppressUserConversions, PartialOverloading);
6866       }
6867     }
6868   }
6869 }
6870 
6871 /// AddMethodCandidate - Adds a named decl (which is some kind of
6872 /// method) as a method candidate to the given overload set.
6873 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
6874                               Expr::Classification ObjectClassification,
6875                               ArrayRef<Expr *> Args,
6876                               OverloadCandidateSet &CandidateSet,
6877                               bool SuppressUserConversions,
6878                               OverloadCandidateParamOrder PO) {
6879   NamedDecl *Decl = FoundDecl.getDecl();
6880   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6881 
6882   if (isa<UsingShadowDecl>(Decl))
6883     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6884 
6885   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6886     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6887            "Expected a member function template");
6888     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6889                                /*ExplicitArgs*/ nullptr, ObjectType,
6890                                ObjectClassification, Args, CandidateSet,
6891                                SuppressUserConversions, false, PO);
6892   } else {
6893     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6894                        ObjectType, ObjectClassification, Args, CandidateSet,
6895                        SuppressUserConversions, false, None, PO);
6896   }
6897 }
6898 
6899 /// AddMethodCandidate - Adds the given C++ member function to the set
6900 /// of candidate functions, using the given function call arguments
6901 /// and the object argument (@c Object). For example, in a call
6902 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6903 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6904 /// allow user-defined conversions via constructors or conversion
6905 /// operators.
6906 void
6907 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6908                          CXXRecordDecl *ActingContext, QualType ObjectType,
6909                          Expr::Classification ObjectClassification,
6910                          ArrayRef<Expr *> Args,
6911                          OverloadCandidateSet &CandidateSet,
6912                          bool SuppressUserConversions,
6913                          bool PartialOverloading,
6914                          ConversionSequenceList EarlyConversions,
6915                          OverloadCandidateParamOrder PO) {
6916   const FunctionProtoType *Proto
6917     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6918   assert(Proto && "Methods without a prototype cannot be overloaded");
6919   assert(!isa<CXXConstructorDecl>(Method) &&
6920          "Use AddOverloadCandidate for constructors");
6921 
6922   if (!CandidateSet.isNewCandidate(Method, PO))
6923     return;
6924 
6925   // C++11 [class.copy]p23: [DR1402]
6926   //   A defaulted move assignment operator that is defined as deleted is
6927   //   ignored by overload resolution.
6928   if (Method->isDefaulted() && Method->isDeleted() &&
6929       Method->isMoveAssignmentOperator())
6930     return;
6931 
6932   // Overload resolution is always an unevaluated context.
6933   EnterExpressionEvaluationContext Unevaluated(
6934       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6935 
6936   // Add this candidate
6937   OverloadCandidate &Candidate =
6938       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6939   Candidate.FoundDecl = FoundDecl;
6940   Candidate.Function = Method;
6941   Candidate.RewriteKind =
6942       CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
6943   Candidate.IsSurrogate = false;
6944   Candidate.IgnoreObjectArgument = false;
6945   Candidate.ExplicitCallArguments = Args.size();
6946 
6947   unsigned NumParams = Proto->getNumParams();
6948 
6949   // (C++ 13.3.2p2): A candidate function having fewer than m
6950   // parameters is viable only if it has an ellipsis in its parameter
6951   // list (8.3.5).
6952   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6953       !Proto->isVariadic() &&
6954       shouldEnforceArgLimit(PartialOverloading, Method)) {
6955     Candidate.Viable = false;
6956     Candidate.FailureKind = ovl_fail_too_many_arguments;
6957     return;
6958   }
6959 
6960   // (C++ 13.3.2p2): A candidate function having more than m parameters
6961   // is viable only if the (m+1)st parameter has a default argument
6962   // (8.3.6). For the purposes of overload resolution, the
6963   // parameter list is truncated on the right, so that there are
6964   // exactly m parameters.
6965   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6966   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6967     // Not enough arguments.
6968     Candidate.Viable = false;
6969     Candidate.FailureKind = ovl_fail_too_few_arguments;
6970     return;
6971   }
6972 
6973   Candidate.Viable = true;
6974 
6975   if (Method->isStatic() || ObjectType.isNull())
6976     // The implicit object argument is ignored.
6977     Candidate.IgnoreObjectArgument = true;
6978   else {
6979     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
6980     // Determine the implicit conversion sequence for the object
6981     // parameter.
6982     Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization(
6983         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6984         Method, ActingContext);
6985     if (Candidate.Conversions[ConvIdx].isBad()) {
6986       Candidate.Viable = false;
6987       Candidate.FailureKind = ovl_fail_bad_conversion;
6988       return;
6989     }
6990   }
6991 
6992   // (CUDA B.1): Check for invalid calls between targets.
6993   if (getLangOpts().CUDA)
6994     if (const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true))
6995       if (!IsAllowedCUDACall(Caller, Method)) {
6996         Candidate.Viable = false;
6997         Candidate.FailureKind = ovl_fail_bad_target;
6998         return;
6999       }
7000 
7001   if (Method->getTrailingRequiresClause()) {
7002     ConstraintSatisfaction Satisfaction;
7003     if (CheckFunctionConstraints(Method, Satisfaction) ||
7004         !Satisfaction.IsSatisfied) {
7005       Candidate.Viable = false;
7006       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7007       return;
7008     }
7009   }
7010 
7011   // Determine the implicit conversion sequences for each of the
7012   // arguments.
7013   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7014     unsigned ConvIdx =
7015         PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
7016     if (Candidate.Conversions[ConvIdx].isInitialized()) {
7017       // We already formed a conversion sequence for this parameter during
7018       // template argument deduction.
7019     } else if (ArgIdx < NumParams) {
7020       // (C++ 13.3.2p3): for F to be a viable function, there shall
7021       // exist for each argument an implicit conversion sequence
7022       // (13.3.3.1) that converts that argument to the corresponding
7023       // parameter of F.
7024       QualType ParamType = Proto->getParamType(ArgIdx);
7025       Candidate.Conversions[ConvIdx]
7026         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7027                                 SuppressUserConversions,
7028                                 /*InOverloadResolution=*/true,
7029                                 /*AllowObjCWritebackConversion=*/
7030                                   getLangOpts().ObjCAutoRefCount);
7031       if (Candidate.Conversions[ConvIdx].isBad()) {
7032         Candidate.Viable = false;
7033         Candidate.FailureKind = ovl_fail_bad_conversion;
7034         return;
7035       }
7036     } else {
7037       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7038       // argument for which there is no corresponding parameter is
7039       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7040       Candidate.Conversions[ConvIdx].setEllipsis();
7041     }
7042   }
7043 
7044   if (EnableIfAttr *FailedAttr =
7045           CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7046     Candidate.Viable = false;
7047     Candidate.FailureKind = ovl_fail_enable_if;
7048     Candidate.DeductionFailure.Data = FailedAttr;
7049     return;
7050   }
7051 
7052   if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
7053       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
7054     Candidate.Viable = false;
7055     Candidate.FailureKind = ovl_non_default_multiversion_function;
7056   }
7057 }
7058 
7059 /// Add a C++ member function template as a candidate to the candidate
7060 /// set, using template argument deduction to produce an appropriate member
7061 /// function template specialization.
7062 void Sema::AddMethodTemplateCandidate(
7063     FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7064     CXXRecordDecl *ActingContext,
7065     TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7066     Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7067     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7068     bool PartialOverloading, OverloadCandidateParamOrder PO) {
7069   if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7070     return;
7071 
7072   // C++ [over.match.funcs]p7:
7073   //   In each case where a candidate is a function template, candidate
7074   //   function template specializations are generated using template argument
7075   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
7076   //   candidate functions in the usual way.113) A given name can refer to one
7077   //   or more function templates and also to a set of overloaded non-template
7078   //   functions. In such a case, the candidate functions generated from each
7079   //   function template are combined with the set of non-template candidate
7080   //   functions.
7081   TemplateDeductionInfo Info(CandidateSet.getLocation());
7082   FunctionDecl *Specialization = nullptr;
7083   ConversionSequenceList Conversions;
7084   if (TemplateDeductionResult Result = DeduceTemplateArguments(
7085           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7086           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7087             return CheckNonDependentConversions(
7088                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7089                 SuppressUserConversions, ActingContext, ObjectType,
7090                 ObjectClassification, PO);
7091           })) {
7092     OverloadCandidate &Candidate =
7093         CandidateSet.addCandidate(Conversions.size(), Conversions);
7094     Candidate.FoundDecl = FoundDecl;
7095     Candidate.Function = MethodTmpl->getTemplatedDecl();
7096     Candidate.Viable = false;
7097     Candidate.RewriteKind =
7098       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7099     Candidate.IsSurrogate = false;
7100     Candidate.IgnoreObjectArgument =
7101         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
7102         ObjectType.isNull();
7103     Candidate.ExplicitCallArguments = Args.size();
7104     if (Result == TDK_NonDependentConversionFailure)
7105       Candidate.FailureKind = ovl_fail_bad_conversion;
7106     else {
7107       Candidate.FailureKind = ovl_fail_bad_deduction;
7108       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7109                                                             Info);
7110     }
7111     return;
7112   }
7113 
7114   // Add the function template specialization produced by template argument
7115   // deduction as a candidate.
7116   assert(Specialization && "Missing member function template specialization?");
7117   assert(isa<CXXMethodDecl>(Specialization) &&
7118          "Specialization is not a member function?");
7119   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
7120                      ActingContext, ObjectType, ObjectClassification, Args,
7121                      CandidateSet, SuppressUserConversions, PartialOverloading,
7122                      Conversions, PO);
7123 }
7124 
7125 /// Determine whether a given function template has a simple explicit specifier
7126 /// or a non-value-dependent explicit-specification that evaluates to true.
7127 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
7128   return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
7129 }
7130 
7131 /// Add a C++ function template specialization as a candidate
7132 /// in the candidate set, using template argument deduction to produce
7133 /// an appropriate function template specialization.
7134 void Sema::AddTemplateOverloadCandidate(
7135     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7136     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7137     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7138     bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7139     OverloadCandidateParamOrder PO) {
7140   if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
7141     return;
7142 
7143   // If the function template has a non-dependent explicit specification,
7144   // exclude it now if appropriate; we are not permitted to perform deduction
7145   // and substitution in this case.
7146   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7147     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7148     Candidate.FoundDecl = FoundDecl;
7149     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7150     Candidate.Viable = false;
7151     Candidate.FailureKind = ovl_fail_explicit;
7152     return;
7153   }
7154 
7155   // C++ [over.match.funcs]p7:
7156   //   In each case where a candidate is a function template, candidate
7157   //   function template specializations are generated using template argument
7158   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
7159   //   candidate functions in the usual way.113) A given name can refer to one
7160   //   or more function templates and also to a set of overloaded non-template
7161   //   functions. In such a case, the candidate functions generated from each
7162   //   function template are combined with the set of non-template candidate
7163   //   functions.
7164   TemplateDeductionInfo Info(CandidateSet.getLocation());
7165   FunctionDecl *Specialization = nullptr;
7166   ConversionSequenceList Conversions;
7167   if (TemplateDeductionResult Result = DeduceTemplateArguments(
7168           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7169           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7170             return CheckNonDependentConversions(
7171                 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7172                 SuppressUserConversions, nullptr, QualType(), {}, PO);
7173           })) {
7174     OverloadCandidate &Candidate =
7175         CandidateSet.addCandidate(Conversions.size(), Conversions);
7176     Candidate.FoundDecl = FoundDecl;
7177     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7178     Candidate.Viable = false;
7179     Candidate.RewriteKind =
7180       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7181     Candidate.IsSurrogate = false;
7182     Candidate.IsADLCandidate = IsADLCandidate;
7183     // Ignore the object argument if there is one, since we don't have an object
7184     // type.
7185     Candidate.IgnoreObjectArgument =
7186         isa<CXXMethodDecl>(Candidate.Function) &&
7187         !isa<CXXConstructorDecl>(Candidate.Function);
7188     Candidate.ExplicitCallArguments = Args.size();
7189     if (Result == TDK_NonDependentConversionFailure)
7190       Candidate.FailureKind = ovl_fail_bad_conversion;
7191     else {
7192       Candidate.FailureKind = ovl_fail_bad_deduction;
7193       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7194                                                             Info);
7195     }
7196     return;
7197   }
7198 
7199   // Add the function template specialization produced by template argument
7200   // deduction as a candidate.
7201   assert(Specialization && "Missing function template specialization?");
7202   AddOverloadCandidate(
7203       Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7204       PartialOverloading, AllowExplicit,
7205       /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO);
7206 }
7207 
7208 /// Check that implicit conversion sequences can be formed for each argument
7209 /// whose corresponding parameter has a non-dependent type, per DR1391's
7210 /// [temp.deduct.call]p10.
7211 bool Sema::CheckNonDependentConversions(
7212     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7213     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7214     ConversionSequenceList &Conversions, bool SuppressUserConversions,
7215     CXXRecordDecl *ActingContext, QualType ObjectType,
7216     Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7217   // FIXME: The cases in which we allow explicit conversions for constructor
7218   // arguments never consider calling a constructor template. It's not clear
7219   // that is correct.
7220   const bool AllowExplicit = false;
7221 
7222   auto *FD = FunctionTemplate->getTemplatedDecl();
7223   auto *Method = dyn_cast<CXXMethodDecl>(FD);
7224   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7225   unsigned ThisConversions = HasThisConversion ? 1 : 0;
7226 
7227   Conversions =
7228       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7229 
7230   // Overload resolution is always an unevaluated context.
7231   EnterExpressionEvaluationContext Unevaluated(
7232       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7233 
7234   // For a method call, check the 'this' conversion here too. DR1391 doesn't
7235   // require that, but this check should never result in a hard error, and
7236   // overload resolution is permitted to sidestep instantiations.
7237   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7238       !ObjectType.isNull()) {
7239     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7240     Conversions[ConvIdx] = TryObjectArgumentInitialization(
7241         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7242         Method, ActingContext);
7243     if (Conversions[ConvIdx].isBad())
7244       return true;
7245   }
7246 
7247   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
7248        ++I) {
7249     QualType ParamType = ParamTypes[I];
7250     if (!ParamType->isDependentType()) {
7251       unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
7252                              ? 0
7253                              : (ThisConversions + I);
7254       Conversions[ConvIdx]
7255         = TryCopyInitialization(*this, Args[I], ParamType,
7256                                 SuppressUserConversions,
7257                                 /*InOverloadResolution=*/true,
7258                                 /*AllowObjCWritebackConversion=*/
7259                                   getLangOpts().ObjCAutoRefCount,
7260                                 AllowExplicit);
7261       if (Conversions[ConvIdx].isBad())
7262         return true;
7263     }
7264   }
7265 
7266   return false;
7267 }
7268 
7269 /// Determine whether this is an allowable conversion from the result
7270 /// of an explicit conversion operator to the expected type, per C++
7271 /// [over.match.conv]p1 and [over.match.ref]p1.
7272 ///
7273 /// \param ConvType The return type of the conversion function.
7274 ///
7275 /// \param ToType The type we are converting to.
7276 ///
7277 /// \param AllowObjCPointerConversion Allow a conversion from one
7278 /// Objective-C pointer to another.
7279 ///
7280 /// \returns true if the conversion is allowable, false otherwise.
7281 static bool isAllowableExplicitConversion(Sema &S,
7282                                           QualType ConvType, QualType ToType,
7283                                           bool AllowObjCPointerConversion) {
7284   QualType ToNonRefType = ToType.getNonReferenceType();
7285 
7286   // Easy case: the types are the same.
7287   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7288     return true;
7289 
7290   // Allow qualification conversions.
7291   bool ObjCLifetimeConversion;
7292   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7293                                   ObjCLifetimeConversion))
7294     return true;
7295 
7296   // If we're not allowed to consider Objective-C pointer conversions,
7297   // we're done.
7298   if (!AllowObjCPointerConversion)
7299     return false;
7300 
7301   // Is this an Objective-C pointer conversion?
7302   bool IncompatibleObjC = false;
7303   QualType ConvertedType;
7304   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7305                                    IncompatibleObjC);
7306 }
7307 
7308 /// AddConversionCandidate - Add a C++ conversion function as a
7309 /// candidate in the candidate set (C++ [over.match.conv],
7310 /// C++ [over.match.copy]). From is the expression we're converting from,
7311 /// and ToType is the type that we're eventually trying to convert to
7312 /// (which may or may not be the same type as the type that the
7313 /// conversion function produces).
7314 void Sema::AddConversionCandidate(
7315     CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7316     CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7317     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7318     bool AllowExplicit, bool AllowResultConversion) {
7319   assert(!Conversion->getDescribedFunctionTemplate() &&
7320          "Conversion function templates use AddTemplateConversionCandidate");
7321   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7322   if (!CandidateSet.isNewCandidate(Conversion))
7323     return;
7324 
7325   // If the conversion function has an undeduced return type, trigger its
7326   // deduction now.
7327   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7328     if (DeduceReturnType(Conversion, From->getExprLoc()))
7329       return;
7330     ConvType = Conversion->getConversionType().getNonReferenceType();
7331   }
7332 
7333   // If we don't allow any conversion of the result type, ignore conversion
7334   // functions that don't convert to exactly (possibly cv-qualified) T.
7335   if (!AllowResultConversion &&
7336       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7337     return;
7338 
7339   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7340   // operator is only a candidate if its return type is the target type or
7341   // can be converted to the target type with a qualification conversion.
7342   //
7343   // FIXME: Include such functions in the candidate list and explain why we
7344   // can't select them.
7345   if (Conversion->isExplicit() &&
7346       !isAllowableExplicitConversion(*this, ConvType, ToType,
7347                                      AllowObjCConversionOnExplicit))
7348     return;
7349 
7350   // Overload resolution is always an unevaluated context.
7351   EnterExpressionEvaluationContext Unevaluated(
7352       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7353 
7354   // Add this candidate
7355   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7356   Candidate.FoundDecl = FoundDecl;
7357   Candidate.Function = Conversion;
7358   Candidate.IsSurrogate = false;
7359   Candidate.IgnoreObjectArgument = false;
7360   Candidate.FinalConversion.setAsIdentityConversion();
7361   Candidate.FinalConversion.setFromType(ConvType);
7362   Candidate.FinalConversion.setAllToTypes(ToType);
7363   Candidate.Viable = true;
7364   Candidate.ExplicitCallArguments = 1;
7365 
7366   // Explicit functions are not actually candidates at all if we're not
7367   // allowing them in this context, but keep them around so we can point
7368   // to them in diagnostics.
7369   if (!AllowExplicit && Conversion->isExplicit()) {
7370     Candidate.Viable = false;
7371     Candidate.FailureKind = ovl_fail_explicit;
7372     return;
7373   }
7374 
7375   // C++ [over.match.funcs]p4:
7376   //   For conversion functions, the function is considered to be a member of
7377   //   the class of the implicit implied object argument for the purpose of
7378   //   defining the type of the implicit object parameter.
7379   //
7380   // Determine the implicit conversion sequence for the implicit
7381   // object parameter.
7382   QualType ImplicitParamType = From->getType();
7383   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7384     ImplicitParamType = FromPtrType->getPointeeType();
7385   CXXRecordDecl *ConversionContext
7386     = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
7387 
7388   Candidate.Conversions[0] = TryObjectArgumentInitialization(
7389       *this, CandidateSet.getLocation(), From->getType(),
7390       From->Classify(Context), Conversion, ConversionContext);
7391 
7392   if (Candidate.Conversions[0].isBad()) {
7393     Candidate.Viable = false;
7394     Candidate.FailureKind = ovl_fail_bad_conversion;
7395     return;
7396   }
7397 
7398   if (Conversion->getTrailingRequiresClause()) {
7399     ConstraintSatisfaction Satisfaction;
7400     if (CheckFunctionConstraints(Conversion, Satisfaction) ||
7401         !Satisfaction.IsSatisfied) {
7402       Candidate.Viable = false;
7403       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7404       return;
7405     }
7406   }
7407 
7408   // We won't go through a user-defined type conversion function to convert a
7409   // derived to base as such conversions are given Conversion Rank. They only
7410   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7411   QualType FromCanon
7412     = Context.getCanonicalType(From->getType().getUnqualifiedType());
7413   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7414   if (FromCanon == ToCanon ||
7415       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7416     Candidate.Viable = false;
7417     Candidate.FailureKind = ovl_fail_trivial_conversion;
7418     return;
7419   }
7420 
7421   // To determine what the conversion from the result of calling the
7422   // conversion function to the type we're eventually trying to
7423   // convert to (ToType), we need to synthesize a call to the
7424   // conversion function and attempt copy initialization from it. This
7425   // makes sure that we get the right semantics with respect to
7426   // lvalues/rvalues and the type. Fortunately, we can allocate this
7427   // call on the stack and we don't need its arguments to be
7428   // well-formed.
7429   DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7430                             VK_LValue, From->getBeginLoc());
7431   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7432                                 Context.getPointerType(Conversion->getType()),
7433                                 CK_FunctionToPointerDecay, &ConversionRef,
7434                                 VK_PRValue, FPOptionsOverride());
7435 
7436   QualType ConversionType = Conversion->getConversionType();
7437   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7438     Candidate.Viable = false;
7439     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7440     return;
7441   }
7442 
7443   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7444 
7445   // Note that it is safe to allocate CallExpr on the stack here because
7446   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7447   // allocator).
7448   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7449 
7450   alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7451   CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7452       Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7453 
7454   ImplicitConversionSequence ICS =
7455       TryCopyInitialization(*this, TheTemporaryCall, ToType,
7456                             /*SuppressUserConversions=*/true,
7457                             /*InOverloadResolution=*/false,
7458                             /*AllowObjCWritebackConversion=*/false);
7459 
7460   switch (ICS.getKind()) {
7461   case ImplicitConversionSequence::StandardConversion:
7462     Candidate.FinalConversion = ICS.Standard;
7463 
7464     // C++ [over.ics.user]p3:
7465     //   If the user-defined conversion is specified by a specialization of a
7466     //   conversion function template, the second standard conversion sequence
7467     //   shall have exact match rank.
7468     if (Conversion->getPrimaryTemplate() &&
7469         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7470       Candidate.Viable = false;
7471       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7472       return;
7473     }
7474 
7475     // C++0x [dcl.init.ref]p5:
7476     //    In the second case, if the reference is an rvalue reference and
7477     //    the second standard conversion sequence of the user-defined
7478     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7479     //    program is ill-formed.
7480     if (ToType->isRValueReferenceType() &&
7481         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7482       Candidate.Viable = false;
7483       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7484       return;
7485     }
7486     break;
7487 
7488   case ImplicitConversionSequence::BadConversion:
7489     Candidate.Viable = false;
7490     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7491     return;
7492 
7493   default:
7494     llvm_unreachable(
7495            "Can only end up with a standard conversion sequence or failure");
7496   }
7497 
7498   if (EnableIfAttr *FailedAttr =
7499           CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7500     Candidate.Viable = false;
7501     Candidate.FailureKind = ovl_fail_enable_if;
7502     Candidate.DeductionFailure.Data = FailedAttr;
7503     return;
7504   }
7505 
7506   if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7507       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7508     Candidate.Viable = false;
7509     Candidate.FailureKind = ovl_non_default_multiversion_function;
7510   }
7511 }
7512 
7513 /// Adds a conversion function template specialization
7514 /// candidate to the overload set, using template argument deduction
7515 /// to deduce the template arguments of the conversion function
7516 /// template from the type that we are converting to (C++
7517 /// [temp.deduct.conv]).
7518 void Sema::AddTemplateConversionCandidate(
7519     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7520     CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7521     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7522     bool AllowExplicit, bool AllowResultConversion) {
7523   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7524          "Only conversion function templates permitted here");
7525 
7526   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7527     return;
7528 
7529   // If the function template has a non-dependent explicit specification,
7530   // exclude it now if appropriate; we are not permitted to perform deduction
7531   // and substitution in this case.
7532   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7533     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7534     Candidate.FoundDecl = FoundDecl;
7535     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7536     Candidate.Viable = false;
7537     Candidate.FailureKind = ovl_fail_explicit;
7538     return;
7539   }
7540 
7541   TemplateDeductionInfo Info(CandidateSet.getLocation());
7542   CXXConversionDecl *Specialization = nullptr;
7543   if (TemplateDeductionResult Result
7544         = DeduceTemplateArguments(FunctionTemplate, ToType,
7545                                   Specialization, Info)) {
7546     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7547     Candidate.FoundDecl = FoundDecl;
7548     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7549     Candidate.Viable = false;
7550     Candidate.FailureKind = ovl_fail_bad_deduction;
7551     Candidate.IsSurrogate = false;
7552     Candidate.IgnoreObjectArgument = false;
7553     Candidate.ExplicitCallArguments = 1;
7554     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7555                                                           Info);
7556     return;
7557   }
7558 
7559   // Add the conversion function template specialization produced by
7560   // template argument deduction as a candidate.
7561   assert(Specialization && "Missing function template specialization?");
7562   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7563                          CandidateSet, AllowObjCConversionOnExplicit,
7564                          AllowExplicit, AllowResultConversion);
7565 }
7566 
7567 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7568 /// converts the given @c Object to a function pointer via the
7569 /// conversion function @c Conversion, and then attempts to call it
7570 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7571 /// the type of function that we'll eventually be calling.
7572 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7573                                  DeclAccessPair FoundDecl,
7574                                  CXXRecordDecl *ActingContext,
7575                                  const FunctionProtoType *Proto,
7576                                  Expr *Object,
7577                                  ArrayRef<Expr *> Args,
7578                                  OverloadCandidateSet& CandidateSet) {
7579   if (!CandidateSet.isNewCandidate(Conversion))
7580     return;
7581 
7582   // Overload resolution is always an unevaluated context.
7583   EnterExpressionEvaluationContext Unevaluated(
7584       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7585 
7586   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7587   Candidate.FoundDecl = FoundDecl;
7588   Candidate.Function = nullptr;
7589   Candidate.Surrogate = Conversion;
7590   Candidate.Viable = true;
7591   Candidate.IsSurrogate = true;
7592   Candidate.IgnoreObjectArgument = false;
7593   Candidate.ExplicitCallArguments = Args.size();
7594 
7595   // Determine the implicit conversion sequence for the implicit
7596   // object parameter.
7597   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7598       *this, CandidateSet.getLocation(), Object->getType(),
7599       Object->Classify(Context), Conversion, ActingContext);
7600   if (ObjectInit.isBad()) {
7601     Candidate.Viable = false;
7602     Candidate.FailureKind = ovl_fail_bad_conversion;
7603     Candidate.Conversions[0] = ObjectInit;
7604     return;
7605   }
7606 
7607   // The first conversion is actually a user-defined conversion whose
7608   // first conversion is ObjectInit's standard conversion (which is
7609   // effectively a reference binding). Record it as such.
7610   Candidate.Conversions[0].setUserDefined();
7611   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7612   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7613   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7614   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7615   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7616   Candidate.Conversions[0].UserDefined.After
7617     = Candidate.Conversions[0].UserDefined.Before;
7618   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7619 
7620   // Find the
7621   unsigned NumParams = Proto->getNumParams();
7622 
7623   // (C++ 13.3.2p2): A candidate function having fewer than m
7624   // parameters is viable only if it has an ellipsis in its parameter
7625   // list (8.3.5).
7626   if (Args.size() > NumParams && !Proto->isVariadic()) {
7627     Candidate.Viable = false;
7628     Candidate.FailureKind = ovl_fail_too_many_arguments;
7629     return;
7630   }
7631 
7632   // Function types don't have any default arguments, so just check if
7633   // we have enough arguments.
7634   if (Args.size() < NumParams) {
7635     // Not enough arguments.
7636     Candidate.Viable = false;
7637     Candidate.FailureKind = ovl_fail_too_few_arguments;
7638     return;
7639   }
7640 
7641   // Determine the implicit conversion sequences for each of the
7642   // arguments.
7643   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7644     if (ArgIdx < NumParams) {
7645       // (C++ 13.3.2p3): for F to be a viable function, there shall
7646       // exist for each argument an implicit conversion sequence
7647       // (13.3.3.1) that converts that argument to the corresponding
7648       // parameter of F.
7649       QualType ParamType = Proto->getParamType(ArgIdx);
7650       Candidate.Conversions[ArgIdx + 1]
7651         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7652                                 /*SuppressUserConversions=*/false,
7653                                 /*InOverloadResolution=*/false,
7654                                 /*AllowObjCWritebackConversion=*/
7655                                   getLangOpts().ObjCAutoRefCount);
7656       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7657         Candidate.Viable = false;
7658         Candidate.FailureKind = ovl_fail_bad_conversion;
7659         return;
7660       }
7661     } else {
7662       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7663       // argument for which there is no corresponding parameter is
7664       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7665       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7666     }
7667   }
7668 
7669   if (EnableIfAttr *FailedAttr =
7670           CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7671     Candidate.Viable = false;
7672     Candidate.FailureKind = ovl_fail_enable_if;
7673     Candidate.DeductionFailure.Data = FailedAttr;
7674     return;
7675   }
7676 }
7677 
7678 /// Add all of the non-member operator function declarations in the given
7679 /// function set to the overload candidate set.
7680 void Sema::AddNonMemberOperatorCandidates(
7681     const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
7682     OverloadCandidateSet &CandidateSet,
7683     TemplateArgumentListInfo *ExplicitTemplateArgs) {
7684   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7685     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7686     ArrayRef<Expr *> FunctionArgs = Args;
7687 
7688     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7689     FunctionDecl *FD =
7690         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7691 
7692     // Don't consider rewritten functions if we're not rewriting.
7693     if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
7694       continue;
7695 
7696     assert(!isa<CXXMethodDecl>(FD) &&
7697            "unqualified operator lookup found a member function");
7698 
7699     if (FunTmpl) {
7700       AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
7701                                    FunctionArgs, CandidateSet);
7702       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7703         AddTemplateOverloadCandidate(
7704             FunTmpl, F.getPair(), ExplicitTemplateArgs,
7705             {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
7706             true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
7707     } else {
7708       if (ExplicitTemplateArgs)
7709         continue;
7710       AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
7711       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7712         AddOverloadCandidate(FD, F.getPair(),
7713                              {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
7714                              false, false, true, false, ADLCallKind::NotADL,
7715                              None, OverloadCandidateParamOrder::Reversed);
7716     }
7717   }
7718 }
7719 
7720 /// Add overload candidates for overloaded operators that are
7721 /// member functions.
7722 ///
7723 /// Add the overloaded operator candidates that are member functions
7724 /// for the operator Op that was used in an operator expression such
7725 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7726 /// CandidateSet will store the added overload candidates. (C++
7727 /// [over.match.oper]).
7728 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7729                                        SourceLocation OpLoc,
7730                                        ArrayRef<Expr *> Args,
7731                                        OverloadCandidateSet &CandidateSet,
7732                                        OverloadCandidateParamOrder PO) {
7733   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7734 
7735   // C++ [over.match.oper]p3:
7736   //   For a unary operator @ with an operand of a type whose
7737   //   cv-unqualified version is T1, and for a binary operator @ with
7738   //   a left operand of a type whose cv-unqualified version is T1 and
7739   //   a right operand of a type whose cv-unqualified version is T2,
7740   //   three sets of candidate functions, designated member
7741   //   candidates, non-member candidates and built-in candidates, are
7742   //   constructed as follows:
7743   QualType T1 = Args[0]->getType();
7744 
7745   //     -- If T1 is a complete class type or a class currently being
7746   //        defined, the set of member candidates is the result of the
7747   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7748   //        the set of member candidates is empty.
7749   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7750     // Complete the type if it can be completed.
7751     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7752       return;
7753     // If the type is neither complete nor being defined, bail out now.
7754     if (!T1Rec->getDecl()->getDefinition())
7755       return;
7756 
7757     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7758     LookupQualifiedName(Operators, T1Rec->getDecl());
7759     Operators.suppressDiagnostics();
7760 
7761     for (LookupResult::iterator Oper = Operators.begin(),
7762                              OperEnd = Operators.end();
7763          Oper != OperEnd;
7764          ++Oper)
7765       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7766                          Args[0]->Classify(Context), Args.slice(1),
7767                          CandidateSet, /*SuppressUserConversion=*/false, PO);
7768   }
7769 }
7770 
7771 /// AddBuiltinCandidate - Add a candidate for a built-in
7772 /// operator. ResultTy and ParamTys are the result and parameter types
7773 /// of the built-in candidate, respectively. Args and NumArgs are the
7774 /// arguments being passed to the candidate. IsAssignmentOperator
7775 /// should be true when this built-in candidate is an assignment
7776 /// operator. NumContextualBoolArguments is the number of arguments
7777 /// (at the beginning of the argument list) that will be contextually
7778 /// converted to bool.
7779 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7780                                OverloadCandidateSet& CandidateSet,
7781                                bool IsAssignmentOperator,
7782                                unsigned NumContextualBoolArguments) {
7783   // Overload resolution is always an unevaluated context.
7784   EnterExpressionEvaluationContext Unevaluated(
7785       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7786 
7787   // Add this candidate
7788   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7789   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7790   Candidate.Function = nullptr;
7791   Candidate.IsSurrogate = false;
7792   Candidate.IgnoreObjectArgument = false;
7793   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7794 
7795   // Determine the implicit conversion sequences for each of the
7796   // arguments.
7797   Candidate.Viable = true;
7798   Candidate.ExplicitCallArguments = Args.size();
7799   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7800     // C++ [over.match.oper]p4:
7801     //   For the built-in assignment operators, conversions of the
7802     //   left operand are restricted as follows:
7803     //     -- no temporaries are introduced to hold the left operand, and
7804     //     -- no user-defined conversions are applied to the left
7805     //        operand to achieve a type match with the left-most
7806     //        parameter of a built-in candidate.
7807     //
7808     // We block these conversions by turning off user-defined
7809     // conversions, since that is the only way that initialization of
7810     // a reference to a non-class type can occur from something that
7811     // is not of the same type.
7812     if (ArgIdx < NumContextualBoolArguments) {
7813       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7814              "Contextual conversion to bool requires bool type");
7815       Candidate.Conversions[ArgIdx]
7816         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7817     } else {
7818       Candidate.Conversions[ArgIdx]
7819         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7820                                 ArgIdx == 0 && IsAssignmentOperator,
7821                                 /*InOverloadResolution=*/false,
7822                                 /*AllowObjCWritebackConversion=*/
7823                                   getLangOpts().ObjCAutoRefCount);
7824     }
7825     if (Candidate.Conversions[ArgIdx].isBad()) {
7826       Candidate.Viable = false;
7827       Candidate.FailureKind = ovl_fail_bad_conversion;
7828       break;
7829     }
7830   }
7831 }
7832 
7833 namespace {
7834 
7835 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7836 /// candidate operator functions for built-in operators (C++
7837 /// [over.built]). The types are separated into pointer types and
7838 /// enumeration types.
7839 class BuiltinCandidateTypeSet  {
7840   /// TypeSet - A set of types.
7841   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7842                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7843 
7844   /// PointerTypes - The set of pointer types that will be used in the
7845   /// built-in candidates.
7846   TypeSet PointerTypes;
7847 
7848   /// MemberPointerTypes - The set of member pointer types that will be
7849   /// used in the built-in candidates.
7850   TypeSet MemberPointerTypes;
7851 
7852   /// EnumerationTypes - The set of enumeration types that will be
7853   /// used in the built-in candidates.
7854   TypeSet EnumerationTypes;
7855 
7856   /// The set of vector types that will be used in the built-in
7857   /// candidates.
7858   TypeSet VectorTypes;
7859 
7860   /// The set of matrix types that will be used in the built-in
7861   /// candidates.
7862   TypeSet MatrixTypes;
7863 
7864   /// A flag indicating non-record types are viable candidates
7865   bool HasNonRecordTypes;
7866 
7867   /// A flag indicating whether either arithmetic or enumeration types
7868   /// were present in the candidate set.
7869   bool HasArithmeticOrEnumeralTypes;
7870 
7871   /// A flag indicating whether the nullptr type was present in the
7872   /// candidate set.
7873   bool HasNullPtrType;
7874 
7875   /// Sema - The semantic analysis instance where we are building the
7876   /// candidate type set.
7877   Sema &SemaRef;
7878 
7879   /// Context - The AST context in which we will build the type sets.
7880   ASTContext &Context;
7881 
7882   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7883                                                const Qualifiers &VisibleQuals);
7884   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7885 
7886 public:
7887   /// iterator - Iterates through the types that are part of the set.
7888   typedef TypeSet::iterator iterator;
7889 
7890   BuiltinCandidateTypeSet(Sema &SemaRef)
7891     : HasNonRecordTypes(false),
7892       HasArithmeticOrEnumeralTypes(false),
7893       HasNullPtrType(false),
7894       SemaRef(SemaRef),
7895       Context(SemaRef.Context) { }
7896 
7897   void AddTypesConvertedFrom(QualType Ty,
7898                              SourceLocation Loc,
7899                              bool AllowUserConversions,
7900                              bool AllowExplicitConversions,
7901                              const Qualifiers &VisibleTypeConversionsQuals);
7902 
7903   llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
7904   llvm::iterator_range<iterator> member_pointer_types() {
7905     return MemberPointerTypes;
7906   }
7907   llvm::iterator_range<iterator> enumeration_types() {
7908     return EnumerationTypes;
7909   }
7910   llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
7911   llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
7912 
7913   bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
7914   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7915   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7916   bool hasNullPtrType() const { return HasNullPtrType; }
7917 };
7918 
7919 } // end anonymous namespace
7920 
7921 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7922 /// the set of pointer types along with any more-qualified variants of
7923 /// that type. For example, if @p Ty is "int const *", this routine
7924 /// will add "int const *", "int const volatile *", "int const
7925 /// restrict *", and "int const volatile restrict *" to the set of
7926 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7927 /// false otherwise.
7928 ///
7929 /// FIXME: what to do about extended qualifiers?
7930 bool
7931 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7932                                              const Qualifiers &VisibleQuals) {
7933 
7934   // Insert this type.
7935   if (!PointerTypes.insert(Ty))
7936     return false;
7937 
7938   QualType PointeeTy;
7939   const PointerType *PointerTy = Ty->getAs<PointerType>();
7940   bool buildObjCPtr = false;
7941   if (!PointerTy) {
7942     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7943     PointeeTy = PTy->getPointeeType();
7944     buildObjCPtr = true;
7945   } else {
7946     PointeeTy = PointerTy->getPointeeType();
7947   }
7948 
7949   // Don't add qualified variants of arrays. For one, they're not allowed
7950   // (the qualifier would sink to the element type), and for another, the
7951   // only overload situation where it matters is subscript or pointer +- int,
7952   // and those shouldn't have qualifier variants anyway.
7953   if (PointeeTy->isArrayType())
7954     return true;
7955 
7956   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7957   bool hasVolatile = VisibleQuals.hasVolatile();
7958   bool hasRestrict = VisibleQuals.hasRestrict();
7959 
7960   // Iterate through all strict supersets of BaseCVR.
7961   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7962     if ((CVR | BaseCVR) != CVR) continue;
7963     // Skip over volatile if no volatile found anywhere in the types.
7964     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7965 
7966     // Skip over restrict if no restrict found anywhere in the types, or if
7967     // the type cannot be restrict-qualified.
7968     if ((CVR & Qualifiers::Restrict) &&
7969         (!hasRestrict ||
7970          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7971       continue;
7972 
7973     // Build qualified pointee type.
7974     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7975 
7976     // Build qualified pointer type.
7977     QualType QPointerTy;
7978     if (!buildObjCPtr)
7979       QPointerTy = Context.getPointerType(QPointeeTy);
7980     else
7981       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7982 
7983     // Insert qualified pointer type.
7984     PointerTypes.insert(QPointerTy);
7985   }
7986 
7987   return true;
7988 }
7989 
7990 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7991 /// to the set of pointer types along with any more-qualified variants of
7992 /// that type. For example, if @p Ty is "int const *", this routine
7993 /// will add "int const *", "int const volatile *", "int const
7994 /// restrict *", and "int const volatile restrict *" to the set of
7995 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7996 /// false otherwise.
7997 ///
7998 /// FIXME: what to do about extended qualifiers?
7999 bool
8000 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8001     QualType Ty) {
8002   // Insert this type.
8003   if (!MemberPointerTypes.insert(Ty))
8004     return false;
8005 
8006   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8007   assert(PointerTy && "type was not a member pointer type!");
8008 
8009   QualType PointeeTy = PointerTy->getPointeeType();
8010   // Don't add qualified variants of arrays. For one, they're not allowed
8011   // (the qualifier would sink to the element type), and for another, the
8012   // only overload situation where it matters is subscript or pointer +- int,
8013   // and those shouldn't have qualifier variants anyway.
8014   if (PointeeTy->isArrayType())
8015     return true;
8016   const Type *ClassTy = PointerTy->getClass();
8017 
8018   // Iterate through all strict supersets of the pointee type's CVR
8019   // qualifiers.
8020   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8021   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8022     if ((CVR | BaseCVR) != CVR) continue;
8023 
8024     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8025     MemberPointerTypes.insert(
8026       Context.getMemberPointerType(QPointeeTy, ClassTy));
8027   }
8028 
8029   return true;
8030 }
8031 
8032 /// AddTypesConvertedFrom - Add each of the types to which the type @p
8033 /// Ty can be implicit converted to the given set of @p Types. We're
8034 /// primarily interested in pointer types and enumeration types. We also
8035 /// take member pointer types, for the conditional operator.
8036 /// AllowUserConversions is true if we should look at the conversion
8037 /// functions of a class type, and AllowExplicitConversions if we
8038 /// should also include the explicit conversion functions of a class
8039 /// type.
8040 void
8041 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
8042                                                SourceLocation Loc,
8043                                                bool AllowUserConversions,
8044                                                bool AllowExplicitConversions,
8045                                                const Qualifiers &VisibleQuals) {
8046   // Only deal with canonical types.
8047   Ty = Context.getCanonicalType(Ty);
8048 
8049   // Look through reference types; they aren't part of the type of an
8050   // expression for the purposes of conversions.
8051   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
8052     Ty = RefTy->getPointeeType();
8053 
8054   // If we're dealing with an array type, decay to the pointer.
8055   if (Ty->isArrayType())
8056     Ty = SemaRef.Context.getArrayDecayedType(Ty);
8057 
8058   // Otherwise, we don't care about qualifiers on the type.
8059   Ty = Ty.getLocalUnqualifiedType();
8060 
8061   // Flag if we ever add a non-record type.
8062   const RecordType *TyRec = Ty->getAs<RecordType>();
8063   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
8064 
8065   // Flag if we encounter an arithmetic type.
8066   HasArithmeticOrEnumeralTypes =
8067     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
8068 
8069   if (Ty->isObjCIdType() || Ty->isObjCClassType())
8070     PointerTypes.insert(Ty);
8071   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
8072     // Insert our type, and its more-qualified variants, into the set
8073     // of types.
8074     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
8075       return;
8076   } else if (Ty->isMemberPointerType()) {
8077     // Member pointers are far easier, since the pointee can't be converted.
8078     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
8079       return;
8080   } else if (Ty->isEnumeralType()) {
8081     HasArithmeticOrEnumeralTypes = true;
8082     EnumerationTypes.insert(Ty);
8083   } else if (Ty->isVectorType()) {
8084     // We treat vector types as arithmetic types in many contexts as an
8085     // extension.
8086     HasArithmeticOrEnumeralTypes = true;
8087     VectorTypes.insert(Ty);
8088   } else if (Ty->isMatrixType()) {
8089     // Similar to vector types, we treat vector types as arithmetic types in
8090     // many contexts as an extension.
8091     HasArithmeticOrEnumeralTypes = true;
8092     MatrixTypes.insert(Ty);
8093   } else if (Ty->isNullPtrType()) {
8094     HasNullPtrType = true;
8095   } else if (AllowUserConversions && TyRec) {
8096     // No conversion functions in incomplete types.
8097     if (!SemaRef.isCompleteType(Loc, Ty))
8098       return;
8099 
8100     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8101     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8102       if (isa<UsingShadowDecl>(D))
8103         D = cast<UsingShadowDecl>(D)->getTargetDecl();
8104 
8105       // Skip conversion function templates; they don't tell us anything
8106       // about which builtin types we can convert to.
8107       if (isa<FunctionTemplateDecl>(D))
8108         continue;
8109 
8110       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
8111       if (AllowExplicitConversions || !Conv->isExplicit()) {
8112         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
8113                               VisibleQuals);
8114       }
8115     }
8116   }
8117 }
8118 /// Helper function for adjusting address spaces for the pointer or reference
8119 /// operands of builtin operators depending on the argument.
8120 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
8121                                                         Expr *Arg) {
8122   return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
8123 }
8124 
8125 /// Helper function for AddBuiltinOperatorCandidates() that adds
8126 /// the volatile- and non-volatile-qualified assignment operators for the
8127 /// given type to the candidate set.
8128 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
8129                                                    QualType T,
8130                                                    ArrayRef<Expr *> Args,
8131                                     OverloadCandidateSet &CandidateSet) {
8132   QualType ParamTypes[2];
8133 
8134   // T& operator=(T&, T)
8135   ParamTypes[0] = S.Context.getLValueReferenceType(
8136       AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
8137   ParamTypes[1] = T;
8138   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8139                         /*IsAssignmentOperator=*/true);
8140 
8141   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
8142     // volatile T& operator=(volatile T&, T)
8143     ParamTypes[0] = S.Context.getLValueReferenceType(
8144         AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
8145                                                 Args[0]));
8146     ParamTypes[1] = T;
8147     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8148                           /*IsAssignmentOperator=*/true);
8149   }
8150 }
8151 
8152 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8153 /// if any, found in visible type conversion functions found in ArgExpr's type.
8154 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8155     Qualifiers VRQuals;
8156     const RecordType *TyRec;
8157     if (const MemberPointerType *RHSMPType =
8158         ArgExpr->getType()->getAs<MemberPointerType>())
8159       TyRec = RHSMPType->getClass()->getAs<RecordType>();
8160     else
8161       TyRec = ArgExpr->getType()->getAs<RecordType>();
8162     if (!TyRec) {
8163       // Just to be safe, assume the worst case.
8164       VRQuals.addVolatile();
8165       VRQuals.addRestrict();
8166       return VRQuals;
8167     }
8168 
8169     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8170     if (!ClassDecl->hasDefinition())
8171       return VRQuals;
8172 
8173     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8174       if (isa<UsingShadowDecl>(D))
8175         D = cast<UsingShadowDecl>(D)->getTargetDecl();
8176       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8177         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8178         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8179           CanTy = ResTypeRef->getPointeeType();
8180         // Need to go down the pointer/mempointer chain and add qualifiers
8181         // as see them.
8182         bool done = false;
8183         while (!done) {
8184           if (CanTy.isRestrictQualified())
8185             VRQuals.addRestrict();
8186           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8187             CanTy = ResTypePtr->getPointeeType();
8188           else if (const MemberPointerType *ResTypeMPtr =
8189                 CanTy->getAs<MemberPointerType>())
8190             CanTy = ResTypeMPtr->getPointeeType();
8191           else
8192             done = true;
8193           if (CanTy.isVolatileQualified())
8194             VRQuals.addVolatile();
8195           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8196             return VRQuals;
8197         }
8198       }
8199     }
8200     return VRQuals;
8201 }
8202 
8203 namespace {
8204 
8205 /// Helper class to manage the addition of builtin operator overload
8206 /// candidates. It provides shared state and utility methods used throughout
8207 /// the process, as well as a helper method to add each group of builtin
8208 /// operator overloads from the standard to a candidate set.
8209 class BuiltinOperatorOverloadBuilder {
8210   // Common instance state available to all overload candidate addition methods.
8211   Sema &S;
8212   ArrayRef<Expr *> Args;
8213   Qualifiers VisibleTypeConversionsQuals;
8214   bool HasArithmeticOrEnumeralCandidateType;
8215   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8216   OverloadCandidateSet &CandidateSet;
8217 
8218   static constexpr int ArithmeticTypesCap = 24;
8219   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8220 
8221   // Define some indices used to iterate over the arithmetic types in
8222   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
8223   // types are that preserved by promotion (C++ [over.built]p2).
8224   unsigned FirstIntegralType,
8225            LastIntegralType;
8226   unsigned FirstPromotedIntegralType,
8227            LastPromotedIntegralType;
8228   unsigned FirstPromotedArithmeticType,
8229            LastPromotedArithmeticType;
8230   unsigned NumArithmeticTypes;
8231 
8232   void InitArithmeticTypes() {
8233     // Start of promoted types.
8234     FirstPromotedArithmeticType = 0;
8235     ArithmeticTypes.push_back(S.Context.FloatTy);
8236     ArithmeticTypes.push_back(S.Context.DoubleTy);
8237     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8238     if (S.Context.getTargetInfo().hasFloat128Type())
8239       ArithmeticTypes.push_back(S.Context.Float128Ty);
8240     if (S.Context.getTargetInfo().hasIbm128Type())
8241       ArithmeticTypes.push_back(S.Context.Ibm128Ty);
8242 
8243     // Start of integral types.
8244     FirstIntegralType = ArithmeticTypes.size();
8245     FirstPromotedIntegralType = ArithmeticTypes.size();
8246     ArithmeticTypes.push_back(S.Context.IntTy);
8247     ArithmeticTypes.push_back(S.Context.LongTy);
8248     ArithmeticTypes.push_back(S.Context.LongLongTy);
8249     if (S.Context.getTargetInfo().hasInt128Type() ||
8250         (S.Context.getAuxTargetInfo() &&
8251          S.Context.getAuxTargetInfo()->hasInt128Type()))
8252       ArithmeticTypes.push_back(S.Context.Int128Ty);
8253     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8254     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8255     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8256     if (S.Context.getTargetInfo().hasInt128Type() ||
8257         (S.Context.getAuxTargetInfo() &&
8258          S.Context.getAuxTargetInfo()->hasInt128Type()))
8259       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8260     LastPromotedIntegralType = ArithmeticTypes.size();
8261     LastPromotedArithmeticType = ArithmeticTypes.size();
8262     // End of promoted types.
8263 
8264     ArithmeticTypes.push_back(S.Context.BoolTy);
8265     ArithmeticTypes.push_back(S.Context.CharTy);
8266     ArithmeticTypes.push_back(S.Context.WCharTy);
8267     if (S.Context.getLangOpts().Char8)
8268       ArithmeticTypes.push_back(S.Context.Char8Ty);
8269     ArithmeticTypes.push_back(S.Context.Char16Ty);
8270     ArithmeticTypes.push_back(S.Context.Char32Ty);
8271     ArithmeticTypes.push_back(S.Context.SignedCharTy);
8272     ArithmeticTypes.push_back(S.Context.ShortTy);
8273     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8274     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8275     LastIntegralType = ArithmeticTypes.size();
8276     NumArithmeticTypes = ArithmeticTypes.size();
8277     // End of integral types.
8278     // FIXME: What about complex? What about half?
8279 
8280     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
8281            "Enough inline storage for all arithmetic types.");
8282   }
8283 
8284   /// Helper method to factor out the common pattern of adding overloads
8285   /// for '++' and '--' builtin operators.
8286   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8287                                            bool HasVolatile,
8288                                            bool HasRestrict) {
8289     QualType ParamTypes[2] = {
8290       S.Context.getLValueReferenceType(CandidateTy),
8291       S.Context.IntTy
8292     };
8293 
8294     // Non-volatile version.
8295     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8296 
8297     // Use a heuristic to reduce number of builtin candidates in the set:
8298     // add volatile version only if there are conversions to a volatile type.
8299     if (HasVolatile) {
8300       ParamTypes[0] =
8301         S.Context.getLValueReferenceType(
8302           S.Context.getVolatileType(CandidateTy));
8303       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8304     }
8305 
8306     // Add restrict version only if there are conversions to a restrict type
8307     // and our candidate type is a non-restrict-qualified pointer.
8308     if (HasRestrict && CandidateTy->isAnyPointerType() &&
8309         !CandidateTy.isRestrictQualified()) {
8310       ParamTypes[0]
8311         = S.Context.getLValueReferenceType(
8312             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8313       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8314 
8315       if (HasVolatile) {
8316         ParamTypes[0]
8317           = S.Context.getLValueReferenceType(
8318               S.Context.getCVRQualifiedType(CandidateTy,
8319                                             (Qualifiers::Volatile |
8320                                              Qualifiers::Restrict)));
8321         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8322       }
8323     }
8324 
8325   }
8326 
8327   /// Helper to add an overload candidate for a binary builtin with types \p L
8328   /// and \p R.
8329   void AddCandidate(QualType L, QualType R) {
8330     QualType LandR[2] = {L, R};
8331     S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8332   }
8333 
8334 public:
8335   BuiltinOperatorOverloadBuilder(
8336     Sema &S, ArrayRef<Expr *> Args,
8337     Qualifiers VisibleTypeConversionsQuals,
8338     bool HasArithmeticOrEnumeralCandidateType,
8339     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8340     OverloadCandidateSet &CandidateSet)
8341     : S(S), Args(Args),
8342       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8343       HasArithmeticOrEnumeralCandidateType(
8344         HasArithmeticOrEnumeralCandidateType),
8345       CandidateTypes(CandidateTypes),
8346       CandidateSet(CandidateSet) {
8347 
8348     InitArithmeticTypes();
8349   }
8350 
8351   // Increment is deprecated for bool since C++17.
8352   //
8353   // C++ [over.built]p3:
8354   //
8355   //   For every pair (T, VQ), where T is an arithmetic type other
8356   //   than bool, and VQ is either volatile or empty, there exist
8357   //   candidate operator functions of the form
8358   //
8359   //       VQ T&      operator++(VQ T&);
8360   //       T          operator++(VQ T&, int);
8361   //
8362   // C++ [over.built]p4:
8363   //
8364   //   For every pair (T, VQ), where T is an arithmetic type other
8365   //   than bool, and VQ is either volatile or empty, there exist
8366   //   candidate operator functions of the form
8367   //
8368   //       VQ T&      operator--(VQ T&);
8369   //       T          operator--(VQ T&, int);
8370   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8371     if (!HasArithmeticOrEnumeralCandidateType)
8372       return;
8373 
8374     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8375       const auto TypeOfT = ArithmeticTypes[Arith];
8376       if (TypeOfT == S.Context.BoolTy) {
8377         if (Op == OO_MinusMinus)
8378           continue;
8379         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8380           continue;
8381       }
8382       addPlusPlusMinusMinusStyleOverloads(
8383         TypeOfT,
8384         VisibleTypeConversionsQuals.hasVolatile(),
8385         VisibleTypeConversionsQuals.hasRestrict());
8386     }
8387   }
8388 
8389   // C++ [over.built]p5:
8390   //
8391   //   For every pair (T, VQ), where T is a cv-qualified or
8392   //   cv-unqualified object type, and VQ is either volatile or
8393   //   empty, there exist candidate operator functions of the form
8394   //
8395   //       T*VQ&      operator++(T*VQ&);
8396   //       T*VQ&      operator--(T*VQ&);
8397   //       T*         operator++(T*VQ&, int);
8398   //       T*         operator--(T*VQ&, int);
8399   void addPlusPlusMinusMinusPointerOverloads() {
8400     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
8401       // Skip pointer types that aren't pointers to object types.
8402       if (!PtrTy->getPointeeType()->isObjectType())
8403         continue;
8404 
8405       addPlusPlusMinusMinusStyleOverloads(
8406           PtrTy,
8407           (!PtrTy.isVolatileQualified() &&
8408            VisibleTypeConversionsQuals.hasVolatile()),
8409           (!PtrTy.isRestrictQualified() &&
8410            VisibleTypeConversionsQuals.hasRestrict()));
8411     }
8412   }
8413 
8414   // C++ [over.built]p6:
8415   //   For every cv-qualified or cv-unqualified object type T, there
8416   //   exist candidate operator functions of the form
8417   //
8418   //       T&         operator*(T*);
8419   //
8420   // C++ [over.built]p7:
8421   //   For every function type T that does not have cv-qualifiers or a
8422   //   ref-qualifier, there exist candidate operator functions of the form
8423   //       T&         operator*(T*);
8424   void addUnaryStarPointerOverloads() {
8425     for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
8426       QualType PointeeTy = ParamTy->getPointeeType();
8427       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8428         continue;
8429 
8430       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8431         if (Proto->getMethodQuals() || Proto->getRefQualifier())
8432           continue;
8433 
8434       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8435     }
8436   }
8437 
8438   // C++ [over.built]p9:
8439   //  For every promoted arithmetic type T, there exist candidate
8440   //  operator functions of the form
8441   //
8442   //       T         operator+(T);
8443   //       T         operator-(T);
8444   void addUnaryPlusOrMinusArithmeticOverloads() {
8445     if (!HasArithmeticOrEnumeralCandidateType)
8446       return;
8447 
8448     for (unsigned Arith = FirstPromotedArithmeticType;
8449          Arith < LastPromotedArithmeticType; ++Arith) {
8450       QualType ArithTy = ArithmeticTypes[Arith];
8451       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8452     }
8453 
8454     // Extension: We also add these operators for vector types.
8455     for (QualType VecTy : CandidateTypes[0].vector_types())
8456       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8457   }
8458 
8459   // C++ [over.built]p8:
8460   //   For every type T, there exist candidate operator functions of
8461   //   the form
8462   //
8463   //       T*         operator+(T*);
8464   void addUnaryPlusPointerOverloads() {
8465     for (QualType ParamTy : CandidateTypes[0].pointer_types())
8466       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8467   }
8468 
8469   // C++ [over.built]p10:
8470   //   For every promoted integral type T, there exist candidate
8471   //   operator functions of the form
8472   //
8473   //        T         operator~(T);
8474   void addUnaryTildePromotedIntegralOverloads() {
8475     if (!HasArithmeticOrEnumeralCandidateType)
8476       return;
8477 
8478     for (unsigned Int = FirstPromotedIntegralType;
8479          Int < LastPromotedIntegralType; ++Int) {
8480       QualType IntTy = ArithmeticTypes[Int];
8481       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8482     }
8483 
8484     // Extension: We also add this operator for vector types.
8485     for (QualType VecTy : CandidateTypes[0].vector_types())
8486       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8487   }
8488 
8489   // C++ [over.match.oper]p16:
8490   //   For every pointer to member type T or type std::nullptr_t, there
8491   //   exist candidate operator functions of the form
8492   //
8493   //        bool operator==(T,T);
8494   //        bool operator!=(T,T);
8495   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8496     /// Set of (canonical) types that we've already handled.
8497     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8498 
8499     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8500       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
8501         // Don't add the same builtin candidate twice.
8502         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
8503           continue;
8504 
8505         QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
8506         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8507       }
8508 
8509       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8510         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8511         if (AddedTypes.insert(NullPtrTy).second) {
8512           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8513           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8514         }
8515       }
8516     }
8517   }
8518 
8519   // C++ [over.built]p15:
8520   //
8521   //   For every T, where T is an enumeration type or a pointer type,
8522   //   there exist candidate operator functions of the form
8523   //
8524   //        bool       operator<(T, T);
8525   //        bool       operator>(T, T);
8526   //        bool       operator<=(T, T);
8527   //        bool       operator>=(T, T);
8528   //        bool       operator==(T, T);
8529   //        bool       operator!=(T, T);
8530   //           R       operator<=>(T, T)
8531   void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
8532     // C++ [over.match.oper]p3:
8533     //   [...]the built-in candidates include all of the candidate operator
8534     //   functions defined in 13.6 that, compared to the given operator, [...]
8535     //   do not have the same parameter-type-list as any non-template non-member
8536     //   candidate.
8537     //
8538     // Note that in practice, this only affects enumeration types because there
8539     // aren't any built-in candidates of record type, and a user-defined operator
8540     // must have an operand of record or enumeration type. Also, the only other
8541     // overloaded operator with enumeration arguments, operator=,
8542     // cannot be overloaded for enumeration types, so this is the only place
8543     // where we must suppress candidates like this.
8544     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8545       UserDefinedBinaryOperators;
8546 
8547     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8548       if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
8549         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8550                                          CEnd = CandidateSet.end();
8551              C != CEnd; ++C) {
8552           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8553             continue;
8554 
8555           if (C->Function->isFunctionTemplateSpecialization())
8556             continue;
8557 
8558           // We interpret "same parameter-type-list" as applying to the
8559           // "synthesized candidate, with the order of the two parameters
8560           // reversed", not to the original function.
8561           bool Reversed = C->isReversed();
8562           QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
8563                                         ->getType()
8564                                         .getUnqualifiedType();
8565           QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
8566                                          ->getType()
8567                                          .getUnqualifiedType();
8568 
8569           // Skip if either parameter isn't of enumeral type.
8570           if (!FirstParamType->isEnumeralType() ||
8571               !SecondParamType->isEnumeralType())
8572             continue;
8573 
8574           // Add this operator to the set of known user-defined operators.
8575           UserDefinedBinaryOperators.insert(
8576             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8577                            S.Context.getCanonicalType(SecondParamType)));
8578         }
8579       }
8580     }
8581 
8582     /// Set of (canonical) types that we've already handled.
8583     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8584 
8585     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8586       for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
8587         // Don't add the same builtin candidate twice.
8588         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8589           continue;
8590         if (IsSpaceship && PtrTy->isFunctionPointerType())
8591           continue;
8592 
8593         QualType ParamTypes[2] = {PtrTy, PtrTy};
8594         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8595       }
8596       for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
8597         CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
8598 
8599         // Don't add the same builtin candidate twice, or if a user defined
8600         // candidate exists.
8601         if (!AddedTypes.insert(CanonType).second ||
8602             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8603                                                             CanonType)))
8604           continue;
8605         QualType ParamTypes[2] = {EnumTy, EnumTy};
8606         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8607       }
8608     }
8609   }
8610 
8611   // C++ [over.built]p13:
8612   //
8613   //   For every cv-qualified or cv-unqualified object type T
8614   //   there exist candidate operator functions of the form
8615   //
8616   //      T*         operator+(T*, ptrdiff_t);
8617   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8618   //      T*         operator-(T*, ptrdiff_t);
8619   //      T*         operator+(ptrdiff_t, T*);
8620   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8621   //
8622   // C++ [over.built]p14:
8623   //
8624   //   For every T, where T is a pointer to object type, there
8625   //   exist candidate operator functions of the form
8626   //
8627   //      ptrdiff_t  operator-(T, T);
8628   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8629     /// Set of (canonical) types that we've already handled.
8630     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8631 
8632     for (int Arg = 0; Arg < 2; ++Arg) {
8633       QualType AsymmetricParamTypes[2] = {
8634         S.Context.getPointerDiffType(),
8635         S.Context.getPointerDiffType(),
8636       };
8637       for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
8638         QualType PointeeTy = PtrTy->getPointeeType();
8639         if (!PointeeTy->isObjectType())
8640           continue;
8641 
8642         AsymmetricParamTypes[Arg] = PtrTy;
8643         if (Arg == 0 || Op == OO_Plus) {
8644           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8645           // T* operator+(ptrdiff_t, T*);
8646           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8647         }
8648         if (Op == OO_Minus) {
8649           // ptrdiff_t operator-(T, T);
8650           if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8651             continue;
8652 
8653           QualType ParamTypes[2] = {PtrTy, PtrTy};
8654           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8655         }
8656       }
8657     }
8658   }
8659 
8660   // C++ [over.built]p12:
8661   //
8662   //   For every pair of promoted arithmetic types L and R, there
8663   //   exist candidate operator functions of the form
8664   //
8665   //        LR         operator*(L, R);
8666   //        LR         operator/(L, R);
8667   //        LR         operator+(L, R);
8668   //        LR         operator-(L, R);
8669   //        bool       operator<(L, R);
8670   //        bool       operator>(L, R);
8671   //        bool       operator<=(L, R);
8672   //        bool       operator>=(L, R);
8673   //        bool       operator==(L, R);
8674   //        bool       operator!=(L, R);
8675   //
8676   //   where LR is the result of the usual arithmetic conversions
8677   //   between types L and R.
8678   //
8679   // C++ [over.built]p24:
8680   //
8681   //   For every pair of promoted arithmetic types L and R, there exist
8682   //   candidate operator functions of the form
8683   //
8684   //        LR       operator?(bool, L, R);
8685   //
8686   //   where LR is the result of the usual arithmetic conversions
8687   //   between types L and R.
8688   // Our candidates ignore the first parameter.
8689   void addGenericBinaryArithmeticOverloads() {
8690     if (!HasArithmeticOrEnumeralCandidateType)
8691       return;
8692 
8693     for (unsigned Left = FirstPromotedArithmeticType;
8694          Left < LastPromotedArithmeticType; ++Left) {
8695       for (unsigned Right = FirstPromotedArithmeticType;
8696            Right < LastPromotedArithmeticType; ++Right) {
8697         QualType LandR[2] = { ArithmeticTypes[Left],
8698                               ArithmeticTypes[Right] };
8699         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8700       }
8701     }
8702 
8703     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8704     // conditional operator for vector types.
8705     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8706       for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
8707         QualType LandR[2] = {Vec1Ty, Vec2Ty};
8708         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8709       }
8710   }
8711 
8712   /// Add binary operator overloads for each candidate matrix type M1, M2:
8713   ///  * (M1, M1) -> M1
8714   ///  * (M1, M1.getElementType()) -> M1
8715   ///  * (M2.getElementType(), M2) -> M2
8716   ///  * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
8717   void addMatrixBinaryArithmeticOverloads() {
8718     if (!HasArithmeticOrEnumeralCandidateType)
8719       return;
8720 
8721     for (QualType M1 : CandidateTypes[0].matrix_types()) {
8722       AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
8723       AddCandidate(M1, M1);
8724     }
8725 
8726     for (QualType M2 : CandidateTypes[1].matrix_types()) {
8727       AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
8728       if (!CandidateTypes[0].containsMatrixType(M2))
8729         AddCandidate(M2, M2);
8730     }
8731   }
8732 
8733   // C++2a [over.built]p14:
8734   //
8735   //   For every integral type T there exists a candidate operator function
8736   //   of the form
8737   //
8738   //        std::strong_ordering operator<=>(T, T)
8739   //
8740   // C++2a [over.built]p15:
8741   //
8742   //   For every pair of floating-point types L and R, there exists a candidate
8743   //   operator function of the form
8744   //
8745   //       std::partial_ordering operator<=>(L, R);
8746   //
8747   // FIXME: The current specification for integral types doesn't play nice with
8748   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8749   // comparisons. Under the current spec this can lead to ambiguity during
8750   // overload resolution. For example:
8751   //
8752   //   enum A : int {a};
8753   //   auto x = (a <=> (long)42);
8754   //
8755   //   error: call is ambiguous for arguments 'A' and 'long'.
8756   //   note: candidate operator<=>(int, int)
8757   //   note: candidate operator<=>(long, long)
8758   //
8759   // To avoid this error, this function deviates from the specification and adds
8760   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8761   // arithmetic types (the same as the generic relational overloads).
8762   //
8763   // For now this function acts as a placeholder.
8764   void addThreeWayArithmeticOverloads() {
8765     addGenericBinaryArithmeticOverloads();
8766   }
8767 
8768   // C++ [over.built]p17:
8769   //
8770   //   For every pair of promoted integral types L and R, there
8771   //   exist candidate operator functions of the form
8772   //
8773   //      LR         operator%(L, R);
8774   //      LR         operator&(L, R);
8775   //      LR         operator^(L, R);
8776   //      LR         operator|(L, R);
8777   //      L          operator<<(L, R);
8778   //      L          operator>>(L, R);
8779   //
8780   //   where LR is the result of the usual arithmetic conversions
8781   //   between types L and R.
8782   void addBinaryBitwiseArithmeticOverloads() {
8783     if (!HasArithmeticOrEnumeralCandidateType)
8784       return;
8785 
8786     for (unsigned Left = FirstPromotedIntegralType;
8787          Left < LastPromotedIntegralType; ++Left) {
8788       for (unsigned Right = FirstPromotedIntegralType;
8789            Right < LastPromotedIntegralType; ++Right) {
8790         QualType LandR[2] = { ArithmeticTypes[Left],
8791                               ArithmeticTypes[Right] };
8792         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8793       }
8794     }
8795   }
8796 
8797   // C++ [over.built]p20:
8798   //
8799   //   For every pair (T, VQ), where T is an enumeration or
8800   //   pointer to member type and VQ is either volatile or
8801   //   empty, there exist candidate operator functions of the form
8802   //
8803   //        VQ T&      operator=(VQ T&, T);
8804   void addAssignmentMemberPointerOrEnumeralOverloads() {
8805     /// Set of (canonical) types that we've already handled.
8806     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8807 
8808     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8809       for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
8810         if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
8811           continue;
8812 
8813         AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
8814       }
8815 
8816       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
8817         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
8818           continue;
8819 
8820         AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
8821       }
8822     }
8823   }
8824 
8825   // C++ [over.built]p19:
8826   //
8827   //   For every pair (T, VQ), where T is any type and VQ is either
8828   //   volatile or empty, there exist candidate operator functions
8829   //   of the form
8830   //
8831   //        T*VQ&      operator=(T*VQ&, T*);
8832   //
8833   // C++ [over.built]p21:
8834   //
8835   //   For every pair (T, VQ), where T is a cv-qualified or
8836   //   cv-unqualified object type and VQ is either volatile or
8837   //   empty, there exist candidate operator functions of the form
8838   //
8839   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8840   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8841   void addAssignmentPointerOverloads(bool isEqualOp) {
8842     /// Set of (canonical) types that we've already handled.
8843     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8844 
8845     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
8846       // If this is operator=, keep track of the builtin candidates we added.
8847       if (isEqualOp)
8848         AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
8849       else if (!PtrTy->getPointeeType()->isObjectType())
8850         continue;
8851 
8852       // non-volatile version
8853       QualType ParamTypes[2] = {
8854           S.Context.getLValueReferenceType(PtrTy),
8855           isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
8856       };
8857       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8858                             /*IsAssignmentOperator=*/ isEqualOp);
8859 
8860       bool NeedVolatile = !PtrTy.isVolatileQualified() &&
8861                           VisibleTypeConversionsQuals.hasVolatile();
8862       if (NeedVolatile) {
8863         // volatile version
8864         ParamTypes[0] =
8865             S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy));
8866         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8867                               /*IsAssignmentOperator=*/isEqualOp);
8868       }
8869 
8870       if (!PtrTy.isRestrictQualified() &&
8871           VisibleTypeConversionsQuals.hasRestrict()) {
8872         // restrict version
8873         ParamTypes[0] =
8874             S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy));
8875         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8876                               /*IsAssignmentOperator=*/isEqualOp);
8877 
8878         if (NeedVolatile) {
8879           // volatile restrict version
8880           ParamTypes[0] =
8881               S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
8882                   PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
8883           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8884                                 /*IsAssignmentOperator=*/isEqualOp);
8885         }
8886       }
8887     }
8888 
8889     if (isEqualOp) {
8890       for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
8891         // Make sure we don't add the same candidate twice.
8892         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8893           continue;
8894 
8895         QualType ParamTypes[2] = {
8896             S.Context.getLValueReferenceType(PtrTy),
8897             PtrTy,
8898         };
8899 
8900         // non-volatile version
8901         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8902                               /*IsAssignmentOperator=*/true);
8903 
8904         bool NeedVolatile = !PtrTy.isVolatileQualified() &&
8905                             VisibleTypeConversionsQuals.hasVolatile();
8906         if (NeedVolatile) {
8907           // volatile version
8908           ParamTypes[0] = S.Context.getLValueReferenceType(
8909               S.Context.getVolatileType(PtrTy));
8910           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8911                                 /*IsAssignmentOperator=*/true);
8912         }
8913 
8914         if (!PtrTy.isRestrictQualified() &&
8915             VisibleTypeConversionsQuals.hasRestrict()) {
8916           // restrict version
8917           ParamTypes[0] = S.Context.getLValueReferenceType(
8918               S.Context.getRestrictType(PtrTy));
8919           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8920                                 /*IsAssignmentOperator=*/true);
8921 
8922           if (NeedVolatile) {
8923             // volatile restrict version
8924             ParamTypes[0] =
8925                 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
8926                     PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
8927             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8928                                   /*IsAssignmentOperator=*/true);
8929           }
8930         }
8931       }
8932     }
8933   }
8934 
8935   // C++ [over.built]p18:
8936   //
8937   //   For every triple (L, VQ, R), where L is an arithmetic type,
8938   //   VQ is either volatile or empty, and R is a promoted
8939   //   arithmetic type, there exist candidate operator functions of
8940   //   the form
8941   //
8942   //        VQ L&      operator=(VQ L&, R);
8943   //        VQ L&      operator*=(VQ L&, R);
8944   //        VQ L&      operator/=(VQ L&, R);
8945   //        VQ L&      operator+=(VQ L&, R);
8946   //        VQ L&      operator-=(VQ L&, R);
8947   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8948     if (!HasArithmeticOrEnumeralCandidateType)
8949       return;
8950 
8951     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8952       for (unsigned Right = FirstPromotedArithmeticType;
8953            Right < LastPromotedArithmeticType; ++Right) {
8954         QualType ParamTypes[2];
8955         ParamTypes[1] = ArithmeticTypes[Right];
8956         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8957             S, ArithmeticTypes[Left], Args[0]);
8958         // Add this built-in operator as a candidate (VQ is empty).
8959         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8960         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8961                               /*IsAssignmentOperator=*/isEqualOp);
8962 
8963         // Add this built-in operator as a candidate (VQ is 'volatile').
8964         if (VisibleTypeConversionsQuals.hasVolatile()) {
8965           ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy);
8966           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8967           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8968                                 /*IsAssignmentOperator=*/isEqualOp);
8969         }
8970       }
8971     }
8972 
8973     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8974     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8975       for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
8976         QualType ParamTypes[2];
8977         ParamTypes[1] = Vec2Ty;
8978         // Add this built-in operator as a candidate (VQ is empty).
8979         ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
8980         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8981                               /*IsAssignmentOperator=*/isEqualOp);
8982 
8983         // Add this built-in operator as a candidate (VQ is 'volatile').
8984         if (VisibleTypeConversionsQuals.hasVolatile()) {
8985           ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
8986           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8987           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8988                                 /*IsAssignmentOperator=*/isEqualOp);
8989         }
8990       }
8991   }
8992 
8993   // C++ [over.built]p22:
8994   //
8995   //   For every triple (L, VQ, R), where L is an integral type, VQ
8996   //   is either volatile or empty, and R is a promoted integral
8997   //   type, there exist candidate operator functions of the form
8998   //
8999   //        VQ L&       operator%=(VQ L&, R);
9000   //        VQ L&       operator<<=(VQ L&, R);
9001   //        VQ L&       operator>>=(VQ L&, R);
9002   //        VQ L&       operator&=(VQ L&, R);
9003   //        VQ L&       operator^=(VQ L&, R);
9004   //        VQ L&       operator|=(VQ L&, R);
9005   void addAssignmentIntegralOverloads() {
9006     if (!HasArithmeticOrEnumeralCandidateType)
9007       return;
9008 
9009     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
9010       for (unsigned Right = FirstPromotedIntegralType;
9011            Right < LastPromotedIntegralType; ++Right) {
9012         QualType ParamTypes[2];
9013         ParamTypes[1] = ArithmeticTypes[Right];
9014         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
9015             S, ArithmeticTypes[Left], Args[0]);
9016         // Add this built-in operator as a candidate (VQ is empty).
9017         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
9018         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9019         if (VisibleTypeConversionsQuals.hasVolatile()) {
9020           // Add this built-in operator as a candidate (VQ is 'volatile').
9021           ParamTypes[0] = LeftBaseTy;
9022           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
9023           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
9024           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9025         }
9026       }
9027     }
9028   }
9029 
9030   // C++ [over.operator]p23:
9031   //
9032   //   There also exist candidate operator functions of the form
9033   //
9034   //        bool        operator!(bool);
9035   //        bool        operator&&(bool, bool);
9036   //        bool        operator||(bool, bool);
9037   void addExclaimOverload() {
9038     QualType ParamTy = S.Context.BoolTy;
9039     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
9040                           /*IsAssignmentOperator=*/false,
9041                           /*NumContextualBoolArguments=*/1);
9042   }
9043   void addAmpAmpOrPipePipeOverload() {
9044     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
9045     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9046                           /*IsAssignmentOperator=*/false,
9047                           /*NumContextualBoolArguments=*/2);
9048   }
9049 
9050   // C++ [over.built]p13:
9051   //
9052   //   For every cv-qualified or cv-unqualified object type T there
9053   //   exist candidate operator functions of the form
9054   //
9055   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
9056   //        T&         operator[](T*, ptrdiff_t);
9057   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
9058   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
9059   //        T&         operator[](ptrdiff_t, T*);
9060   void addSubscriptOverloads() {
9061     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9062       QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
9063       QualType PointeeType = PtrTy->getPointeeType();
9064       if (!PointeeType->isObjectType())
9065         continue;
9066 
9067       // T& operator[](T*, ptrdiff_t)
9068       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9069     }
9070 
9071     for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9072       QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
9073       QualType PointeeType = PtrTy->getPointeeType();
9074       if (!PointeeType->isObjectType())
9075         continue;
9076 
9077       // T& operator[](ptrdiff_t, T*)
9078       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9079     }
9080   }
9081 
9082   // C++ [over.built]p11:
9083   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9084   //    C1 is the same type as C2 or is a derived class of C2, T is an object
9085   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9086   //    there exist candidate operator functions of the form
9087   //
9088   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9089   //
9090   //    where CV12 is the union of CV1 and CV2.
9091   void addArrowStarOverloads() {
9092     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9093       QualType C1Ty = PtrTy;
9094       QualType C1;
9095       QualifierCollector Q1;
9096       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
9097       if (!isa<RecordType>(C1))
9098         continue;
9099       // heuristic to reduce number of builtin candidates in the set.
9100       // Add volatile/restrict version only if there are conversions to a
9101       // volatile/restrict type.
9102       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9103         continue;
9104       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9105         continue;
9106       for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
9107         const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
9108         QualType C2 = QualType(mptr->getClass(), 0);
9109         C2 = C2.getUnqualifiedType();
9110         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9111           break;
9112         QualType ParamTypes[2] = {PtrTy, MemPtrTy};
9113         // build CV12 T&
9114         QualType T = mptr->getPointeeType();
9115         if (!VisibleTypeConversionsQuals.hasVolatile() &&
9116             T.isVolatileQualified())
9117           continue;
9118         if (!VisibleTypeConversionsQuals.hasRestrict() &&
9119             T.isRestrictQualified())
9120           continue;
9121         T = Q1.apply(S.Context, T);
9122         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9123       }
9124     }
9125   }
9126 
9127   // Note that we don't consider the first argument, since it has been
9128   // contextually converted to bool long ago. The candidates below are
9129   // therefore added as binary.
9130   //
9131   // C++ [over.built]p25:
9132   //   For every type T, where T is a pointer, pointer-to-member, or scoped
9133   //   enumeration type, there exist candidate operator functions of the form
9134   //
9135   //        T        operator?(bool, T, T);
9136   //
9137   void addConditionalOperatorOverloads() {
9138     /// Set of (canonical) types that we've already handled.
9139     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9140 
9141     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9142       for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9143         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9144           continue;
9145 
9146         QualType ParamTypes[2] = {PtrTy, PtrTy};
9147         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9148       }
9149 
9150       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9151         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9152           continue;
9153 
9154         QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9155         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9156       }
9157 
9158       if (S.getLangOpts().CPlusPlus11) {
9159         for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9160           if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
9161             continue;
9162 
9163           if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9164             continue;
9165 
9166           QualType ParamTypes[2] = {EnumTy, EnumTy};
9167           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9168         }
9169       }
9170     }
9171   }
9172 };
9173 
9174 } // end anonymous namespace
9175 
9176 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
9177 /// operator overloads to the candidate set (C++ [over.built]), based
9178 /// on the operator @p Op and the arguments given. For example, if the
9179 /// operator is a binary '+', this routine might add "int
9180 /// operator+(int, int)" to cover integer addition.
9181 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9182                                         SourceLocation OpLoc,
9183                                         ArrayRef<Expr *> Args,
9184                                         OverloadCandidateSet &CandidateSet) {
9185   // Find all of the types that the arguments can convert to, but only
9186   // if the operator we're looking at has built-in operator candidates
9187   // that make use of these types. Also record whether we encounter non-record
9188   // candidate types or either arithmetic or enumeral candidate types.
9189   Qualifiers VisibleTypeConversionsQuals;
9190   VisibleTypeConversionsQuals.addConst();
9191   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
9192     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9193 
9194   bool HasNonRecordCandidateType = false;
9195   bool HasArithmeticOrEnumeralCandidateType = false;
9196   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9197   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9198     CandidateTypes.emplace_back(*this);
9199     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9200                                                  OpLoc,
9201                                                  true,
9202                                                  (Op == OO_Exclaim ||
9203                                                   Op == OO_AmpAmp ||
9204                                                   Op == OO_PipePipe),
9205                                                  VisibleTypeConversionsQuals);
9206     HasNonRecordCandidateType = HasNonRecordCandidateType ||
9207         CandidateTypes[ArgIdx].hasNonRecordTypes();
9208     HasArithmeticOrEnumeralCandidateType =
9209         HasArithmeticOrEnumeralCandidateType ||
9210         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9211   }
9212 
9213   // Exit early when no non-record types have been added to the candidate set
9214   // for any of the arguments to the operator.
9215   //
9216   // We can't exit early for !, ||, or &&, since there we have always have
9217   // 'bool' overloads.
9218   if (!HasNonRecordCandidateType &&
9219       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9220     return;
9221 
9222   // Setup an object to manage the common state for building overloads.
9223   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9224                                            VisibleTypeConversionsQuals,
9225                                            HasArithmeticOrEnumeralCandidateType,
9226                                            CandidateTypes, CandidateSet);
9227 
9228   // Dispatch over the operation to add in only those overloads which apply.
9229   switch (Op) {
9230   case OO_None:
9231   case NUM_OVERLOADED_OPERATORS:
9232     llvm_unreachable("Expected an overloaded operator");
9233 
9234   case OO_New:
9235   case OO_Delete:
9236   case OO_Array_New:
9237   case OO_Array_Delete:
9238   case OO_Call:
9239     llvm_unreachable(
9240                     "Special operators don't use AddBuiltinOperatorCandidates");
9241 
9242   case OO_Comma:
9243   case OO_Arrow:
9244   case OO_Coawait:
9245     // C++ [over.match.oper]p3:
9246     //   -- For the operator ',', the unary operator '&', the
9247     //      operator '->', or the operator 'co_await', the
9248     //      built-in candidates set is empty.
9249     break;
9250 
9251   case OO_Plus: // '+' is either unary or binary
9252     if (Args.size() == 1)
9253       OpBuilder.addUnaryPlusPointerOverloads();
9254     LLVM_FALLTHROUGH;
9255 
9256   case OO_Minus: // '-' is either unary or binary
9257     if (Args.size() == 1) {
9258       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9259     } else {
9260       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9261       OpBuilder.addGenericBinaryArithmeticOverloads();
9262       OpBuilder.addMatrixBinaryArithmeticOverloads();
9263     }
9264     break;
9265 
9266   case OO_Star: // '*' is either unary or binary
9267     if (Args.size() == 1)
9268       OpBuilder.addUnaryStarPointerOverloads();
9269     else {
9270       OpBuilder.addGenericBinaryArithmeticOverloads();
9271       OpBuilder.addMatrixBinaryArithmeticOverloads();
9272     }
9273     break;
9274 
9275   case OO_Slash:
9276     OpBuilder.addGenericBinaryArithmeticOverloads();
9277     break;
9278 
9279   case OO_PlusPlus:
9280   case OO_MinusMinus:
9281     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9282     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9283     break;
9284 
9285   case OO_EqualEqual:
9286   case OO_ExclaimEqual:
9287     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9288     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9289     OpBuilder.addGenericBinaryArithmeticOverloads();
9290     break;
9291 
9292   case OO_Less:
9293   case OO_Greater:
9294   case OO_LessEqual:
9295   case OO_GreaterEqual:
9296     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9297     OpBuilder.addGenericBinaryArithmeticOverloads();
9298     break;
9299 
9300   case OO_Spaceship:
9301     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
9302     OpBuilder.addThreeWayArithmeticOverloads();
9303     break;
9304 
9305   case OO_Percent:
9306   case OO_Caret:
9307   case OO_Pipe:
9308   case OO_LessLess:
9309   case OO_GreaterGreater:
9310     OpBuilder.addBinaryBitwiseArithmeticOverloads();
9311     break;
9312 
9313   case OO_Amp: // '&' is either unary or binary
9314     if (Args.size() == 1)
9315       // C++ [over.match.oper]p3:
9316       //   -- For the operator ',', the unary operator '&', or the
9317       //      operator '->', the built-in candidates set is empty.
9318       break;
9319 
9320     OpBuilder.addBinaryBitwiseArithmeticOverloads();
9321     break;
9322 
9323   case OO_Tilde:
9324     OpBuilder.addUnaryTildePromotedIntegralOverloads();
9325     break;
9326 
9327   case OO_Equal:
9328     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9329     LLVM_FALLTHROUGH;
9330 
9331   case OO_PlusEqual:
9332   case OO_MinusEqual:
9333     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9334     LLVM_FALLTHROUGH;
9335 
9336   case OO_StarEqual:
9337   case OO_SlashEqual:
9338     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9339     break;
9340 
9341   case OO_PercentEqual:
9342   case OO_LessLessEqual:
9343   case OO_GreaterGreaterEqual:
9344   case OO_AmpEqual:
9345   case OO_CaretEqual:
9346   case OO_PipeEqual:
9347     OpBuilder.addAssignmentIntegralOverloads();
9348     break;
9349 
9350   case OO_Exclaim:
9351     OpBuilder.addExclaimOverload();
9352     break;
9353 
9354   case OO_AmpAmp:
9355   case OO_PipePipe:
9356     OpBuilder.addAmpAmpOrPipePipeOverload();
9357     break;
9358 
9359   case OO_Subscript:
9360     if (Args.size() == 2)
9361       OpBuilder.addSubscriptOverloads();
9362     break;
9363 
9364   case OO_ArrowStar:
9365     OpBuilder.addArrowStarOverloads();
9366     break;
9367 
9368   case OO_Conditional:
9369     OpBuilder.addConditionalOperatorOverloads();
9370     OpBuilder.addGenericBinaryArithmeticOverloads();
9371     break;
9372   }
9373 }
9374 
9375 /// Add function candidates found via argument-dependent lookup
9376 /// to the set of overloading candidates.
9377 ///
9378 /// This routine performs argument-dependent name lookup based on the
9379 /// given function name (which may also be an operator name) and adds
9380 /// all of the overload candidates found by ADL to the overload
9381 /// candidate set (C++ [basic.lookup.argdep]).
9382 void
9383 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9384                                            SourceLocation Loc,
9385                                            ArrayRef<Expr *> Args,
9386                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
9387                                            OverloadCandidateSet& CandidateSet,
9388                                            bool PartialOverloading) {
9389   ADLResult Fns;
9390 
9391   // FIXME: This approach for uniquing ADL results (and removing
9392   // redundant candidates from the set) relies on pointer-equality,
9393   // which means we need to key off the canonical decl.  However,
9394   // always going back to the canonical decl might not get us the
9395   // right set of default arguments.  What default arguments are
9396   // we supposed to consider on ADL candidates, anyway?
9397 
9398   // FIXME: Pass in the explicit template arguments?
9399   ArgumentDependentLookup(Name, Loc, Args, Fns);
9400 
9401   // Erase all of the candidates we already knew about.
9402   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9403                                    CandEnd = CandidateSet.end();
9404        Cand != CandEnd; ++Cand)
9405     if (Cand->Function) {
9406       Fns.erase(Cand->Function);
9407       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9408         Fns.erase(FunTmpl);
9409     }
9410 
9411   // For each of the ADL candidates we found, add it to the overload
9412   // set.
9413   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9414     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9415 
9416     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9417       if (ExplicitTemplateArgs)
9418         continue;
9419 
9420       AddOverloadCandidate(
9421           FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
9422           PartialOverloading, /*AllowExplicit=*/true,
9423           /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
9424       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) {
9425         AddOverloadCandidate(
9426             FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
9427             /*SuppressUserConversions=*/false, PartialOverloading,
9428             /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
9429             ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed);
9430       }
9431     } else {
9432       auto *FTD = cast<FunctionTemplateDecl>(*I);
9433       AddTemplateOverloadCandidate(
9434           FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
9435           /*SuppressUserConversions=*/false, PartialOverloading,
9436           /*AllowExplicit=*/true, ADLCallKind::UsesADL);
9437       if (CandidateSet.getRewriteInfo().shouldAddReversed(
9438               Context, FTD->getTemplatedDecl())) {
9439         AddTemplateOverloadCandidate(
9440             FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
9441             CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
9442             /*AllowExplicit=*/true, ADLCallKind::UsesADL,
9443             OverloadCandidateParamOrder::Reversed);
9444       }
9445     }
9446   }
9447 }
9448 
9449 namespace {
9450 enum class Comparison { Equal, Better, Worse };
9451 }
9452 
9453 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9454 /// overload resolution.
9455 ///
9456 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9457 /// Cand1's first N enable_if attributes have precisely the same conditions as
9458 /// Cand2's first N enable_if attributes (where N = the number of enable_if
9459 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9460 ///
9461 /// Note that you can have a pair of candidates such that Cand1's enable_if
9462 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9463 /// worse than Cand1's.
9464 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9465                                        const FunctionDecl *Cand2) {
9466   // Common case: One (or both) decls don't have enable_if attrs.
9467   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9468   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9469   if (!Cand1Attr || !Cand2Attr) {
9470     if (Cand1Attr == Cand2Attr)
9471       return Comparison::Equal;
9472     return Cand1Attr ? Comparison::Better : Comparison::Worse;
9473   }
9474 
9475   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9476   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9477 
9478   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9479   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9480     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9481     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9482 
9483     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9484     // has fewer enable_if attributes than Cand2, and vice versa.
9485     if (!Cand1A)
9486       return Comparison::Worse;
9487     if (!Cand2A)
9488       return Comparison::Better;
9489 
9490     Cand1ID.clear();
9491     Cand2ID.clear();
9492 
9493     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9494     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9495     if (Cand1ID != Cand2ID)
9496       return Comparison::Worse;
9497   }
9498 
9499   return Comparison::Equal;
9500 }
9501 
9502 static Comparison
9503 isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9504                               const OverloadCandidate &Cand2) {
9505   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9506       !Cand2.Function->isMultiVersion())
9507     return Comparison::Equal;
9508 
9509   // If both are invalid, they are equal. If one of them is invalid, the other
9510   // is better.
9511   if (Cand1.Function->isInvalidDecl()) {
9512     if (Cand2.Function->isInvalidDecl())
9513       return Comparison::Equal;
9514     return Comparison::Worse;
9515   }
9516   if (Cand2.Function->isInvalidDecl())
9517     return Comparison::Better;
9518 
9519   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9520   // cpu_dispatch, else arbitrarily based on the identifiers.
9521   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9522   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9523   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9524   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9525 
9526   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9527     return Comparison::Equal;
9528 
9529   if (Cand1CPUDisp && !Cand2CPUDisp)
9530     return Comparison::Better;
9531   if (Cand2CPUDisp && !Cand1CPUDisp)
9532     return Comparison::Worse;
9533 
9534   if (Cand1CPUSpec && Cand2CPUSpec) {
9535     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9536       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
9537                  ? Comparison::Better
9538                  : Comparison::Worse;
9539 
9540     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9541         FirstDiff = std::mismatch(
9542             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9543             Cand2CPUSpec->cpus_begin(),
9544             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9545               return LHS->getName() == RHS->getName();
9546             });
9547 
9548     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9549            "Two different cpu-specific versions should not have the same "
9550            "identifier list, otherwise they'd be the same decl!");
9551     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
9552                ? Comparison::Better
9553                : Comparison::Worse;
9554   }
9555   llvm_unreachable("No way to get here unless both had cpu_dispatch");
9556 }
9557 
9558 /// Compute the type of the implicit object parameter for the given function,
9559 /// if any. Returns None if there is no implicit object parameter, and a null
9560 /// QualType if there is a 'matches anything' implicit object parameter.
9561 static Optional<QualType> getImplicitObjectParamType(ASTContext &Context,
9562                                                      const FunctionDecl *F) {
9563   if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
9564     return llvm::None;
9565 
9566   auto *M = cast<CXXMethodDecl>(F);
9567   // Static member functions' object parameters match all types.
9568   if (M->isStatic())
9569     return QualType();
9570 
9571   QualType T = M->getThisObjectType();
9572   if (M->getRefQualifier() == RQ_RValue)
9573     return Context.getRValueReferenceType(T);
9574   return Context.getLValueReferenceType(T);
9575 }
9576 
9577 static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1,
9578                                    const FunctionDecl *F2, unsigned NumParams) {
9579   if (declaresSameEntity(F1, F2))
9580     return true;
9581 
9582   auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
9583     if (First) {
9584       if (Optional<QualType> T = getImplicitObjectParamType(Context, F))
9585         return *T;
9586     }
9587     assert(I < F->getNumParams());
9588     return F->getParamDecl(I++)->getType();
9589   };
9590 
9591   unsigned I1 = 0, I2 = 0;
9592   for (unsigned I = 0; I != NumParams; ++I) {
9593     QualType T1 = NextParam(F1, I1, I == 0);
9594     QualType T2 = NextParam(F2, I2, I == 0);
9595     assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
9596     if (!Context.hasSameUnqualifiedType(T1, T2))
9597       return false;
9598   }
9599   return true;
9600 }
9601 
9602 /// We're allowed to use constraints partial ordering only if the candidates
9603 /// have the same parameter types:
9604 /// [temp.func.order]p6.2.2 [...] or if the function parameters that
9605 /// positionally correspond between the two templates are not of the same type,
9606 /// neither template is more specialized than the other.
9607 /// [over.match.best]p2.6
9608 /// F1 and F2 are non-template functions with the same parameter-type-lists,
9609 /// and F1 is more constrained than F2 [...]
9610 static bool canCompareFunctionConstraints(Sema &S,
9611                                           const OverloadCandidate &Cand1,
9612                                           const OverloadCandidate &Cand2) {
9613   // FIXME: Per P2113R0 we also need to compare the template parameter lists
9614   // when comparing template functions.
9615   if (Cand1.Function && Cand2.Function && Cand1.Function->hasPrototype() &&
9616       Cand2.Function->hasPrototype()) {
9617     auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType());
9618     auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType());
9619     if (PT1->getNumParams() == PT2->getNumParams() &&
9620         PT1->isVariadic() == PT2->isVariadic() &&
9621         S.FunctionParamTypesAreEqual(PT1, PT2, nullptr,
9622                                      Cand1.isReversed() ^ Cand2.isReversed()))
9623       return true;
9624   }
9625   return false;
9626 }
9627 
9628 /// isBetterOverloadCandidate - Determines whether the first overload
9629 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9630 bool clang::isBetterOverloadCandidate(
9631     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9632     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9633   // Define viable functions to be better candidates than non-viable
9634   // functions.
9635   if (!Cand2.Viable)
9636     return Cand1.Viable;
9637   else if (!Cand1.Viable)
9638     return false;
9639 
9640   // [CUDA] A function with 'never' preference is marked not viable, therefore
9641   // is never shown up here. The worst preference shown up here is 'wrong side',
9642   // e.g. an H function called by a HD function in device compilation. This is
9643   // valid AST as long as the HD function is not emitted, e.g. it is an inline
9644   // function which is called only by an H function. A deferred diagnostic will
9645   // be triggered if it is emitted. However a wrong-sided function is still
9646   // a viable candidate here.
9647   //
9648   // If Cand1 can be emitted and Cand2 cannot be emitted in the current
9649   // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
9650   // can be emitted, Cand1 is not better than Cand2. This rule should have
9651   // precedence over other rules.
9652   //
9653   // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
9654   // other rules should be used to determine which is better. This is because
9655   // host/device based overloading resolution is mostly for determining
9656   // viability of a function. If two functions are both viable, other factors
9657   // should take precedence in preference, e.g. the standard-defined preferences
9658   // like argument conversion ranks or enable_if partial-ordering. The
9659   // preference for pass-object-size parameters is probably most similar to a
9660   // type-based-overloading decision and so should take priority.
9661   //
9662   // If other rules cannot determine which is better, CUDA preference will be
9663   // used again to determine which is better.
9664   //
9665   // TODO: Currently IdentifyCUDAPreference does not return correct values
9666   // for functions called in global variable initializers due to missing
9667   // correct context about device/host. Therefore we can only enforce this
9668   // rule when there is a caller. We should enforce this rule for functions
9669   // in global variable initializers once proper context is added.
9670   //
9671   // TODO: We can only enable the hostness based overloading resolution when
9672   // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
9673   // overloading resolution diagnostics.
9674   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
9675       S.getLangOpts().GPUExcludeWrongSideOverloads) {
9676     if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
9677       bool IsCallerImplicitHD = Sema::isCUDAImplicitHostDeviceFunction(Caller);
9678       bool IsCand1ImplicitHD =
9679           Sema::isCUDAImplicitHostDeviceFunction(Cand1.Function);
9680       bool IsCand2ImplicitHD =
9681           Sema::isCUDAImplicitHostDeviceFunction(Cand2.Function);
9682       auto P1 = S.IdentifyCUDAPreference(Caller, Cand1.Function);
9683       auto P2 = S.IdentifyCUDAPreference(Caller, Cand2.Function);
9684       assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never);
9685       // The implicit HD function may be a function in a system header which
9686       // is forced by pragma. In device compilation, if we prefer HD candidates
9687       // over wrong-sided candidates, overloading resolution may change, which
9688       // may result in non-deferrable diagnostics. As a workaround, we let
9689       // implicit HD candidates take equal preference as wrong-sided candidates.
9690       // This will preserve the overloading resolution.
9691       // TODO: We still need special handling of implicit HD functions since
9692       // they may incur other diagnostics to be deferred. We should make all
9693       // host/device related diagnostics deferrable and remove special handling
9694       // of implicit HD functions.
9695       auto EmitThreshold =
9696           (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
9697            (IsCand1ImplicitHD || IsCand2ImplicitHD))
9698               ? Sema::CFP_Never
9699               : Sema::CFP_WrongSide;
9700       auto Cand1Emittable = P1 > EmitThreshold;
9701       auto Cand2Emittable = P2 > EmitThreshold;
9702       if (Cand1Emittable && !Cand2Emittable)
9703         return true;
9704       if (!Cand1Emittable && Cand2Emittable)
9705         return false;
9706     }
9707   }
9708 
9709   // C++ [over.match.best]p1:
9710   //
9711   //   -- if F is a static member function, ICS1(F) is defined such
9712   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9713   //      any function G, and, symmetrically, ICS1(G) is neither
9714   //      better nor worse than ICS1(F).
9715   unsigned StartArg = 0;
9716   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9717     StartArg = 1;
9718 
9719   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9720     // We don't allow incompatible pointer conversions in C++.
9721     if (!S.getLangOpts().CPlusPlus)
9722       return ICS.isStandard() &&
9723              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9724 
9725     // The only ill-formed conversion we allow in C++ is the string literal to
9726     // char* conversion, which is only considered ill-formed after C++11.
9727     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9728            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9729   };
9730 
9731   // Define functions that don't require ill-formed conversions for a given
9732   // argument to be better candidates than functions that do.
9733   unsigned NumArgs = Cand1.Conversions.size();
9734   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9735   bool HasBetterConversion = false;
9736   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9737     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9738     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9739     if (Cand1Bad != Cand2Bad) {
9740       if (Cand1Bad)
9741         return false;
9742       HasBetterConversion = true;
9743     }
9744   }
9745 
9746   if (HasBetterConversion)
9747     return true;
9748 
9749   // C++ [over.match.best]p1:
9750   //   A viable function F1 is defined to be a better function than another
9751   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9752   //   conversion sequence than ICSi(F2), and then...
9753   bool HasWorseConversion = false;
9754   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9755     switch (CompareImplicitConversionSequences(S, Loc,
9756                                                Cand1.Conversions[ArgIdx],
9757                                                Cand2.Conversions[ArgIdx])) {
9758     case ImplicitConversionSequence::Better:
9759       // Cand1 has a better conversion sequence.
9760       HasBetterConversion = true;
9761       break;
9762 
9763     case ImplicitConversionSequence::Worse:
9764       if (Cand1.Function && Cand2.Function &&
9765           Cand1.isReversed() != Cand2.isReversed() &&
9766           haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function,
9767                                  NumArgs)) {
9768         // Work around large-scale breakage caused by considering reversed
9769         // forms of operator== in C++20:
9770         //
9771         // When comparing a function against a reversed function with the same
9772         // parameter types, if we have a better conversion for one argument and
9773         // a worse conversion for the other, the implicit conversion sequences
9774         // are treated as being equally good.
9775         //
9776         // This prevents a comparison function from being considered ambiguous
9777         // with a reversed form that is written in the same way.
9778         //
9779         // We diagnose this as an extension from CreateOverloadedBinOp.
9780         HasWorseConversion = true;
9781         break;
9782       }
9783 
9784       // Cand1 can't be better than Cand2.
9785       return false;
9786 
9787     case ImplicitConversionSequence::Indistinguishable:
9788       // Do nothing.
9789       break;
9790     }
9791   }
9792 
9793   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9794   //       ICSj(F2), or, if not that,
9795   if (HasBetterConversion && !HasWorseConversion)
9796     return true;
9797 
9798   //   -- the context is an initialization by user-defined conversion
9799   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9800   //      from the return type of F1 to the destination type (i.e.,
9801   //      the type of the entity being initialized) is a better
9802   //      conversion sequence than the standard conversion sequence
9803   //      from the return type of F2 to the destination type.
9804   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9805       Cand1.Function && Cand2.Function &&
9806       isa<CXXConversionDecl>(Cand1.Function) &&
9807       isa<CXXConversionDecl>(Cand2.Function)) {
9808     // First check whether we prefer one of the conversion functions over the
9809     // other. This only distinguishes the results in non-standard, extension
9810     // cases such as the conversion from a lambda closure type to a function
9811     // pointer or block.
9812     ImplicitConversionSequence::CompareKind Result =
9813         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9814     if (Result == ImplicitConversionSequence::Indistinguishable)
9815       Result = CompareStandardConversionSequences(S, Loc,
9816                                                   Cand1.FinalConversion,
9817                                                   Cand2.FinalConversion);
9818 
9819     if (Result != ImplicitConversionSequence::Indistinguishable)
9820       return Result == ImplicitConversionSequence::Better;
9821 
9822     // FIXME: Compare kind of reference binding if conversion functions
9823     // convert to a reference type used in direct reference binding, per
9824     // C++14 [over.match.best]p1 section 2 bullet 3.
9825   }
9826 
9827   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9828   // as combined with the resolution to CWG issue 243.
9829   //
9830   // When the context is initialization by constructor ([over.match.ctor] or
9831   // either phase of [over.match.list]), a constructor is preferred over
9832   // a conversion function.
9833   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9834       Cand1.Function && Cand2.Function &&
9835       isa<CXXConstructorDecl>(Cand1.Function) !=
9836           isa<CXXConstructorDecl>(Cand2.Function))
9837     return isa<CXXConstructorDecl>(Cand1.Function);
9838 
9839   //    -- F1 is a non-template function and F2 is a function template
9840   //       specialization, or, if not that,
9841   bool Cand1IsSpecialization = Cand1.Function &&
9842                                Cand1.Function->getPrimaryTemplate();
9843   bool Cand2IsSpecialization = Cand2.Function &&
9844                                Cand2.Function->getPrimaryTemplate();
9845   if (Cand1IsSpecialization != Cand2IsSpecialization)
9846     return Cand2IsSpecialization;
9847 
9848   //   -- F1 and F2 are function template specializations, and the function
9849   //      template for F1 is more specialized than the template for F2
9850   //      according to the partial ordering rules described in 14.5.5.2, or,
9851   //      if not that,
9852   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9853     if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
9854             Cand1.Function->getPrimaryTemplate(),
9855             Cand2.Function->getPrimaryTemplate(), Loc,
9856             isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
9857                                                    : TPOC_Call,
9858             Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments,
9859             Cand1.isReversed() ^ Cand2.isReversed(),
9860             canCompareFunctionConstraints(S, Cand1, Cand2)))
9861       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9862   }
9863 
9864   //   -— F1 and F2 are non-template functions with the same
9865   //      parameter-type-lists, and F1 is more constrained than F2 [...],
9866   if (!Cand1IsSpecialization && !Cand2IsSpecialization &&
9867       canCompareFunctionConstraints(S, Cand1, Cand2)) {
9868     Expr *RC1 = Cand1.Function->getTrailingRequiresClause();
9869     Expr *RC2 = Cand2.Function->getTrailingRequiresClause();
9870     if (RC1 && RC2) {
9871       bool AtLeastAsConstrained1, AtLeastAsConstrained2;
9872       if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function, {RC2},
9873                                    AtLeastAsConstrained1) ||
9874           S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function, {RC1},
9875                                    AtLeastAsConstrained2))
9876         return false;
9877       if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
9878         return AtLeastAsConstrained1;
9879     } else if (RC1 || RC2) {
9880       return RC1 != nullptr;
9881     }
9882   }
9883 
9884   //   -- F1 is a constructor for a class D, F2 is a constructor for a base
9885   //      class B of D, and for all arguments the corresponding parameters of
9886   //      F1 and F2 have the same type.
9887   // FIXME: Implement the "all parameters have the same type" check.
9888   bool Cand1IsInherited =
9889       isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9890   bool Cand2IsInherited =
9891       isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9892   if (Cand1IsInherited != Cand2IsInherited)
9893     return Cand2IsInherited;
9894   else if (Cand1IsInherited) {
9895     assert(Cand2IsInherited);
9896     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9897     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9898     if (Cand1Class->isDerivedFrom(Cand2Class))
9899       return true;
9900     if (Cand2Class->isDerivedFrom(Cand1Class))
9901       return false;
9902     // Inherited from sibling base classes: still ambiguous.
9903   }
9904 
9905   //   -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
9906   //   -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
9907   //      with reversed order of parameters and F1 is not
9908   //
9909   // We rank reversed + different operator as worse than just reversed, but
9910   // that comparison can never happen, because we only consider reversing for
9911   // the maximally-rewritten operator (== or <=>).
9912   if (Cand1.RewriteKind != Cand2.RewriteKind)
9913     return Cand1.RewriteKind < Cand2.RewriteKind;
9914 
9915   // Check C++17 tie-breakers for deduction guides.
9916   {
9917     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9918     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9919     if (Guide1 && Guide2) {
9920       //  -- F1 is generated from a deduction-guide and F2 is not
9921       if (Guide1->isImplicit() != Guide2->isImplicit())
9922         return Guide2->isImplicit();
9923 
9924       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9925       if (Guide1->isCopyDeductionCandidate())
9926         return true;
9927     }
9928   }
9929 
9930   // Check for enable_if value-based overload resolution.
9931   if (Cand1.Function && Cand2.Function) {
9932     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9933     if (Cmp != Comparison::Equal)
9934       return Cmp == Comparison::Better;
9935   }
9936 
9937   bool HasPS1 = Cand1.Function != nullptr &&
9938                 functionHasPassObjectSizeParams(Cand1.Function);
9939   bool HasPS2 = Cand2.Function != nullptr &&
9940                 functionHasPassObjectSizeParams(Cand2.Function);
9941   if (HasPS1 != HasPS2 && HasPS1)
9942     return true;
9943 
9944   auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
9945   if (MV == Comparison::Better)
9946     return true;
9947   if (MV == Comparison::Worse)
9948     return false;
9949 
9950   // If other rules cannot determine which is better, CUDA preference is used
9951   // to determine which is better.
9952   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9953     FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
9954     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9955            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9956   }
9957 
9958   // General member function overloading is handled above, so this only handles
9959   // constructors with address spaces.
9960   // This only handles address spaces since C++ has no other
9961   // qualifier that can be used with constructors.
9962   const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
9963   const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
9964   if (CD1 && CD2) {
9965     LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
9966     LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
9967     if (AS1 != AS2) {
9968       if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
9969         return true;
9970       if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
9971         return false;
9972     }
9973   }
9974 
9975   return false;
9976 }
9977 
9978 /// Determine whether two declarations are "equivalent" for the purposes of
9979 /// name lookup and overload resolution. This applies when the same internal/no
9980 /// linkage entity is defined by two modules (probably by textually including
9981 /// the same header). In such a case, we don't consider the declarations to
9982 /// declare the same entity, but we also don't want lookups with both
9983 /// declarations visible to be ambiguous in some cases (this happens when using
9984 /// a modularized libstdc++).
9985 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9986                                                   const NamedDecl *B) {
9987   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9988   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9989   if (!VA || !VB)
9990     return false;
9991 
9992   // The declarations must be declaring the same name as an internal linkage
9993   // entity in different modules.
9994   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9995           VB->getDeclContext()->getRedeclContext()) ||
9996       getOwningModule(VA) == getOwningModule(VB) ||
9997       VA->isExternallyVisible() || VB->isExternallyVisible())
9998     return false;
9999 
10000   // Check that the declarations appear to be equivalent.
10001   //
10002   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
10003   // For constants and functions, we should check the initializer or body is
10004   // the same. For non-constant variables, we shouldn't allow it at all.
10005   if (Context.hasSameType(VA->getType(), VB->getType()))
10006     return true;
10007 
10008   // Enum constants within unnamed enumerations will have different types, but
10009   // may still be similar enough to be interchangeable for our purposes.
10010   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
10011     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
10012       // Only handle anonymous enums. If the enumerations were named and
10013       // equivalent, they would have been merged to the same type.
10014       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
10015       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
10016       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
10017           !Context.hasSameType(EnumA->getIntegerType(),
10018                                EnumB->getIntegerType()))
10019         return false;
10020       // Allow this only if the value is the same for both enumerators.
10021       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
10022     }
10023   }
10024 
10025   // Nothing else is sufficiently similar.
10026   return false;
10027 }
10028 
10029 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
10030     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
10031   assert(D && "Unknown declaration");
10032   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
10033 
10034   Module *M = getOwningModule(D);
10035   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
10036       << !M << (M ? M->getFullModuleName() : "");
10037 
10038   for (auto *E : Equiv) {
10039     Module *M = getOwningModule(E);
10040     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
10041         << !M << (M ? M->getFullModuleName() : "");
10042   }
10043 }
10044 
10045 /// Computes the best viable function (C++ 13.3.3)
10046 /// within an overload candidate set.
10047 ///
10048 /// \param Loc The location of the function name (or operator symbol) for
10049 /// which overload resolution occurs.
10050 ///
10051 /// \param Best If overload resolution was successful or found a deleted
10052 /// function, \p Best points to the candidate function found.
10053 ///
10054 /// \returns The result of overload resolution.
10055 OverloadingResult
10056 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
10057                                          iterator &Best) {
10058   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
10059   std::transform(begin(), end(), std::back_inserter(Candidates),
10060                  [](OverloadCandidate &Cand) { return &Cand; });
10061 
10062   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
10063   // are accepted by both clang and NVCC. However, during a particular
10064   // compilation mode only one call variant is viable. We need to
10065   // exclude non-viable overload candidates from consideration based
10066   // only on their host/device attributes. Specifically, if one
10067   // candidate call is WrongSide and the other is SameSide, we ignore
10068   // the WrongSide candidate.
10069   // We only need to remove wrong-sided candidates here if
10070   // -fgpu-exclude-wrong-side-overloads is off. When
10071   // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
10072   // uniformly in isBetterOverloadCandidate.
10073   if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) {
10074     const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10075     bool ContainsSameSideCandidate =
10076         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
10077           // Check viable function only.
10078           return Cand->Viable && Cand->Function &&
10079                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
10080                      Sema::CFP_SameSide;
10081         });
10082     if (ContainsSameSideCandidate) {
10083       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
10084         // Check viable function only to avoid unnecessary data copying/moving.
10085         return Cand->Viable && Cand->Function &&
10086                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
10087                    Sema::CFP_WrongSide;
10088       };
10089       llvm::erase_if(Candidates, IsWrongSideCandidate);
10090     }
10091   }
10092 
10093   // Find the best viable function.
10094   Best = end();
10095   for (auto *Cand : Candidates) {
10096     Cand->Best = false;
10097     if (Cand->Viable)
10098       if (Best == end() ||
10099           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
10100         Best = Cand;
10101   }
10102 
10103   // If we didn't find any viable functions, abort.
10104   if (Best == end())
10105     return OR_No_Viable_Function;
10106 
10107   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
10108 
10109   llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
10110   PendingBest.push_back(&*Best);
10111   Best->Best = true;
10112 
10113   // Make sure that this function is better than every other viable
10114   // function. If not, we have an ambiguity.
10115   while (!PendingBest.empty()) {
10116     auto *Curr = PendingBest.pop_back_val();
10117     for (auto *Cand : Candidates) {
10118       if (Cand->Viable && !Cand->Best &&
10119           !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
10120         PendingBest.push_back(Cand);
10121         Cand->Best = true;
10122 
10123         if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
10124                                                      Curr->Function))
10125           EquivalentCands.push_back(Cand->Function);
10126         else
10127           Best = end();
10128       }
10129     }
10130   }
10131 
10132   // If we found more than one best candidate, this is ambiguous.
10133   if (Best == end())
10134     return OR_Ambiguous;
10135 
10136   // Best is the best viable function.
10137   if (Best->Function && Best->Function->isDeleted())
10138     return OR_Deleted;
10139 
10140   if (!EquivalentCands.empty())
10141     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
10142                                                     EquivalentCands);
10143 
10144   return OR_Success;
10145 }
10146 
10147 namespace {
10148 
10149 enum OverloadCandidateKind {
10150   oc_function,
10151   oc_method,
10152   oc_reversed_binary_operator,
10153   oc_constructor,
10154   oc_implicit_default_constructor,
10155   oc_implicit_copy_constructor,
10156   oc_implicit_move_constructor,
10157   oc_implicit_copy_assignment,
10158   oc_implicit_move_assignment,
10159   oc_implicit_equality_comparison,
10160   oc_inherited_constructor
10161 };
10162 
10163 enum OverloadCandidateSelect {
10164   ocs_non_template,
10165   ocs_template,
10166   ocs_described_template,
10167 };
10168 
10169 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
10170 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
10171                           OverloadCandidateRewriteKind CRK,
10172                           std::string &Description) {
10173 
10174   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
10175   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
10176     isTemplate = true;
10177     Description = S.getTemplateArgumentBindingsText(
10178         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
10179   }
10180 
10181   OverloadCandidateSelect Select = [&]() {
10182     if (!Description.empty())
10183       return ocs_described_template;
10184     return isTemplate ? ocs_template : ocs_non_template;
10185   }();
10186 
10187   OverloadCandidateKind Kind = [&]() {
10188     if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
10189       return oc_implicit_equality_comparison;
10190 
10191     if (CRK & CRK_Reversed)
10192       return oc_reversed_binary_operator;
10193 
10194     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
10195       if (!Ctor->isImplicit()) {
10196         if (isa<ConstructorUsingShadowDecl>(Found))
10197           return oc_inherited_constructor;
10198         else
10199           return oc_constructor;
10200       }
10201 
10202       if (Ctor->isDefaultConstructor())
10203         return oc_implicit_default_constructor;
10204 
10205       if (Ctor->isMoveConstructor())
10206         return oc_implicit_move_constructor;
10207 
10208       assert(Ctor->isCopyConstructor() &&
10209              "unexpected sort of implicit constructor");
10210       return oc_implicit_copy_constructor;
10211     }
10212 
10213     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
10214       // This actually gets spelled 'candidate function' for now, but
10215       // it doesn't hurt to split it out.
10216       if (!Meth->isImplicit())
10217         return oc_method;
10218 
10219       if (Meth->isMoveAssignmentOperator())
10220         return oc_implicit_move_assignment;
10221 
10222       if (Meth->isCopyAssignmentOperator())
10223         return oc_implicit_copy_assignment;
10224 
10225       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
10226       return oc_method;
10227     }
10228 
10229     return oc_function;
10230   }();
10231 
10232   return std::make_pair(Kind, Select);
10233 }
10234 
10235 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
10236   // FIXME: It'd be nice to only emit a note once per using-decl per overload
10237   // set.
10238   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
10239     S.Diag(FoundDecl->getLocation(),
10240            diag::note_ovl_candidate_inherited_constructor)
10241       << Shadow->getNominatedBaseClass();
10242 }
10243 
10244 } // end anonymous namespace
10245 
10246 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
10247                                     const FunctionDecl *FD) {
10248   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
10249     bool AlwaysTrue;
10250     if (EnableIf->getCond()->isValueDependent() ||
10251         !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
10252       return false;
10253     if (!AlwaysTrue)
10254       return false;
10255   }
10256   return true;
10257 }
10258 
10259 /// Returns true if we can take the address of the function.
10260 ///
10261 /// \param Complain - If true, we'll emit a diagnostic
10262 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
10263 ///   we in overload resolution?
10264 /// \param Loc - The location of the statement we're complaining about. Ignored
10265 ///   if we're not complaining, or if we're in overload resolution.
10266 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
10267                                               bool Complain,
10268                                               bool InOverloadResolution,
10269                                               SourceLocation Loc) {
10270   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
10271     if (Complain) {
10272       if (InOverloadResolution)
10273         S.Diag(FD->getBeginLoc(),
10274                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
10275       else
10276         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
10277     }
10278     return false;
10279   }
10280 
10281   if (FD->getTrailingRequiresClause()) {
10282     ConstraintSatisfaction Satisfaction;
10283     if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
10284       return false;
10285     if (!Satisfaction.IsSatisfied) {
10286       if (Complain) {
10287         if (InOverloadResolution) {
10288           SmallString<128> TemplateArgString;
10289           if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
10290             TemplateArgString += " ";
10291             TemplateArgString += S.getTemplateArgumentBindingsText(
10292                 FunTmpl->getTemplateParameters(),
10293                 *FD->getTemplateSpecializationArgs());
10294           }
10295 
10296           S.Diag(FD->getBeginLoc(),
10297                  diag::note_ovl_candidate_unsatisfied_constraints)
10298               << TemplateArgString;
10299         } else
10300           S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
10301               << FD;
10302         S.DiagnoseUnsatisfiedConstraint(Satisfaction);
10303       }
10304       return false;
10305     }
10306   }
10307 
10308   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
10309     return P->hasAttr<PassObjectSizeAttr>();
10310   });
10311   if (I == FD->param_end())
10312     return true;
10313 
10314   if (Complain) {
10315     // Add one to ParamNo because it's user-facing
10316     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
10317     if (InOverloadResolution)
10318       S.Diag(FD->getLocation(),
10319              diag::note_ovl_candidate_has_pass_object_size_params)
10320           << ParamNo;
10321     else
10322       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
10323           << FD << ParamNo;
10324   }
10325   return false;
10326 }
10327 
10328 static bool checkAddressOfCandidateIsAvailable(Sema &S,
10329                                                const FunctionDecl *FD) {
10330   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
10331                                            /*InOverloadResolution=*/true,
10332                                            /*Loc=*/SourceLocation());
10333 }
10334 
10335 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10336                                              bool Complain,
10337                                              SourceLocation Loc) {
10338   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
10339                                              /*InOverloadResolution=*/false,
10340                                              Loc);
10341 }
10342 
10343 // Don't print candidates other than the one that matches the calling
10344 // convention of the call operator, since that is guaranteed to exist.
10345 static bool shouldSkipNotingLambdaConversionDecl(FunctionDecl *Fn) {
10346   const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
10347 
10348   if (!ConvD)
10349     return false;
10350   const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
10351   if (!RD->isLambda())
10352     return false;
10353 
10354   CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
10355   CallingConv CallOpCC =
10356       CallOp->getType()->castAs<FunctionType>()->getCallConv();
10357   QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
10358   CallingConv ConvToCC =
10359       ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
10360 
10361   return ConvToCC != CallOpCC;
10362 }
10363 
10364 // Notes the location of an overload candidate.
10365 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
10366                                  OverloadCandidateRewriteKind RewriteKind,
10367                                  QualType DestType, bool TakingAddress) {
10368   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
10369     return;
10370   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
10371       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
10372     return;
10373   if (shouldSkipNotingLambdaConversionDecl(Fn))
10374     return;
10375 
10376   std::string FnDesc;
10377   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
10378       ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
10379   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
10380                          << (unsigned)KSPair.first << (unsigned)KSPair.second
10381                          << Fn << FnDesc;
10382 
10383   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
10384   Diag(Fn->getLocation(), PD);
10385   MaybeEmitInheritedConstructorNote(*this, Found);
10386 }
10387 
10388 static void
10389 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
10390   // Perhaps the ambiguity was caused by two atomic constraints that are
10391   // 'identical' but not equivalent:
10392   //
10393   // void foo() requires (sizeof(T) > 4) { } // #1
10394   // void foo() requires (sizeof(T) > 4) && T::value { } // #2
10395   //
10396   // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
10397   // #2 to subsume #1, but these constraint are not considered equivalent
10398   // according to the subsumption rules because they are not the same
10399   // source-level construct. This behavior is quite confusing and we should try
10400   // to help the user figure out what happened.
10401 
10402   SmallVector<const Expr *, 3> FirstAC, SecondAC;
10403   FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
10404   for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10405     if (!I->Function)
10406       continue;
10407     SmallVector<const Expr *, 3> AC;
10408     if (auto *Template = I->Function->getPrimaryTemplate())
10409       Template->getAssociatedConstraints(AC);
10410     else
10411       I->Function->getAssociatedConstraints(AC);
10412     if (AC.empty())
10413       continue;
10414     if (FirstCand == nullptr) {
10415       FirstCand = I->Function;
10416       FirstAC = AC;
10417     } else if (SecondCand == nullptr) {
10418       SecondCand = I->Function;
10419       SecondAC = AC;
10420     } else {
10421       // We have more than one pair of constrained functions - this check is
10422       // expensive and we'd rather not try to diagnose it.
10423       return;
10424     }
10425   }
10426   if (!SecondCand)
10427     return;
10428   // The diagnostic can only happen if there are associated constraints on
10429   // both sides (there needs to be some identical atomic constraint).
10430   if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
10431                                                       SecondCand, SecondAC))
10432     // Just show the user one diagnostic, they'll probably figure it out
10433     // from here.
10434     return;
10435 }
10436 
10437 // Notes the location of all overload candidates designated through
10438 // OverloadedExpr
10439 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
10440                                      bool TakingAddress) {
10441   assert(OverloadedExpr->getType() == Context.OverloadTy);
10442 
10443   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
10444   OverloadExpr *OvlExpr = Ovl.Expression;
10445 
10446   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10447                             IEnd = OvlExpr->decls_end();
10448        I != IEnd; ++I) {
10449     if (FunctionTemplateDecl *FunTmpl =
10450                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
10451       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
10452                             TakingAddress);
10453     } else if (FunctionDecl *Fun
10454                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
10455       NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
10456     }
10457   }
10458 }
10459 
10460 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
10461 /// "lead" diagnostic; it will be given two arguments, the source and
10462 /// target types of the conversion.
10463 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
10464                                  Sema &S,
10465                                  SourceLocation CaretLoc,
10466                                  const PartialDiagnostic &PDiag) const {
10467   S.Diag(CaretLoc, PDiag)
10468     << Ambiguous.getFromType() << Ambiguous.getToType();
10469   unsigned CandsShown = 0;
10470   AmbiguousConversionSequence::const_iterator I, E;
10471   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
10472     if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
10473       break;
10474     ++CandsShown;
10475     S.NoteOverloadCandidate(I->first, I->second);
10476   }
10477   S.Diags.overloadCandidatesShown(CandsShown);
10478   if (I != E)
10479     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
10480 }
10481 
10482 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
10483                                   unsigned I, bool TakingCandidateAddress) {
10484   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
10485   assert(Conv.isBad());
10486   assert(Cand->Function && "for now, candidate must be a function");
10487   FunctionDecl *Fn = Cand->Function;
10488 
10489   // There's a conversion slot for the object argument if this is a
10490   // non-constructor method.  Note that 'I' corresponds the
10491   // conversion-slot index.
10492   bool isObjectArgument = false;
10493   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
10494     if (I == 0)
10495       isObjectArgument = true;
10496     else
10497       I--;
10498   }
10499 
10500   std::string FnDesc;
10501   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10502       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
10503                                 FnDesc);
10504 
10505   Expr *FromExpr = Conv.Bad.FromExpr;
10506   QualType FromTy = Conv.Bad.getFromType();
10507   QualType ToTy = Conv.Bad.getToType();
10508 
10509   if (FromTy == S.Context.OverloadTy) {
10510     assert(FromExpr && "overload set argument came from implicit argument?");
10511     Expr *E = FromExpr->IgnoreParens();
10512     if (isa<UnaryOperator>(E))
10513       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
10514     DeclarationName Name = cast<OverloadExpr>(E)->getName();
10515 
10516     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
10517         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10518         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
10519         << Name << I + 1;
10520     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10521     return;
10522   }
10523 
10524   // Do some hand-waving analysis to see if the non-viability is due
10525   // to a qualifier mismatch.
10526   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
10527   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
10528   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
10529     CToTy = RT->getPointeeType();
10530   else {
10531     // TODO: detect and diagnose the full richness of const mismatches.
10532     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
10533       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
10534         CFromTy = FromPT->getPointeeType();
10535         CToTy = ToPT->getPointeeType();
10536       }
10537   }
10538 
10539   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
10540       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
10541     Qualifiers FromQs = CFromTy.getQualifiers();
10542     Qualifiers ToQs = CToTy.getQualifiers();
10543 
10544     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
10545       if (isObjectArgument)
10546         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
10547             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10548             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10549             << FromQs.getAddressSpace() << ToQs.getAddressSpace();
10550       else
10551         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
10552             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10553             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10554             << FromQs.getAddressSpace() << ToQs.getAddressSpace()
10555             << ToTy->isReferenceType() << I + 1;
10556       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10557       return;
10558     }
10559 
10560     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10561       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
10562           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10563           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10564           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
10565           << (unsigned)isObjectArgument << I + 1;
10566       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10567       return;
10568     }
10569 
10570     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
10571       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
10572           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10573           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10574           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
10575           << (unsigned)isObjectArgument << I + 1;
10576       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10577       return;
10578     }
10579 
10580     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
10581       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
10582           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10583           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10584           << FromQs.hasUnaligned() << I + 1;
10585       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10586       return;
10587     }
10588 
10589     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
10590     assert(CVR && "expected qualifiers mismatch");
10591 
10592     if (isObjectArgument) {
10593       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
10594           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10595           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10596           << (CVR - 1);
10597     } else {
10598       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
10599           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10600           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10601           << (CVR - 1) << I + 1;
10602     }
10603     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10604     return;
10605   }
10606 
10607   if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
10608       Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
10609     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
10610         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10611         << (unsigned)isObjectArgument << I + 1
10612         << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
10613         << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
10614     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10615     return;
10616   }
10617 
10618   // Special diagnostic for failure to convert an initializer list, since
10619   // telling the user that it has type void is not useful.
10620   if (FromExpr && isa<InitListExpr>(FromExpr)) {
10621     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
10622         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10623         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10624         << ToTy << (unsigned)isObjectArgument << I + 1
10625         << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1
10626             : Conv.Bad.Kind == BadConversionSequence::too_many_initializers
10627                 ? 2
10628                 : 0);
10629     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10630     return;
10631   }
10632 
10633   // Diagnose references or pointers to incomplete types differently,
10634   // since it's far from impossible that the incompleteness triggered
10635   // the failure.
10636   QualType TempFromTy = FromTy.getNonReferenceType();
10637   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
10638     TempFromTy = PTy->getPointeeType();
10639   if (TempFromTy->isIncompleteType()) {
10640     // Emit the generic diagnostic and, optionally, add the hints to it.
10641     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
10642         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10643         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10644         << ToTy << (unsigned)isObjectArgument << I + 1
10645         << (unsigned)(Cand->Fix.Kind);
10646 
10647     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10648     return;
10649   }
10650 
10651   // Diagnose base -> derived pointer conversions.
10652   unsigned BaseToDerivedConversion = 0;
10653   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
10654     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
10655       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10656                                                FromPtrTy->getPointeeType()) &&
10657           !FromPtrTy->getPointeeType()->isIncompleteType() &&
10658           !ToPtrTy->getPointeeType()->isIncompleteType() &&
10659           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
10660                           FromPtrTy->getPointeeType()))
10661         BaseToDerivedConversion = 1;
10662     }
10663   } else if (const ObjCObjectPointerType *FromPtrTy
10664                                     = FromTy->getAs<ObjCObjectPointerType>()) {
10665     if (const ObjCObjectPointerType *ToPtrTy
10666                                         = ToTy->getAs<ObjCObjectPointerType>())
10667       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
10668         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
10669           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10670                                                 FromPtrTy->getPointeeType()) &&
10671               FromIface->isSuperClassOf(ToIface))
10672             BaseToDerivedConversion = 2;
10673   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
10674     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
10675         !FromTy->isIncompleteType() &&
10676         !ToRefTy->getPointeeType()->isIncompleteType() &&
10677         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
10678       BaseToDerivedConversion = 3;
10679     }
10680   }
10681 
10682   if (BaseToDerivedConversion) {
10683     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
10684         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10685         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10686         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
10687     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10688     return;
10689   }
10690 
10691   if (isa<ObjCObjectPointerType>(CFromTy) &&
10692       isa<PointerType>(CToTy)) {
10693       Qualifiers FromQs = CFromTy.getQualifiers();
10694       Qualifiers ToQs = CToTy.getQualifiers();
10695       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10696         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
10697             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10698             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10699             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
10700         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10701         return;
10702       }
10703   }
10704 
10705   if (TakingCandidateAddress &&
10706       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
10707     return;
10708 
10709   // Emit the generic diagnostic and, optionally, add the hints to it.
10710   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
10711   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10712         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10713         << ToTy << (unsigned)isObjectArgument << I + 1
10714         << (unsigned)(Cand->Fix.Kind);
10715 
10716   // If we can fix the conversion, suggest the FixIts.
10717   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
10718        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
10719     FDiag << *HI;
10720   S.Diag(Fn->getLocation(), FDiag);
10721 
10722   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10723 }
10724 
10725 /// Additional arity mismatch diagnosis specific to a function overload
10726 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
10727 /// over a candidate in any candidate set.
10728 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
10729                                unsigned NumArgs) {
10730   FunctionDecl *Fn = Cand->Function;
10731   unsigned MinParams = Fn->getMinRequiredArguments();
10732 
10733   // With invalid overloaded operators, it's possible that we think we
10734   // have an arity mismatch when in fact it looks like we have the
10735   // right number of arguments, because only overloaded operators have
10736   // the weird behavior of overloading member and non-member functions.
10737   // Just don't report anything.
10738   if (Fn->isInvalidDecl() &&
10739       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
10740     return true;
10741 
10742   if (NumArgs < MinParams) {
10743     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
10744            (Cand->FailureKind == ovl_fail_bad_deduction &&
10745             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
10746   } else {
10747     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
10748            (Cand->FailureKind == ovl_fail_bad_deduction &&
10749             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
10750   }
10751 
10752   return false;
10753 }
10754 
10755 /// General arity mismatch diagnosis over a candidate in a candidate set.
10756 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
10757                                   unsigned NumFormalArgs) {
10758   assert(isa<FunctionDecl>(D) &&
10759       "The templated declaration should at least be a function"
10760       " when diagnosing bad template argument deduction due to too many"
10761       " or too few arguments");
10762 
10763   FunctionDecl *Fn = cast<FunctionDecl>(D);
10764 
10765   // TODO: treat calls to a missing default constructor as a special case
10766   const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
10767   unsigned MinParams = Fn->getMinRequiredArguments();
10768 
10769   // at least / at most / exactly
10770   unsigned mode, modeCount;
10771   if (NumFormalArgs < MinParams) {
10772     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
10773         FnTy->isTemplateVariadic())
10774       mode = 0; // "at least"
10775     else
10776       mode = 2; // "exactly"
10777     modeCount = MinParams;
10778   } else {
10779     if (MinParams != FnTy->getNumParams())
10780       mode = 1; // "at most"
10781     else
10782       mode = 2; // "exactly"
10783     modeCount = FnTy->getNumParams();
10784   }
10785 
10786   std::string Description;
10787   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10788       ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
10789 
10790   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10791     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10792         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10793         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
10794   else
10795     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
10796         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10797         << Description << mode << modeCount << NumFormalArgs;
10798 
10799   MaybeEmitInheritedConstructorNote(S, Found);
10800 }
10801 
10802 /// Arity mismatch diagnosis specific to a function overload candidate.
10803 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
10804                                   unsigned NumFormalArgs) {
10805   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
10806     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10807 }
10808 
10809 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10810   if (TemplateDecl *TD = Templated->getDescribedTemplate())
10811     return TD;
10812   llvm_unreachable("Unsupported: Getting the described template declaration"
10813                    " for bad deduction diagnosis");
10814 }
10815 
10816 /// Diagnose a failed template-argument deduction.
10817 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10818                                  DeductionFailureInfo &DeductionFailure,
10819                                  unsigned NumArgs,
10820                                  bool TakingCandidateAddress) {
10821   TemplateParameter Param = DeductionFailure.getTemplateParameter();
10822   NamedDecl *ParamD;
10823   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10824   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10825   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10826   switch (DeductionFailure.Result) {
10827   case Sema::TDK_Success:
10828     llvm_unreachable("TDK_success while diagnosing bad deduction");
10829 
10830   case Sema::TDK_Incomplete: {
10831     assert(ParamD && "no parameter found for incomplete deduction result");
10832     S.Diag(Templated->getLocation(),
10833            diag::note_ovl_candidate_incomplete_deduction)
10834         << ParamD->getDeclName();
10835     MaybeEmitInheritedConstructorNote(S, Found);
10836     return;
10837   }
10838 
10839   case Sema::TDK_IncompletePack: {
10840     assert(ParamD && "no parameter found for incomplete deduction result");
10841     S.Diag(Templated->getLocation(),
10842            diag::note_ovl_candidate_incomplete_deduction_pack)
10843         << ParamD->getDeclName()
10844         << (DeductionFailure.getFirstArg()->pack_size() + 1)
10845         << *DeductionFailure.getFirstArg();
10846     MaybeEmitInheritedConstructorNote(S, Found);
10847     return;
10848   }
10849 
10850   case Sema::TDK_Underqualified: {
10851     assert(ParamD && "no parameter found for bad qualifiers deduction result");
10852     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10853 
10854     QualType Param = DeductionFailure.getFirstArg()->getAsType();
10855 
10856     // Param will have been canonicalized, but it should just be a
10857     // qualified version of ParamD, so move the qualifiers to that.
10858     QualifierCollector Qs;
10859     Qs.strip(Param);
10860     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10861     assert(S.Context.hasSameType(Param, NonCanonParam));
10862 
10863     // Arg has also been canonicalized, but there's nothing we can do
10864     // about that.  It also doesn't matter as much, because it won't
10865     // have any template parameters in it (because deduction isn't
10866     // done on dependent types).
10867     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10868 
10869     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10870         << ParamD->getDeclName() << Arg << NonCanonParam;
10871     MaybeEmitInheritedConstructorNote(S, Found);
10872     return;
10873   }
10874 
10875   case Sema::TDK_Inconsistent: {
10876     assert(ParamD && "no parameter found for inconsistent deduction result");
10877     int which = 0;
10878     if (isa<TemplateTypeParmDecl>(ParamD))
10879       which = 0;
10880     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10881       // Deduction might have failed because we deduced arguments of two
10882       // different types for a non-type template parameter.
10883       // FIXME: Use a different TDK value for this.
10884       QualType T1 =
10885           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10886       QualType T2 =
10887           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10888       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10889         S.Diag(Templated->getLocation(),
10890                diag::note_ovl_candidate_inconsistent_deduction_types)
10891           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10892           << *DeductionFailure.getSecondArg() << T2;
10893         MaybeEmitInheritedConstructorNote(S, Found);
10894         return;
10895       }
10896 
10897       which = 1;
10898     } else {
10899       which = 2;
10900     }
10901 
10902     // Tweak the diagnostic if the problem is that we deduced packs of
10903     // different arities. We'll print the actual packs anyway in case that
10904     // includes additional useful information.
10905     if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
10906         DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
10907         DeductionFailure.getFirstArg()->pack_size() !=
10908             DeductionFailure.getSecondArg()->pack_size()) {
10909       which = 3;
10910     }
10911 
10912     S.Diag(Templated->getLocation(),
10913            diag::note_ovl_candidate_inconsistent_deduction)
10914         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10915         << *DeductionFailure.getSecondArg();
10916     MaybeEmitInheritedConstructorNote(S, Found);
10917     return;
10918   }
10919 
10920   case Sema::TDK_InvalidExplicitArguments:
10921     assert(ParamD && "no parameter found for invalid explicit arguments");
10922     if (ParamD->getDeclName())
10923       S.Diag(Templated->getLocation(),
10924              diag::note_ovl_candidate_explicit_arg_mismatch_named)
10925           << ParamD->getDeclName();
10926     else {
10927       int index = 0;
10928       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10929         index = TTP->getIndex();
10930       else if (NonTypeTemplateParmDecl *NTTP
10931                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10932         index = NTTP->getIndex();
10933       else
10934         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10935       S.Diag(Templated->getLocation(),
10936              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10937           << (index + 1);
10938     }
10939     MaybeEmitInheritedConstructorNote(S, Found);
10940     return;
10941 
10942   case Sema::TDK_ConstraintsNotSatisfied: {
10943     // Format the template argument list into the argument string.
10944     SmallString<128> TemplateArgString;
10945     TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
10946     TemplateArgString = " ";
10947     TemplateArgString += S.getTemplateArgumentBindingsText(
10948         getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10949     if (TemplateArgString.size() == 1)
10950       TemplateArgString.clear();
10951     S.Diag(Templated->getLocation(),
10952            diag::note_ovl_candidate_unsatisfied_constraints)
10953         << TemplateArgString;
10954 
10955     S.DiagnoseUnsatisfiedConstraint(
10956         static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
10957     return;
10958   }
10959   case Sema::TDK_TooManyArguments:
10960   case Sema::TDK_TooFewArguments:
10961     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10962     return;
10963 
10964   case Sema::TDK_InstantiationDepth:
10965     S.Diag(Templated->getLocation(),
10966            diag::note_ovl_candidate_instantiation_depth);
10967     MaybeEmitInheritedConstructorNote(S, Found);
10968     return;
10969 
10970   case Sema::TDK_SubstitutionFailure: {
10971     // Format the template argument list into the argument string.
10972     SmallString<128> TemplateArgString;
10973     if (TemplateArgumentList *Args =
10974             DeductionFailure.getTemplateArgumentList()) {
10975       TemplateArgString = " ";
10976       TemplateArgString += S.getTemplateArgumentBindingsText(
10977           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10978       if (TemplateArgString.size() == 1)
10979         TemplateArgString.clear();
10980     }
10981 
10982     // If this candidate was disabled by enable_if, say so.
10983     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10984     if (PDiag && PDiag->second.getDiagID() ==
10985           diag::err_typename_nested_not_found_enable_if) {
10986       // FIXME: Use the source range of the condition, and the fully-qualified
10987       //        name of the enable_if template. These are both present in PDiag.
10988       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10989         << "'enable_if'" << TemplateArgString;
10990       return;
10991     }
10992 
10993     // We found a specific requirement that disabled the enable_if.
10994     if (PDiag && PDiag->second.getDiagID() ==
10995         diag::err_typename_nested_not_found_requirement) {
10996       S.Diag(Templated->getLocation(),
10997              diag::note_ovl_candidate_disabled_by_requirement)
10998         << PDiag->second.getStringArg(0) << TemplateArgString;
10999       return;
11000     }
11001 
11002     // Format the SFINAE diagnostic into the argument string.
11003     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
11004     //        formatted message in another diagnostic.
11005     SmallString<128> SFINAEArgString;
11006     SourceRange R;
11007     if (PDiag) {
11008       SFINAEArgString = ": ";
11009       R = SourceRange(PDiag->first, PDiag->first);
11010       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
11011     }
11012 
11013     S.Diag(Templated->getLocation(),
11014            diag::note_ovl_candidate_substitution_failure)
11015         << TemplateArgString << SFINAEArgString << R;
11016     MaybeEmitInheritedConstructorNote(S, Found);
11017     return;
11018   }
11019 
11020   case Sema::TDK_DeducedMismatch:
11021   case Sema::TDK_DeducedMismatchNested: {
11022     // Format the template argument list into the argument string.
11023     SmallString<128> TemplateArgString;
11024     if (TemplateArgumentList *Args =
11025             DeductionFailure.getTemplateArgumentList()) {
11026       TemplateArgString = " ";
11027       TemplateArgString += S.getTemplateArgumentBindingsText(
11028           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11029       if (TemplateArgString.size() == 1)
11030         TemplateArgString.clear();
11031     }
11032 
11033     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
11034         << (*DeductionFailure.getCallArgIndex() + 1)
11035         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
11036         << TemplateArgString
11037         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
11038     break;
11039   }
11040 
11041   case Sema::TDK_NonDeducedMismatch: {
11042     // FIXME: Provide a source location to indicate what we couldn't match.
11043     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
11044     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
11045     if (FirstTA.getKind() == TemplateArgument::Template &&
11046         SecondTA.getKind() == TemplateArgument::Template) {
11047       TemplateName FirstTN = FirstTA.getAsTemplate();
11048       TemplateName SecondTN = SecondTA.getAsTemplate();
11049       if (FirstTN.getKind() == TemplateName::Template &&
11050           SecondTN.getKind() == TemplateName::Template) {
11051         if (FirstTN.getAsTemplateDecl()->getName() ==
11052             SecondTN.getAsTemplateDecl()->getName()) {
11053           // FIXME: This fixes a bad diagnostic where both templates are named
11054           // the same.  This particular case is a bit difficult since:
11055           // 1) It is passed as a string to the diagnostic printer.
11056           // 2) The diagnostic printer only attempts to find a better
11057           //    name for types, not decls.
11058           // Ideally, this should folded into the diagnostic printer.
11059           S.Diag(Templated->getLocation(),
11060                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
11061               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
11062           return;
11063         }
11064       }
11065     }
11066 
11067     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
11068         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
11069       return;
11070 
11071     // FIXME: For generic lambda parameters, check if the function is a lambda
11072     // call operator, and if so, emit a prettier and more informative
11073     // diagnostic that mentions 'auto' and lambda in addition to
11074     // (or instead of?) the canonical template type parameters.
11075     S.Diag(Templated->getLocation(),
11076            diag::note_ovl_candidate_non_deduced_mismatch)
11077         << FirstTA << SecondTA;
11078     return;
11079   }
11080   // TODO: diagnose these individually, then kill off
11081   // note_ovl_candidate_bad_deduction, which is uselessly vague.
11082   case Sema::TDK_MiscellaneousDeductionFailure:
11083     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
11084     MaybeEmitInheritedConstructorNote(S, Found);
11085     return;
11086   case Sema::TDK_CUDATargetMismatch:
11087     S.Diag(Templated->getLocation(),
11088            diag::note_cuda_ovl_candidate_target_mismatch);
11089     return;
11090   }
11091 }
11092 
11093 /// Diagnose a failed template-argument deduction, for function calls.
11094 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
11095                                  unsigned NumArgs,
11096                                  bool TakingCandidateAddress) {
11097   unsigned TDK = Cand->DeductionFailure.Result;
11098   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
11099     if (CheckArityMismatch(S, Cand, NumArgs))
11100       return;
11101   }
11102   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
11103                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
11104 }
11105 
11106 /// CUDA: diagnose an invalid call across targets.
11107 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
11108   FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11109   FunctionDecl *Callee = Cand->Function;
11110 
11111   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
11112                            CalleeTarget = S.IdentifyCUDATarget(Callee);
11113 
11114   std::string FnDesc;
11115   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11116       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
11117                                 Cand->getRewriteKind(), FnDesc);
11118 
11119   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
11120       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11121       << FnDesc /* Ignored */
11122       << CalleeTarget << CallerTarget;
11123 
11124   // This could be an implicit constructor for which we could not infer the
11125   // target due to a collsion. Diagnose that case.
11126   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
11127   if (Meth != nullptr && Meth->isImplicit()) {
11128     CXXRecordDecl *ParentClass = Meth->getParent();
11129     Sema::CXXSpecialMember CSM;
11130 
11131     switch (FnKindPair.first) {
11132     default:
11133       return;
11134     case oc_implicit_default_constructor:
11135       CSM = Sema::CXXDefaultConstructor;
11136       break;
11137     case oc_implicit_copy_constructor:
11138       CSM = Sema::CXXCopyConstructor;
11139       break;
11140     case oc_implicit_move_constructor:
11141       CSM = Sema::CXXMoveConstructor;
11142       break;
11143     case oc_implicit_copy_assignment:
11144       CSM = Sema::CXXCopyAssignment;
11145       break;
11146     case oc_implicit_move_assignment:
11147       CSM = Sema::CXXMoveAssignment;
11148       break;
11149     };
11150 
11151     bool ConstRHS = false;
11152     if (Meth->getNumParams()) {
11153       if (const ReferenceType *RT =
11154               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
11155         ConstRHS = RT->getPointeeType().isConstQualified();
11156       }
11157     }
11158 
11159     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
11160                                               /* ConstRHS */ ConstRHS,
11161                                               /* Diagnose */ true);
11162   }
11163 }
11164 
11165 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
11166   FunctionDecl *Callee = Cand->Function;
11167   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
11168 
11169   S.Diag(Callee->getLocation(),
11170          diag::note_ovl_candidate_disabled_by_function_cond_attr)
11171       << Attr->getCond()->getSourceRange() << Attr->getMessage();
11172 }
11173 
11174 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
11175   ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function);
11176   assert(ES.isExplicit() && "not an explicit candidate");
11177 
11178   unsigned Kind;
11179   switch (Cand->Function->getDeclKind()) {
11180   case Decl::Kind::CXXConstructor:
11181     Kind = 0;
11182     break;
11183   case Decl::Kind::CXXConversion:
11184     Kind = 1;
11185     break;
11186   case Decl::Kind::CXXDeductionGuide:
11187     Kind = Cand->Function->isImplicit() ? 0 : 2;
11188     break;
11189   default:
11190     llvm_unreachable("invalid Decl");
11191   }
11192 
11193   // Note the location of the first (in-class) declaration; a redeclaration
11194   // (particularly an out-of-class definition) will typically lack the
11195   // 'explicit' specifier.
11196   // FIXME: This is probably a good thing to do for all 'candidate' notes.
11197   FunctionDecl *First = Cand->Function->getFirstDecl();
11198   if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
11199     First = Pattern->getFirstDecl();
11200 
11201   S.Diag(First->getLocation(),
11202          diag::note_ovl_candidate_explicit)
11203       << Kind << (ES.getExpr() ? 1 : 0)
11204       << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
11205 }
11206 
11207 /// Generates a 'note' diagnostic for an overload candidate.  We've
11208 /// already generated a primary error at the call site.
11209 ///
11210 /// It really does need to be a single diagnostic with its caret
11211 /// pointed at the candidate declaration.  Yes, this creates some
11212 /// major challenges of technical writing.  Yes, this makes pointing
11213 /// out problems with specific arguments quite awkward.  It's still
11214 /// better than generating twenty screens of text for every failed
11215 /// overload.
11216 ///
11217 /// It would be great to be able to express per-candidate problems
11218 /// more richly for those diagnostic clients that cared, but we'd
11219 /// still have to be just as careful with the default diagnostics.
11220 /// \param CtorDestAS Addr space of object being constructed (for ctor
11221 /// candidates only).
11222 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
11223                                   unsigned NumArgs,
11224                                   bool TakingCandidateAddress,
11225                                   LangAS CtorDestAS = LangAS::Default) {
11226   FunctionDecl *Fn = Cand->Function;
11227   if (shouldSkipNotingLambdaConversionDecl(Fn))
11228     return;
11229 
11230   // Note deleted candidates, but only if they're viable.
11231   if (Cand->Viable) {
11232     if (Fn->isDeleted()) {
11233       std::string FnDesc;
11234       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11235           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11236                                     Cand->getRewriteKind(), FnDesc);
11237 
11238       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
11239           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11240           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
11241       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11242       return;
11243     }
11244 
11245     // We don't really have anything else to say about viable candidates.
11246     S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11247     return;
11248   }
11249 
11250   switch (Cand->FailureKind) {
11251   case ovl_fail_too_many_arguments:
11252   case ovl_fail_too_few_arguments:
11253     return DiagnoseArityMismatch(S, Cand, NumArgs);
11254 
11255   case ovl_fail_bad_deduction:
11256     return DiagnoseBadDeduction(S, Cand, NumArgs,
11257                                 TakingCandidateAddress);
11258 
11259   case ovl_fail_illegal_constructor: {
11260     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
11261       << (Fn->getPrimaryTemplate() ? 1 : 0);
11262     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11263     return;
11264   }
11265 
11266   case ovl_fail_object_addrspace_mismatch: {
11267     Qualifiers QualsForPrinting;
11268     QualsForPrinting.setAddressSpace(CtorDestAS);
11269     S.Diag(Fn->getLocation(),
11270            diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
11271         << QualsForPrinting;
11272     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11273     return;
11274   }
11275 
11276   case ovl_fail_trivial_conversion:
11277   case ovl_fail_bad_final_conversion:
11278   case ovl_fail_final_conversion_not_exact:
11279     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11280 
11281   case ovl_fail_bad_conversion: {
11282     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
11283     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
11284       if (Cand->Conversions[I].isBad())
11285         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
11286 
11287     // FIXME: this currently happens when we're called from SemaInit
11288     // when user-conversion overload fails.  Figure out how to handle
11289     // those conditions and diagnose them well.
11290     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11291   }
11292 
11293   case ovl_fail_bad_target:
11294     return DiagnoseBadTarget(S, Cand);
11295 
11296   case ovl_fail_enable_if:
11297     return DiagnoseFailedEnableIfAttr(S, Cand);
11298 
11299   case ovl_fail_explicit:
11300     return DiagnoseFailedExplicitSpec(S, Cand);
11301 
11302   case ovl_fail_inhctor_slice:
11303     // It's generally not interesting to note copy/move constructors here.
11304     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
11305       return;
11306     S.Diag(Fn->getLocation(),
11307            diag::note_ovl_candidate_inherited_constructor_slice)
11308       << (Fn->getPrimaryTemplate() ? 1 : 0)
11309       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
11310     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11311     return;
11312 
11313   case ovl_fail_addr_not_available: {
11314     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
11315     (void)Available;
11316     assert(!Available);
11317     break;
11318   }
11319   case ovl_non_default_multiversion_function:
11320     // Do nothing, these should simply be ignored.
11321     break;
11322 
11323   case ovl_fail_constraints_not_satisfied: {
11324     std::string FnDesc;
11325     std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11326         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11327                                   Cand->getRewriteKind(), FnDesc);
11328 
11329     S.Diag(Fn->getLocation(),
11330            diag::note_ovl_candidate_constraints_not_satisfied)
11331         << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11332         << FnDesc /* Ignored */;
11333     ConstraintSatisfaction Satisfaction;
11334     if (S.CheckFunctionConstraints(Fn, Satisfaction))
11335       break;
11336     S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11337   }
11338   }
11339 }
11340 
11341 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
11342   if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate))
11343     return;
11344 
11345   // Desugar the type of the surrogate down to a function type,
11346   // retaining as many typedefs as possible while still showing
11347   // the function type (and, therefore, its parameter types).
11348   QualType FnType = Cand->Surrogate->getConversionType();
11349   bool isLValueReference = false;
11350   bool isRValueReference = false;
11351   bool isPointer = false;
11352   if (const LValueReferenceType *FnTypeRef =
11353         FnType->getAs<LValueReferenceType>()) {
11354     FnType = FnTypeRef->getPointeeType();
11355     isLValueReference = true;
11356   } else if (const RValueReferenceType *FnTypeRef =
11357                FnType->getAs<RValueReferenceType>()) {
11358     FnType = FnTypeRef->getPointeeType();
11359     isRValueReference = true;
11360   }
11361   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
11362     FnType = FnTypePtr->getPointeeType();
11363     isPointer = true;
11364   }
11365   // Desugar down to a function type.
11366   FnType = QualType(FnType->getAs<FunctionType>(), 0);
11367   // Reconstruct the pointer/reference as appropriate.
11368   if (isPointer) FnType = S.Context.getPointerType(FnType);
11369   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
11370   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
11371 
11372   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
11373     << FnType;
11374 }
11375 
11376 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
11377                                          SourceLocation OpLoc,
11378                                          OverloadCandidate *Cand) {
11379   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
11380   std::string TypeStr("operator");
11381   TypeStr += Opc;
11382   TypeStr += "(";
11383   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
11384   if (Cand->Conversions.size() == 1) {
11385     TypeStr += ")";
11386     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11387   } else {
11388     TypeStr += ", ";
11389     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
11390     TypeStr += ")";
11391     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11392   }
11393 }
11394 
11395 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
11396                                          OverloadCandidate *Cand) {
11397   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
11398     if (ICS.isBad()) break; // all meaningless after first invalid
11399     if (!ICS.isAmbiguous()) continue;
11400 
11401     ICS.DiagnoseAmbiguousConversion(
11402         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
11403   }
11404 }
11405 
11406 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
11407   if (Cand->Function)
11408     return Cand->Function->getLocation();
11409   if (Cand->IsSurrogate)
11410     return Cand->Surrogate->getLocation();
11411   return SourceLocation();
11412 }
11413 
11414 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
11415   switch ((Sema::TemplateDeductionResult)DFI.Result) {
11416   case Sema::TDK_Success:
11417   case Sema::TDK_NonDependentConversionFailure:
11418     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
11419 
11420   case Sema::TDK_Invalid:
11421   case Sema::TDK_Incomplete:
11422   case Sema::TDK_IncompletePack:
11423     return 1;
11424 
11425   case Sema::TDK_Underqualified:
11426   case Sema::TDK_Inconsistent:
11427     return 2;
11428 
11429   case Sema::TDK_SubstitutionFailure:
11430   case Sema::TDK_DeducedMismatch:
11431   case Sema::TDK_ConstraintsNotSatisfied:
11432   case Sema::TDK_DeducedMismatchNested:
11433   case Sema::TDK_NonDeducedMismatch:
11434   case Sema::TDK_MiscellaneousDeductionFailure:
11435   case Sema::TDK_CUDATargetMismatch:
11436     return 3;
11437 
11438   case Sema::TDK_InstantiationDepth:
11439     return 4;
11440 
11441   case Sema::TDK_InvalidExplicitArguments:
11442     return 5;
11443 
11444   case Sema::TDK_TooManyArguments:
11445   case Sema::TDK_TooFewArguments:
11446     return 6;
11447   }
11448   llvm_unreachable("Unhandled deduction result");
11449 }
11450 
11451 namespace {
11452 struct CompareOverloadCandidatesForDisplay {
11453   Sema &S;
11454   SourceLocation Loc;
11455   size_t NumArgs;
11456   OverloadCandidateSet::CandidateSetKind CSK;
11457 
11458   CompareOverloadCandidatesForDisplay(
11459       Sema &S, SourceLocation Loc, size_t NArgs,
11460       OverloadCandidateSet::CandidateSetKind CSK)
11461       : S(S), NumArgs(NArgs), CSK(CSK) {}
11462 
11463   OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
11464     // If there are too many or too few arguments, that's the high-order bit we
11465     // want to sort by, even if the immediate failure kind was something else.
11466     if (C->FailureKind == ovl_fail_too_many_arguments ||
11467         C->FailureKind == ovl_fail_too_few_arguments)
11468       return static_cast<OverloadFailureKind>(C->FailureKind);
11469 
11470     if (C->Function) {
11471       if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
11472         return ovl_fail_too_many_arguments;
11473       if (NumArgs < C->Function->getMinRequiredArguments())
11474         return ovl_fail_too_few_arguments;
11475     }
11476 
11477     return static_cast<OverloadFailureKind>(C->FailureKind);
11478   }
11479 
11480   bool operator()(const OverloadCandidate *L,
11481                   const OverloadCandidate *R) {
11482     // Fast-path this check.
11483     if (L == R) return false;
11484 
11485     // Order first by viability.
11486     if (L->Viable) {
11487       if (!R->Viable) return true;
11488 
11489       // TODO: introduce a tri-valued comparison for overload
11490       // candidates.  Would be more worthwhile if we had a sort
11491       // that could exploit it.
11492       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
11493         return true;
11494       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
11495         return false;
11496     } else if (R->Viable)
11497       return false;
11498 
11499     assert(L->Viable == R->Viable);
11500 
11501     // Criteria by which we can sort non-viable candidates:
11502     if (!L->Viable) {
11503       OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
11504       OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
11505 
11506       // 1. Arity mismatches come after other candidates.
11507       if (LFailureKind == ovl_fail_too_many_arguments ||
11508           LFailureKind == ovl_fail_too_few_arguments) {
11509         if (RFailureKind == ovl_fail_too_many_arguments ||
11510             RFailureKind == ovl_fail_too_few_arguments) {
11511           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
11512           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
11513           if (LDist == RDist) {
11514             if (LFailureKind == RFailureKind)
11515               // Sort non-surrogates before surrogates.
11516               return !L->IsSurrogate && R->IsSurrogate;
11517             // Sort candidates requiring fewer parameters than there were
11518             // arguments given after candidates requiring more parameters
11519             // than there were arguments given.
11520             return LFailureKind == ovl_fail_too_many_arguments;
11521           }
11522           return LDist < RDist;
11523         }
11524         return false;
11525       }
11526       if (RFailureKind == ovl_fail_too_many_arguments ||
11527           RFailureKind == ovl_fail_too_few_arguments)
11528         return true;
11529 
11530       // 2. Bad conversions come first and are ordered by the number
11531       // of bad conversions and quality of good conversions.
11532       if (LFailureKind == ovl_fail_bad_conversion) {
11533         if (RFailureKind != ovl_fail_bad_conversion)
11534           return true;
11535 
11536         // The conversion that can be fixed with a smaller number of changes,
11537         // comes first.
11538         unsigned numLFixes = L->Fix.NumConversionsFixed;
11539         unsigned numRFixes = R->Fix.NumConversionsFixed;
11540         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
11541         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
11542         if (numLFixes != numRFixes) {
11543           return numLFixes < numRFixes;
11544         }
11545 
11546         // If there's any ordering between the defined conversions...
11547         // FIXME: this might not be transitive.
11548         assert(L->Conversions.size() == R->Conversions.size());
11549 
11550         int leftBetter = 0;
11551         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
11552         for (unsigned E = L->Conversions.size(); I != E; ++I) {
11553           switch (CompareImplicitConversionSequences(S, Loc,
11554                                                      L->Conversions[I],
11555                                                      R->Conversions[I])) {
11556           case ImplicitConversionSequence::Better:
11557             leftBetter++;
11558             break;
11559 
11560           case ImplicitConversionSequence::Worse:
11561             leftBetter--;
11562             break;
11563 
11564           case ImplicitConversionSequence::Indistinguishable:
11565             break;
11566           }
11567         }
11568         if (leftBetter > 0) return true;
11569         if (leftBetter < 0) return false;
11570 
11571       } else if (RFailureKind == ovl_fail_bad_conversion)
11572         return false;
11573 
11574       if (LFailureKind == ovl_fail_bad_deduction) {
11575         if (RFailureKind != ovl_fail_bad_deduction)
11576           return true;
11577 
11578         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11579           return RankDeductionFailure(L->DeductionFailure)
11580                < RankDeductionFailure(R->DeductionFailure);
11581       } else if (RFailureKind == ovl_fail_bad_deduction)
11582         return false;
11583 
11584       // TODO: others?
11585     }
11586 
11587     // Sort everything else by location.
11588     SourceLocation LLoc = GetLocationForCandidate(L);
11589     SourceLocation RLoc = GetLocationForCandidate(R);
11590 
11591     // Put candidates without locations (e.g. builtins) at the end.
11592     if (LLoc.isInvalid()) return false;
11593     if (RLoc.isInvalid()) return true;
11594 
11595     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11596   }
11597 };
11598 }
11599 
11600 /// CompleteNonViableCandidate - Normally, overload resolution only
11601 /// computes up to the first bad conversion. Produces the FixIt set if
11602 /// possible.
11603 static void
11604 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
11605                            ArrayRef<Expr *> Args,
11606                            OverloadCandidateSet::CandidateSetKind CSK) {
11607   assert(!Cand->Viable);
11608 
11609   // Don't do anything on failures other than bad conversion.
11610   if (Cand->FailureKind != ovl_fail_bad_conversion)
11611     return;
11612 
11613   // We only want the FixIts if all the arguments can be corrected.
11614   bool Unfixable = false;
11615   // Use a implicit copy initialization to check conversion fixes.
11616   Cand->Fix.setConversionChecker(TryCopyInitialization);
11617 
11618   // Attempt to fix the bad conversion.
11619   unsigned ConvCount = Cand->Conversions.size();
11620   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
11621        ++ConvIdx) {
11622     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
11623     if (Cand->Conversions[ConvIdx].isInitialized() &&
11624         Cand->Conversions[ConvIdx].isBad()) {
11625       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11626       break;
11627     }
11628   }
11629 
11630   // FIXME: this should probably be preserved from the overload
11631   // operation somehow.
11632   bool SuppressUserConversions = false;
11633 
11634   unsigned ConvIdx = 0;
11635   unsigned ArgIdx = 0;
11636   ArrayRef<QualType> ParamTypes;
11637   bool Reversed = Cand->isReversed();
11638 
11639   if (Cand->IsSurrogate) {
11640     QualType ConvType
11641       = Cand->Surrogate->getConversionType().getNonReferenceType();
11642     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11643       ConvType = ConvPtrType->getPointeeType();
11644     ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
11645     // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11646     ConvIdx = 1;
11647   } else if (Cand->Function) {
11648     ParamTypes =
11649         Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
11650     if (isa<CXXMethodDecl>(Cand->Function) &&
11651         !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
11652       // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11653       ConvIdx = 1;
11654       if (CSK == OverloadCandidateSet::CSK_Operator &&
11655           Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
11656           Cand->Function->getDeclName().getCXXOverloadedOperator() !=
11657               OO_Subscript)
11658         // Argument 0 is 'this', which doesn't have a corresponding parameter.
11659         ArgIdx = 1;
11660     }
11661   } else {
11662     // Builtin operator.
11663     assert(ConvCount <= 3);
11664     ParamTypes = Cand->BuiltinParamTypes;
11665   }
11666 
11667   // Fill in the rest of the conversions.
11668   for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
11669        ConvIdx != ConvCount;
11670        ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
11671     assert(ArgIdx < Args.size() && "no argument for this arg conversion");
11672     if (Cand->Conversions[ConvIdx].isInitialized()) {
11673       // We've already checked this conversion.
11674     } else if (ParamIdx < ParamTypes.size()) {
11675       if (ParamTypes[ParamIdx]->isDependentType())
11676         Cand->Conversions[ConvIdx].setAsIdentityConversion(
11677             Args[ArgIdx]->getType());
11678       else {
11679         Cand->Conversions[ConvIdx] =
11680             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
11681                                   SuppressUserConversions,
11682                                   /*InOverloadResolution=*/true,
11683                                   /*AllowObjCWritebackConversion=*/
11684                                   S.getLangOpts().ObjCAutoRefCount);
11685         // Store the FixIt in the candidate if it exists.
11686         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
11687           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11688       }
11689     } else
11690       Cand->Conversions[ConvIdx].setEllipsis();
11691   }
11692 }
11693 
11694 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
11695     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11696     SourceLocation OpLoc,
11697     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11698   // Sort the candidates by viability and position.  Sorting directly would
11699   // be prohibitive, so we make a set of pointers and sort those.
11700   SmallVector<OverloadCandidate*, 32> Cands;
11701   if (OCD == OCD_AllCandidates) Cands.reserve(size());
11702   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11703     if (!Filter(*Cand))
11704       continue;
11705     switch (OCD) {
11706     case OCD_AllCandidates:
11707       if (!Cand->Viable) {
11708         if (!Cand->Function && !Cand->IsSurrogate) {
11709           // This a non-viable builtin candidate.  We do not, in general,
11710           // want to list every possible builtin candidate.
11711           continue;
11712         }
11713         CompleteNonViableCandidate(S, Cand, Args, Kind);
11714       }
11715       break;
11716 
11717     case OCD_ViableCandidates:
11718       if (!Cand->Viable)
11719         continue;
11720       break;
11721 
11722     case OCD_AmbiguousCandidates:
11723       if (!Cand->Best)
11724         continue;
11725       break;
11726     }
11727 
11728     Cands.push_back(Cand);
11729   }
11730 
11731   llvm::stable_sort(
11732       Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
11733 
11734   return Cands;
11735 }
11736 
11737 bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
11738                                             SourceLocation OpLoc) {
11739   bool DeferHint = false;
11740   if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
11741     // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
11742     // host device candidates.
11743     auto WrongSidedCands =
11744         CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
11745           return (Cand.Viable == false &&
11746                   Cand.FailureKind == ovl_fail_bad_target) ||
11747                  (Cand.Function &&
11748                   Cand.Function->template hasAttr<CUDAHostAttr>() &&
11749                   Cand.Function->template hasAttr<CUDADeviceAttr>());
11750         });
11751     DeferHint = !WrongSidedCands.empty();
11752   }
11753   return DeferHint;
11754 }
11755 
11756 /// When overload resolution fails, prints diagnostic messages containing the
11757 /// candidates in the candidate set.
11758 void OverloadCandidateSet::NoteCandidates(
11759     PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
11760     ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
11761     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11762 
11763   auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
11764 
11765   S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
11766 
11767   NoteCandidates(S, Args, Cands, Opc, OpLoc);
11768 
11769   if (OCD == OCD_AmbiguousCandidates)
11770     MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
11771 }
11772 
11773 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
11774                                           ArrayRef<OverloadCandidate *> Cands,
11775                                           StringRef Opc, SourceLocation OpLoc) {
11776   bool ReportedAmbiguousConversions = false;
11777 
11778   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11779   unsigned CandsShown = 0;
11780   auto I = Cands.begin(), E = Cands.end();
11781   for (; I != E; ++I) {
11782     OverloadCandidate *Cand = *I;
11783 
11784     if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
11785         ShowOverloads == Ovl_Best) {
11786       break;
11787     }
11788     ++CandsShown;
11789 
11790     if (Cand->Function)
11791       NoteFunctionCandidate(S, Cand, Args.size(),
11792                             /*TakingCandidateAddress=*/false, DestAS);
11793     else if (Cand->IsSurrogate)
11794       NoteSurrogateCandidate(S, Cand);
11795     else {
11796       assert(Cand->Viable &&
11797              "Non-viable built-in candidates are not added to Cands.");
11798       // Generally we only see ambiguities including viable builtin
11799       // operators if overload resolution got screwed up by an
11800       // ambiguous user-defined conversion.
11801       //
11802       // FIXME: It's quite possible for different conversions to see
11803       // different ambiguities, though.
11804       if (!ReportedAmbiguousConversions) {
11805         NoteAmbiguousUserConversions(S, OpLoc, Cand);
11806         ReportedAmbiguousConversions = true;
11807       }
11808 
11809       // If this is a viable builtin, print it.
11810       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
11811     }
11812   }
11813 
11814   // Inform S.Diags that we've shown an overload set with N elements.  This may
11815   // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
11816   S.Diags.overloadCandidatesShown(CandsShown);
11817 
11818   if (I != E)
11819     S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
11820            shouldDeferDiags(S, Args, OpLoc))
11821         << int(E - I);
11822 }
11823 
11824 static SourceLocation
11825 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
11826   return Cand->Specialization ? Cand->Specialization->getLocation()
11827                               : SourceLocation();
11828 }
11829 
11830 namespace {
11831 struct CompareTemplateSpecCandidatesForDisplay {
11832   Sema &S;
11833   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
11834 
11835   bool operator()(const TemplateSpecCandidate *L,
11836                   const TemplateSpecCandidate *R) {
11837     // Fast-path this check.
11838     if (L == R)
11839       return false;
11840 
11841     // Assuming that both candidates are not matches...
11842 
11843     // Sort by the ranking of deduction failures.
11844     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11845       return RankDeductionFailure(L->DeductionFailure) <
11846              RankDeductionFailure(R->DeductionFailure);
11847 
11848     // Sort everything else by location.
11849     SourceLocation LLoc = GetLocationForCandidate(L);
11850     SourceLocation RLoc = GetLocationForCandidate(R);
11851 
11852     // Put candidates without locations (e.g. builtins) at the end.
11853     if (LLoc.isInvalid())
11854       return false;
11855     if (RLoc.isInvalid())
11856       return true;
11857 
11858     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11859   }
11860 };
11861 }
11862 
11863 /// Diagnose a template argument deduction failure.
11864 /// We are treating these failures as overload failures due to bad
11865 /// deductions.
11866 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
11867                                                  bool ForTakingAddress) {
11868   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
11869                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
11870 }
11871 
11872 void TemplateSpecCandidateSet::destroyCandidates() {
11873   for (iterator i = begin(), e = end(); i != e; ++i) {
11874     i->DeductionFailure.Destroy();
11875   }
11876 }
11877 
11878 void TemplateSpecCandidateSet::clear() {
11879   destroyCandidates();
11880   Candidates.clear();
11881 }
11882 
11883 /// NoteCandidates - When no template specialization match is found, prints
11884 /// diagnostic messages containing the non-matching specializations that form
11885 /// the candidate set.
11886 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
11887 /// OCD == OCD_AllCandidates and Cand->Viable == false.
11888 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
11889   // Sort the candidates by position (assuming no candidate is a match).
11890   // Sorting directly would be prohibitive, so we make a set of pointers
11891   // and sort those.
11892   SmallVector<TemplateSpecCandidate *, 32> Cands;
11893   Cands.reserve(size());
11894   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11895     if (Cand->Specialization)
11896       Cands.push_back(Cand);
11897     // Otherwise, this is a non-matching builtin candidate.  We do not,
11898     // in general, want to list every possible builtin candidate.
11899   }
11900 
11901   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
11902 
11903   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
11904   // for generalization purposes (?).
11905   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11906 
11907   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
11908   unsigned CandsShown = 0;
11909   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11910     TemplateSpecCandidate *Cand = *I;
11911 
11912     // Set an arbitrary limit on the number of candidates we'll spam
11913     // the user with.  FIXME: This limit should depend on details of the
11914     // candidate list.
11915     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
11916       break;
11917     ++CandsShown;
11918 
11919     assert(Cand->Specialization &&
11920            "Non-matching built-in candidates are not added to Cands.");
11921     Cand->NoteDeductionFailure(S, ForTakingAddress);
11922   }
11923 
11924   if (I != E)
11925     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
11926 }
11927 
11928 // [PossiblyAFunctionType]  -->   [Return]
11929 // NonFunctionType --> NonFunctionType
11930 // R (A) --> R(A)
11931 // R (*)(A) --> R (A)
11932 // R (&)(A) --> R (A)
11933 // R (S::*)(A) --> R (A)
11934 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
11935   QualType Ret = PossiblyAFunctionType;
11936   if (const PointerType *ToTypePtr =
11937     PossiblyAFunctionType->getAs<PointerType>())
11938     Ret = ToTypePtr->getPointeeType();
11939   else if (const ReferenceType *ToTypeRef =
11940     PossiblyAFunctionType->getAs<ReferenceType>())
11941     Ret = ToTypeRef->getPointeeType();
11942   else if (const MemberPointerType *MemTypePtr =
11943     PossiblyAFunctionType->getAs<MemberPointerType>())
11944     Ret = MemTypePtr->getPointeeType();
11945   Ret =
11946     Context.getCanonicalType(Ret).getUnqualifiedType();
11947   return Ret;
11948 }
11949 
11950 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
11951                                  bool Complain = true) {
11952   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
11953       S.DeduceReturnType(FD, Loc, Complain))
11954     return true;
11955 
11956   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
11957   if (S.getLangOpts().CPlusPlus17 &&
11958       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
11959       !S.ResolveExceptionSpec(Loc, FPT))
11960     return true;
11961 
11962   return false;
11963 }
11964 
11965 namespace {
11966 // A helper class to help with address of function resolution
11967 // - allows us to avoid passing around all those ugly parameters
11968 class AddressOfFunctionResolver {
11969   Sema& S;
11970   Expr* SourceExpr;
11971   const QualType& TargetType;
11972   QualType TargetFunctionType; // Extracted function type from target type
11973 
11974   bool Complain;
11975   //DeclAccessPair& ResultFunctionAccessPair;
11976   ASTContext& Context;
11977 
11978   bool TargetTypeIsNonStaticMemberFunction;
11979   bool FoundNonTemplateFunction;
11980   bool StaticMemberFunctionFromBoundPointer;
11981   bool HasComplained;
11982 
11983   OverloadExpr::FindResult OvlExprInfo;
11984   OverloadExpr *OvlExpr;
11985   TemplateArgumentListInfo OvlExplicitTemplateArgs;
11986   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
11987   TemplateSpecCandidateSet FailedCandidates;
11988 
11989 public:
11990   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
11991                             const QualType &TargetType, bool Complain)
11992       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
11993         Complain(Complain), Context(S.getASTContext()),
11994         TargetTypeIsNonStaticMemberFunction(
11995             !!TargetType->getAs<MemberPointerType>()),
11996         FoundNonTemplateFunction(false),
11997         StaticMemberFunctionFromBoundPointer(false),
11998         HasComplained(false),
11999         OvlExprInfo(OverloadExpr::find(SourceExpr)),
12000         OvlExpr(OvlExprInfo.Expression),
12001         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
12002     ExtractUnqualifiedFunctionTypeFromTargetType();
12003 
12004     if (TargetFunctionType->isFunctionType()) {
12005       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
12006         if (!UME->isImplicitAccess() &&
12007             !S.ResolveSingleFunctionTemplateSpecialization(UME))
12008           StaticMemberFunctionFromBoundPointer = true;
12009     } else if (OvlExpr->hasExplicitTemplateArgs()) {
12010       DeclAccessPair dap;
12011       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
12012               OvlExpr, false, &dap)) {
12013         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
12014           if (!Method->isStatic()) {
12015             // If the target type is a non-function type and the function found
12016             // is a non-static member function, pretend as if that was the
12017             // target, it's the only possible type to end up with.
12018             TargetTypeIsNonStaticMemberFunction = true;
12019 
12020             // And skip adding the function if its not in the proper form.
12021             // We'll diagnose this due to an empty set of functions.
12022             if (!OvlExprInfo.HasFormOfMemberPointer)
12023               return;
12024           }
12025 
12026         Matches.push_back(std::make_pair(dap, Fn));
12027       }
12028       return;
12029     }
12030 
12031     if (OvlExpr->hasExplicitTemplateArgs())
12032       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
12033 
12034     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
12035       // C++ [over.over]p4:
12036       //   If more than one function is selected, [...]
12037       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
12038         if (FoundNonTemplateFunction)
12039           EliminateAllTemplateMatches();
12040         else
12041           EliminateAllExceptMostSpecializedTemplate();
12042       }
12043     }
12044 
12045     if (S.getLangOpts().CUDA && Matches.size() > 1)
12046       EliminateSuboptimalCudaMatches();
12047   }
12048 
12049   bool hasComplained() const { return HasComplained; }
12050 
12051 private:
12052   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
12053     QualType Discard;
12054     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
12055            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
12056   }
12057 
12058   /// \return true if A is considered a better overload candidate for the
12059   /// desired type than B.
12060   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
12061     // If A doesn't have exactly the correct type, we don't want to classify it
12062     // as "better" than anything else. This way, the user is required to
12063     // disambiguate for us if there are multiple candidates and no exact match.
12064     return candidateHasExactlyCorrectType(A) &&
12065            (!candidateHasExactlyCorrectType(B) ||
12066             compareEnableIfAttrs(S, A, B) == Comparison::Better);
12067   }
12068 
12069   /// \return true if we were able to eliminate all but one overload candidate,
12070   /// false otherwise.
12071   bool eliminiateSuboptimalOverloadCandidates() {
12072     // Same algorithm as overload resolution -- one pass to pick the "best",
12073     // another pass to be sure that nothing is better than the best.
12074     auto Best = Matches.begin();
12075     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
12076       if (isBetterCandidate(I->second, Best->second))
12077         Best = I;
12078 
12079     const FunctionDecl *BestFn = Best->second;
12080     auto IsBestOrInferiorToBest = [this, BestFn](
12081         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
12082       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
12083     };
12084 
12085     // Note: We explicitly leave Matches unmodified if there isn't a clear best
12086     // option, so we can potentially give the user a better error
12087     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
12088       return false;
12089     Matches[0] = *Best;
12090     Matches.resize(1);
12091     return true;
12092   }
12093 
12094   bool isTargetTypeAFunction() const {
12095     return TargetFunctionType->isFunctionType();
12096   }
12097 
12098   // [ToType]     [Return]
12099 
12100   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
12101   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
12102   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
12103   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
12104     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
12105   }
12106 
12107   // return true if any matching specializations were found
12108   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
12109                                    const DeclAccessPair& CurAccessFunPair) {
12110     if (CXXMethodDecl *Method
12111               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
12112       // Skip non-static function templates when converting to pointer, and
12113       // static when converting to member pointer.
12114       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
12115         return false;
12116     }
12117     else if (TargetTypeIsNonStaticMemberFunction)
12118       return false;
12119 
12120     // C++ [over.over]p2:
12121     //   If the name is a function template, template argument deduction is
12122     //   done (14.8.2.2), and if the argument deduction succeeds, the
12123     //   resulting template argument list is used to generate a single
12124     //   function template specialization, which is added to the set of
12125     //   overloaded functions considered.
12126     FunctionDecl *Specialization = nullptr;
12127     TemplateDeductionInfo Info(FailedCandidates.getLocation());
12128     if (Sema::TemplateDeductionResult Result
12129           = S.DeduceTemplateArguments(FunctionTemplate,
12130                                       &OvlExplicitTemplateArgs,
12131                                       TargetFunctionType, Specialization,
12132                                       Info, /*IsAddressOfFunction*/true)) {
12133       // Make a note of the failed deduction for diagnostics.
12134       FailedCandidates.addCandidate()
12135           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
12136                MakeDeductionFailureInfo(Context, Result, Info));
12137       return false;
12138     }
12139 
12140     // Template argument deduction ensures that we have an exact match or
12141     // compatible pointer-to-function arguments that would be adjusted by ICS.
12142     // This function template specicalization works.
12143     assert(S.isSameOrCompatibleFunctionType(
12144               Context.getCanonicalType(Specialization->getType()),
12145               Context.getCanonicalType(TargetFunctionType)));
12146 
12147     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
12148       return false;
12149 
12150     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
12151     return true;
12152   }
12153 
12154   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
12155                                       const DeclAccessPair& CurAccessFunPair) {
12156     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12157       // Skip non-static functions when converting to pointer, and static
12158       // when converting to member pointer.
12159       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
12160         return false;
12161     }
12162     else if (TargetTypeIsNonStaticMemberFunction)
12163       return false;
12164 
12165     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
12166       if (S.getLangOpts().CUDA)
12167         if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true))
12168           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
12169             return false;
12170       if (FunDecl->isMultiVersion()) {
12171         const auto *TA = FunDecl->getAttr<TargetAttr>();
12172         if (TA && !TA->isDefaultVersion())
12173           return false;
12174       }
12175 
12176       // If any candidate has a placeholder return type, trigger its deduction
12177       // now.
12178       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
12179                                Complain)) {
12180         HasComplained |= Complain;
12181         return false;
12182       }
12183 
12184       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
12185         return false;
12186 
12187       // If we're in C, we need to support types that aren't exactly identical.
12188       if (!S.getLangOpts().CPlusPlus ||
12189           candidateHasExactlyCorrectType(FunDecl)) {
12190         Matches.push_back(std::make_pair(
12191             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
12192         FoundNonTemplateFunction = true;
12193         return true;
12194       }
12195     }
12196 
12197     return false;
12198   }
12199 
12200   bool FindAllFunctionsThatMatchTargetTypeExactly() {
12201     bool Ret = false;
12202 
12203     // If the overload expression doesn't have the form of a pointer to
12204     // member, don't try to convert it to a pointer-to-member type.
12205     if (IsInvalidFormOfPointerToMemberFunction())
12206       return false;
12207 
12208     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12209                                E = OvlExpr->decls_end();
12210          I != E; ++I) {
12211       // Look through any using declarations to find the underlying function.
12212       NamedDecl *Fn = (*I)->getUnderlyingDecl();
12213 
12214       // C++ [over.over]p3:
12215       //   Non-member functions and static member functions match
12216       //   targets of type "pointer-to-function" or "reference-to-function."
12217       //   Nonstatic member functions match targets of
12218       //   type "pointer-to-member-function."
12219       // Note that according to DR 247, the containing class does not matter.
12220       if (FunctionTemplateDecl *FunctionTemplate
12221                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
12222         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
12223           Ret = true;
12224       }
12225       // If we have explicit template arguments supplied, skip non-templates.
12226       else if (!OvlExpr->hasExplicitTemplateArgs() &&
12227                AddMatchingNonTemplateFunction(Fn, I.getPair()))
12228         Ret = true;
12229     }
12230     assert(Ret || Matches.empty());
12231     return Ret;
12232   }
12233 
12234   void EliminateAllExceptMostSpecializedTemplate() {
12235     //   [...] and any given function template specialization F1 is
12236     //   eliminated if the set contains a second function template
12237     //   specialization whose function template is more specialized
12238     //   than the function template of F1 according to the partial
12239     //   ordering rules of 14.5.5.2.
12240 
12241     // The algorithm specified above is quadratic. We instead use a
12242     // two-pass algorithm (similar to the one used to identify the
12243     // best viable function in an overload set) that identifies the
12244     // best function template (if it exists).
12245 
12246     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
12247     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
12248       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
12249 
12250     // TODO: It looks like FailedCandidates does not serve much purpose
12251     // here, since the no_viable diagnostic has index 0.
12252     UnresolvedSetIterator Result = S.getMostSpecialized(
12253         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
12254         SourceExpr->getBeginLoc(), S.PDiag(),
12255         S.PDiag(diag::err_addr_ovl_ambiguous)
12256             << Matches[0].second->getDeclName(),
12257         S.PDiag(diag::note_ovl_candidate)
12258             << (unsigned)oc_function << (unsigned)ocs_described_template,
12259         Complain, TargetFunctionType);
12260 
12261     if (Result != MatchesCopy.end()) {
12262       // Make it the first and only element
12263       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
12264       Matches[0].second = cast<FunctionDecl>(*Result);
12265       Matches.resize(1);
12266     } else
12267       HasComplained |= Complain;
12268   }
12269 
12270   void EliminateAllTemplateMatches() {
12271     //   [...] any function template specializations in the set are
12272     //   eliminated if the set also contains a non-template function, [...]
12273     for (unsigned I = 0, N = Matches.size(); I != N; ) {
12274       if (Matches[I].second->getPrimaryTemplate() == nullptr)
12275         ++I;
12276       else {
12277         Matches[I] = Matches[--N];
12278         Matches.resize(N);
12279       }
12280     }
12281   }
12282 
12283   void EliminateSuboptimalCudaMatches() {
12284     S.EraseUnwantedCUDAMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
12285                                Matches);
12286   }
12287 
12288 public:
12289   void ComplainNoMatchesFound() const {
12290     assert(Matches.empty());
12291     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
12292         << OvlExpr->getName() << TargetFunctionType
12293         << OvlExpr->getSourceRange();
12294     if (FailedCandidates.empty())
12295       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12296                                   /*TakingAddress=*/true);
12297     else {
12298       // We have some deduction failure messages. Use them to diagnose
12299       // the function templates, and diagnose the non-template candidates
12300       // normally.
12301       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12302                                  IEnd = OvlExpr->decls_end();
12303            I != IEnd; ++I)
12304         if (FunctionDecl *Fun =
12305                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
12306           if (!functionHasPassObjectSizeParams(Fun))
12307             S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
12308                                     /*TakingAddress=*/true);
12309       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
12310     }
12311   }
12312 
12313   bool IsInvalidFormOfPointerToMemberFunction() const {
12314     return TargetTypeIsNonStaticMemberFunction &&
12315       !OvlExprInfo.HasFormOfMemberPointer;
12316   }
12317 
12318   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
12319       // TODO: Should we condition this on whether any functions might
12320       // have matched, or is it more appropriate to do that in callers?
12321       // TODO: a fixit wouldn't hurt.
12322       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
12323         << TargetType << OvlExpr->getSourceRange();
12324   }
12325 
12326   bool IsStaticMemberFunctionFromBoundPointer() const {
12327     return StaticMemberFunctionFromBoundPointer;
12328   }
12329 
12330   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
12331     S.Diag(OvlExpr->getBeginLoc(),
12332            diag::err_invalid_form_pointer_member_function)
12333         << OvlExpr->getSourceRange();
12334   }
12335 
12336   void ComplainOfInvalidConversion() const {
12337     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
12338         << OvlExpr->getName() << TargetType;
12339   }
12340 
12341   void ComplainMultipleMatchesFound() const {
12342     assert(Matches.size() > 1);
12343     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
12344         << OvlExpr->getName() << OvlExpr->getSourceRange();
12345     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12346                                 /*TakingAddress=*/true);
12347   }
12348 
12349   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
12350 
12351   int getNumMatches() const { return Matches.size(); }
12352 
12353   FunctionDecl* getMatchingFunctionDecl() const {
12354     if (Matches.size() != 1) return nullptr;
12355     return Matches[0].second;
12356   }
12357 
12358   const DeclAccessPair* getMatchingFunctionAccessPair() const {
12359     if (Matches.size() != 1) return nullptr;
12360     return &Matches[0].first;
12361   }
12362 };
12363 }
12364 
12365 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
12366 /// an overloaded function (C++ [over.over]), where @p From is an
12367 /// expression with overloaded function type and @p ToType is the type
12368 /// we're trying to resolve to. For example:
12369 ///
12370 /// @code
12371 /// int f(double);
12372 /// int f(int);
12373 ///
12374 /// int (*pfd)(double) = f; // selects f(double)
12375 /// @endcode
12376 ///
12377 /// This routine returns the resulting FunctionDecl if it could be
12378 /// resolved, and NULL otherwise. When @p Complain is true, this
12379 /// routine will emit diagnostics if there is an error.
12380 FunctionDecl *
12381 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
12382                                          QualType TargetType,
12383                                          bool Complain,
12384                                          DeclAccessPair &FoundResult,
12385                                          bool *pHadMultipleCandidates) {
12386   assert(AddressOfExpr->getType() == Context.OverloadTy);
12387 
12388   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
12389                                      Complain);
12390   int NumMatches = Resolver.getNumMatches();
12391   FunctionDecl *Fn = nullptr;
12392   bool ShouldComplain = Complain && !Resolver.hasComplained();
12393   if (NumMatches == 0 && ShouldComplain) {
12394     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
12395       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
12396     else
12397       Resolver.ComplainNoMatchesFound();
12398   }
12399   else if (NumMatches > 1 && ShouldComplain)
12400     Resolver.ComplainMultipleMatchesFound();
12401   else if (NumMatches == 1) {
12402     Fn = Resolver.getMatchingFunctionDecl();
12403     assert(Fn);
12404     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
12405       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
12406     FoundResult = *Resolver.getMatchingFunctionAccessPair();
12407     if (Complain) {
12408       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
12409         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
12410       else
12411         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
12412     }
12413   }
12414 
12415   if (pHadMultipleCandidates)
12416     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
12417   return Fn;
12418 }
12419 
12420 /// Given an expression that refers to an overloaded function, try to
12421 /// resolve that function to a single function that can have its address taken.
12422 /// This will modify `Pair` iff it returns non-null.
12423 ///
12424 /// This routine can only succeed if from all of the candidates in the overload
12425 /// set for SrcExpr that can have their addresses taken, there is one candidate
12426 /// that is more constrained than the rest.
12427 FunctionDecl *
12428 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
12429   OverloadExpr::FindResult R = OverloadExpr::find(E);
12430   OverloadExpr *Ovl = R.Expression;
12431   bool IsResultAmbiguous = false;
12432   FunctionDecl *Result = nullptr;
12433   DeclAccessPair DAP;
12434   SmallVector<FunctionDecl *, 2> AmbiguousDecls;
12435 
12436   auto CheckMoreConstrained =
12437       [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> {
12438         SmallVector<const Expr *, 1> AC1, AC2;
12439         FD1->getAssociatedConstraints(AC1);
12440         FD2->getAssociatedConstraints(AC2);
12441         bool AtLeastAsConstrained1, AtLeastAsConstrained2;
12442         if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
12443           return None;
12444         if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
12445           return None;
12446         if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
12447           return None;
12448         return AtLeastAsConstrained1;
12449       };
12450 
12451   // Don't use the AddressOfResolver because we're specifically looking for
12452   // cases where we have one overload candidate that lacks
12453   // enable_if/pass_object_size/...
12454   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
12455     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
12456     if (!FD)
12457       return nullptr;
12458 
12459     if (!checkAddressOfFunctionIsAvailable(FD))
12460       continue;
12461 
12462     // We have more than one result - see if it is more constrained than the
12463     // previous one.
12464     if (Result) {
12465       Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD,
12466                                                                         Result);
12467       if (!MoreConstrainedThanPrevious) {
12468         IsResultAmbiguous = true;
12469         AmbiguousDecls.push_back(FD);
12470         continue;
12471       }
12472       if (!*MoreConstrainedThanPrevious)
12473         continue;
12474       // FD is more constrained - replace Result with it.
12475     }
12476     IsResultAmbiguous = false;
12477     DAP = I.getPair();
12478     Result = FD;
12479   }
12480 
12481   if (IsResultAmbiguous)
12482     return nullptr;
12483 
12484   if (Result) {
12485     SmallVector<const Expr *, 1> ResultAC;
12486     // We skipped over some ambiguous declarations which might be ambiguous with
12487     // the selected result.
12488     for (FunctionDecl *Skipped : AmbiguousDecls)
12489       if (!CheckMoreConstrained(Skipped, Result).hasValue())
12490         return nullptr;
12491     Pair = DAP;
12492   }
12493   return Result;
12494 }
12495 
12496 /// Given an overloaded function, tries to turn it into a non-overloaded
12497 /// function reference using resolveAddressOfSingleOverloadCandidate. This
12498 /// will perform access checks, diagnose the use of the resultant decl, and, if
12499 /// requested, potentially perform a function-to-pointer decay.
12500 ///
12501 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
12502 /// Otherwise, returns true. This may emit diagnostics and return true.
12503 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
12504     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
12505   Expr *E = SrcExpr.get();
12506   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
12507 
12508   DeclAccessPair DAP;
12509   FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
12510   if (!Found || Found->isCPUDispatchMultiVersion() ||
12511       Found->isCPUSpecificMultiVersion())
12512     return false;
12513 
12514   // Emitting multiple diagnostics for a function that is both inaccessible and
12515   // unavailable is consistent with our behavior elsewhere. So, always check
12516   // for both.
12517   DiagnoseUseOfDecl(Found, E->getExprLoc());
12518   CheckAddressOfMemberAccess(E, DAP);
12519   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
12520   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
12521     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
12522   else
12523     SrcExpr = Fixed;
12524   return true;
12525 }
12526 
12527 /// Given an expression that refers to an overloaded function, try to
12528 /// resolve that overloaded function expression down to a single function.
12529 ///
12530 /// This routine can only resolve template-ids that refer to a single function
12531 /// template, where that template-id refers to a single template whose template
12532 /// arguments are either provided by the template-id or have defaults,
12533 /// as described in C++0x [temp.arg.explicit]p3.
12534 ///
12535 /// If no template-ids are found, no diagnostics are emitted and NULL is
12536 /// returned.
12537 FunctionDecl *
12538 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
12539                                                   bool Complain,
12540                                                   DeclAccessPair *FoundResult) {
12541   // C++ [over.over]p1:
12542   //   [...] [Note: any redundant set of parentheses surrounding the
12543   //   overloaded function name is ignored (5.1). ]
12544   // C++ [over.over]p1:
12545   //   [...] The overloaded function name can be preceded by the &
12546   //   operator.
12547 
12548   // If we didn't actually find any template-ids, we're done.
12549   if (!ovl->hasExplicitTemplateArgs())
12550     return nullptr;
12551 
12552   TemplateArgumentListInfo ExplicitTemplateArgs;
12553   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
12554   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
12555 
12556   // Look through all of the overloaded functions, searching for one
12557   // whose type matches exactly.
12558   FunctionDecl *Matched = nullptr;
12559   for (UnresolvedSetIterator I = ovl->decls_begin(),
12560          E = ovl->decls_end(); I != E; ++I) {
12561     // C++0x [temp.arg.explicit]p3:
12562     //   [...] In contexts where deduction is done and fails, or in contexts
12563     //   where deduction is not done, if a template argument list is
12564     //   specified and it, along with any default template arguments,
12565     //   identifies a single function template specialization, then the
12566     //   template-id is an lvalue for the function template specialization.
12567     FunctionTemplateDecl *FunctionTemplate
12568       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
12569 
12570     // C++ [over.over]p2:
12571     //   If the name is a function template, template argument deduction is
12572     //   done (14.8.2.2), and if the argument deduction succeeds, the
12573     //   resulting template argument list is used to generate a single
12574     //   function template specialization, which is added to the set of
12575     //   overloaded functions considered.
12576     FunctionDecl *Specialization = nullptr;
12577     TemplateDeductionInfo Info(FailedCandidates.getLocation());
12578     if (TemplateDeductionResult Result
12579           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
12580                                     Specialization, Info,
12581                                     /*IsAddressOfFunction*/true)) {
12582       // Make a note of the failed deduction for diagnostics.
12583       // TODO: Actually use the failed-deduction info?
12584       FailedCandidates.addCandidate()
12585           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
12586                MakeDeductionFailureInfo(Context, Result, Info));
12587       continue;
12588     }
12589 
12590     assert(Specialization && "no specialization and no error?");
12591 
12592     // Multiple matches; we can't resolve to a single declaration.
12593     if (Matched) {
12594       if (Complain) {
12595         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
12596           << ovl->getName();
12597         NoteAllOverloadCandidates(ovl);
12598       }
12599       return nullptr;
12600     }
12601 
12602     Matched = Specialization;
12603     if (FoundResult) *FoundResult = I.getPair();
12604   }
12605 
12606   if (Matched &&
12607       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
12608     return nullptr;
12609 
12610   return Matched;
12611 }
12612 
12613 // Resolve and fix an overloaded expression that can be resolved
12614 // because it identifies a single function template specialization.
12615 //
12616 // Last three arguments should only be supplied if Complain = true
12617 //
12618 // Return true if it was logically possible to so resolve the
12619 // expression, regardless of whether or not it succeeded.  Always
12620 // returns true if 'complain' is set.
12621 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
12622                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
12623                       bool complain, SourceRange OpRangeForComplaining,
12624                                            QualType DestTypeForComplaining,
12625                                             unsigned DiagIDForComplaining) {
12626   assert(SrcExpr.get()->getType() == Context.OverloadTy);
12627 
12628   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
12629 
12630   DeclAccessPair found;
12631   ExprResult SingleFunctionExpression;
12632   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
12633                            ovl.Expression, /*complain*/ false, &found)) {
12634     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
12635       SrcExpr = ExprError();
12636       return true;
12637     }
12638 
12639     // It is only correct to resolve to an instance method if we're
12640     // resolving a form that's permitted to be a pointer to member.
12641     // Otherwise we'll end up making a bound member expression, which
12642     // is illegal in all the contexts we resolve like this.
12643     if (!ovl.HasFormOfMemberPointer &&
12644         isa<CXXMethodDecl>(fn) &&
12645         cast<CXXMethodDecl>(fn)->isInstance()) {
12646       if (!complain) return false;
12647 
12648       Diag(ovl.Expression->getExprLoc(),
12649            diag::err_bound_member_function)
12650         << 0 << ovl.Expression->getSourceRange();
12651 
12652       // TODO: I believe we only end up here if there's a mix of
12653       // static and non-static candidates (otherwise the expression
12654       // would have 'bound member' type, not 'overload' type).
12655       // Ideally we would note which candidate was chosen and why
12656       // the static candidates were rejected.
12657       SrcExpr = ExprError();
12658       return true;
12659     }
12660 
12661     // Fix the expression to refer to 'fn'.
12662     SingleFunctionExpression =
12663         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
12664 
12665     // If desired, do function-to-pointer decay.
12666     if (doFunctionPointerConverion) {
12667       SingleFunctionExpression =
12668         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
12669       if (SingleFunctionExpression.isInvalid()) {
12670         SrcExpr = ExprError();
12671         return true;
12672       }
12673     }
12674   }
12675 
12676   if (!SingleFunctionExpression.isUsable()) {
12677     if (complain) {
12678       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
12679         << ovl.Expression->getName()
12680         << DestTypeForComplaining
12681         << OpRangeForComplaining
12682         << ovl.Expression->getQualifierLoc().getSourceRange();
12683       NoteAllOverloadCandidates(SrcExpr.get());
12684 
12685       SrcExpr = ExprError();
12686       return true;
12687     }
12688 
12689     return false;
12690   }
12691 
12692   SrcExpr = SingleFunctionExpression;
12693   return true;
12694 }
12695 
12696 /// Add a single candidate to the overload set.
12697 static void AddOverloadedCallCandidate(Sema &S,
12698                                        DeclAccessPair FoundDecl,
12699                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
12700                                        ArrayRef<Expr *> Args,
12701                                        OverloadCandidateSet &CandidateSet,
12702                                        bool PartialOverloading,
12703                                        bool KnownValid) {
12704   NamedDecl *Callee = FoundDecl.getDecl();
12705   if (isa<UsingShadowDecl>(Callee))
12706     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
12707 
12708   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
12709     if (ExplicitTemplateArgs) {
12710       assert(!KnownValid && "Explicit template arguments?");
12711       return;
12712     }
12713     // Prevent ill-formed function decls to be added as overload candidates.
12714     if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
12715       return;
12716 
12717     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
12718                            /*SuppressUserConversions=*/false,
12719                            PartialOverloading);
12720     return;
12721   }
12722 
12723   if (FunctionTemplateDecl *FuncTemplate
12724       = dyn_cast<FunctionTemplateDecl>(Callee)) {
12725     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
12726                                    ExplicitTemplateArgs, Args, CandidateSet,
12727                                    /*SuppressUserConversions=*/false,
12728                                    PartialOverloading);
12729     return;
12730   }
12731 
12732   assert(!KnownValid && "unhandled case in overloaded call candidate");
12733 }
12734 
12735 /// Add the overload candidates named by callee and/or found by argument
12736 /// dependent lookup to the given overload set.
12737 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
12738                                        ArrayRef<Expr *> Args,
12739                                        OverloadCandidateSet &CandidateSet,
12740                                        bool PartialOverloading) {
12741 
12742 #ifndef NDEBUG
12743   // Verify that ArgumentDependentLookup is consistent with the rules
12744   // in C++0x [basic.lookup.argdep]p3:
12745   //
12746   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
12747   //   and let Y be the lookup set produced by argument dependent
12748   //   lookup (defined as follows). If X contains
12749   //
12750   //     -- a declaration of a class member, or
12751   //
12752   //     -- a block-scope function declaration that is not a
12753   //        using-declaration, or
12754   //
12755   //     -- a declaration that is neither a function or a function
12756   //        template
12757   //
12758   //   then Y is empty.
12759 
12760   if (ULE->requiresADL()) {
12761     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12762            E = ULE->decls_end(); I != E; ++I) {
12763       assert(!(*I)->getDeclContext()->isRecord());
12764       assert(isa<UsingShadowDecl>(*I) ||
12765              !(*I)->getDeclContext()->isFunctionOrMethod());
12766       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
12767     }
12768   }
12769 #endif
12770 
12771   // It would be nice to avoid this copy.
12772   TemplateArgumentListInfo TABuffer;
12773   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12774   if (ULE->hasExplicitTemplateArgs()) {
12775     ULE->copyTemplateArgumentsInto(TABuffer);
12776     ExplicitTemplateArgs = &TABuffer;
12777   }
12778 
12779   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12780          E = ULE->decls_end(); I != E; ++I)
12781     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12782                                CandidateSet, PartialOverloading,
12783                                /*KnownValid*/ true);
12784 
12785   if (ULE->requiresADL())
12786     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
12787                                          Args, ExplicitTemplateArgs,
12788                                          CandidateSet, PartialOverloading);
12789 }
12790 
12791 /// Add the call candidates from the given set of lookup results to the given
12792 /// overload set. Non-function lookup results are ignored.
12793 void Sema::AddOverloadedCallCandidates(
12794     LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
12795     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
12796   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12797     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12798                                CandidateSet, false, /*KnownValid*/ false);
12799 }
12800 
12801 /// Determine whether a declaration with the specified name could be moved into
12802 /// a different namespace.
12803 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
12804   switch (Name.getCXXOverloadedOperator()) {
12805   case OO_New: case OO_Array_New:
12806   case OO_Delete: case OO_Array_Delete:
12807     return false;
12808 
12809   default:
12810     return true;
12811   }
12812 }
12813 
12814 /// Attempt to recover from an ill-formed use of a non-dependent name in a
12815 /// template, where the non-dependent name was declared after the template
12816 /// was defined. This is common in code written for a compilers which do not
12817 /// correctly implement two-stage name lookup.
12818 ///
12819 /// Returns true if a viable candidate was found and a diagnostic was issued.
12820 static bool DiagnoseTwoPhaseLookup(
12821     Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
12822     LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
12823     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
12824     CXXRecordDecl **FoundInClass = nullptr) {
12825   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
12826     return false;
12827 
12828   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
12829     if (DC->isTransparentContext())
12830       continue;
12831 
12832     SemaRef.LookupQualifiedName(R, DC);
12833 
12834     if (!R.empty()) {
12835       R.suppressDiagnostics();
12836 
12837       OverloadCandidateSet Candidates(FnLoc, CSK);
12838       SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
12839                                           Candidates);
12840 
12841       OverloadCandidateSet::iterator Best;
12842       OverloadingResult OR =
12843           Candidates.BestViableFunction(SemaRef, FnLoc, Best);
12844 
12845       if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
12846         // We either found non-function declarations or a best viable function
12847         // at class scope. A class-scope lookup result disables ADL. Don't
12848         // look past this, but let the caller know that we found something that
12849         // either is, or might be, usable in this class.
12850         if (FoundInClass) {
12851           *FoundInClass = RD;
12852           if (OR == OR_Success) {
12853             R.clear();
12854             R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
12855             R.resolveKind();
12856           }
12857         }
12858         return false;
12859       }
12860 
12861       if (OR != OR_Success) {
12862         // There wasn't a unique best function or function template.
12863         return false;
12864       }
12865 
12866       // Find the namespaces where ADL would have looked, and suggest
12867       // declaring the function there instead.
12868       Sema::AssociatedNamespaceSet AssociatedNamespaces;
12869       Sema::AssociatedClassSet AssociatedClasses;
12870       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
12871                                                  AssociatedNamespaces,
12872                                                  AssociatedClasses);
12873       Sema::AssociatedNamespaceSet SuggestedNamespaces;
12874       if (canBeDeclaredInNamespace(R.getLookupName())) {
12875         DeclContext *Std = SemaRef.getStdNamespace();
12876         for (Sema::AssociatedNamespaceSet::iterator
12877                it = AssociatedNamespaces.begin(),
12878                end = AssociatedNamespaces.end(); it != end; ++it) {
12879           // Never suggest declaring a function within namespace 'std'.
12880           if (Std && Std->Encloses(*it))
12881             continue;
12882 
12883           // Never suggest declaring a function within a namespace with a
12884           // reserved name, like __gnu_cxx.
12885           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
12886           if (NS &&
12887               NS->getQualifiedNameAsString().find("__") != std::string::npos)
12888             continue;
12889 
12890           SuggestedNamespaces.insert(*it);
12891         }
12892       }
12893 
12894       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
12895         << R.getLookupName();
12896       if (SuggestedNamespaces.empty()) {
12897         SemaRef.Diag(Best->Function->getLocation(),
12898                      diag::note_not_found_by_two_phase_lookup)
12899           << R.getLookupName() << 0;
12900       } else if (SuggestedNamespaces.size() == 1) {
12901         SemaRef.Diag(Best->Function->getLocation(),
12902                      diag::note_not_found_by_two_phase_lookup)
12903           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
12904       } else {
12905         // FIXME: It would be useful to list the associated namespaces here,
12906         // but the diagnostics infrastructure doesn't provide a way to produce
12907         // a localized representation of a list of items.
12908         SemaRef.Diag(Best->Function->getLocation(),
12909                      diag::note_not_found_by_two_phase_lookup)
12910           << R.getLookupName() << 2;
12911       }
12912 
12913       // Try to recover by calling this function.
12914       return true;
12915     }
12916 
12917     R.clear();
12918   }
12919 
12920   return false;
12921 }
12922 
12923 /// Attempt to recover from ill-formed use of a non-dependent operator in a
12924 /// template, where the non-dependent operator was declared after the template
12925 /// was defined.
12926 ///
12927 /// Returns true if a viable candidate was found and a diagnostic was issued.
12928 static bool
12929 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
12930                                SourceLocation OpLoc,
12931                                ArrayRef<Expr *> Args) {
12932   DeclarationName OpName =
12933     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
12934   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
12935   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
12936                                 OverloadCandidateSet::CSK_Operator,
12937                                 /*ExplicitTemplateArgs=*/nullptr, Args);
12938 }
12939 
12940 namespace {
12941 class BuildRecoveryCallExprRAII {
12942   Sema &SemaRef;
12943 public:
12944   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
12945     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
12946     SemaRef.IsBuildingRecoveryCallExpr = true;
12947   }
12948 
12949   ~BuildRecoveryCallExprRAII() {
12950     SemaRef.IsBuildingRecoveryCallExpr = false;
12951   }
12952 };
12953 
12954 }
12955 
12956 /// Attempts to recover from a call where no functions were found.
12957 ///
12958 /// This function will do one of three things:
12959 ///  * Diagnose, recover, and return a recovery expression.
12960 ///  * Diagnose, fail to recover, and return ExprError().
12961 ///  * Do not diagnose, do not recover, and return ExprResult(). The caller is
12962 ///    expected to diagnose as appropriate.
12963 static ExprResult
12964 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12965                       UnresolvedLookupExpr *ULE,
12966                       SourceLocation LParenLoc,
12967                       MutableArrayRef<Expr *> Args,
12968                       SourceLocation RParenLoc,
12969                       bool EmptyLookup, bool AllowTypoCorrection) {
12970   // Do not try to recover if it is already building a recovery call.
12971   // This stops infinite loops for template instantiations like
12972   //
12973   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
12974   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
12975   if (SemaRef.IsBuildingRecoveryCallExpr)
12976     return ExprResult();
12977   BuildRecoveryCallExprRAII RCE(SemaRef);
12978 
12979   CXXScopeSpec SS;
12980   SS.Adopt(ULE->getQualifierLoc());
12981   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
12982 
12983   TemplateArgumentListInfo TABuffer;
12984   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12985   if (ULE->hasExplicitTemplateArgs()) {
12986     ULE->copyTemplateArgumentsInto(TABuffer);
12987     ExplicitTemplateArgs = &TABuffer;
12988   }
12989 
12990   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
12991                  Sema::LookupOrdinaryName);
12992   CXXRecordDecl *FoundInClass = nullptr;
12993   if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
12994                              OverloadCandidateSet::CSK_Normal,
12995                              ExplicitTemplateArgs, Args, &FoundInClass)) {
12996     // OK, diagnosed a two-phase lookup issue.
12997   } else if (EmptyLookup) {
12998     // Try to recover from an empty lookup with typo correction.
12999     R.clear();
13000     NoTypoCorrectionCCC NoTypoValidator{};
13001     FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
13002                                                 ExplicitTemplateArgs != nullptr,
13003                                                 dyn_cast<MemberExpr>(Fn));
13004     CorrectionCandidateCallback &Validator =
13005         AllowTypoCorrection
13006             ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
13007             : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
13008     if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
13009                                     Args))
13010       return ExprError();
13011   } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
13012     // We found a usable declaration of the name in a dependent base of some
13013     // enclosing class.
13014     // FIXME: We should also explain why the candidates found by name lookup
13015     // were not viable.
13016     if (SemaRef.DiagnoseDependentMemberLookup(R))
13017       return ExprError();
13018   } else {
13019     // We had viable candidates and couldn't recover; let the caller diagnose
13020     // this.
13021     return ExprResult();
13022   }
13023 
13024   // If we get here, we should have issued a diagnostic and formed a recovery
13025   // lookup result.
13026   assert(!R.empty() && "lookup results empty despite recovery");
13027 
13028   // If recovery created an ambiguity, just bail out.
13029   if (R.isAmbiguous()) {
13030     R.suppressDiagnostics();
13031     return ExprError();
13032   }
13033 
13034   // Build an implicit member call if appropriate.  Just drop the
13035   // casts and such from the call, we don't really care.
13036   ExprResult NewFn = ExprError();
13037   if ((*R.begin())->isCXXClassMember())
13038     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
13039                                                     ExplicitTemplateArgs, S);
13040   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
13041     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
13042                                         ExplicitTemplateArgs);
13043   else
13044     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
13045 
13046   if (NewFn.isInvalid())
13047     return ExprError();
13048 
13049   // This shouldn't cause an infinite loop because we're giving it
13050   // an expression with viable lookup results, which should never
13051   // end up here.
13052   return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
13053                                MultiExprArg(Args.data(), Args.size()),
13054                                RParenLoc);
13055 }
13056 
13057 /// Constructs and populates an OverloadedCandidateSet from
13058 /// the given function.
13059 /// \returns true when an the ExprResult output parameter has been set.
13060 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
13061                                   UnresolvedLookupExpr *ULE,
13062                                   MultiExprArg Args,
13063                                   SourceLocation RParenLoc,
13064                                   OverloadCandidateSet *CandidateSet,
13065                                   ExprResult *Result) {
13066 #ifndef NDEBUG
13067   if (ULE->requiresADL()) {
13068     // To do ADL, we must have found an unqualified name.
13069     assert(!ULE->getQualifier() && "qualified name with ADL");
13070 
13071     // We don't perform ADL for implicit declarations of builtins.
13072     // Verify that this was correctly set up.
13073     FunctionDecl *F;
13074     if (ULE->decls_begin() != ULE->decls_end() &&
13075         ULE->decls_begin() + 1 == ULE->decls_end() &&
13076         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
13077         F->getBuiltinID() && F->isImplicit())
13078       llvm_unreachable("performing ADL for builtin");
13079 
13080     // We don't perform ADL in C.
13081     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
13082   }
13083 #endif
13084 
13085   UnbridgedCastsSet UnbridgedCasts;
13086   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
13087     *Result = ExprError();
13088     return true;
13089   }
13090 
13091   // Add the functions denoted by the callee to the set of candidate
13092   // functions, including those from argument-dependent lookup.
13093   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
13094 
13095   if (getLangOpts().MSVCCompat &&
13096       CurContext->isDependentContext() && !isSFINAEContext() &&
13097       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
13098 
13099     OverloadCandidateSet::iterator Best;
13100     if (CandidateSet->empty() ||
13101         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
13102             OR_No_Viable_Function) {
13103       // In Microsoft mode, if we are inside a template class member function
13104       // then create a type dependent CallExpr. The goal is to postpone name
13105       // lookup to instantiation time to be able to search into type dependent
13106       // base classes.
13107       CallExpr *CE =
13108           CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
13109                            RParenLoc, CurFPFeatureOverrides());
13110       CE->markDependentForPostponedNameLookup();
13111       *Result = CE;
13112       return true;
13113     }
13114   }
13115 
13116   if (CandidateSet->empty())
13117     return false;
13118 
13119   UnbridgedCasts.restore();
13120   return false;
13121 }
13122 
13123 // Guess at what the return type for an unresolvable overload should be.
13124 static QualType chooseRecoveryType(OverloadCandidateSet &CS,
13125                                    OverloadCandidateSet::iterator *Best) {
13126   llvm::Optional<QualType> Result;
13127   // Adjust Type after seeing a candidate.
13128   auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
13129     if (!Candidate.Function)
13130       return;
13131     if (Candidate.Function->isInvalidDecl())
13132       return;
13133     QualType T = Candidate.Function->getReturnType();
13134     if (T.isNull())
13135       return;
13136     if (!Result)
13137       Result = T;
13138     else if (Result != T)
13139       Result = QualType();
13140   };
13141 
13142   // Look for an unambiguous type from a progressively larger subset.
13143   // e.g. if types disagree, but all *viable* overloads return int, choose int.
13144   //
13145   // First, consider only the best candidate.
13146   if (Best && *Best != CS.end())
13147     ConsiderCandidate(**Best);
13148   // Next, consider only viable candidates.
13149   if (!Result)
13150     for (const auto &C : CS)
13151       if (C.Viable)
13152         ConsiderCandidate(C);
13153   // Finally, consider all candidates.
13154   if (!Result)
13155     for (const auto &C : CS)
13156       ConsiderCandidate(C);
13157 
13158   if (!Result)
13159     return QualType();
13160   auto Value = Result.getValue();
13161   if (Value.isNull() || Value->isUndeducedType())
13162     return QualType();
13163   return Value;
13164 }
13165 
13166 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
13167 /// the completed call expression. If overload resolution fails, emits
13168 /// diagnostics and returns ExprError()
13169 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
13170                                            UnresolvedLookupExpr *ULE,
13171                                            SourceLocation LParenLoc,
13172                                            MultiExprArg Args,
13173                                            SourceLocation RParenLoc,
13174                                            Expr *ExecConfig,
13175                                            OverloadCandidateSet *CandidateSet,
13176                                            OverloadCandidateSet::iterator *Best,
13177                                            OverloadingResult OverloadResult,
13178                                            bool AllowTypoCorrection) {
13179   switch (OverloadResult) {
13180   case OR_Success: {
13181     FunctionDecl *FDecl = (*Best)->Function;
13182     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
13183     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
13184       return ExprError();
13185     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13186     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
13187                                          ExecConfig, /*IsExecConfig=*/false,
13188                                          (*Best)->IsADLCandidate);
13189   }
13190 
13191   case OR_No_Viable_Function: {
13192     // Try to recover by looking for viable functions which the user might
13193     // have meant to call.
13194     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
13195                                                 Args, RParenLoc,
13196                                                 CandidateSet->empty(),
13197                                                 AllowTypoCorrection);
13198     if (Recovery.isInvalid() || Recovery.isUsable())
13199       return Recovery;
13200 
13201     // If the user passes in a function that we can't take the address of, we
13202     // generally end up emitting really bad error messages. Here, we attempt to
13203     // emit better ones.
13204     for (const Expr *Arg : Args) {
13205       if (!Arg->getType()->isFunctionType())
13206         continue;
13207       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
13208         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13209         if (FD &&
13210             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13211                                                        Arg->getExprLoc()))
13212           return ExprError();
13213       }
13214     }
13215 
13216     CandidateSet->NoteCandidates(
13217         PartialDiagnosticAt(
13218             Fn->getBeginLoc(),
13219             SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
13220                 << ULE->getName() << Fn->getSourceRange()),
13221         SemaRef, OCD_AllCandidates, Args);
13222     break;
13223   }
13224 
13225   case OR_Ambiguous:
13226     CandidateSet->NoteCandidates(
13227         PartialDiagnosticAt(Fn->getBeginLoc(),
13228                             SemaRef.PDiag(diag::err_ovl_ambiguous_call)
13229                                 << ULE->getName() << Fn->getSourceRange()),
13230         SemaRef, OCD_AmbiguousCandidates, Args);
13231     break;
13232 
13233   case OR_Deleted: {
13234     CandidateSet->NoteCandidates(
13235         PartialDiagnosticAt(Fn->getBeginLoc(),
13236                             SemaRef.PDiag(diag::err_ovl_deleted_call)
13237                                 << ULE->getName() << Fn->getSourceRange()),
13238         SemaRef, OCD_AllCandidates, Args);
13239 
13240     // We emitted an error for the unavailable/deleted function call but keep
13241     // the call in the AST.
13242     FunctionDecl *FDecl = (*Best)->Function;
13243     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13244     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
13245                                          ExecConfig, /*IsExecConfig=*/false,
13246                                          (*Best)->IsADLCandidate);
13247   }
13248   }
13249 
13250   // Overload resolution failed, try to recover.
13251   SmallVector<Expr *, 8> SubExprs = {Fn};
13252   SubExprs.append(Args.begin(), Args.end());
13253   return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
13254                                     chooseRecoveryType(*CandidateSet, Best));
13255 }
13256 
13257 static void markUnaddressableCandidatesUnviable(Sema &S,
13258                                                 OverloadCandidateSet &CS) {
13259   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
13260     if (I->Viable &&
13261         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
13262       I->Viable = false;
13263       I->FailureKind = ovl_fail_addr_not_available;
13264     }
13265   }
13266 }
13267 
13268 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
13269 /// (which eventually refers to the declaration Func) and the call
13270 /// arguments Args/NumArgs, attempt to resolve the function call down
13271 /// to a specific function. If overload resolution succeeds, returns
13272 /// the call expression produced by overload resolution.
13273 /// Otherwise, emits diagnostics and returns ExprError.
13274 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
13275                                          UnresolvedLookupExpr *ULE,
13276                                          SourceLocation LParenLoc,
13277                                          MultiExprArg Args,
13278                                          SourceLocation RParenLoc,
13279                                          Expr *ExecConfig,
13280                                          bool AllowTypoCorrection,
13281                                          bool CalleesAddressIsTaken) {
13282   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
13283                                     OverloadCandidateSet::CSK_Normal);
13284   ExprResult result;
13285 
13286   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
13287                              &result))
13288     return result;
13289 
13290   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
13291   // functions that aren't addressible are considered unviable.
13292   if (CalleesAddressIsTaken)
13293     markUnaddressableCandidatesUnviable(*this, CandidateSet);
13294 
13295   OverloadCandidateSet::iterator Best;
13296   OverloadingResult OverloadResult =
13297       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
13298 
13299   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
13300                                   ExecConfig, &CandidateSet, &Best,
13301                                   OverloadResult, AllowTypoCorrection);
13302 }
13303 
13304 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
13305   return Functions.size() > 1 ||
13306          (Functions.size() == 1 &&
13307           isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl()));
13308 }
13309 
13310 ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
13311                                             NestedNameSpecifierLoc NNSLoc,
13312                                             DeclarationNameInfo DNI,
13313                                             const UnresolvedSetImpl &Fns,
13314                                             bool PerformADL) {
13315   return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI,
13316                                       PerformADL, IsOverloaded(Fns),
13317                                       Fns.begin(), Fns.end());
13318 }
13319 
13320 /// Create a unary operation that may resolve to an overloaded
13321 /// operator.
13322 ///
13323 /// \param OpLoc The location of the operator itself (e.g., '*').
13324 ///
13325 /// \param Opc The UnaryOperatorKind that describes this operator.
13326 ///
13327 /// \param Fns The set of non-member functions that will be
13328 /// considered by overload resolution. The caller needs to build this
13329 /// set based on the context using, e.g.,
13330 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13331 /// set should not contain any member functions; those will be added
13332 /// by CreateOverloadedUnaryOp().
13333 ///
13334 /// \param Input The input argument.
13335 ExprResult
13336 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
13337                               const UnresolvedSetImpl &Fns,
13338                               Expr *Input, bool PerformADL) {
13339   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
13340   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
13341   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13342   // TODO: provide better source location info.
13343   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13344 
13345   if (checkPlaceholderForOverload(*this, Input))
13346     return ExprError();
13347 
13348   Expr *Args[2] = { Input, nullptr };
13349   unsigned NumArgs = 1;
13350 
13351   // For post-increment and post-decrement, add the implicit '0' as
13352   // the second argument, so that we know this is a post-increment or
13353   // post-decrement.
13354   if (Opc == UO_PostInc || Opc == UO_PostDec) {
13355     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13356     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
13357                                      SourceLocation());
13358     NumArgs = 2;
13359   }
13360 
13361   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
13362 
13363   if (Input->isTypeDependent()) {
13364     if (Fns.empty())
13365       return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy,
13366                                    VK_PRValue, OK_Ordinary, OpLoc, false,
13367                                    CurFPFeatureOverrides());
13368 
13369     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13370     ExprResult Fn = CreateUnresolvedLookupExpr(
13371         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
13372     if (Fn.isInvalid())
13373       return ExprError();
13374     return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
13375                                        Context.DependentTy, VK_PRValue, OpLoc,
13376                                        CurFPFeatureOverrides());
13377   }
13378 
13379   // Build an empty overload set.
13380   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
13381 
13382   // Add the candidates from the given function set.
13383   AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
13384 
13385   // Add operator candidates that are member functions.
13386   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13387 
13388   // Add candidates from ADL.
13389   if (PerformADL) {
13390     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
13391                                          /*ExplicitTemplateArgs*/nullptr,
13392                                          CandidateSet);
13393   }
13394 
13395   // Add builtin operator candidates.
13396   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13397 
13398   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13399 
13400   // Perform overload resolution.
13401   OverloadCandidateSet::iterator Best;
13402   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13403   case OR_Success: {
13404     // We found a built-in operator or an overloaded operator.
13405     FunctionDecl *FnDecl = Best->Function;
13406 
13407     if (FnDecl) {
13408       Expr *Base = nullptr;
13409       // We matched an overloaded operator. Build a call to that
13410       // operator.
13411 
13412       // Convert the arguments.
13413       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13414         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
13415 
13416         ExprResult InputRes =
13417           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
13418                                               Best->FoundDecl, Method);
13419         if (InputRes.isInvalid())
13420           return ExprError();
13421         Base = Input = InputRes.get();
13422       } else {
13423         // Convert the arguments.
13424         ExprResult InputInit
13425           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13426                                                       Context,
13427                                                       FnDecl->getParamDecl(0)),
13428                                       SourceLocation(),
13429                                       Input);
13430         if (InputInit.isInvalid())
13431           return ExprError();
13432         Input = InputInit.get();
13433       }
13434 
13435       // Build the actual expression node.
13436       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
13437                                                 Base, HadMultipleCandidates,
13438                                                 OpLoc);
13439       if (FnExpr.isInvalid())
13440         return ExprError();
13441 
13442       // Determine the result type.
13443       QualType ResultTy = FnDecl->getReturnType();
13444       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13445       ResultTy = ResultTy.getNonLValueExprType(Context);
13446 
13447       Args[0] = Input;
13448       CallExpr *TheCall = CXXOperatorCallExpr::Create(
13449           Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
13450           CurFPFeatureOverrides(), Best->IsADLCandidate);
13451 
13452       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
13453         return ExprError();
13454 
13455       if (CheckFunctionCall(FnDecl, TheCall,
13456                             FnDecl->getType()->castAs<FunctionProtoType>()))
13457         return ExprError();
13458       return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
13459     } else {
13460       // We matched a built-in operator. Convert the arguments, then
13461       // break out so that we will build the appropriate built-in
13462       // operator node.
13463       ExprResult InputRes = PerformImplicitConversion(
13464           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
13465           CCK_ForBuiltinOverloadedOp);
13466       if (InputRes.isInvalid())
13467         return ExprError();
13468       Input = InputRes.get();
13469       break;
13470     }
13471   }
13472 
13473   case OR_No_Viable_Function:
13474     // This is an erroneous use of an operator which can be overloaded by
13475     // a non-member function. Check for non-member operators which were
13476     // defined too late to be candidates.
13477     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
13478       // FIXME: Recover by calling the found function.
13479       return ExprError();
13480 
13481     // No viable function; fall through to handling this as a
13482     // built-in operator, which will produce an error message for us.
13483     break;
13484 
13485   case OR_Ambiguous:
13486     CandidateSet.NoteCandidates(
13487         PartialDiagnosticAt(OpLoc,
13488                             PDiag(diag::err_ovl_ambiguous_oper_unary)
13489                                 << UnaryOperator::getOpcodeStr(Opc)
13490                                 << Input->getType() << Input->getSourceRange()),
13491         *this, OCD_AmbiguousCandidates, ArgsArray,
13492         UnaryOperator::getOpcodeStr(Opc), OpLoc);
13493     return ExprError();
13494 
13495   case OR_Deleted:
13496     CandidateSet.NoteCandidates(
13497         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
13498                                        << UnaryOperator::getOpcodeStr(Opc)
13499                                        << Input->getSourceRange()),
13500         *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
13501         OpLoc);
13502     return ExprError();
13503   }
13504 
13505   // Either we found no viable overloaded operator or we matched a
13506   // built-in operator. In either case, fall through to trying to
13507   // build a built-in operation.
13508   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13509 }
13510 
13511 /// Perform lookup for an overloaded binary operator.
13512 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
13513                                  OverloadedOperatorKind Op,
13514                                  const UnresolvedSetImpl &Fns,
13515                                  ArrayRef<Expr *> Args, bool PerformADL) {
13516   SourceLocation OpLoc = CandidateSet.getLocation();
13517 
13518   OverloadedOperatorKind ExtraOp =
13519       CandidateSet.getRewriteInfo().AllowRewrittenCandidates
13520           ? getRewrittenOverloadedOperator(Op)
13521           : OO_None;
13522 
13523   // Add the candidates from the given function set. This also adds the
13524   // rewritten candidates using these functions if necessary.
13525   AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
13526 
13527   // Add operator candidates that are member functions.
13528   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13529   if (CandidateSet.getRewriteInfo().shouldAddReversed(Op))
13530     AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
13531                                 OverloadCandidateParamOrder::Reversed);
13532 
13533   // In C++20, also add any rewritten member candidates.
13534   if (ExtraOp) {
13535     AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
13536     if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp))
13537       AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
13538                                   CandidateSet,
13539                                   OverloadCandidateParamOrder::Reversed);
13540   }
13541 
13542   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
13543   // performed for an assignment operator (nor for operator[] nor operator->,
13544   // which don't get here).
13545   if (Op != OO_Equal && PerformADL) {
13546     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13547     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
13548                                          /*ExplicitTemplateArgs*/ nullptr,
13549                                          CandidateSet);
13550     if (ExtraOp) {
13551       DeclarationName ExtraOpName =
13552           Context.DeclarationNames.getCXXOperatorName(ExtraOp);
13553       AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
13554                                            /*ExplicitTemplateArgs*/ nullptr,
13555                                            CandidateSet);
13556     }
13557   }
13558 
13559   // Add builtin operator candidates.
13560   //
13561   // FIXME: We don't add any rewritten candidates here. This is strictly
13562   // incorrect; a builtin candidate could be hidden by a non-viable candidate,
13563   // resulting in our selecting a rewritten builtin candidate. For example:
13564   //
13565   //   enum class E { e };
13566   //   bool operator!=(E, E) requires false;
13567   //   bool k = E::e != E::e;
13568   //
13569   // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
13570   // it seems unreasonable to consider rewritten builtin candidates. A core
13571   // issue has been filed proposing to removed this requirement.
13572   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13573 }
13574 
13575 /// Create a binary operation that may resolve to an overloaded
13576 /// operator.
13577 ///
13578 /// \param OpLoc The location of the operator itself (e.g., '+').
13579 ///
13580 /// \param Opc The BinaryOperatorKind that describes this operator.
13581 ///
13582 /// \param Fns The set of non-member functions that will be
13583 /// considered by overload resolution. The caller needs to build this
13584 /// set based on the context using, e.g.,
13585 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13586 /// set should not contain any member functions; those will be added
13587 /// by CreateOverloadedBinOp().
13588 ///
13589 /// \param LHS Left-hand argument.
13590 /// \param RHS Right-hand argument.
13591 /// \param PerformADL Whether to consider operator candidates found by ADL.
13592 /// \param AllowRewrittenCandidates Whether to consider candidates found by
13593 ///        C++20 operator rewrites.
13594 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
13595 ///        the function in question. Such a function is never a candidate in
13596 ///        our overload resolution. This also enables synthesizing a three-way
13597 ///        comparison from < and == as described in C++20 [class.spaceship]p1.
13598 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
13599                                        BinaryOperatorKind Opc,
13600                                        const UnresolvedSetImpl &Fns, Expr *LHS,
13601                                        Expr *RHS, bool PerformADL,
13602                                        bool AllowRewrittenCandidates,
13603                                        FunctionDecl *DefaultedFn) {
13604   Expr *Args[2] = { LHS, RHS };
13605   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
13606 
13607   if (!getLangOpts().CPlusPlus20)
13608     AllowRewrittenCandidates = false;
13609 
13610   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
13611 
13612   // If either side is type-dependent, create an appropriate dependent
13613   // expression.
13614   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13615     if (Fns.empty()) {
13616       // If there are no functions to store, just build a dependent
13617       // BinaryOperator or CompoundAssignment.
13618       if (BinaryOperator::isCompoundAssignmentOp(Opc))
13619         return CompoundAssignOperator::Create(
13620             Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
13621             OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
13622             Context.DependentTy);
13623       return BinaryOperator::Create(
13624           Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
13625           OK_Ordinary, OpLoc, CurFPFeatureOverrides());
13626     }
13627 
13628     // FIXME: save results of ADL from here?
13629     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13630     // TODO: provide better source location info in DNLoc component.
13631     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13632     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13633     ExprResult Fn = CreateUnresolvedLookupExpr(
13634         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
13635     if (Fn.isInvalid())
13636       return ExprError();
13637     return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
13638                                        Context.DependentTy, VK_PRValue, OpLoc,
13639                                        CurFPFeatureOverrides());
13640   }
13641 
13642   // Always do placeholder-like conversions on the RHS.
13643   if (checkPlaceholderForOverload(*this, Args[1]))
13644     return ExprError();
13645 
13646   // Do placeholder-like conversion on the LHS; note that we should
13647   // not get here with a PseudoObject LHS.
13648   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
13649   if (checkPlaceholderForOverload(*this, Args[0]))
13650     return ExprError();
13651 
13652   // If this is the assignment operator, we only perform overload resolution
13653   // if the left-hand side is a class or enumeration type. This is actually
13654   // a hack. The standard requires that we do overload resolution between the
13655   // various built-in candidates, but as DR507 points out, this can lead to
13656   // problems. So we do it this way, which pretty much follows what GCC does.
13657   // Note that we go the traditional code path for compound assignment forms.
13658   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
13659     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13660 
13661   // If this is the .* operator, which is not overloadable, just
13662   // create a built-in binary operator.
13663   if (Opc == BO_PtrMemD)
13664     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13665 
13666   // Build the overload set.
13667   OverloadCandidateSet CandidateSet(
13668       OpLoc, OverloadCandidateSet::CSK_Operator,
13669       OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates));
13670   if (DefaultedFn)
13671     CandidateSet.exclude(DefaultedFn);
13672   LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
13673 
13674   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13675 
13676   // Perform overload resolution.
13677   OverloadCandidateSet::iterator Best;
13678   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13679     case OR_Success: {
13680       // We found a built-in operator or an overloaded operator.
13681       FunctionDecl *FnDecl = Best->Function;
13682 
13683       bool IsReversed = Best->isReversed();
13684       if (IsReversed)
13685         std::swap(Args[0], Args[1]);
13686 
13687       if (FnDecl) {
13688         Expr *Base = nullptr;
13689         // We matched an overloaded operator. Build a call to that
13690         // operator.
13691 
13692         OverloadedOperatorKind ChosenOp =
13693             FnDecl->getDeclName().getCXXOverloadedOperator();
13694 
13695         // C++2a [over.match.oper]p9:
13696         //   If a rewritten operator== candidate is selected by overload
13697         //   resolution for an operator@, its return type shall be cv bool
13698         if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
13699             !FnDecl->getReturnType()->isBooleanType()) {
13700           bool IsExtension =
13701               FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
13702           Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
13703                                   : diag::err_ovl_rewrite_equalequal_not_bool)
13704               << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
13705               << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13706           Diag(FnDecl->getLocation(), diag::note_declared_at);
13707           if (!IsExtension)
13708             return ExprError();
13709         }
13710 
13711         if (AllowRewrittenCandidates && !IsReversed &&
13712             CandidateSet.getRewriteInfo().isReversible()) {
13713           // We could have reversed this operator, but didn't. Check if some
13714           // reversed form was a viable candidate, and if so, if it had a
13715           // better conversion for either parameter. If so, this call is
13716           // formally ambiguous, and allowing it is an extension.
13717           llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
13718           for (OverloadCandidate &Cand : CandidateSet) {
13719             if (Cand.Viable && Cand.Function && Cand.isReversed() &&
13720                 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) {
13721               for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
13722                 if (CompareImplicitConversionSequences(
13723                         *this, OpLoc, Cand.Conversions[ArgIdx],
13724                         Best->Conversions[ArgIdx]) ==
13725                     ImplicitConversionSequence::Better) {
13726                   AmbiguousWith.push_back(Cand.Function);
13727                   break;
13728                 }
13729               }
13730             }
13731           }
13732 
13733           if (!AmbiguousWith.empty()) {
13734             bool AmbiguousWithSelf =
13735                 AmbiguousWith.size() == 1 &&
13736                 declaresSameEntity(AmbiguousWith.front(), FnDecl);
13737             Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
13738                 << BinaryOperator::getOpcodeStr(Opc)
13739                 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
13740                 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13741             if (AmbiguousWithSelf) {
13742               Diag(FnDecl->getLocation(),
13743                    diag::note_ovl_ambiguous_oper_binary_reversed_self);
13744             } else {
13745               Diag(FnDecl->getLocation(),
13746                    diag::note_ovl_ambiguous_oper_binary_selected_candidate);
13747               for (auto *F : AmbiguousWith)
13748                 Diag(F->getLocation(),
13749                      diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
13750             }
13751           }
13752         }
13753 
13754         // Convert the arguments.
13755         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13756           // Best->Access is only meaningful for class members.
13757           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
13758 
13759           ExprResult Arg1 =
13760             PerformCopyInitialization(
13761               InitializedEntity::InitializeParameter(Context,
13762                                                      FnDecl->getParamDecl(0)),
13763               SourceLocation(), Args[1]);
13764           if (Arg1.isInvalid())
13765             return ExprError();
13766 
13767           ExprResult Arg0 =
13768             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13769                                                 Best->FoundDecl, Method);
13770           if (Arg0.isInvalid())
13771             return ExprError();
13772           Base = Args[0] = Arg0.getAs<Expr>();
13773           Args[1] = RHS = Arg1.getAs<Expr>();
13774         } else {
13775           // Convert the arguments.
13776           ExprResult Arg0 = PerformCopyInitialization(
13777             InitializedEntity::InitializeParameter(Context,
13778                                                    FnDecl->getParamDecl(0)),
13779             SourceLocation(), Args[0]);
13780           if (Arg0.isInvalid())
13781             return ExprError();
13782 
13783           ExprResult Arg1 =
13784             PerformCopyInitialization(
13785               InitializedEntity::InitializeParameter(Context,
13786                                                      FnDecl->getParamDecl(1)),
13787               SourceLocation(), Args[1]);
13788           if (Arg1.isInvalid())
13789             return ExprError();
13790           Args[0] = LHS = Arg0.getAs<Expr>();
13791           Args[1] = RHS = Arg1.getAs<Expr>();
13792         }
13793 
13794         // Build the actual expression node.
13795         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13796                                                   Best->FoundDecl, Base,
13797                                                   HadMultipleCandidates, OpLoc);
13798         if (FnExpr.isInvalid())
13799           return ExprError();
13800 
13801         // Determine the result type.
13802         QualType ResultTy = FnDecl->getReturnType();
13803         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13804         ResultTy = ResultTy.getNonLValueExprType(Context);
13805 
13806         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13807             Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
13808             CurFPFeatureOverrides(), Best->IsADLCandidate);
13809 
13810         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
13811                                 FnDecl))
13812           return ExprError();
13813 
13814         ArrayRef<const Expr *> ArgsArray(Args, 2);
13815         const Expr *ImplicitThis = nullptr;
13816         // Cut off the implicit 'this'.
13817         if (isa<CXXMethodDecl>(FnDecl)) {
13818           ImplicitThis = ArgsArray[0];
13819           ArgsArray = ArgsArray.slice(1);
13820         }
13821 
13822         // Check for a self move.
13823         if (Op == OO_Equal)
13824           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
13825 
13826         if (ImplicitThis) {
13827           QualType ThisType = Context.getPointerType(ImplicitThis->getType());
13828           QualType ThisTypeFromDecl = Context.getPointerType(
13829               cast<CXXMethodDecl>(FnDecl)->getThisObjectType());
13830 
13831           CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
13832                             ThisTypeFromDecl);
13833         }
13834 
13835         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
13836                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
13837                   VariadicDoesNotApply);
13838 
13839         ExprResult R = MaybeBindToTemporary(TheCall);
13840         if (R.isInvalid())
13841           return ExprError();
13842 
13843         R = CheckForImmediateInvocation(R, FnDecl);
13844         if (R.isInvalid())
13845           return ExprError();
13846 
13847         // For a rewritten candidate, we've already reversed the arguments
13848         // if needed. Perform the rest of the rewrite now.
13849         if ((Best->RewriteKind & CRK_DifferentOperator) ||
13850             (Op == OO_Spaceship && IsReversed)) {
13851           if (Op == OO_ExclaimEqual) {
13852             assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
13853             R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
13854           } else {
13855             assert(ChosenOp == OO_Spaceship && "unexpected operator name");
13856             llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13857             Expr *ZeroLiteral =
13858                 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
13859 
13860             Sema::CodeSynthesisContext Ctx;
13861             Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
13862             Ctx.Entity = FnDecl;
13863             pushCodeSynthesisContext(Ctx);
13864 
13865             R = CreateOverloadedBinOp(
13866                 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
13867                 IsReversed ? R.get() : ZeroLiteral, PerformADL,
13868                 /*AllowRewrittenCandidates=*/false);
13869 
13870             popCodeSynthesisContext();
13871           }
13872           if (R.isInvalid())
13873             return ExprError();
13874         } else {
13875           assert(ChosenOp == Op && "unexpected operator name");
13876         }
13877 
13878         // Make a note in the AST if we did any rewriting.
13879         if (Best->RewriteKind != CRK_None)
13880           R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
13881 
13882         return R;
13883       } else {
13884         // We matched a built-in operator. Convert the arguments, then
13885         // break out so that we will build the appropriate built-in
13886         // operator node.
13887         ExprResult ArgsRes0 = PerformImplicitConversion(
13888             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13889             AA_Passing, CCK_ForBuiltinOverloadedOp);
13890         if (ArgsRes0.isInvalid())
13891           return ExprError();
13892         Args[0] = ArgsRes0.get();
13893 
13894         ExprResult ArgsRes1 = PerformImplicitConversion(
13895             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13896             AA_Passing, CCK_ForBuiltinOverloadedOp);
13897         if (ArgsRes1.isInvalid())
13898           return ExprError();
13899         Args[1] = ArgsRes1.get();
13900         break;
13901       }
13902     }
13903 
13904     case OR_No_Viable_Function: {
13905       // C++ [over.match.oper]p9:
13906       //   If the operator is the operator , [...] and there are no
13907       //   viable functions, then the operator is assumed to be the
13908       //   built-in operator and interpreted according to clause 5.
13909       if (Opc == BO_Comma)
13910         break;
13911 
13912       // When defaulting an 'operator<=>', we can try to synthesize a three-way
13913       // compare result using '==' and '<'.
13914       if (DefaultedFn && Opc == BO_Cmp) {
13915         ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
13916                                                           Args[1], DefaultedFn);
13917         if (E.isInvalid() || E.isUsable())
13918           return E;
13919       }
13920 
13921       // For class as left operand for assignment or compound assignment
13922       // operator do not fall through to handling in built-in, but report that
13923       // no overloaded assignment operator found
13924       ExprResult Result = ExprError();
13925       StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
13926       auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
13927                                                    Args, OpLoc);
13928       DeferDiagsRAII DDR(*this,
13929                          CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
13930       if (Args[0]->getType()->isRecordType() &&
13931           Opc >= BO_Assign && Opc <= BO_OrAssign) {
13932         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
13933              << BinaryOperator::getOpcodeStr(Opc)
13934              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13935         if (Args[0]->getType()->isIncompleteType()) {
13936           Diag(OpLoc, diag::note_assign_lhs_incomplete)
13937             << Args[0]->getType()
13938             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13939         }
13940       } else {
13941         // This is an erroneous use of an operator which can be overloaded by
13942         // a non-member function. Check for non-member operators which were
13943         // defined too late to be candidates.
13944         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
13945           // FIXME: Recover by calling the found function.
13946           return ExprError();
13947 
13948         // No viable function; try to create a built-in operation, which will
13949         // produce an error. Then, show the non-viable candidates.
13950         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13951       }
13952       assert(Result.isInvalid() &&
13953              "C++ binary operator overloading is missing candidates!");
13954       CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
13955       return Result;
13956     }
13957 
13958     case OR_Ambiguous:
13959       CandidateSet.NoteCandidates(
13960           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13961                                          << BinaryOperator::getOpcodeStr(Opc)
13962                                          << Args[0]->getType()
13963                                          << Args[1]->getType()
13964                                          << Args[0]->getSourceRange()
13965                                          << Args[1]->getSourceRange()),
13966           *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13967           OpLoc);
13968       return ExprError();
13969 
13970     case OR_Deleted:
13971       if (isImplicitlyDeleted(Best->Function)) {
13972         FunctionDecl *DeletedFD = Best->Function;
13973         DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
13974         if (DFK.isSpecialMember()) {
13975           Diag(OpLoc, diag::err_ovl_deleted_special_oper)
13976             << Args[0]->getType() << DFK.asSpecialMember();
13977         } else {
13978           assert(DFK.isComparison());
13979           Diag(OpLoc, diag::err_ovl_deleted_comparison)
13980             << Args[0]->getType() << DeletedFD;
13981         }
13982 
13983         // The user probably meant to call this special member. Just
13984         // explain why it's deleted.
13985         NoteDeletedFunction(DeletedFD);
13986         return ExprError();
13987       }
13988       CandidateSet.NoteCandidates(
13989           PartialDiagnosticAt(
13990               OpLoc, PDiag(diag::err_ovl_deleted_oper)
13991                          << getOperatorSpelling(Best->Function->getDeclName()
13992                                                     .getCXXOverloadedOperator())
13993                          << Args[0]->getSourceRange()
13994                          << Args[1]->getSourceRange()),
13995           *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13996           OpLoc);
13997       return ExprError();
13998   }
13999 
14000   // We matched a built-in operator; build it.
14001   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14002 }
14003 
14004 ExprResult Sema::BuildSynthesizedThreeWayComparison(
14005     SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
14006     FunctionDecl *DefaultedFn) {
14007   const ComparisonCategoryInfo *Info =
14008       Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
14009   // If we're not producing a known comparison category type, we can't
14010   // synthesize a three-way comparison. Let the caller diagnose this.
14011   if (!Info)
14012     return ExprResult((Expr*)nullptr);
14013 
14014   // If we ever want to perform this synthesis more generally, we will need to
14015   // apply the temporary materialization conversion to the operands.
14016   assert(LHS->isGLValue() && RHS->isGLValue() &&
14017          "cannot use prvalue expressions more than once");
14018   Expr *OrigLHS = LHS;
14019   Expr *OrigRHS = RHS;
14020 
14021   // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
14022   // each of them multiple times below.
14023   LHS = new (Context)
14024       OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
14025                       LHS->getObjectKind(), LHS);
14026   RHS = new (Context)
14027       OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
14028                       RHS->getObjectKind(), RHS);
14029 
14030   ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
14031                                         DefaultedFn);
14032   if (Eq.isInvalid())
14033     return ExprError();
14034 
14035   ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
14036                                           true, DefaultedFn);
14037   if (Less.isInvalid())
14038     return ExprError();
14039 
14040   ExprResult Greater;
14041   if (Info->isPartial()) {
14042     Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
14043                                     DefaultedFn);
14044     if (Greater.isInvalid())
14045       return ExprError();
14046   }
14047 
14048   // Form the list of comparisons we're going to perform.
14049   struct Comparison {
14050     ExprResult Cmp;
14051     ComparisonCategoryResult Result;
14052   } Comparisons[4] =
14053   { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
14054                           : ComparisonCategoryResult::Equivalent},
14055     {Less, ComparisonCategoryResult::Less},
14056     {Greater, ComparisonCategoryResult::Greater},
14057     {ExprResult(), ComparisonCategoryResult::Unordered},
14058   };
14059 
14060   int I = Info->isPartial() ? 3 : 2;
14061 
14062   // Combine the comparisons with suitable conditional expressions.
14063   ExprResult Result;
14064   for (; I >= 0; --I) {
14065     // Build a reference to the comparison category constant.
14066     auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
14067     // FIXME: Missing a constant for a comparison category. Diagnose this?
14068     if (!VI)
14069       return ExprResult((Expr*)nullptr);
14070     ExprResult ThisResult =
14071         BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
14072     if (ThisResult.isInvalid())
14073       return ExprError();
14074 
14075     // Build a conditional unless this is the final case.
14076     if (Result.get()) {
14077       Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
14078                                   ThisResult.get(), Result.get());
14079       if (Result.isInvalid())
14080         return ExprError();
14081     } else {
14082       Result = ThisResult;
14083     }
14084   }
14085 
14086   // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
14087   // bind the OpaqueValueExprs before they're (repeatedly) used.
14088   Expr *SyntacticForm = BinaryOperator::Create(
14089       Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
14090       Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
14091       CurFPFeatureOverrides());
14092   Expr *SemanticForm[] = {LHS, RHS, Result.get()};
14093   return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
14094 }
14095 
14096 static bool PrepareArgumentsForCallToObjectOfClassType(
14097     Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
14098     MultiExprArg Args, SourceLocation LParenLoc) {
14099 
14100   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14101   unsigned NumParams = Proto->getNumParams();
14102   unsigned NumArgsSlots =
14103       MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
14104   // Build the full argument list for the method call (the implicit object
14105   // parameter is placed at the beginning of the list).
14106   MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
14107   bool IsError = false;
14108   // Initialize the implicit object parameter.
14109   // Check the argument types.
14110   for (unsigned i = 0; i != NumParams; i++) {
14111     Expr *Arg;
14112     if (i < Args.size()) {
14113       Arg = Args[i];
14114       ExprResult InputInit =
14115           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
14116                                           S.Context, Method->getParamDecl(i)),
14117                                       SourceLocation(), Arg);
14118       IsError |= InputInit.isInvalid();
14119       Arg = InputInit.getAs<Expr>();
14120     } else {
14121       ExprResult DefArg =
14122           S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14123       if (DefArg.isInvalid()) {
14124         IsError = true;
14125         break;
14126       }
14127       Arg = DefArg.getAs<Expr>();
14128     }
14129 
14130     MethodArgs.push_back(Arg);
14131   }
14132   return IsError;
14133 }
14134 
14135 ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
14136                                                     SourceLocation RLoc,
14137                                                     Expr *Base,
14138                                                     MultiExprArg ArgExpr) {
14139   SmallVector<Expr *, 2> Args;
14140   Args.push_back(Base);
14141   for (auto e : ArgExpr) {
14142     Args.push_back(e);
14143   }
14144   DeclarationName OpName =
14145       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
14146 
14147   SourceRange Range = ArgExpr.empty()
14148                           ? SourceRange{}
14149                           : SourceRange(ArgExpr.front()->getBeginLoc(),
14150                                         ArgExpr.back()->getEndLoc());
14151 
14152   // If either side is type-dependent, create an appropriate dependent
14153   // expression.
14154   if (Expr::hasAnyTypeDependentArguments(Args)) {
14155 
14156     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14157     // CHECKME: no 'operator' keyword?
14158     DeclarationNameInfo OpNameInfo(OpName, LLoc);
14159     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
14160     ExprResult Fn = CreateUnresolvedLookupExpr(
14161         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
14162     if (Fn.isInvalid())
14163       return ExprError();
14164     // Can't add any actual overloads yet
14165 
14166     return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
14167                                        Context.DependentTy, VK_PRValue, RLoc,
14168                                        CurFPFeatureOverrides());
14169   }
14170 
14171   // Handle placeholders
14172   UnbridgedCastsSet UnbridgedCasts;
14173   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14174     return ExprError();
14175   }
14176   // Build an empty overload set.
14177   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
14178 
14179   // Subscript can only be overloaded as a member function.
14180 
14181   // Add operator candidates that are member functions.
14182   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
14183 
14184   // Add builtin operator candidates.
14185   if (Args.size() == 2)
14186     AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
14187 
14188   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14189 
14190   // Perform overload resolution.
14191   OverloadCandidateSet::iterator Best;
14192   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
14193     case OR_Success: {
14194       // We found a built-in operator or an overloaded operator.
14195       FunctionDecl *FnDecl = Best->Function;
14196 
14197       if (FnDecl) {
14198         // We matched an overloaded operator. Build a call to that
14199         // operator.
14200 
14201         CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
14202 
14203         // Convert the arguments.
14204         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
14205         SmallVector<Expr *, 2> MethodArgs;
14206         ExprResult Arg0 = PerformObjectArgumentInitialization(
14207             Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14208         if (Arg0.isInvalid())
14209           return ExprError();
14210 
14211         MethodArgs.push_back(Arg0.get());
14212         bool IsError = PrepareArgumentsForCallToObjectOfClassType(
14213             *this, MethodArgs, Method, ArgExpr, LLoc);
14214         if (IsError)
14215           return ExprError();
14216 
14217         // Build the actual expression node.
14218         DeclarationNameInfo OpLocInfo(OpName, LLoc);
14219         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
14220         ExprResult FnExpr = CreateFunctionRefExpr(
14221             *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
14222             OpLocInfo.getLoc(), OpLocInfo.getInfo());
14223         if (FnExpr.isInvalid())
14224           return ExprError();
14225 
14226         // Determine the result type
14227         QualType ResultTy = FnDecl->getReturnType();
14228         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14229         ResultTy = ResultTy.getNonLValueExprType(Context);
14230 
14231         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14232             Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
14233             CurFPFeatureOverrides());
14234         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
14235           return ExprError();
14236 
14237         if (CheckFunctionCall(Method, TheCall,
14238                               Method->getType()->castAs<FunctionProtoType>()))
14239           return ExprError();
14240 
14241         return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14242                                            FnDecl);
14243       } else {
14244         // We matched a built-in operator. Convert the arguments, then
14245         // break out so that we will build the appropriate built-in
14246         // operator node.
14247         ExprResult ArgsRes0 = PerformImplicitConversion(
14248             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
14249             AA_Passing, CCK_ForBuiltinOverloadedOp);
14250         if (ArgsRes0.isInvalid())
14251           return ExprError();
14252         Args[0] = ArgsRes0.get();
14253 
14254         ExprResult ArgsRes1 = PerformImplicitConversion(
14255             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
14256             AA_Passing, CCK_ForBuiltinOverloadedOp);
14257         if (ArgsRes1.isInvalid())
14258           return ExprError();
14259         Args[1] = ArgsRes1.get();
14260 
14261         break;
14262       }
14263     }
14264 
14265     case OR_No_Viable_Function: {
14266       PartialDiagnostic PD =
14267           CandidateSet.empty()
14268               ? (PDiag(diag::err_ovl_no_oper)
14269                  << Args[0]->getType() << /*subscript*/ 0
14270                  << Args[0]->getSourceRange() << Range)
14271               : (PDiag(diag::err_ovl_no_viable_subscript)
14272                  << Args[0]->getType() << Args[0]->getSourceRange() << Range);
14273       CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
14274                                   OCD_AllCandidates, ArgExpr, "[]", LLoc);
14275       return ExprError();
14276     }
14277 
14278     case OR_Ambiguous:
14279       if (Args.size() == 2) {
14280         CandidateSet.NoteCandidates(
14281             PartialDiagnosticAt(
14282                 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
14283                           << "[]" << Args[0]->getType() << Args[1]->getType()
14284                           << Args[0]->getSourceRange() << Range),
14285             *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
14286       } else {
14287         CandidateSet.NoteCandidates(
14288             PartialDiagnosticAt(LLoc,
14289                                 PDiag(diag::err_ovl_ambiguous_subscript_call)
14290                                     << Args[0]->getType()
14291                                     << Args[0]->getSourceRange() << Range),
14292             *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
14293       }
14294       return ExprError();
14295 
14296     case OR_Deleted:
14297       CandidateSet.NoteCandidates(
14298           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
14299                                         << "[]" << Args[0]->getSourceRange()
14300                                         << Range),
14301           *this, OCD_AllCandidates, Args, "[]", LLoc);
14302       return ExprError();
14303     }
14304 
14305   // We matched a built-in operator; build it.
14306   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
14307 }
14308 
14309 /// BuildCallToMemberFunction - Build a call to a member
14310 /// function. MemExpr is the expression that refers to the member
14311 /// function (and includes the object parameter), Args/NumArgs are the
14312 /// arguments to the function call (not including the object
14313 /// parameter). The caller needs to validate that the member
14314 /// expression refers to a non-static member function or an overloaded
14315 /// member function.
14316 ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
14317                                            SourceLocation LParenLoc,
14318                                            MultiExprArg Args,
14319                                            SourceLocation RParenLoc,
14320                                            Expr *ExecConfig, bool IsExecConfig,
14321                                            bool AllowRecovery) {
14322   assert(MemExprE->getType() == Context.BoundMemberTy ||
14323          MemExprE->getType() == Context.OverloadTy);
14324 
14325   // Dig out the member expression. This holds both the object
14326   // argument and the member function we're referring to.
14327   Expr *NakedMemExpr = MemExprE->IgnoreParens();
14328 
14329   // Determine whether this is a call to a pointer-to-member function.
14330   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
14331     assert(op->getType() == Context.BoundMemberTy);
14332     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
14333 
14334     QualType fnType =
14335       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
14336 
14337     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
14338     QualType resultType = proto->getCallResultType(Context);
14339     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
14340 
14341     // Check that the object type isn't more qualified than the
14342     // member function we're calling.
14343     Qualifiers funcQuals = proto->getMethodQuals();
14344 
14345     QualType objectType = op->getLHS()->getType();
14346     if (op->getOpcode() == BO_PtrMemI)
14347       objectType = objectType->castAs<PointerType>()->getPointeeType();
14348     Qualifiers objectQuals = objectType.getQualifiers();
14349 
14350     Qualifiers difference = objectQuals - funcQuals;
14351     difference.removeObjCGCAttr();
14352     difference.removeAddressSpace();
14353     if (difference) {
14354       std::string qualsString = difference.getAsString();
14355       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
14356         << fnType.getUnqualifiedType()
14357         << qualsString
14358         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
14359     }
14360 
14361     CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
14362         Context, MemExprE, Args, resultType, valueKind, RParenLoc,
14363         CurFPFeatureOverrides(), proto->getNumParams());
14364 
14365     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
14366                             call, nullptr))
14367       return ExprError();
14368 
14369     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
14370       return ExprError();
14371 
14372     if (CheckOtherCall(call, proto))
14373       return ExprError();
14374 
14375     return MaybeBindToTemporary(call);
14376   }
14377 
14378   // We only try to build a recovery expr at this level if we can preserve
14379   // the return type, otherwise we return ExprError() and let the caller
14380   // recover.
14381   auto BuildRecoveryExpr = [&](QualType Type) {
14382     if (!AllowRecovery)
14383       return ExprError();
14384     std::vector<Expr *> SubExprs = {MemExprE};
14385     llvm::append_range(SubExprs, Args);
14386     return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
14387                               Type);
14388   };
14389   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
14390     return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
14391                             RParenLoc, CurFPFeatureOverrides());
14392 
14393   UnbridgedCastsSet UnbridgedCasts;
14394   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14395     return ExprError();
14396 
14397   MemberExpr *MemExpr;
14398   CXXMethodDecl *Method = nullptr;
14399   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
14400   NestedNameSpecifier *Qualifier = nullptr;
14401   if (isa<MemberExpr>(NakedMemExpr)) {
14402     MemExpr = cast<MemberExpr>(NakedMemExpr);
14403     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
14404     FoundDecl = MemExpr->getFoundDecl();
14405     Qualifier = MemExpr->getQualifier();
14406     UnbridgedCasts.restore();
14407   } else {
14408     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
14409     Qualifier = UnresExpr->getQualifier();
14410 
14411     QualType ObjectType = UnresExpr->getBaseType();
14412     Expr::Classification ObjectClassification
14413       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
14414                             : UnresExpr->getBase()->Classify(Context);
14415 
14416     // Add overload candidates
14417     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
14418                                       OverloadCandidateSet::CSK_Normal);
14419 
14420     // FIXME: avoid copy.
14421     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14422     if (UnresExpr->hasExplicitTemplateArgs()) {
14423       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14424       TemplateArgs = &TemplateArgsBuffer;
14425     }
14426 
14427     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
14428            E = UnresExpr->decls_end(); I != E; ++I) {
14429 
14430       NamedDecl *Func = *I;
14431       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
14432       if (isa<UsingShadowDecl>(Func))
14433         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
14434 
14435 
14436       // Microsoft supports direct constructor calls.
14437       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
14438         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
14439                              CandidateSet,
14440                              /*SuppressUserConversions*/ false);
14441       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
14442         // If explicit template arguments were provided, we can't call a
14443         // non-template member function.
14444         if (TemplateArgs)
14445           continue;
14446 
14447         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
14448                            ObjectClassification, Args, CandidateSet,
14449                            /*SuppressUserConversions=*/false);
14450       } else {
14451         AddMethodTemplateCandidate(
14452             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
14453             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
14454             /*SuppressUserConversions=*/false);
14455       }
14456     }
14457 
14458     DeclarationName DeclName = UnresExpr->getMemberName();
14459 
14460     UnbridgedCasts.restore();
14461 
14462     OverloadCandidateSet::iterator Best;
14463     bool Succeeded = false;
14464     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
14465                                             Best)) {
14466     case OR_Success:
14467       Method = cast<CXXMethodDecl>(Best->Function);
14468       FoundDecl = Best->FoundDecl;
14469       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
14470       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
14471         break;
14472       // If FoundDecl is different from Method (such as if one is a template
14473       // and the other a specialization), make sure DiagnoseUseOfDecl is
14474       // called on both.
14475       // FIXME: This would be more comprehensively addressed by modifying
14476       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
14477       // being used.
14478       if (Method != FoundDecl.getDecl() &&
14479                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
14480         break;
14481       Succeeded = true;
14482       break;
14483 
14484     case OR_No_Viable_Function:
14485       CandidateSet.NoteCandidates(
14486           PartialDiagnosticAt(
14487               UnresExpr->getMemberLoc(),
14488               PDiag(diag::err_ovl_no_viable_member_function_in_call)
14489                   << DeclName << MemExprE->getSourceRange()),
14490           *this, OCD_AllCandidates, Args);
14491       break;
14492     case OR_Ambiguous:
14493       CandidateSet.NoteCandidates(
14494           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14495                               PDiag(diag::err_ovl_ambiguous_member_call)
14496                                   << DeclName << MemExprE->getSourceRange()),
14497           *this, OCD_AmbiguousCandidates, Args);
14498       break;
14499     case OR_Deleted:
14500       CandidateSet.NoteCandidates(
14501           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14502                               PDiag(diag::err_ovl_deleted_member_call)
14503                                   << DeclName << MemExprE->getSourceRange()),
14504           *this, OCD_AllCandidates, Args);
14505       break;
14506     }
14507     // Overload resolution fails, try to recover.
14508     if (!Succeeded)
14509       return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
14510 
14511     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
14512 
14513     // If overload resolution picked a static member, build a
14514     // non-member call based on that function.
14515     if (Method->isStatic()) {
14516       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
14517                                    ExecConfig, IsExecConfig);
14518     }
14519 
14520     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
14521   }
14522 
14523   QualType ResultType = Method->getReturnType();
14524   ExprValueKind VK = Expr::getValueKindForType(ResultType);
14525   ResultType = ResultType.getNonLValueExprType(Context);
14526 
14527   assert(Method && "Member call to something that isn't a method?");
14528   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14529   CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create(
14530       Context, MemExprE, Args, ResultType, VK, RParenLoc,
14531       CurFPFeatureOverrides(), Proto->getNumParams());
14532 
14533   // Check for a valid return type.
14534   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
14535                           TheCall, Method))
14536     return BuildRecoveryExpr(ResultType);
14537 
14538   // Convert the object argument (for a non-static member function call).
14539   // We only need to do this if there was actually an overload; otherwise
14540   // it was done at lookup.
14541   if (!Method->isStatic()) {
14542     ExprResult ObjectArg =
14543       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
14544                                           FoundDecl, Method);
14545     if (ObjectArg.isInvalid())
14546       return ExprError();
14547     MemExpr->setBase(ObjectArg.get());
14548   }
14549 
14550   // Convert the rest of the arguments
14551   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
14552                               RParenLoc))
14553     return BuildRecoveryExpr(ResultType);
14554 
14555   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14556 
14557   if (CheckFunctionCall(Method, TheCall, Proto))
14558     return ExprError();
14559 
14560   // In the case the method to call was not selected by the overloading
14561   // resolution process, we still need to handle the enable_if attribute. Do
14562   // that here, so it will not hide previous -- and more relevant -- errors.
14563   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
14564     if (const EnableIfAttr *Attr =
14565             CheckEnableIf(Method, LParenLoc, Args, true)) {
14566       Diag(MemE->getMemberLoc(),
14567            diag::err_ovl_no_viable_member_function_in_call)
14568           << Method << Method->getSourceRange();
14569       Diag(Method->getLocation(),
14570            diag::note_ovl_candidate_disabled_by_function_cond_attr)
14571           << Attr->getCond()->getSourceRange() << Attr->getMessage();
14572       return ExprError();
14573     }
14574   }
14575 
14576   if ((isa<CXXConstructorDecl>(CurContext) ||
14577        isa<CXXDestructorDecl>(CurContext)) &&
14578       TheCall->getMethodDecl()->isPure()) {
14579     const CXXMethodDecl *MD = TheCall->getMethodDecl();
14580 
14581     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
14582         MemExpr->performsVirtualDispatch(getLangOpts())) {
14583       Diag(MemExpr->getBeginLoc(),
14584            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
14585           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
14586           << MD->getParent();
14587 
14588       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
14589       if (getLangOpts().AppleKext)
14590         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
14591             << MD->getParent() << MD->getDeclName();
14592     }
14593   }
14594 
14595   if (CXXDestructorDecl *DD =
14596           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
14597     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
14598     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
14599     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
14600                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
14601                          MemExpr->getMemberLoc());
14602   }
14603 
14604   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14605                                      TheCall->getMethodDecl());
14606 }
14607 
14608 /// BuildCallToObjectOfClassType - Build a call to an object of class
14609 /// type (C++ [over.call.object]), which can end up invoking an
14610 /// overloaded function call operator (@c operator()) or performing a
14611 /// user-defined conversion on the object argument.
14612 ExprResult
14613 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
14614                                    SourceLocation LParenLoc,
14615                                    MultiExprArg Args,
14616                                    SourceLocation RParenLoc) {
14617   if (checkPlaceholderForOverload(*this, Obj))
14618     return ExprError();
14619   ExprResult Object = Obj;
14620 
14621   UnbridgedCastsSet UnbridgedCasts;
14622   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14623     return ExprError();
14624 
14625   assert(Object.get()->getType()->isRecordType() &&
14626          "Requires object type argument");
14627 
14628   // C++ [over.call.object]p1:
14629   //  If the primary-expression E in the function call syntax
14630   //  evaluates to a class object of type "cv T", then the set of
14631   //  candidate functions includes at least the function call
14632   //  operators of T. The function call operators of T are obtained by
14633   //  ordinary lookup of the name operator() in the context of
14634   //  (E).operator().
14635   OverloadCandidateSet CandidateSet(LParenLoc,
14636                                     OverloadCandidateSet::CSK_Operator);
14637   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
14638 
14639   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
14640                           diag::err_incomplete_object_call, Object.get()))
14641     return true;
14642 
14643   const auto *Record = Object.get()->getType()->castAs<RecordType>();
14644   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
14645   LookupQualifiedName(R, Record->getDecl());
14646   R.suppressDiagnostics();
14647 
14648   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14649        Oper != OperEnd; ++Oper) {
14650     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
14651                        Object.get()->Classify(Context), Args, CandidateSet,
14652                        /*SuppressUserConversion=*/false);
14653   }
14654 
14655   // C++ [over.call.object]p2:
14656   //   In addition, for each (non-explicit in C++0x) conversion function
14657   //   declared in T of the form
14658   //
14659   //        operator conversion-type-id () cv-qualifier;
14660   //
14661   //   where cv-qualifier is the same cv-qualification as, or a
14662   //   greater cv-qualification than, cv, and where conversion-type-id
14663   //   denotes the type "pointer to function of (P1,...,Pn) returning
14664   //   R", or the type "reference to pointer to function of
14665   //   (P1,...,Pn) returning R", or the type "reference to function
14666   //   of (P1,...,Pn) returning R", a surrogate call function [...]
14667   //   is also considered as a candidate function. Similarly,
14668   //   surrogate call functions are added to the set of candidate
14669   //   functions for each conversion function declared in an
14670   //   accessible base class provided the function is not hidden
14671   //   within T by another intervening declaration.
14672   const auto &Conversions =
14673       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
14674   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
14675     NamedDecl *D = *I;
14676     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
14677     if (isa<UsingShadowDecl>(D))
14678       D = cast<UsingShadowDecl>(D)->getTargetDecl();
14679 
14680     // Skip over templated conversion functions; they aren't
14681     // surrogates.
14682     if (isa<FunctionTemplateDecl>(D))
14683       continue;
14684 
14685     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
14686     if (!Conv->isExplicit()) {
14687       // Strip the reference type (if any) and then the pointer type (if
14688       // any) to get down to what might be a function type.
14689       QualType ConvType = Conv->getConversionType().getNonReferenceType();
14690       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
14691         ConvType = ConvPtrType->getPointeeType();
14692 
14693       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
14694       {
14695         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
14696                               Object.get(), Args, CandidateSet);
14697       }
14698     }
14699   }
14700 
14701   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14702 
14703   // Perform overload resolution.
14704   OverloadCandidateSet::iterator Best;
14705   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
14706                                           Best)) {
14707   case OR_Success:
14708     // Overload resolution succeeded; we'll build the appropriate call
14709     // below.
14710     break;
14711 
14712   case OR_No_Viable_Function: {
14713     PartialDiagnostic PD =
14714         CandidateSet.empty()
14715             ? (PDiag(diag::err_ovl_no_oper)
14716                << Object.get()->getType() << /*call*/ 1
14717                << Object.get()->getSourceRange())
14718             : (PDiag(diag::err_ovl_no_viable_object_call)
14719                << Object.get()->getType() << Object.get()->getSourceRange());
14720     CandidateSet.NoteCandidates(
14721         PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
14722         OCD_AllCandidates, Args);
14723     break;
14724   }
14725   case OR_Ambiguous:
14726     CandidateSet.NoteCandidates(
14727         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14728                             PDiag(diag::err_ovl_ambiguous_object_call)
14729                                 << Object.get()->getType()
14730                                 << Object.get()->getSourceRange()),
14731         *this, OCD_AmbiguousCandidates, Args);
14732     break;
14733 
14734   case OR_Deleted:
14735     CandidateSet.NoteCandidates(
14736         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14737                             PDiag(diag::err_ovl_deleted_object_call)
14738                                 << Object.get()->getType()
14739                                 << Object.get()->getSourceRange()),
14740         *this, OCD_AllCandidates, Args);
14741     break;
14742   }
14743 
14744   if (Best == CandidateSet.end())
14745     return true;
14746 
14747   UnbridgedCasts.restore();
14748 
14749   if (Best->Function == nullptr) {
14750     // Since there is no function declaration, this is one of the
14751     // surrogate candidates. Dig out the conversion function.
14752     CXXConversionDecl *Conv
14753       = cast<CXXConversionDecl>(
14754                          Best->Conversions[0].UserDefined.ConversionFunction);
14755 
14756     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
14757                               Best->FoundDecl);
14758     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
14759       return ExprError();
14760     assert(Conv == Best->FoundDecl.getDecl() &&
14761              "Found Decl & conversion-to-functionptr should be same, right?!");
14762     // We selected one of the surrogate functions that converts the
14763     // object parameter to a function pointer. Perform the conversion
14764     // on the object argument, then let BuildCallExpr finish the job.
14765 
14766     // Create an implicit member expr to refer to the conversion operator.
14767     // and then call it.
14768     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
14769                                              Conv, HadMultipleCandidates);
14770     if (Call.isInvalid())
14771       return ExprError();
14772     // Record usage of conversion in an implicit cast.
14773     Call = ImplicitCastExpr::Create(
14774         Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
14775         nullptr, VK_PRValue, CurFPFeatureOverrides());
14776 
14777     return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
14778   }
14779 
14780   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
14781 
14782   // We found an overloaded operator(). Build a CXXOperatorCallExpr
14783   // that calls this method, using Object for the implicit object
14784   // parameter and passing along the remaining arguments.
14785   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14786 
14787   // An error diagnostic has already been printed when parsing the declaration.
14788   if (Method->isInvalidDecl())
14789     return ExprError();
14790 
14791   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14792   unsigned NumParams = Proto->getNumParams();
14793 
14794   DeclarationNameInfo OpLocInfo(
14795                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
14796   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
14797   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14798                                            Obj, HadMultipleCandidates,
14799                                            OpLocInfo.getLoc(),
14800                                            OpLocInfo.getInfo());
14801   if (NewFn.isInvalid())
14802     return true;
14803 
14804   SmallVector<Expr *, 8> MethodArgs;
14805   MethodArgs.reserve(NumParams + 1);
14806 
14807   bool IsError = false;
14808 
14809   // Initialize the implicit object parameter.
14810   ExprResult ObjRes =
14811     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
14812                                         Best->FoundDecl, Method);
14813   if (ObjRes.isInvalid())
14814     IsError = true;
14815   else
14816     Object = ObjRes;
14817   MethodArgs.push_back(Object.get());
14818 
14819   IsError |= PrepareArgumentsForCallToObjectOfClassType(
14820       *this, MethodArgs, Method, Args, LParenLoc);
14821 
14822   // If this is a variadic call, handle args passed through "...".
14823   if (Proto->isVariadic()) {
14824     // Promote the arguments (C99 6.5.2.2p7).
14825     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
14826       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
14827                                                         nullptr);
14828       IsError |= Arg.isInvalid();
14829       MethodArgs.push_back(Arg.get());
14830     }
14831   }
14832 
14833   if (IsError)
14834     return true;
14835 
14836   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14837 
14838   // Once we've built TheCall, all of the expressions are properly owned.
14839   QualType ResultTy = Method->getReturnType();
14840   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14841   ResultTy = ResultTy.getNonLValueExprType(Context);
14842 
14843   CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14844       Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
14845       CurFPFeatureOverrides());
14846 
14847   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
14848     return true;
14849 
14850   if (CheckFunctionCall(Method, TheCall, Proto))
14851     return true;
14852 
14853   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
14854 }
14855 
14856 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
14857 ///  (if one exists), where @c Base is an expression of class type and
14858 /// @c Member is the name of the member we're trying to find.
14859 ExprResult
14860 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
14861                                bool *NoArrowOperatorFound) {
14862   assert(Base->getType()->isRecordType() &&
14863          "left-hand side must have class type");
14864 
14865   if (checkPlaceholderForOverload(*this, Base))
14866     return ExprError();
14867 
14868   SourceLocation Loc = Base->getExprLoc();
14869 
14870   // C++ [over.ref]p1:
14871   //
14872   //   [...] An expression x->m is interpreted as (x.operator->())->m
14873   //   for a class object x of type T if T::operator->() exists and if
14874   //   the operator is selected as the best match function by the
14875   //   overload resolution mechanism (13.3).
14876   DeclarationName OpName =
14877     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
14878   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
14879 
14880   if (RequireCompleteType(Loc, Base->getType(),
14881                           diag::err_typecheck_incomplete_tag, Base))
14882     return ExprError();
14883 
14884   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
14885   LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
14886   R.suppressDiagnostics();
14887 
14888   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14889        Oper != OperEnd; ++Oper) {
14890     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
14891                        None, CandidateSet, /*SuppressUserConversion=*/false);
14892   }
14893 
14894   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14895 
14896   // Perform overload resolution.
14897   OverloadCandidateSet::iterator Best;
14898   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14899   case OR_Success:
14900     // Overload resolution succeeded; we'll build the call below.
14901     break;
14902 
14903   case OR_No_Viable_Function: {
14904     auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
14905     if (CandidateSet.empty()) {
14906       QualType BaseType = Base->getType();
14907       if (NoArrowOperatorFound) {
14908         // Report this specific error to the caller instead of emitting a
14909         // diagnostic, as requested.
14910         *NoArrowOperatorFound = true;
14911         return ExprError();
14912       }
14913       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
14914         << BaseType << Base->getSourceRange();
14915       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
14916         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
14917           << FixItHint::CreateReplacement(OpLoc, ".");
14918       }
14919     } else
14920       Diag(OpLoc, diag::err_ovl_no_viable_oper)
14921         << "operator->" << Base->getSourceRange();
14922     CandidateSet.NoteCandidates(*this, Base, Cands);
14923     return ExprError();
14924   }
14925   case OR_Ambiguous:
14926     CandidateSet.NoteCandidates(
14927         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
14928                                        << "->" << Base->getType()
14929                                        << Base->getSourceRange()),
14930         *this, OCD_AmbiguousCandidates, Base);
14931     return ExprError();
14932 
14933   case OR_Deleted:
14934     CandidateSet.NoteCandidates(
14935         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14936                                        << "->" << Base->getSourceRange()),
14937         *this, OCD_AllCandidates, Base);
14938     return ExprError();
14939   }
14940 
14941   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
14942 
14943   // Convert the object parameter.
14944   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14945   ExprResult BaseResult =
14946     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
14947                                         Best->FoundDecl, Method);
14948   if (BaseResult.isInvalid())
14949     return ExprError();
14950   Base = BaseResult.get();
14951 
14952   // Build the operator call.
14953   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14954                                             Base, HadMultipleCandidates, OpLoc);
14955   if (FnExpr.isInvalid())
14956     return ExprError();
14957 
14958   QualType ResultTy = Method->getReturnType();
14959   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14960   ResultTy = ResultTy.getNonLValueExprType(Context);
14961   CXXOperatorCallExpr *TheCall =
14962       CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
14963                                   ResultTy, VK, OpLoc, CurFPFeatureOverrides());
14964 
14965   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
14966     return ExprError();
14967 
14968   if (CheckFunctionCall(Method, TheCall,
14969                         Method->getType()->castAs<FunctionProtoType>()))
14970     return ExprError();
14971 
14972   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
14973 }
14974 
14975 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
14976 /// a literal operator described by the provided lookup results.
14977 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
14978                                           DeclarationNameInfo &SuffixInfo,
14979                                           ArrayRef<Expr*> Args,
14980                                           SourceLocation LitEndLoc,
14981                                        TemplateArgumentListInfo *TemplateArgs) {
14982   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
14983 
14984   OverloadCandidateSet CandidateSet(UDSuffixLoc,
14985                                     OverloadCandidateSet::CSK_Normal);
14986   AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
14987                                  TemplateArgs);
14988 
14989   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14990 
14991   // Perform overload resolution. This will usually be trivial, but might need
14992   // to perform substitutions for a literal operator template.
14993   OverloadCandidateSet::iterator Best;
14994   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
14995   case OR_Success:
14996   case OR_Deleted:
14997     break;
14998 
14999   case OR_No_Viable_Function:
15000     CandidateSet.NoteCandidates(
15001         PartialDiagnosticAt(UDSuffixLoc,
15002                             PDiag(diag::err_ovl_no_viable_function_in_call)
15003                                 << R.getLookupName()),
15004         *this, OCD_AllCandidates, Args);
15005     return ExprError();
15006 
15007   case OR_Ambiguous:
15008     CandidateSet.NoteCandidates(
15009         PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
15010                                                 << R.getLookupName()),
15011         *this, OCD_AmbiguousCandidates, Args);
15012     return ExprError();
15013   }
15014 
15015   FunctionDecl *FD = Best->Function;
15016   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
15017                                         nullptr, HadMultipleCandidates,
15018                                         SuffixInfo.getLoc(),
15019                                         SuffixInfo.getInfo());
15020   if (Fn.isInvalid())
15021     return true;
15022 
15023   // Check the argument types. This should almost always be a no-op, except
15024   // that array-to-pointer decay is applied to string literals.
15025   Expr *ConvArgs[2];
15026   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
15027     ExprResult InputInit = PerformCopyInitialization(
15028       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
15029       SourceLocation(), Args[ArgIdx]);
15030     if (InputInit.isInvalid())
15031       return true;
15032     ConvArgs[ArgIdx] = InputInit.get();
15033   }
15034 
15035   QualType ResultTy = FD->getReturnType();
15036   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15037   ResultTy = ResultTy.getNonLValueExprType(Context);
15038 
15039   UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
15040       Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
15041       VK, LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
15042 
15043   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
15044     return ExprError();
15045 
15046   if (CheckFunctionCall(FD, UDL, nullptr))
15047     return ExprError();
15048 
15049   return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
15050 }
15051 
15052 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
15053 /// given LookupResult is non-empty, it is assumed to describe a member which
15054 /// will be invoked. Otherwise, the function will be found via argument
15055 /// dependent lookup.
15056 /// CallExpr is set to a valid expression and FRS_Success returned on success,
15057 /// otherwise CallExpr is set to ExprError() and some non-success value
15058 /// is returned.
15059 Sema::ForRangeStatus
15060 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
15061                                 SourceLocation RangeLoc,
15062                                 const DeclarationNameInfo &NameInfo,
15063                                 LookupResult &MemberLookup,
15064                                 OverloadCandidateSet *CandidateSet,
15065                                 Expr *Range, ExprResult *CallExpr) {
15066   Scope *S = nullptr;
15067 
15068   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
15069   if (!MemberLookup.empty()) {
15070     ExprResult MemberRef =
15071         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
15072                                  /*IsPtr=*/false, CXXScopeSpec(),
15073                                  /*TemplateKWLoc=*/SourceLocation(),
15074                                  /*FirstQualifierInScope=*/nullptr,
15075                                  MemberLookup,
15076                                  /*TemplateArgs=*/nullptr, S);
15077     if (MemberRef.isInvalid()) {
15078       *CallExpr = ExprError();
15079       return FRS_DiagnosticIssued;
15080     }
15081     *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
15082     if (CallExpr->isInvalid()) {
15083       *CallExpr = ExprError();
15084       return FRS_DiagnosticIssued;
15085     }
15086   } else {
15087     ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
15088                                                 NestedNameSpecifierLoc(),
15089                                                 NameInfo, UnresolvedSet<0>());
15090     if (FnR.isInvalid())
15091       return FRS_DiagnosticIssued;
15092     UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
15093 
15094     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
15095                                                     CandidateSet, CallExpr);
15096     if (CandidateSet->empty() || CandidateSetError) {
15097       *CallExpr = ExprError();
15098       return FRS_NoViableFunction;
15099     }
15100     OverloadCandidateSet::iterator Best;
15101     OverloadingResult OverloadResult =
15102         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
15103 
15104     if (OverloadResult == OR_No_Viable_Function) {
15105       *CallExpr = ExprError();
15106       return FRS_NoViableFunction;
15107     }
15108     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
15109                                          Loc, nullptr, CandidateSet, &Best,
15110                                          OverloadResult,
15111                                          /*AllowTypoCorrection=*/false);
15112     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
15113       *CallExpr = ExprError();
15114       return FRS_DiagnosticIssued;
15115     }
15116   }
15117   return FRS_Success;
15118 }
15119 
15120 
15121 /// FixOverloadedFunctionReference - E is an expression that refers to
15122 /// a C++ overloaded function (possibly with some parentheses and
15123 /// perhaps a '&' around it). We have resolved the overloaded function
15124 /// to the function declaration Fn, so patch up the expression E to
15125 /// refer (possibly indirectly) to Fn. Returns the new expr.
15126 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
15127                                            FunctionDecl *Fn) {
15128   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
15129     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
15130                                                    Found, Fn);
15131     if (SubExpr == PE->getSubExpr())
15132       return PE;
15133 
15134     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
15135   }
15136 
15137   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
15138     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
15139                                                    Found, Fn);
15140     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
15141                                SubExpr->getType()) &&
15142            "Implicit cast type cannot be determined from overload");
15143     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
15144     if (SubExpr == ICE->getSubExpr())
15145       return ICE;
15146 
15147     return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
15148                                     SubExpr, nullptr, ICE->getValueKind(),
15149                                     CurFPFeatureOverrides());
15150   }
15151 
15152   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
15153     if (!GSE->isResultDependent()) {
15154       Expr *SubExpr =
15155           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
15156       if (SubExpr == GSE->getResultExpr())
15157         return GSE;
15158 
15159       // Replace the resulting type information before rebuilding the generic
15160       // selection expression.
15161       ArrayRef<Expr *> A = GSE->getAssocExprs();
15162       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
15163       unsigned ResultIdx = GSE->getResultIndex();
15164       AssocExprs[ResultIdx] = SubExpr;
15165 
15166       return GenericSelectionExpr::Create(
15167           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
15168           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
15169           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
15170           ResultIdx);
15171     }
15172     // Rather than fall through to the unreachable, return the original generic
15173     // selection expression.
15174     return GSE;
15175   }
15176 
15177   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
15178     assert(UnOp->getOpcode() == UO_AddrOf &&
15179            "Can only take the address of an overloaded function");
15180     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
15181       if (Method->isStatic()) {
15182         // Do nothing: static member functions aren't any different
15183         // from non-member functions.
15184       } else {
15185         // Fix the subexpression, which really has to be an
15186         // UnresolvedLookupExpr holding an overloaded member function
15187         // or template.
15188         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
15189                                                        Found, Fn);
15190         if (SubExpr == UnOp->getSubExpr())
15191           return UnOp;
15192 
15193         assert(isa<DeclRefExpr>(SubExpr)
15194                && "fixed to something other than a decl ref");
15195         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
15196                && "fixed to a member ref with no nested name qualifier");
15197 
15198         // We have taken the address of a pointer to member
15199         // function. Perform the computation here so that we get the
15200         // appropriate pointer to member type.
15201         QualType ClassType
15202           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
15203         QualType MemPtrType
15204           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
15205         // Under the MS ABI, lock down the inheritance model now.
15206         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15207           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
15208 
15209         return UnaryOperator::Create(
15210             Context, SubExpr, UO_AddrOf, MemPtrType, VK_PRValue, OK_Ordinary,
15211             UnOp->getOperatorLoc(), false, CurFPFeatureOverrides());
15212       }
15213     }
15214     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
15215                                                    Found, Fn);
15216     if (SubExpr == UnOp->getSubExpr())
15217       return UnOp;
15218 
15219     // FIXME: This can't currently fail, but in principle it could.
15220     return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf, SubExpr)
15221         .get();
15222   }
15223 
15224   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15225     // FIXME: avoid copy.
15226     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15227     if (ULE->hasExplicitTemplateArgs()) {
15228       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
15229       TemplateArgs = &TemplateArgsBuffer;
15230     }
15231 
15232     QualType Type = Fn->getType();
15233     ExprValueKind ValueKind = getLangOpts().CPlusPlus ? VK_LValue : VK_PRValue;
15234 
15235     // FIXME: Duplicated from BuildDeclarationNameExpr.
15236     if (unsigned BID = Fn->getBuiltinID()) {
15237       if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
15238         Type = Context.BuiltinFnTy;
15239         ValueKind = VK_PRValue;
15240       }
15241     }
15242 
15243     DeclRefExpr *DRE = BuildDeclRefExpr(
15244         Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
15245         Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
15246     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
15247     return DRE;
15248   }
15249 
15250   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
15251     // FIXME: avoid copy.
15252     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15253     if (MemExpr->hasExplicitTemplateArgs()) {
15254       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
15255       TemplateArgs = &TemplateArgsBuffer;
15256     }
15257 
15258     Expr *Base;
15259 
15260     // If we're filling in a static method where we used to have an
15261     // implicit member access, rewrite to a simple decl ref.
15262     if (MemExpr->isImplicitAccess()) {
15263       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
15264         DeclRefExpr *DRE = BuildDeclRefExpr(
15265             Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
15266             MemExpr->getQualifierLoc(), Found.getDecl(),
15267             MemExpr->getTemplateKeywordLoc(), TemplateArgs);
15268         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
15269         return DRE;
15270       } else {
15271         SourceLocation Loc = MemExpr->getMemberLoc();
15272         if (MemExpr->getQualifier())
15273           Loc = MemExpr->getQualifierLoc().getBeginLoc();
15274         Base =
15275             BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
15276       }
15277     } else
15278       Base = MemExpr->getBase();
15279 
15280     ExprValueKind valueKind;
15281     QualType type;
15282     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
15283       valueKind = VK_LValue;
15284       type = Fn->getType();
15285     } else {
15286       valueKind = VK_PRValue;
15287       type = Context.BoundMemberTy;
15288     }
15289 
15290     return BuildMemberExpr(
15291         Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
15292         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
15293         /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
15294         type, valueKind, OK_Ordinary, TemplateArgs);
15295   }
15296 
15297   llvm_unreachable("Invalid reference to overloaded function");
15298 }
15299 
15300 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
15301                                                 DeclAccessPair Found,
15302                                                 FunctionDecl *Fn) {
15303   return FixOverloadedFunctionReference(E.get(), Found, Fn);
15304 }
15305 
15306 bool clang::shouldEnforceArgLimit(bool PartialOverloading,
15307                                   FunctionDecl *Function) {
15308   if (!PartialOverloading || !Function)
15309     return true;
15310   if (Function->isVariadic())
15311     return false;
15312   if (const auto *Proto =
15313           dyn_cast<FunctionProtoType>(Function->getFunctionType()))
15314     if (Proto->isTemplateVariadic())
15315       return false;
15316   if (auto *Pattern = Function->getTemplateInstantiationPattern())
15317     if (const auto *Proto =
15318             dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
15319       if (Proto->isTemplateVariadic())
15320         return false;
15321   return true;
15322 }
15323