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,
1621                                QualType ToType, ImplicitConversionKind &ICK) {
1622   // We need at least one of these types to be a vector type to have a vector
1623   // conversion.
1624   if (!ToType->isVectorType() && !FromType->isVectorType())
1625     return false;
1626 
1627   // Identical types require no conversions.
1628   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1629     return false;
1630 
1631   // There are no conversions between extended vector types, only identity.
1632   if (ToType->isExtVectorType()) {
1633     // There are no conversions between extended vector types other than the
1634     // identity conversion.
1635     if (FromType->isExtVectorType())
1636       return false;
1637 
1638     // Vector splat from any arithmetic type to a vector.
1639     if (FromType->isArithmeticType()) {
1640       ICK = ICK_Vector_Splat;
1641       return true;
1642     }
1643   }
1644 
1645   if (ToType->isSizelessBuiltinType() || FromType->isSizelessBuiltinType())
1646     if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
1647         S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
1648       ICK = ICK_SVE_Vector_Conversion;
1649       return true;
1650     }
1651 
1652   // We can perform the conversion between vector types in the following cases:
1653   // 1)vector types are equivalent AltiVec and GCC vector types
1654   // 2)lax vector conversions are permitted and the vector types are of the
1655   //   same size
1656   // 3)the destination type does not have the ARM MVE strict-polymorphism
1657   //   attribute, which inhibits lax vector conversion for overload resolution
1658   //   only
1659   if (ToType->isVectorType() && FromType->isVectorType()) {
1660     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1661         (S.isLaxVectorConversion(FromType, ToType) &&
1662          !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
1663       ICK = ICK_Vector_Conversion;
1664       return true;
1665     }
1666   }
1667 
1668   return false;
1669 }
1670 
1671 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1672                                 bool InOverloadResolution,
1673                                 StandardConversionSequence &SCS,
1674                                 bool CStyle);
1675 
1676 /// IsStandardConversion - Determines whether there is a standard
1677 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1678 /// expression From to the type ToType. Standard conversion sequences
1679 /// only consider non-class types; for conversions that involve class
1680 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1681 /// contain the standard conversion sequence required to perform this
1682 /// conversion and this routine will return true. Otherwise, this
1683 /// routine will return false and the value of SCS is unspecified.
1684 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1685                                  bool InOverloadResolution,
1686                                  StandardConversionSequence &SCS,
1687                                  bool CStyle,
1688                                  bool AllowObjCWritebackConversion) {
1689   QualType FromType = From->getType();
1690 
1691   // Standard conversions (C++ [conv])
1692   SCS.setAsIdentityConversion();
1693   SCS.IncompatibleObjC = false;
1694   SCS.setFromType(FromType);
1695   SCS.CopyConstructor = nullptr;
1696 
1697   // There are no standard conversions for class types in C++, so
1698   // abort early. When overloading in C, however, we do permit them.
1699   if (S.getLangOpts().CPlusPlus &&
1700       (FromType->isRecordType() || ToType->isRecordType()))
1701     return false;
1702 
1703   // The first conversion can be an lvalue-to-rvalue conversion,
1704   // array-to-pointer conversion, or function-to-pointer conversion
1705   // (C++ 4p1).
1706 
1707   if (FromType == S.Context.OverloadTy) {
1708     DeclAccessPair AccessPair;
1709     if (FunctionDecl *Fn
1710           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1711                                                  AccessPair)) {
1712       // We were able to resolve the address of the overloaded function,
1713       // so we can convert to the type of that function.
1714       FromType = Fn->getType();
1715       SCS.setFromType(FromType);
1716 
1717       // we can sometimes resolve &foo<int> regardless of ToType, so check
1718       // if the type matches (identity) or we are converting to bool
1719       if (!S.Context.hasSameUnqualifiedType(
1720                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1721         QualType resultTy;
1722         // if the function type matches except for [[noreturn]], it's ok
1723         if (!S.IsFunctionConversion(FromType,
1724               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1725           // otherwise, only a boolean conversion is standard
1726           if (!ToType->isBooleanType())
1727             return false;
1728       }
1729 
1730       // Check if the "from" expression is taking the address of an overloaded
1731       // function and recompute the FromType accordingly. Take advantage of the
1732       // fact that non-static member functions *must* have such an address-of
1733       // expression.
1734       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1735       if (Method && !Method->isStatic()) {
1736         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1737                "Non-unary operator on non-static member address");
1738         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1739                == UO_AddrOf &&
1740                "Non-address-of operator on non-static member address");
1741         const Type *ClassType
1742           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1743         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1744       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1745         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1746                UO_AddrOf &&
1747                "Non-address-of operator for overloaded function expression");
1748         FromType = S.Context.getPointerType(FromType);
1749       }
1750 
1751       // Check that we've computed the proper type after overload resolution.
1752       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1753       // be calling it from within an NDEBUG block.
1754       assert(S.Context.hasSameType(
1755         FromType,
1756         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1757     } else {
1758       return false;
1759     }
1760   }
1761   // Lvalue-to-rvalue conversion (C++11 4.1):
1762   //   A glvalue (3.10) of a non-function, non-array type T can
1763   //   be converted to a prvalue.
1764   bool argIsLValue = From->isGLValue();
1765   if (argIsLValue &&
1766       !FromType->isFunctionType() && !FromType->isArrayType() &&
1767       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1768     SCS.First = ICK_Lvalue_To_Rvalue;
1769 
1770     // C11 6.3.2.1p2:
1771     //   ... if the lvalue has atomic type, the value has the non-atomic version
1772     //   of the type of the lvalue ...
1773     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1774       FromType = Atomic->getValueType();
1775 
1776     // If T is a non-class type, the type of the rvalue is the
1777     // cv-unqualified version of T. Otherwise, the type of the rvalue
1778     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1779     // just strip the qualifiers because they don't matter.
1780     FromType = FromType.getUnqualifiedType();
1781   } else if (FromType->isArrayType()) {
1782     // Array-to-pointer conversion (C++ 4.2)
1783     SCS.First = ICK_Array_To_Pointer;
1784 
1785     // An lvalue or rvalue of type "array of N T" or "array of unknown
1786     // bound of T" can be converted to an rvalue of type "pointer to
1787     // T" (C++ 4.2p1).
1788     FromType = S.Context.getArrayDecayedType(FromType);
1789 
1790     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1791       // This conversion is deprecated in C++03 (D.4)
1792       SCS.DeprecatedStringLiteralToCharPtr = true;
1793 
1794       // For the purpose of ranking in overload resolution
1795       // (13.3.3.1.1), this conversion is considered an
1796       // array-to-pointer conversion followed by a qualification
1797       // conversion (4.4). (C++ 4.2p2)
1798       SCS.Second = ICK_Identity;
1799       SCS.Third = ICK_Qualification;
1800       SCS.QualificationIncludesObjCLifetime = false;
1801       SCS.setAllToTypes(FromType);
1802       return true;
1803     }
1804   } else if (FromType->isFunctionType() && argIsLValue) {
1805     // Function-to-pointer conversion (C++ 4.3).
1806     SCS.First = ICK_Function_To_Pointer;
1807 
1808     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1809       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1810         if (!S.checkAddressOfFunctionIsAvailable(FD))
1811           return false;
1812 
1813     // An lvalue of function type T can be converted to an rvalue of
1814     // type "pointer to T." The result is a pointer to the
1815     // function. (C++ 4.3p1).
1816     FromType = S.Context.getPointerType(FromType);
1817   } else {
1818     // We don't require any conversions for the first step.
1819     SCS.First = ICK_Identity;
1820   }
1821   SCS.setToType(0, FromType);
1822 
1823   // The second conversion can be an integral promotion, floating
1824   // point promotion, integral conversion, floating point conversion,
1825   // floating-integral conversion, pointer conversion,
1826   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1827   // For overloading in C, this can also be a "compatible-type"
1828   // conversion.
1829   bool IncompatibleObjC = false;
1830   ImplicitConversionKind SecondICK = ICK_Identity;
1831   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1832     // The unqualified versions of the types are the same: there's no
1833     // conversion to do.
1834     SCS.Second = ICK_Identity;
1835   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1836     // Integral promotion (C++ 4.5).
1837     SCS.Second = ICK_Integral_Promotion;
1838     FromType = ToType.getUnqualifiedType();
1839   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1840     // Floating point promotion (C++ 4.6).
1841     SCS.Second = ICK_Floating_Promotion;
1842     FromType = ToType.getUnqualifiedType();
1843   } else if (S.IsComplexPromotion(FromType, ToType)) {
1844     // Complex promotion (Clang extension)
1845     SCS.Second = ICK_Complex_Promotion;
1846     FromType = ToType.getUnqualifiedType();
1847   } else if (ToType->isBooleanType() &&
1848              (FromType->isArithmeticType() ||
1849               FromType->isAnyPointerType() ||
1850               FromType->isBlockPointerType() ||
1851               FromType->isMemberPointerType())) {
1852     // Boolean conversions (C++ 4.12).
1853     SCS.Second = ICK_Boolean_Conversion;
1854     FromType = S.Context.BoolTy;
1855   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1856              ToType->isIntegralType(S.Context)) {
1857     // Integral conversions (C++ 4.7).
1858     SCS.Second = ICK_Integral_Conversion;
1859     FromType = ToType.getUnqualifiedType();
1860   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1861     // Complex conversions (C99 6.3.1.6)
1862     SCS.Second = ICK_Complex_Conversion;
1863     FromType = ToType.getUnqualifiedType();
1864   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1865              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1866     // Complex-real conversions (C99 6.3.1.7)
1867     SCS.Second = ICK_Complex_Real;
1868     FromType = ToType.getUnqualifiedType();
1869   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1870     // FIXME: disable conversions between long double, __ibm128 and __float128
1871     // if their representation is different until there is back end support
1872     // We of course allow this conversion if long double is really double.
1873 
1874     // Conversions between bfloat and other floats are not permitted.
1875     if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty)
1876       return false;
1877 
1878     // Conversions between IEEE-quad and IBM-extended semantics are not
1879     // permitted.
1880     const llvm::fltSemantics &FromSem =
1881         S.Context.getFloatTypeSemantics(FromType);
1882     const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
1883     if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
1884          &ToSem == &llvm::APFloat::IEEEquad()) ||
1885         (&FromSem == &llvm::APFloat::IEEEquad() &&
1886          &ToSem == &llvm::APFloat::PPCDoubleDouble()))
1887       return false;
1888 
1889     // Floating point conversions (C++ 4.8).
1890     SCS.Second = ICK_Floating_Conversion;
1891     FromType = ToType.getUnqualifiedType();
1892   } else if ((FromType->isRealFloatingType() &&
1893               ToType->isIntegralType(S.Context)) ||
1894              (FromType->isIntegralOrUnscopedEnumerationType() &&
1895               ToType->isRealFloatingType())) {
1896     // Conversions between bfloat and int are not permitted.
1897     if (FromType->isBFloat16Type() || ToType->isBFloat16Type())
1898       return false;
1899 
1900     // Floating-integral conversions (C++ 4.9).
1901     SCS.Second = ICK_Floating_Integral;
1902     FromType = ToType.getUnqualifiedType();
1903   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1904     SCS.Second = ICK_Block_Pointer_Conversion;
1905   } else if (AllowObjCWritebackConversion &&
1906              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1907     SCS.Second = ICK_Writeback_Conversion;
1908   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1909                                    FromType, IncompatibleObjC)) {
1910     // Pointer conversions (C++ 4.10).
1911     SCS.Second = ICK_Pointer_Conversion;
1912     SCS.IncompatibleObjC = IncompatibleObjC;
1913     FromType = FromType.getUnqualifiedType();
1914   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1915                                          InOverloadResolution, FromType)) {
1916     // Pointer to member conversions (4.11).
1917     SCS.Second = ICK_Pointer_Member;
1918   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1919     SCS.Second = SecondICK;
1920     FromType = ToType.getUnqualifiedType();
1921   } else if (!S.getLangOpts().CPlusPlus &&
1922              S.Context.typesAreCompatible(ToType, FromType)) {
1923     // Compatible conversions (Clang extension for C function overloading)
1924     SCS.Second = ICK_Compatible_Conversion;
1925     FromType = ToType.getUnqualifiedType();
1926   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1927                                              InOverloadResolution,
1928                                              SCS, CStyle)) {
1929     SCS.Second = ICK_TransparentUnionConversion;
1930     FromType = ToType;
1931   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1932                                  CStyle)) {
1933     // tryAtomicConversion has updated the standard conversion sequence
1934     // appropriately.
1935     return true;
1936   } else if (ToType->isEventT() &&
1937              From->isIntegerConstantExpr(S.getASTContext()) &&
1938              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1939     SCS.Second = ICK_Zero_Event_Conversion;
1940     FromType = ToType;
1941   } else if (ToType->isQueueT() &&
1942              From->isIntegerConstantExpr(S.getASTContext()) &&
1943              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1944     SCS.Second = ICK_Zero_Queue_Conversion;
1945     FromType = ToType;
1946   } else if (ToType->isSamplerT() &&
1947              From->isIntegerConstantExpr(S.getASTContext())) {
1948     SCS.Second = ICK_Compatible_Conversion;
1949     FromType = ToType;
1950   } else {
1951     // No second conversion required.
1952     SCS.Second = ICK_Identity;
1953   }
1954   SCS.setToType(1, FromType);
1955 
1956   // The third conversion can be a function pointer conversion or a
1957   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1958   bool ObjCLifetimeConversion;
1959   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1960     // Function pointer conversions (removing 'noexcept') including removal of
1961     // 'noreturn' (Clang extension).
1962     SCS.Third = ICK_Function_Conversion;
1963   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1964                                          ObjCLifetimeConversion)) {
1965     SCS.Third = ICK_Qualification;
1966     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1967     FromType = ToType;
1968   } else {
1969     // No conversion required
1970     SCS.Third = ICK_Identity;
1971   }
1972 
1973   // C++ [over.best.ics]p6:
1974   //   [...] Any difference in top-level cv-qualification is
1975   //   subsumed by the initialization itself and does not constitute
1976   //   a conversion. [...]
1977   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1978   QualType CanonTo = S.Context.getCanonicalType(ToType);
1979   if (CanonFrom.getLocalUnqualifiedType()
1980                                      == CanonTo.getLocalUnqualifiedType() &&
1981       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1982     FromType = ToType;
1983     CanonFrom = CanonTo;
1984   }
1985 
1986   SCS.setToType(2, FromType);
1987 
1988   if (CanonFrom == CanonTo)
1989     return true;
1990 
1991   // If we have not converted the argument type to the parameter type,
1992   // this is a bad conversion sequence, unless we're resolving an overload in C.
1993   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1994     return false;
1995 
1996   ExprResult ER = ExprResult{From};
1997   Sema::AssignConvertType Conv =
1998       S.CheckSingleAssignmentConstraints(ToType, ER,
1999                                          /*Diagnose=*/false,
2000                                          /*DiagnoseCFAudited=*/false,
2001                                          /*ConvertRHS=*/false);
2002   ImplicitConversionKind SecondConv;
2003   switch (Conv) {
2004   case Sema::Compatible:
2005     SecondConv = ICK_C_Only_Conversion;
2006     break;
2007   // For our purposes, discarding qualifiers is just as bad as using an
2008   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2009   // qualifiers, as well.
2010   case Sema::CompatiblePointerDiscardsQualifiers:
2011   case Sema::IncompatiblePointer:
2012   case Sema::IncompatiblePointerSign:
2013     SecondConv = ICK_Incompatible_Pointer_Conversion;
2014     break;
2015   default:
2016     return false;
2017   }
2018 
2019   // First can only be an lvalue conversion, so we pretend that this was the
2020   // second conversion. First should already be valid from earlier in the
2021   // function.
2022   SCS.Second = SecondConv;
2023   SCS.setToType(1, ToType);
2024 
2025   // Third is Identity, because Second should rank us worse than any other
2026   // conversion. This could also be ICK_Qualification, but it's simpler to just
2027   // lump everything in with the second conversion, and we don't gain anything
2028   // from making this ICK_Qualification.
2029   SCS.Third = ICK_Identity;
2030   SCS.setToType(2, ToType);
2031   return true;
2032 }
2033 
2034 static bool
2035 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2036                                      QualType &ToType,
2037                                      bool InOverloadResolution,
2038                                      StandardConversionSequence &SCS,
2039                                      bool CStyle) {
2040 
2041   const RecordType *UT = ToType->getAsUnionType();
2042   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2043     return false;
2044   // The field to initialize within the transparent union.
2045   RecordDecl *UD = UT->getDecl();
2046   // It's compatible if the expression matches any of the fields.
2047   for (const auto *it : UD->fields()) {
2048     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2049                              CStyle, /*AllowObjCWritebackConversion=*/false)) {
2050       ToType = it->getType();
2051       return true;
2052     }
2053   }
2054   return false;
2055 }
2056 
2057 /// IsIntegralPromotion - Determines whether the conversion from the
2058 /// expression From (whose potentially-adjusted type is FromType) to
2059 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
2060 /// sets PromotedType to the promoted type.
2061 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2062   const BuiltinType *To = ToType->getAs<BuiltinType>();
2063   // All integers are built-in.
2064   if (!To) {
2065     return false;
2066   }
2067 
2068   // An rvalue of type char, signed char, unsigned char, short int, or
2069   // unsigned short int can be converted to an rvalue of type int if
2070   // int can represent all the values of the source type; otherwise,
2071   // the source rvalue can be converted to an rvalue of type unsigned
2072   // int (C++ 4.5p1).
2073   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
2074       !FromType->isEnumeralType()) {
2075     if (// We can promote any signed, promotable integer type to an int
2076         (FromType->isSignedIntegerType() ||
2077          // We can promote any unsigned integer type whose size is
2078          // less than int to an int.
2079          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2080       return To->getKind() == BuiltinType::Int;
2081     }
2082 
2083     return To->getKind() == BuiltinType::UInt;
2084   }
2085 
2086   // C++11 [conv.prom]p3:
2087   //   A prvalue of an unscoped enumeration type whose underlying type is not
2088   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2089   //   following types that can represent all the values of the enumeration
2090   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
2091   //   unsigned int, long int, unsigned long int, long long int, or unsigned
2092   //   long long int. If none of the types in that list can represent all the
2093   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2094   //   type can be converted to an rvalue a prvalue of the extended integer type
2095   //   with lowest integer conversion rank (4.13) greater than the rank of long
2096   //   long in which all the values of the enumeration can be represented. If
2097   //   there are two such extended types, the signed one is chosen.
2098   // C++11 [conv.prom]p4:
2099   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
2100   //   can be converted to a prvalue of its underlying type. Moreover, if
2101   //   integral promotion can be applied to its underlying type, a prvalue of an
2102   //   unscoped enumeration type whose underlying type is fixed can also be
2103   //   converted to a prvalue of the promoted underlying type.
2104   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2105     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2106     // provided for a scoped enumeration.
2107     if (FromEnumType->getDecl()->isScoped())
2108       return false;
2109 
2110     // We can perform an integral promotion to the underlying type of the enum,
2111     // even if that's not the promoted type. Note that the check for promoting
2112     // the underlying type is based on the type alone, and does not consider
2113     // the bitfield-ness of the actual source expression.
2114     if (FromEnumType->getDecl()->isFixed()) {
2115       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2116       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2117              IsIntegralPromotion(nullptr, Underlying, ToType);
2118     }
2119 
2120     // We have already pre-calculated the promotion type, so this is trivial.
2121     if (ToType->isIntegerType() &&
2122         isCompleteType(From->getBeginLoc(), FromType))
2123       return Context.hasSameUnqualifiedType(
2124           ToType, FromEnumType->getDecl()->getPromotionType());
2125 
2126     // C++ [conv.prom]p5:
2127     //   If the bit-field has an enumerated type, it is treated as any other
2128     //   value of that type for promotion purposes.
2129     //
2130     // ... so do not fall through into the bit-field checks below in C++.
2131     if (getLangOpts().CPlusPlus)
2132       return false;
2133   }
2134 
2135   // C++0x [conv.prom]p2:
2136   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2137   //   to an rvalue a prvalue of the first of the following types that can
2138   //   represent all the values of its underlying type: int, unsigned int,
2139   //   long int, unsigned long int, long long int, or unsigned long long int.
2140   //   If none of the types in that list can represent all the values of its
2141   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2142   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2143   //   type.
2144   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2145       ToType->isIntegerType()) {
2146     // Determine whether the type we're converting from is signed or
2147     // unsigned.
2148     bool FromIsSigned = FromType->isSignedIntegerType();
2149     uint64_t FromSize = Context.getTypeSize(FromType);
2150 
2151     // The types we'll try to promote to, in the appropriate
2152     // order. Try each of these types.
2153     QualType PromoteTypes[6] = {
2154       Context.IntTy, Context.UnsignedIntTy,
2155       Context.LongTy, Context.UnsignedLongTy ,
2156       Context.LongLongTy, Context.UnsignedLongLongTy
2157     };
2158     for (int Idx = 0; Idx < 6; ++Idx) {
2159       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2160       if (FromSize < ToSize ||
2161           (FromSize == ToSize &&
2162            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2163         // We found the type that we can promote to. If this is the
2164         // type we wanted, we have a promotion. Otherwise, no
2165         // promotion.
2166         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2167       }
2168     }
2169   }
2170 
2171   // An rvalue for an integral bit-field (9.6) can be converted to an
2172   // rvalue of type int if int can represent all the values of the
2173   // bit-field; otherwise, it can be converted to unsigned int if
2174   // unsigned int can represent all the values of the bit-field. If
2175   // the bit-field is larger yet, no integral promotion applies to
2176   // it. If the bit-field has an enumerated type, it is treated as any
2177   // other value of that type for promotion purposes (C++ 4.5p3).
2178   // FIXME: We should delay checking of bit-fields until we actually perform the
2179   // conversion.
2180   //
2181   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2182   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2183   // bit-fields and those whose underlying type is larger than int) for GCC
2184   // compatibility.
2185   if (From) {
2186     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2187       Optional<llvm::APSInt> BitWidth;
2188       if (FromType->isIntegralType(Context) &&
2189           (BitWidth =
2190                MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2191         llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2192         ToSize = Context.getTypeSize(ToType);
2193 
2194         // Are we promoting to an int from a bitfield that fits in an int?
2195         if (*BitWidth < ToSize ||
2196             (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2197           return To->getKind() == BuiltinType::Int;
2198         }
2199 
2200         // Are we promoting to an unsigned int from an unsigned bitfield
2201         // that fits into an unsigned int?
2202         if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2203           return To->getKind() == BuiltinType::UInt;
2204         }
2205 
2206         return false;
2207       }
2208     }
2209   }
2210 
2211   // An rvalue of type bool can be converted to an rvalue of type int,
2212   // with false becoming zero and true becoming one (C++ 4.5p4).
2213   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2214     return true;
2215   }
2216 
2217   return false;
2218 }
2219 
2220 /// IsFloatingPointPromotion - Determines whether the conversion from
2221 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2222 /// returns true and sets PromotedType to the promoted type.
2223 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2224   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2225     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2226       /// An rvalue of type float can be converted to an rvalue of type
2227       /// double. (C++ 4.6p1).
2228       if (FromBuiltin->getKind() == BuiltinType::Float &&
2229           ToBuiltin->getKind() == BuiltinType::Double)
2230         return true;
2231 
2232       // C99 6.3.1.5p1:
2233       //   When a float is promoted to double or long double, or a
2234       //   double is promoted to long double [...].
2235       if (!getLangOpts().CPlusPlus &&
2236           (FromBuiltin->getKind() == BuiltinType::Float ||
2237            FromBuiltin->getKind() == BuiltinType::Double) &&
2238           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2239            ToBuiltin->getKind() == BuiltinType::Float128 ||
2240            ToBuiltin->getKind() == BuiltinType::Ibm128))
2241         return true;
2242 
2243       // Half can be promoted to float.
2244       if (!getLangOpts().NativeHalfType &&
2245            FromBuiltin->getKind() == BuiltinType::Half &&
2246           ToBuiltin->getKind() == BuiltinType::Float)
2247         return true;
2248     }
2249 
2250   return false;
2251 }
2252 
2253 /// Determine if a conversion is a complex promotion.
2254 ///
2255 /// A complex promotion is defined as a complex -> complex conversion
2256 /// where the conversion between the underlying real types is a
2257 /// floating-point or integral promotion.
2258 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2259   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2260   if (!FromComplex)
2261     return false;
2262 
2263   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2264   if (!ToComplex)
2265     return false;
2266 
2267   return IsFloatingPointPromotion(FromComplex->getElementType(),
2268                                   ToComplex->getElementType()) ||
2269     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2270                         ToComplex->getElementType());
2271 }
2272 
2273 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2274 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2275 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2276 /// if non-empty, will be a pointer to ToType that may or may not have
2277 /// the right set of qualifiers on its pointee.
2278 ///
2279 static QualType
2280 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2281                                    QualType ToPointee, QualType ToType,
2282                                    ASTContext &Context,
2283                                    bool StripObjCLifetime = false) {
2284   assert((FromPtr->getTypeClass() == Type::Pointer ||
2285           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2286          "Invalid similarly-qualified pointer type");
2287 
2288   /// Conversions to 'id' subsume cv-qualifier conversions.
2289   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2290     return ToType.getUnqualifiedType();
2291 
2292   QualType CanonFromPointee
2293     = Context.getCanonicalType(FromPtr->getPointeeType());
2294   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2295   Qualifiers Quals = CanonFromPointee.getQualifiers();
2296 
2297   if (StripObjCLifetime)
2298     Quals.removeObjCLifetime();
2299 
2300   // Exact qualifier match -> return the pointer type we're converting to.
2301   if (CanonToPointee.getLocalQualifiers() == Quals) {
2302     // ToType is exactly what we need. Return it.
2303     if (!ToType.isNull())
2304       return ToType.getUnqualifiedType();
2305 
2306     // Build a pointer to ToPointee. It has the right qualifiers
2307     // already.
2308     if (isa<ObjCObjectPointerType>(ToType))
2309       return Context.getObjCObjectPointerType(ToPointee);
2310     return Context.getPointerType(ToPointee);
2311   }
2312 
2313   // Just build a canonical type that has the right qualifiers.
2314   QualType QualifiedCanonToPointee
2315     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2316 
2317   if (isa<ObjCObjectPointerType>(ToType))
2318     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2319   return Context.getPointerType(QualifiedCanonToPointee);
2320 }
2321 
2322 static bool isNullPointerConstantForConversion(Expr *Expr,
2323                                                bool InOverloadResolution,
2324                                                ASTContext &Context) {
2325   // Handle value-dependent integral null pointer constants correctly.
2326   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2327   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2328       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2329     return !InOverloadResolution;
2330 
2331   return Expr->isNullPointerConstant(Context,
2332                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2333                                         : Expr::NPC_ValueDependentIsNull);
2334 }
2335 
2336 /// IsPointerConversion - Determines whether the conversion of the
2337 /// expression From, which has the (possibly adjusted) type FromType,
2338 /// can be converted to the type ToType via a pointer conversion (C++
2339 /// 4.10). If so, returns true and places the converted type (that
2340 /// might differ from ToType in its cv-qualifiers at some level) into
2341 /// ConvertedType.
2342 ///
2343 /// This routine also supports conversions to and from block pointers
2344 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2345 /// pointers to interfaces. FIXME: Once we've determined the
2346 /// appropriate overloading rules for Objective-C, we may want to
2347 /// split the Objective-C checks into a different routine; however,
2348 /// GCC seems to consider all of these conversions to be pointer
2349 /// conversions, so for now they live here. IncompatibleObjC will be
2350 /// set if the conversion is an allowed Objective-C conversion that
2351 /// should result in a warning.
2352 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2353                                bool InOverloadResolution,
2354                                QualType& ConvertedType,
2355                                bool &IncompatibleObjC) {
2356   IncompatibleObjC = false;
2357   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2358                               IncompatibleObjC))
2359     return true;
2360 
2361   // Conversion from a null pointer constant to any Objective-C pointer type.
2362   if (ToType->isObjCObjectPointerType() &&
2363       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2364     ConvertedType = ToType;
2365     return true;
2366   }
2367 
2368   // Blocks: Block pointers can be converted to void*.
2369   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2370       ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2371     ConvertedType = ToType;
2372     return true;
2373   }
2374   // Blocks: A null pointer constant can be converted to a block
2375   // pointer type.
2376   if (ToType->isBlockPointerType() &&
2377       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2378     ConvertedType = ToType;
2379     return true;
2380   }
2381 
2382   // If the left-hand-side is nullptr_t, the right side can be a null
2383   // pointer constant.
2384   if (ToType->isNullPtrType() &&
2385       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2386     ConvertedType = ToType;
2387     return true;
2388   }
2389 
2390   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2391   if (!ToTypePtr)
2392     return false;
2393 
2394   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2395   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2396     ConvertedType = ToType;
2397     return true;
2398   }
2399 
2400   // Beyond this point, both types need to be pointers
2401   // , including objective-c pointers.
2402   QualType ToPointeeType = ToTypePtr->getPointeeType();
2403   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2404       !getLangOpts().ObjCAutoRefCount) {
2405     ConvertedType = BuildSimilarlyQualifiedPointerType(
2406         FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2407         Context);
2408     return true;
2409   }
2410   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2411   if (!FromTypePtr)
2412     return false;
2413 
2414   QualType FromPointeeType = FromTypePtr->getPointeeType();
2415 
2416   // If the unqualified pointee types are the same, this can't be a
2417   // pointer conversion, so don't do all of the work below.
2418   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2419     return false;
2420 
2421   // An rvalue of type "pointer to cv T," where T is an object type,
2422   // can be converted to an rvalue of type "pointer to cv void" (C++
2423   // 4.10p2).
2424   if (FromPointeeType->isIncompleteOrObjectType() &&
2425       ToPointeeType->isVoidType()) {
2426     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2427                                                        ToPointeeType,
2428                                                        ToType, Context,
2429                                                    /*StripObjCLifetime=*/true);
2430     return true;
2431   }
2432 
2433   // MSVC allows implicit function to void* type conversion.
2434   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2435       ToPointeeType->isVoidType()) {
2436     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2437                                                        ToPointeeType,
2438                                                        ToType, Context);
2439     return true;
2440   }
2441 
2442   // When we're overloading in C, we allow a special kind of pointer
2443   // conversion for compatible-but-not-identical pointee types.
2444   if (!getLangOpts().CPlusPlus &&
2445       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2446     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2447                                                        ToPointeeType,
2448                                                        ToType, Context);
2449     return true;
2450   }
2451 
2452   // C++ [conv.ptr]p3:
2453   //
2454   //   An rvalue of type "pointer to cv D," where D is a class type,
2455   //   can be converted to an rvalue of type "pointer to cv B," where
2456   //   B is a base class (clause 10) of D. If B is an inaccessible
2457   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2458   //   necessitates this conversion is ill-formed. The result of the
2459   //   conversion is a pointer to the base class sub-object of the
2460   //   derived class object. The null pointer value is converted to
2461   //   the null pointer value of the destination type.
2462   //
2463   // Note that we do not check for ambiguity or inaccessibility
2464   // here. That is handled by CheckPointerConversion.
2465   if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2466       ToPointeeType->isRecordType() &&
2467       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2468       IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2469     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2470                                                        ToPointeeType,
2471                                                        ToType, Context);
2472     return true;
2473   }
2474 
2475   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2476       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2477     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2478                                                        ToPointeeType,
2479                                                        ToType, Context);
2480     return true;
2481   }
2482 
2483   return false;
2484 }
2485 
2486 /// Adopt the given qualifiers for the given type.
2487 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2488   Qualifiers TQs = T.getQualifiers();
2489 
2490   // Check whether qualifiers already match.
2491   if (TQs == Qs)
2492     return T;
2493 
2494   if (Qs.compatiblyIncludes(TQs))
2495     return Context.getQualifiedType(T, Qs);
2496 
2497   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2498 }
2499 
2500 /// isObjCPointerConversion - Determines whether this is an
2501 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2502 /// with the same arguments and return values.
2503 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2504                                    QualType& ConvertedType,
2505                                    bool &IncompatibleObjC) {
2506   if (!getLangOpts().ObjC)
2507     return false;
2508 
2509   // The set of qualifiers on the type we're converting from.
2510   Qualifiers FromQualifiers = FromType.getQualifiers();
2511 
2512   // First, we handle all conversions on ObjC object pointer types.
2513   const ObjCObjectPointerType* ToObjCPtr =
2514     ToType->getAs<ObjCObjectPointerType>();
2515   const ObjCObjectPointerType *FromObjCPtr =
2516     FromType->getAs<ObjCObjectPointerType>();
2517 
2518   if (ToObjCPtr && FromObjCPtr) {
2519     // If the pointee types are the same (ignoring qualifications),
2520     // then this is not a pointer conversion.
2521     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2522                                        FromObjCPtr->getPointeeType()))
2523       return false;
2524 
2525     // Conversion between Objective-C pointers.
2526     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2527       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2528       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2529       if (getLangOpts().CPlusPlus && LHS && RHS &&
2530           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2531                                                 FromObjCPtr->getPointeeType()))
2532         return false;
2533       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2534                                                    ToObjCPtr->getPointeeType(),
2535                                                          ToType, Context);
2536       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2537       return true;
2538     }
2539 
2540     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2541       // Okay: this is some kind of implicit downcast of Objective-C
2542       // interfaces, which is permitted. However, we're going to
2543       // complain about it.
2544       IncompatibleObjC = true;
2545       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2546                                                    ToObjCPtr->getPointeeType(),
2547                                                          ToType, Context);
2548       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2549       return true;
2550     }
2551   }
2552   // Beyond this point, both types need to be C pointers or block pointers.
2553   QualType ToPointeeType;
2554   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2555     ToPointeeType = ToCPtr->getPointeeType();
2556   else if (const BlockPointerType *ToBlockPtr =
2557             ToType->getAs<BlockPointerType>()) {
2558     // Objective C++: We're able to convert from a pointer to any object
2559     // to a block pointer type.
2560     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2561       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2562       return true;
2563     }
2564     ToPointeeType = ToBlockPtr->getPointeeType();
2565   }
2566   else if (FromType->getAs<BlockPointerType>() &&
2567            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2568     // Objective C++: We're able to convert from a block pointer type to a
2569     // pointer to any object.
2570     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2571     return true;
2572   }
2573   else
2574     return false;
2575 
2576   QualType FromPointeeType;
2577   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2578     FromPointeeType = FromCPtr->getPointeeType();
2579   else if (const BlockPointerType *FromBlockPtr =
2580            FromType->getAs<BlockPointerType>())
2581     FromPointeeType = FromBlockPtr->getPointeeType();
2582   else
2583     return false;
2584 
2585   // If we have pointers to pointers, recursively check whether this
2586   // is an Objective-C conversion.
2587   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2588       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2589                               IncompatibleObjC)) {
2590     // We always complain about this conversion.
2591     IncompatibleObjC = true;
2592     ConvertedType = Context.getPointerType(ConvertedType);
2593     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2594     return true;
2595   }
2596   // Allow conversion of pointee being objective-c pointer to another one;
2597   // as in I* to id.
2598   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2599       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2600       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2601                               IncompatibleObjC)) {
2602 
2603     ConvertedType = Context.getPointerType(ConvertedType);
2604     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2605     return true;
2606   }
2607 
2608   // If we have pointers to functions or blocks, check whether the only
2609   // differences in the argument and result types are in Objective-C
2610   // pointer conversions. If so, we permit the conversion (but
2611   // complain about it).
2612   const FunctionProtoType *FromFunctionType
2613     = FromPointeeType->getAs<FunctionProtoType>();
2614   const FunctionProtoType *ToFunctionType
2615     = ToPointeeType->getAs<FunctionProtoType>();
2616   if (FromFunctionType && ToFunctionType) {
2617     // If the function types are exactly the same, this isn't an
2618     // Objective-C pointer conversion.
2619     if (Context.getCanonicalType(FromPointeeType)
2620           == Context.getCanonicalType(ToPointeeType))
2621       return false;
2622 
2623     // Perform the quick checks that will tell us whether these
2624     // function types are obviously different.
2625     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2626         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2627         FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2628       return false;
2629 
2630     bool HasObjCConversion = false;
2631     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2632         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2633       // Okay, the types match exactly. Nothing to do.
2634     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2635                                        ToFunctionType->getReturnType(),
2636                                        ConvertedType, IncompatibleObjC)) {
2637       // Okay, we have an Objective-C pointer conversion.
2638       HasObjCConversion = true;
2639     } else {
2640       // Function types are too different. Abort.
2641       return false;
2642     }
2643 
2644     // Check argument types.
2645     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2646          ArgIdx != NumArgs; ++ArgIdx) {
2647       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2648       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2649       if (Context.getCanonicalType(FromArgType)
2650             == Context.getCanonicalType(ToArgType)) {
2651         // Okay, the types match exactly. Nothing to do.
2652       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2653                                          ConvertedType, IncompatibleObjC)) {
2654         // Okay, we have an Objective-C pointer conversion.
2655         HasObjCConversion = true;
2656       } else {
2657         // Argument types are too different. Abort.
2658         return false;
2659       }
2660     }
2661 
2662     if (HasObjCConversion) {
2663       // We had an Objective-C conversion. Allow this pointer
2664       // conversion, but complain about it.
2665       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2666       IncompatibleObjC = true;
2667       return true;
2668     }
2669   }
2670 
2671   return false;
2672 }
2673 
2674 /// Determine whether this is an Objective-C writeback conversion,
2675 /// used for parameter passing when performing automatic reference counting.
2676 ///
2677 /// \param FromType The type we're converting form.
2678 ///
2679 /// \param ToType The type we're converting to.
2680 ///
2681 /// \param ConvertedType The type that will be produced after applying
2682 /// this conversion.
2683 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2684                                      QualType &ConvertedType) {
2685   if (!getLangOpts().ObjCAutoRefCount ||
2686       Context.hasSameUnqualifiedType(FromType, ToType))
2687     return false;
2688 
2689   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2690   QualType ToPointee;
2691   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2692     ToPointee = ToPointer->getPointeeType();
2693   else
2694     return false;
2695 
2696   Qualifiers ToQuals = ToPointee.getQualifiers();
2697   if (!ToPointee->isObjCLifetimeType() ||
2698       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2699       !ToQuals.withoutObjCLifetime().empty())
2700     return false;
2701 
2702   // Argument must be a pointer to __strong to __weak.
2703   QualType FromPointee;
2704   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2705     FromPointee = FromPointer->getPointeeType();
2706   else
2707     return false;
2708 
2709   Qualifiers FromQuals = FromPointee.getQualifiers();
2710   if (!FromPointee->isObjCLifetimeType() ||
2711       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2712        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2713     return false;
2714 
2715   // Make sure that we have compatible qualifiers.
2716   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2717   if (!ToQuals.compatiblyIncludes(FromQuals))
2718     return false;
2719 
2720   // Remove qualifiers from the pointee type we're converting from; they
2721   // aren't used in the compatibility check belong, and we'll be adding back
2722   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2723   FromPointee = FromPointee.getUnqualifiedType();
2724 
2725   // The unqualified form of the pointee types must be compatible.
2726   ToPointee = ToPointee.getUnqualifiedType();
2727   bool IncompatibleObjC;
2728   if (Context.typesAreCompatible(FromPointee, ToPointee))
2729     FromPointee = ToPointee;
2730   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2731                                     IncompatibleObjC))
2732     return false;
2733 
2734   /// Construct the type we're converting to, which is a pointer to
2735   /// __autoreleasing pointee.
2736   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2737   ConvertedType = Context.getPointerType(FromPointee);
2738   return true;
2739 }
2740 
2741 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2742                                     QualType& ConvertedType) {
2743   QualType ToPointeeType;
2744   if (const BlockPointerType *ToBlockPtr =
2745         ToType->getAs<BlockPointerType>())
2746     ToPointeeType = ToBlockPtr->getPointeeType();
2747   else
2748     return false;
2749 
2750   QualType FromPointeeType;
2751   if (const BlockPointerType *FromBlockPtr =
2752       FromType->getAs<BlockPointerType>())
2753     FromPointeeType = FromBlockPtr->getPointeeType();
2754   else
2755     return false;
2756   // We have pointer to blocks, check whether the only
2757   // differences in the argument and result types are in Objective-C
2758   // pointer conversions. If so, we permit the conversion.
2759 
2760   const FunctionProtoType *FromFunctionType
2761     = FromPointeeType->getAs<FunctionProtoType>();
2762   const FunctionProtoType *ToFunctionType
2763     = ToPointeeType->getAs<FunctionProtoType>();
2764 
2765   if (!FromFunctionType || !ToFunctionType)
2766     return false;
2767 
2768   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2769     return true;
2770 
2771   // Perform the quick checks that will tell us whether these
2772   // function types are obviously different.
2773   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2774       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2775     return false;
2776 
2777   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2778   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2779   if (FromEInfo != ToEInfo)
2780     return false;
2781 
2782   bool IncompatibleObjC = false;
2783   if (Context.hasSameType(FromFunctionType->getReturnType(),
2784                           ToFunctionType->getReturnType())) {
2785     // Okay, the types match exactly. Nothing to do.
2786   } else {
2787     QualType RHS = FromFunctionType->getReturnType();
2788     QualType LHS = ToFunctionType->getReturnType();
2789     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2790         !RHS.hasQualifiers() && LHS.hasQualifiers())
2791        LHS = LHS.getUnqualifiedType();
2792 
2793      if (Context.hasSameType(RHS,LHS)) {
2794        // OK exact match.
2795      } else if (isObjCPointerConversion(RHS, LHS,
2796                                         ConvertedType, IncompatibleObjC)) {
2797      if (IncompatibleObjC)
2798        return false;
2799      // Okay, we have an Objective-C pointer conversion.
2800      }
2801      else
2802        return false;
2803    }
2804 
2805    // Check argument types.
2806    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2807         ArgIdx != NumArgs; ++ArgIdx) {
2808      IncompatibleObjC = false;
2809      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2810      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2811      if (Context.hasSameType(FromArgType, ToArgType)) {
2812        // Okay, the types match exactly. Nothing to do.
2813      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2814                                         ConvertedType, IncompatibleObjC)) {
2815        if (IncompatibleObjC)
2816          return false;
2817        // Okay, we have an Objective-C pointer conversion.
2818      } else
2819        // Argument types are too different. Abort.
2820        return false;
2821    }
2822 
2823    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2824    bool CanUseToFPT, CanUseFromFPT;
2825    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2826                                       CanUseToFPT, CanUseFromFPT,
2827                                       NewParamInfos))
2828      return false;
2829 
2830    ConvertedType = ToType;
2831    return true;
2832 }
2833 
2834 enum {
2835   ft_default,
2836   ft_different_class,
2837   ft_parameter_arity,
2838   ft_parameter_mismatch,
2839   ft_return_type,
2840   ft_qualifer_mismatch,
2841   ft_noexcept
2842 };
2843 
2844 /// Attempts to get the FunctionProtoType from a Type. Handles
2845 /// MemberFunctionPointers properly.
2846 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2847   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2848     return FPT;
2849 
2850   if (auto *MPT = FromType->getAs<MemberPointerType>())
2851     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2852 
2853   return nullptr;
2854 }
2855 
2856 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2857 /// function types.  Catches different number of parameter, mismatch in
2858 /// parameter types, and different return types.
2859 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2860                                       QualType FromType, QualType ToType) {
2861   // If either type is not valid, include no extra info.
2862   if (FromType.isNull() || ToType.isNull()) {
2863     PDiag << ft_default;
2864     return;
2865   }
2866 
2867   // Get the function type from the pointers.
2868   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2869     const auto *FromMember = FromType->castAs<MemberPointerType>(),
2870                *ToMember = ToType->castAs<MemberPointerType>();
2871     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2872       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2873             << QualType(FromMember->getClass(), 0);
2874       return;
2875     }
2876     FromType = FromMember->getPointeeType();
2877     ToType = ToMember->getPointeeType();
2878   }
2879 
2880   if (FromType->isPointerType())
2881     FromType = FromType->getPointeeType();
2882   if (ToType->isPointerType())
2883     ToType = ToType->getPointeeType();
2884 
2885   // Remove references.
2886   FromType = FromType.getNonReferenceType();
2887   ToType = ToType.getNonReferenceType();
2888 
2889   // Don't print extra info for non-specialized template functions.
2890   if (FromType->isInstantiationDependentType() &&
2891       !FromType->getAs<TemplateSpecializationType>()) {
2892     PDiag << ft_default;
2893     return;
2894   }
2895 
2896   // No extra info for same types.
2897   if (Context.hasSameType(FromType, ToType)) {
2898     PDiag << ft_default;
2899     return;
2900   }
2901 
2902   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2903                           *ToFunction = tryGetFunctionProtoType(ToType);
2904 
2905   // Both types need to be function types.
2906   if (!FromFunction || !ToFunction) {
2907     PDiag << ft_default;
2908     return;
2909   }
2910 
2911   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2912     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2913           << FromFunction->getNumParams();
2914     return;
2915   }
2916 
2917   // Handle different parameter types.
2918   unsigned ArgPos;
2919   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2920     PDiag << ft_parameter_mismatch << ArgPos + 1
2921           << ToFunction->getParamType(ArgPos)
2922           << FromFunction->getParamType(ArgPos);
2923     return;
2924   }
2925 
2926   // Handle different return type.
2927   if (!Context.hasSameType(FromFunction->getReturnType(),
2928                            ToFunction->getReturnType())) {
2929     PDiag << ft_return_type << ToFunction->getReturnType()
2930           << FromFunction->getReturnType();
2931     return;
2932   }
2933 
2934   if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2935     PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2936           << FromFunction->getMethodQuals();
2937     return;
2938   }
2939 
2940   // Handle exception specification differences on canonical type (in C++17
2941   // onwards).
2942   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2943           ->isNothrow() !=
2944       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2945           ->isNothrow()) {
2946     PDiag << ft_noexcept;
2947     return;
2948   }
2949 
2950   // Unable to find a difference, so add no extra info.
2951   PDiag << ft_default;
2952 }
2953 
2954 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2955 /// for equality of their argument types. Caller has already checked that
2956 /// they have same number of arguments.  If the parameters are different,
2957 /// ArgPos will have the parameter index of the first different parameter.
2958 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2959                                       const FunctionProtoType *NewType,
2960                                       unsigned *ArgPos) {
2961   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2962                                               N = NewType->param_type_begin(),
2963                                               E = OldType->param_type_end();
2964        O && (O != E); ++O, ++N) {
2965     // Ignore address spaces in pointee type. This is to disallow overloading
2966     // on __ptr32/__ptr64 address spaces.
2967     QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType());
2968     QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType());
2969 
2970     if (!Context.hasSameType(Old, New)) {
2971       if (ArgPos)
2972         *ArgPos = O - OldType->param_type_begin();
2973       return false;
2974     }
2975   }
2976   return true;
2977 }
2978 
2979 /// CheckPointerConversion - Check the pointer conversion from the
2980 /// expression From to the type ToType. This routine checks for
2981 /// ambiguous or inaccessible derived-to-base pointer
2982 /// conversions for which IsPointerConversion has already returned
2983 /// true. It returns true and produces a diagnostic if there was an
2984 /// error, or returns false otherwise.
2985 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2986                                   CastKind &Kind,
2987                                   CXXCastPath& BasePath,
2988                                   bool IgnoreBaseAccess,
2989                                   bool Diagnose) {
2990   QualType FromType = From->getType();
2991   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2992 
2993   Kind = CK_BitCast;
2994 
2995   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2996       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2997           Expr::NPCK_ZeroExpression) {
2998     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2999       DiagRuntimeBehavior(From->getExprLoc(), From,
3000                           PDiag(diag::warn_impcast_bool_to_null_pointer)
3001                             << ToType << From->getSourceRange());
3002     else if (!isUnevaluatedContext())
3003       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3004         << ToType << From->getSourceRange();
3005   }
3006   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3007     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3008       QualType FromPointeeType = FromPtrType->getPointeeType(),
3009                ToPointeeType   = ToPtrType->getPointeeType();
3010 
3011       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3012           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3013         // We must have a derived-to-base conversion. Check an
3014         // ambiguous or inaccessible conversion.
3015         unsigned InaccessibleID = 0;
3016         unsigned AmbiguousID = 0;
3017         if (Diagnose) {
3018           InaccessibleID = diag::err_upcast_to_inaccessible_base;
3019           AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3020         }
3021         if (CheckDerivedToBaseConversion(
3022                 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3023                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3024                 &BasePath, IgnoreBaseAccess))
3025           return true;
3026 
3027         // The conversion was successful.
3028         Kind = CK_DerivedToBase;
3029       }
3030 
3031       if (Diagnose && !IsCStyleOrFunctionalCast &&
3032           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3033         assert(getLangOpts().MSVCCompat &&
3034                "this should only be possible with MSVCCompat!");
3035         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3036             << From->getSourceRange();
3037       }
3038     }
3039   } else if (const ObjCObjectPointerType *ToPtrType =
3040                ToType->getAs<ObjCObjectPointerType>()) {
3041     if (const ObjCObjectPointerType *FromPtrType =
3042           FromType->getAs<ObjCObjectPointerType>()) {
3043       // Objective-C++ conversions are always okay.
3044       // FIXME: We should have a different class of conversions for the
3045       // Objective-C++ implicit conversions.
3046       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3047         return false;
3048     } else if (FromType->isBlockPointerType()) {
3049       Kind = CK_BlockPointerToObjCPointerCast;
3050     } else {
3051       Kind = CK_CPointerToObjCPointerCast;
3052     }
3053   } else if (ToType->isBlockPointerType()) {
3054     if (!FromType->isBlockPointerType())
3055       Kind = CK_AnyPointerToBlockPointerCast;
3056   }
3057 
3058   // We shouldn't fall into this case unless it's valid for other
3059   // reasons.
3060   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3061     Kind = CK_NullToPointer;
3062 
3063   return false;
3064 }
3065 
3066 /// IsMemberPointerConversion - Determines whether the conversion of the
3067 /// expression From, which has the (possibly adjusted) type FromType, can be
3068 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
3069 /// If so, returns true and places the converted type (that might differ from
3070 /// ToType in its cv-qualifiers at some level) into ConvertedType.
3071 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3072                                      QualType ToType,
3073                                      bool InOverloadResolution,
3074                                      QualType &ConvertedType) {
3075   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3076   if (!ToTypePtr)
3077     return false;
3078 
3079   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3080   if (From->isNullPointerConstant(Context,
3081                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3082                                         : Expr::NPC_ValueDependentIsNull)) {
3083     ConvertedType = ToType;
3084     return true;
3085   }
3086 
3087   // Otherwise, both types have to be member pointers.
3088   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3089   if (!FromTypePtr)
3090     return false;
3091 
3092   // A pointer to member of B can be converted to a pointer to member of D,
3093   // where D is derived from B (C++ 4.11p2).
3094   QualType FromClass(FromTypePtr->getClass(), 0);
3095   QualType ToClass(ToTypePtr->getClass(), 0);
3096 
3097   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3098       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3099     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3100                                                  ToClass.getTypePtr());
3101     return true;
3102   }
3103 
3104   return false;
3105 }
3106 
3107 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3108 /// expression From to the type ToType. This routine checks for ambiguous or
3109 /// virtual or inaccessible base-to-derived member pointer conversions
3110 /// for which IsMemberPointerConversion has already returned true. It returns
3111 /// true and produces a diagnostic if there was an error, or returns false
3112 /// otherwise.
3113 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3114                                         CastKind &Kind,
3115                                         CXXCastPath &BasePath,
3116                                         bool IgnoreBaseAccess) {
3117   QualType FromType = From->getType();
3118   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3119   if (!FromPtrType) {
3120     // This must be a null pointer to member pointer conversion
3121     assert(From->isNullPointerConstant(Context,
3122                                        Expr::NPC_ValueDependentIsNull) &&
3123            "Expr must be null pointer constant!");
3124     Kind = CK_NullToMemberPointer;
3125     return false;
3126   }
3127 
3128   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3129   assert(ToPtrType && "No member pointer cast has a target type "
3130                       "that is not a member pointer.");
3131 
3132   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3133   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3134 
3135   // FIXME: What about dependent types?
3136   assert(FromClass->isRecordType() && "Pointer into non-class.");
3137   assert(ToClass->isRecordType() && "Pointer into non-class.");
3138 
3139   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3140                      /*DetectVirtual=*/true);
3141   bool DerivationOkay =
3142       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3143   assert(DerivationOkay &&
3144          "Should not have been called if derivation isn't OK.");
3145   (void)DerivationOkay;
3146 
3147   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3148                                   getUnqualifiedType())) {
3149     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3150     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3151       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3152     return true;
3153   }
3154 
3155   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3156     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3157       << FromClass << ToClass << QualType(VBase, 0)
3158       << From->getSourceRange();
3159     return true;
3160   }
3161 
3162   if (!IgnoreBaseAccess)
3163     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3164                          Paths.front(),
3165                          diag::err_downcast_from_inaccessible_base);
3166 
3167   // Must be a base to derived member conversion.
3168   BuildBasePathArray(Paths, BasePath);
3169   Kind = CK_BaseToDerivedMemberPointer;
3170   return false;
3171 }
3172 
3173 /// Determine whether the lifetime conversion between the two given
3174 /// qualifiers sets is nontrivial.
3175 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3176                                                Qualifiers ToQuals) {
3177   // Converting anything to const __unsafe_unretained is trivial.
3178   if (ToQuals.hasConst() &&
3179       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3180     return false;
3181 
3182   return true;
3183 }
3184 
3185 /// Perform a single iteration of the loop for checking if a qualification
3186 /// conversion is valid.
3187 ///
3188 /// Specifically, check whether any change between the qualifiers of \p
3189 /// FromType and \p ToType is permissible, given knowledge about whether every
3190 /// outer layer is const-qualified.
3191 static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3192                                           bool CStyle, bool IsTopLevel,
3193                                           bool &PreviousToQualsIncludeConst,
3194                                           bool &ObjCLifetimeConversion) {
3195   Qualifiers FromQuals = FromType.getQualifiers();
3196   Qualifiers ToQuals = ToType.getQualifiers();
3197 
3198   // Ignore __unaligned qualifier if this type is void.
3199   if (ToType.getUnqualifiedType()->isVoidType())
3200     FromQuals.removeUnaligned();
3201 
3202   // Objective-C ARC:
3203   //   Check Objective-C lifetime conversions.
3204   if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3205     if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3206       if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3207         ObjCLifetimeConversion = true;
3208       FromQuals.removeObjCLifetime();
3209       ToQuals.removeObjCLifetime();
3210     } else {
3211       // Qualification conversions cannot cast between different
3212       // Objective-C lifetime qualifiers.
3213       return false;
3214     }
3215   }
3216 
3217   // Allow addition/removal of GC attributes but not changing GC attributes.
3218   if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3219       (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3220     FromQuals.removeObjCGCAttr();
3221     ToQuals.removeObjCGCAttr();
3222   }
3223 
3224   //   -- for every j > 0, if const is in cv 1,j then const is in cv
3225   //      2,j, and similarly for volatile.
3226   if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3227     return false;
3228 
3229   // If address spaces mismatch:
3230   //  - in top level it is only valid to convert to addr space that is a
3231   //    superset in all cases apart from C-style casts where we allow
3232   //    conversions between overlapping address spaces.
3233   //  - in non-top levels it is not a valid conversion.
3234   if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3235       (!IsTopLevel ||
3236        !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3237          (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3238     return false;
3239 
3240   //   -- if the cv 1,j and cv 2,j are different, then const is in
3241   //      every cv for 0 < k < j.
3242   if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3243       !PreviousToQualsIncludeConst)
3244     return false;
3245 
3246   // The following wording is from C++20, where the result of the conversion
3247   // is T3, not T2.
3248   //   -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3249   //      "array of unknown bound of"
3250   if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3251     return false;
3252 
3253   //   -- if the resulting P3,i is different from P1,i [...], then const is
3254   //      added to every cv 3_k for 0 < k < i.
3255   if (!CStyle && FromType->isConstantArrayType() &&
3256       ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3257     return false;
3258 
3259   // Keep track of whether all prior cv-qualifiers in the "to" type
3260   // include const.
3261   PreviousToQualsIncludeConst =
3262       PreviousToQualsIncludeConst && ToQuals.hasConst();
3263   return true;
3264 }
3265 
3266 /// IsQualificationConversion - Determines whether the conversion from
3267 /// an rvalue of type FromType to ToType is a qualification conversion
3268 /// (C++ 4.4).
3269 ///
3270 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3271 /// when the qualification conversion involves a change in the Objective-C
3272 /// object lifetime.
3273 bool
3274 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3275                                 bool CStyle, bool &ObjCLifetimeConversion) {
3276   FromType = Context.getCanonicalType(FromType);
3277   ToType = Context.getCanonicalType(ToType);
3278   ObjCLifetimeConversion = false;
3279 
3280   // If FromType and ToType are the same type, this is not a
3281   // qualification conversion.
3282   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3283     return false;
3284 
3285   // (C++ 4.4p4):
3286   //   A conversion can add cv-qualifiers at levels other than the first
3287   //   in multi-level pointers, subject to the following rules: [...]
3288   bool PreviousToQualsIncludeConst = true;
3289   bool UnwrappedAnyPointer = false;
3290   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3291     if (!isQualificationConversionStep(
3292             FromType, ToType, CStyle, !UnwrappedAnyPointer,
3293             PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3294       return false;
3295     UnwrappedAnyPointer = true;
3296   }
3297 
3298   // We are left with FromType and ToType being the pointee types
3299   // after unwrapping the original FromType and ToType the same number
3300   // of times. If we unwrapped any pointers, and if FromType and
3301   // ToType have the same unqualified type (since we checked
3302   // qualifiers above), then this is a qualification conversion.
3303   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3304 }
3305 
3306 /// - Determine whether this is a conversion from a scalar type to an
3307 /// atomic type.
3308 ///
3309 /// If successful, updates \c SCS's second and third steps in the conversion
3310 /// sequence to finish the conversion.
3311 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3312                                 bool InOverloadResolution,
3313                                 StandardConversionSequence &SCS,
3314                                 bool CStyle) {
3315   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3316   if (!ToAtomic)
3317     return false;
3318 
3319   StandardConversionSequence InnerSCS;
3320   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3321                             InOverloadResolution, InnerSCS,
3322                             CStyle, /*AllowObjCWritebackConversion=*/false))
3323     return false;
3324 
3325   SCS.Second = InnerSCS.Second;
3326   SCS.setToType(1, InnerSCS.getToType(1));
3327   SCS.Third = InnerSCS.Third;
3328   SCS.QualificationIncludesObjCLifetime
3329     = InnerSCS.QualificationIncludesObjCLifetime;
3330   SCS.setToType(2, InnerSCS.getToType(2));
3331   return true;
3332 }
3333 
3334 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3335                                               CXXConstructorDecl *Constructor,
3336                                               QualType Type) {
3337   const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3338   if (CtorType->getNumParams() > 0) {
3339     QualType FirstArg = CtorType->getParamType(0);
3340     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3341       return true;
3342   }
3343   return false;
3344 }
3345 
3346 static OverloadingResult
3347 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3348                                        CXXRecordDecl *To,
3349                                        UserDefinedConversionSequence &User,
3350                                        OverloadCandidateSet &CandidateSet,
3351                                        bool AllowExplicit) {
3352   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3353   for (auto *D : S.LookupConstructors(To)) {
3354     auto Info = getConstructorInfo(D);
3355     if (!Info)
3356       continue;
3357 
3358     bool Usable = !Info.Constructor->isInvalidDecl() &&
3359                   S.isInitListConstructor(Info.Constructor);
3360     if (Usable) {
3361       bool SuppressUserConversions = false;
3362       if (Info.ConstructorTmpl)
3363         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3364                                        /*ExplicitArgs*/ nullptr, From,
3365                                        CandidateSet, SuppressUserConversions,
3366                                        /*PartialOverloading*/ false,
3367                                        AllowExplicit);
3368       else
3369         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3370                                CandidateSet, SuppressUserConversions,
3371                                /*PartialOverloading*/ false, AllowExplicit);
3372     }
3373   }
3374 
3375   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3376 
3377   OverloadCandidateSet::iterator Best;
3378   switch (auto Result =
3379               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3380   case OR_Deleted:
3381   case OR_Success: {
3382     // Record the standard conversion we used and the conversion function.
3383     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3384     QualType ThisType = Constructor->getThisType();
3385     // Initializer lists don't have conversions as such.
3386     User.Before.setAsIdentityConversion();
3387     User.HadMultipleCandidates = HadMultipleCandidates;
3388     User.ConversionFunction = Constructor;
3389     User.FoundConversionFunction = Best->FoundDecl;
3390     User.After.setAsIdentityConversion();
3391     User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3392     User.After.setAllToTypes(ToType);
3393     return Result;
3394   }
3395 
3396   case OR_No_Viable_Function:
3397     return OR_No_Viable_Function;
3398   case OR_Ambiguous:
3399     return OR_Ambiguous;
3400   }
3401 
3402   llvm_unreachable("Invalid OverloadResult!");
3403 }
3404 
3405 /// Determines whether there is a user-defined conversion sequence
3406 /// (C++ [over.ics.user]) that converts expression From to the type
3407 /// ToType. If such a conversion exists, User will contain the
3408 /// user-defined conversion sequence that performs such a conversion
3409 /// and this routine will return true. Otherwise, this routine returns
3410 /// false and User is unspecified.
3411 ///
3412 /// \param AllowExplicit  true if the conversion should consider C++0x
3413 /// "explicit" conversion functions as well as non-explicit conversion
3414 /// functions (C++0x [class.conv.fct]p2).
3415 ///
3416 /// \param AllowObjCConversionOnExplicit true if the conversion should
3417 /// allow an extra Objective-C pointer conversion on uses of explicit
3418 /// constructors. Requires \c AllowExplicit to also be set.
3419 static OverloadingResult
3420 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3421                         UserDefinedConversionSequence &User,
3422                         OverloadCandidateSet &CandidateSet,
3423                         AllowedExplicit AllowExplicit,
3424                         bool AllowObjCConversionOnExplicit) {
3425   assert(AllowExplicit != AllowedExplicit::None ||
3426          !AllowObjCConversionOnExplicit);
3427   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3428 
3429   // Whether we will only visit constructors.
3430   bool ConstructorsOnly = false;
3431 
3432   // If the type we are conversion to is a class type, enumerate its
3433   // constructors.
3434   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3435     // C++ [over.match.ctor]p1:
3436     //   When objects of class type are direct-initialized (8.5), or
3437     //   copy-initialized from an expression of the same or a
3438     //   derived class type (8.5), overload resolution selects the
3439     //   constructor. [...] For copy-initialization, the candidate
3440     //   functions are all the converting constructors (12.3.1) of
3441     //   that class. The argument list is the expression-list within
3442     //   the parentheses of the initializer.
3443     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3444         (From->getType()->getAs<RecordType>() &&
3445          S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3446       ConstructorsOnly = true;
3447 
3448     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3449       // We're not going to find any constructors.
3450     } else if (CXXRecordDecl *ToRecordDecl
3451                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3452 
3453       Expr **Args = &From;
3454       unsigned NumArgs = 1;
3455       bool ListInitializing = false;
3456       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3457         // But first, see if there is an init-list-constructor that will work.
3458         OverloadingResult Result = IsInitializerListConstructorConversion(
3459             S, From, ToType, ToRecordDecl, User, CandidateSet,
3460             AllowExplicit == AllowedExplicit::All);
3461         if (Result != OR_No_Viable_Function)
3462           return Result;
3463         // Never mind.
3464         CandidateSet.clear(
3465             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3466 
3467         // If we're list-initializing, we pass the individual elements as
3468         // arguments, not the entire list.
3469         Args = InitList->getInits();
3470         NumArgs = InitList->getNumInits();
3471         ListInitializing = true;
3472       }
3473 
3474       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3475         auto Info = getConstructorInfo(D);
3476         if (!Info)
3477           continue;
3478 
3479         bool Usable = !Info.Constructor->isInvalidDecl();
3480         if (!ListInitializing)
3481           Usable = Usable && Info.Constructor->isConvertingConstructor(
3482                                  /*AllowExplicit*/ true);
3483         if (Usable) {
3484           bool SuppressUserConversions = !ConstructorsOnly;
3485           // C++20 [over.best.ics.general]/4.5:
3486           //   if the target is the first parameter of a constructor [of class
3487           //   X] and the constructor [...] is a candidate by [...] the second
3488           //   phase of [over.match.list] when the initializer list has exactly
3489           //   one element that is itself an initializer list, [...] and the
3490           //   conversion is to X or reference to cv X, user-defined conversion
3491           //   sequences are not cnosidered.
3492           if (SuppressUserConversions && ListInitializing) {
3493             SuppressUserConversions =
3494                 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
3495                 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3496                                                   ToType);
3497           }
3498           if (Info.ConstructorTmpl)
3499             S.AddTemplateOverloadCandidate(
3500                 Info.ConstructorTmpl, Info.FoundDecl,
3501                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3502                 CandidateSet, SuppressUserConversions,
3503                 /*PartialOverloading*/ false,
3504                 AllowExplicit == AllowedExplicit::All);
3505           else
3506             // Allow one user-defined conversion when user specifies a
3507             // From->ToType conversion via an static cast (c-style, etc).
3508             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3509                                    llvm::makeArrayRef(Args, NumArgs),
3510                                    CandidateSet, SuppressUserConversions,
3511                                    /*PartialOverloading*/ false,
3512                                    AllowExplicit == AllowedExplicit::All);
3513         }
3514       }
3515     }
3516   }
3517 
3518   // Enumerate conversion functions, if we're allowed to.
3519   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3520   } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3521     // No conversion functions from incomplete types.
3522   } else if (const RecordType *FromRecordType =
3523                  From->getType()->getAs<RecordType>()) {
3524     if (CXXRecordDecl *FromRecordDecl
3525          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3526       // Add all of the conversion functions as candidates.
3527       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3528       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3529         DeclAccessPair FoundDecl = I.getPair();
3530         NamedDecl *D = FoundDecl.getDecl();
3531         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3532         if (isa<UsingShadowDecl>(D))
3533           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3534 
3535         CXXConversionDecl *Conv;
3536         FunctionTemplateDecl *ConvTemplate;
3537         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3538           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3539         else
3540           Conv = cast<CXXConversionDecl>(D);
3541 
3542         if (ConvTemplate)
3543           S.AddTemplateConversionCandidate(
3544               ConvTemplate, FoundDecl, ActingContext, From, ToType,
3545               CandidateSet, AllowObjCConversionOnExplicit,
3546               AllowExplicit != AllowedExplicit::None);
3547         else
3548           S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3549                                    CandidateSet, AllowObjCConversionOnExplicit,
3550                                    AllowExplicit != AllowedExplicit::None);
3551       }
3552     }
3553   }
3554 
3555   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3556 
3557   OverloadCandidateSet::iterator Best;
3558   switch (auto Result =
3559               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3560   case OR_Success:
3561   case OR_Deleted:
3562     // Record the standard conversion we used and the conversion function.
3563     if (CXXConstructorDecl *Constructor
3564           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3565       // C++ [over.ics.user]p1:
3566       //   If the user-defined conversion is specified by a
3567       //   constructor (12.3.1), the initial standard conversion
3568       //   sequence converts the source type to the type required by
3569       //   the argument of the constructor.
3570       //
3571       QualType ThisType = Constructor->getThisType();
3572       if (isa<InitListExpr>(From)) {
3573         // Initializer lists don't have conversions as such.
3574         User.Before.setAsIdentityConversion();
3575       } else {
3576         if (Best->Conversions[0].isEllipsis())
3577           User.EllipsisConversion = true;
3578         else {
3579           User.Before = Best->Conversions[0].Standard;
3580           User.EllipsisConversion = false;
3581         }
3582       }
3583       User.HadMultipleCandidates = HadMultipleCandidates;
3584       User.ConversionFunction = Constructor;
3585       User.FoundConversionFunction = Best->FoundDecl;
3586       User.After.setAsIdentityConversion();
3587       User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3588       User.After.setAllToTypes(ToType);
3589       return Result;
3590     }
3591     if (CXXConversionDecl *Conversion
3592                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3593       // C++ [over.ics.user]p1:
3594       //
3595       //   [...] If the user-defined conversion is specified by a
3596       //   conversion function (12.3.2), the initial standard
3597       //   conversion sequence converts the source type to the
3598       //   implicit object parameter of the conversion function.
3599       User.Before = Best->Conversions[0].Standard;
3600       User.HadMultipleCandidates = HadMultipleCandidates;
3601       User.ConversionFunction = Conversion;
3602       User.FoundConversionFunction = Best->FoundDecl;
3603       User.EllipsisConversion = false;
3604 
3605       // C++ [over.ics.user]p2:
3606       //   The second standard conversion sequence converts the
3607       //   result of the user-defined conversion to the target type
3608       //   for the sequence. Since an implicit conversion sequence
3609       //   is an initialization, the special rules for
3610       //   initialization by user-defined conversion apply when
3611       //   selecting the best user-defined conversion for a
3612       //   user-defined conversion sequence (see 13.3.3 and
3613       //   13.3.3.1).
3614       User.After = Best->FinalConversion;
3615       return Result;
3616     }
3617     llvm_unreachable("Not a constructor or conversion function?");
3618 
3619   case OR_No_Viable_Function:
3620     return OR_No_Viable_Function;
3621 
3622   case OR_Ambiguous:
3623     return OR_Ambiguous;
3624   }
3625 
3626   llvm_unreachable("Invalid OverloadResult!");
3627 }
3628 
3629 bool
3630 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3631   ImplicitConversionSequence ICS;
3632   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3633                                     OverloadCandidateSet::CSK_Normal);
3634   OverloadingResult OvResult =
3635     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3636                             CandidateSet, AllowedExplicit::None, false);
3637 
3638   if (!(OvResult == OR_Ambiguous ||
3639         (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3640     return false;
3641 
3642   auto Cands = CandidateSet.CompleteCandidates(
3643       *this,
3644       OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3645       From);
3646   if (OvResult == OR_Ambiguous)
3647     Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3648         << From->getType() << ToType << From->getSourceRange();
3649   else { // OR_No_Viable_Function && !CandidateSet.empty()
3650     if (!RequireCompleteType(From->getBeginLoc(), ToType,
3651                              diag::err_typecheck_nonviable_condition_incomplete,
3652                              From->getType(), From->getSourceRange()))
3653       Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3654           << false << From->getType() << From->getSourceRange() << ToType;
3655   }
3656 
3657   CandidateSet.NoteCandidates(
3658                               *this, From, Cands);
3659   return true;
3660 }
3661 
3662 // Helper for compareConversionFunctions that gets the FunctionType that the
3663 // conversion-operator return  value 'points' to, or nullptr.
3664 static const FunctionType *
3665 getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
3666   const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
3667   const PointerType *RetPtrTy =
3668       ConvFuncTy->getReturnType()->getAs<PointerType>();
3669 
3670   if (!RetPtrTy)
3671     return nullptr;
3672 
3673   return RetPtrTy->getPointeeType()->getAs<FunctionType>();
3674 }
3675 
3676 /// Compare the user-defined conversion functions or constructors
3677 /// of two user-defined conversion sequences to determine whether any ordering
3678 /// is possible.
3679 static ImplicitConversionSequence::CompareKind
3680 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3681                            FunctionDecl *Function2) {
3682   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3683   CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
3684   if (!Conv1 || !Conv2)
3685     return ImplicitConversionSequence::Indistinguishable;
3686 
3687   if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
3688     return ImplicitConversionSequence::Indistinguishable;
3689 
3690   // Objective-C++:
3691   //   If both conversion functions are implicitly-declared conversions from
3692   //   a lambda closure type to a function pointer and a block pointer,
3693   //   respectively, always prefer the conversion to a function pointer,
3694   //   because the function pointer is more lightweight and is more likely
3695   //   to keep code working.
3696   if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
3697     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3698     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3699     if (Block1 != Block2)
3700       return Block1 ? ImplicitConversionSequence::Worse
3701                     : ImplicitConversionSequence::Better;
3702   }
3703 
3704   // In order to support multiple calling conventions for the lambda conversion
3705   // operator (such as when the free and member function calling convention is
3706   // different), prefer the 'free' mechanism, followed by the calling-convention
3707   // of operator(). The latter is in place to support the MSVC-like solution of
3708   // defining ALL of the possible conversions in regards to calling-convention.
3709   const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
3710   const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
3711 
3712   if (Conv1FuncRet && Conv2FuncRet &&
3713       Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
3714     CallingConv Conv1CC = Conv1FuncRet->getCallConv();
3715     CallingConv Conv2CC = Conv2FuncRet->getCallConv();
3716 
3717     CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
3718     const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
3719 
3720     CallingConv CallOpCC =
3721         CallOp->getType()->castAs<FunctionType>()->getCallConv();
3722     CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
3723         CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
3724     CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
3725         CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
3726 
3727     CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
3728     for (CallingConv CC : PrefOrder) {
3729       if (Conv1CC == CC)
3730         return ImplicitConversionSequence::Better;
3731       if (Conv2CC == CC)
3732         return ImplicitConversionSequence::Worse;
3733     }
3734   }
3735 
3736   return ImplicitConversionSequence::Indistinguishable;
3737 }
3738 
3739 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3740     const ImplicitConversionSequence &ICS) {
3741   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3742          (ICS.isUserDefined() &&
3743           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3744 }
3745 
3746 /// CompareImplicitConversionSequences - Compare two implicit
3747 /// conversion sequences to determine whether one is better than the
3748 /// other or if they are indistinguishable (C++ 13.3.3.2).
3749 static ImplicitConversionSequence::CompareKind
3750 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3751                                    const ImplicitConversionSequence& ICS1,
3752                                    const ImplicitConversionSequence& ICS2)
3753 {
3754   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3755   // conversion sequences (as defined in 13.3.3.1)
3756   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3757   //      conversion sequence than a user-defined conversion sequence or
3758   //      an ellipsis conversion sequence, and
3759   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3760   //      conversion sequence than an ellipsis conversion sequence
3761   //      (13.3.3.1.3).
3762   //
3763   // C++0x [over.best.ics]p10:
3764   //   For the purpose of ranking implicit conversion sequences as
3765   //   described in 13.3.3.2, the ambiguous conversion sequence is
3766   //   treated as a user-defined sequence that is indistinguishable
3767   //   from any other user-defined conversion sequence.
3768 
3769   // String literal to 'char *' conversion has been deprecated in C++03. It has
3770   // been removed from C++11. We still accept this conversion, if it happens at
3771   // the best viable function. Otherwise, this conversion is considered worse
3772   // than ellipsis conversion. Consider this as an extension; this is not in the
3773   // standard. For example:
3774   //
3775   // int &f(...);    // #1
3776   // void f(char*);  // #2
3777   // void g() { int &r = f("foo"); }
3778   //
3779   // In C++03, we pick #2 as the best viable function.
3780   // In C++11, we pick #1 as the best viable function, because ellipsis
3781   // conversion is better than string-literal to char* conversion (since there
3782   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3783   // convert arguments, #2 would be the best viable function in C++11.
3784   // If the best viable function has this conversion, a warning will be issued
3785   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3786 
3787   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3788       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3789           hasDeprecatedStringLiteralToCharPtrConversion(ICS2) &&
3790       // Ill-formedness must not differ
3791       ICS1.isBad() == ICS2.isBad())
3792     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3793                ? ImplicitConversionSequence::Worse
3794                : ImplicitConversionSequence::Better;
3795 
3796   if (ICS1.getKindRank() < ICS2.getKindRank())
3797     return ImplicitConversionSequence::Better;
3798   if (ICS2.getKindRank() < ICS1.getKindRank())
3799     return ImplicitConversionSequence::Worse;
3800 
3801   // The following checks require both conversion sequences to be of
3802   // the same kind.
3803   if (ICS1.getKind() != ICS2.getKind())
3804     return ImplicitConversionSequence::Indistinguishable;
3805 
3806   ImplicitConversionSequence::CompareKind Result =
3807       ImplicitConversionSequence::Indistinguishable;
3808 
3809   // Two implicit conversion sequences of the same form are
3810   // indistinguishable conversion sequences unless one of the
3811   // following rules apply: (C++ 13.3.3.2p3):
3812 
3813   // List-initialization sequence L1 is a better conversion sequence than
3814   // list-initialization sequence L2 if:
3815   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3816   //   if not that,
3817   // — L1 and L2 convert to arrays of the same element type, and either the
3818   //   number of elements n_1 initialized by L1 is less than the number of
3819   //   elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
3820   //   an array of unknown bound and L1 does not,
3821   // even if one of the other rules in this paragraph would otherwise apply.
3822   if (!ICS1.isBad()) {
3823     bool StdInit1 = false, StdInit2 = false;
3824     if (ICS1.hasInitializerListContainerType())
3825       StdInit1 = S.isStdInitializerList(ICS1.getInitializerListContainerType(),
3826                                         nullptr);
3827     if (ICS2.hasInitializerListContainerType())
3828       StdInit2 = S.isStdInitializerList(ICS2.getInitializerListContainerType(),
3829                                         nullptr);
3830     if (StdInit1 != StdInit2)
3831       return StdInit1 ? ImplicitConversionSequence::Better
3832                       : ImplicitConversionSequence::Worse;
3833 
3834     if (ICS1.hasInitializerListContainerType() &&
3835         ICS2.hasInitializerListContainerType())
3836       if (auto *CAT1 = S.Context.getAsConstantArrayType(
3837               ICS1.getInitializerListContainerType()))
3838         if (auto *CAT2 = S.Context.getAsConstantArrayType(
3839                 ICS2.getInitializerListContainerType())) {
3840           if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
3841                                                CAT2->getElementType())) {
3842             // Both to arrays of the same element type
3843             if (CAT1->getSize() != CAT2->getSize())
3844               // Different sized, the smaller wins
3845               return CAT1->getSize().ult(CAT2->getSize())
3846                          ? ImplicitConversionSequence::Better
3847                          : ImplicitConversionSequence::Worse;
3848             if (ICS1.isInitializerListOfIncompleteArray() !=
3849                 ICS2.isInitializerListOfIncompleteArray())
3850               // One is incomplete, it loses
3851               return ICS2.isInitializerListOfIncompleteArray()
3852                          ? ImplicitConversionSequence::Better
3853                          : ImplicitConversionSequence::Worse;
3854           }
3855         }
3856   }
3857 
3858   if (ICS1.isStandard())
3859     // Standard conversion sequence S1 is a better conversion sequence than
3860     // standard conversion sequence S2 if [...]
3861     Result = CompareStandardConversionSequences(S, Loc,
3862                                                 ICS1.Standard, ICS2.Standard);
3863   else if (ICS1.isUserDefined()) {
3864     // User-defined conversion sequence U1 is a better conversion
3865     // sequence than another user-defined conversion sequence U2 if
3866     // they contain the same user-defined conversion function or
3867     // constructor and if the second standard conversion sequence of
3868     // U1 is better than the second standard conversion sequence of
3869     // U2 (C++ 13.3.3.2p3).
3870     if (ICS1.UserDefined.ConversionFunction ==
3871           ICS2.UserDefined.ConversionFunction)
3872       Result = CompareStandardConversionSequences(S, Loc,
3873                                                   ICS1.UserDefined.After,
3874                                                   ICS2.UserDefined.After);
3875     else
3876       Result = compareConversionFunctions(S,
3877                                           ICS1.UserDefined.ConversionFunction,
3878                                           ICS2.UserDefined.ConversionFunction);
3879   }
3880 
3881   return Result;
3882 }
3883 
3884 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3885 // determine if one is a proper subset of the other.
3886 static ImplicitConversionSequence::CompareKind
3887 compareStandardConversionSubsets(ASTContext &Context,
3888                                  const StandardConversionSequence& SCS1,
3889                                  const StandardConversionSequence& SCS2) {
3890   ImplicitConversionSequence::CompareKind Result
3891     = ImplicitConversionSequence::Indistinguishable;
3892 
3893   // the identity conversion sequence is considered to be a subsequence of
3894   // any non-identity conversion sequence
3895   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3896     return ImplicitConversionSequence::Better;
3897   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3898     return ImplicitConversionSequence::Worse;
3899 
3900   if (SCS1.Second != SCS2.Second) {
3901     if (SCS1.Second == ICK_Identity)
3902       Result = ImplicitConversionSequence::Better;
3903     else if (SCS2.Second == ICK_Identity)
3904       Result = ImplicitConversionSequence::Worse;
3905     else
3906       return ImplicitConversionSequence::Indistinguishable;
3907   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3908     return ImplicitConversionSequence::Indistinguishable;
3909 
3910   if (SCS1.Third == SCS2.Third) {
3911     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3912                              : ImplicitConversionSequence::Indistinguishable;
3913   }
3914 
3915   if (SCS1.Third == ICK_Identity)
3916     return Result == ImplicitConversionSequence::Worse
3917              ? ImplicitConversionSequence::Indistinguishable
3918              : ImplicitConversionSequence::Better;
3919 
3920   if (SCS2.Third == ICK_Identity)
3921     return Result == ImplicitConversionSequence::Better
3922              ? ImplicitConversionSequence::Indistinguishable
3923              : ImplicitConversionSequence::Worse;
3924 
3925   return ImplicitConversionSequence::Indistinguishable;
3926 }
3927 
3928 /// Determine whether one of the given reference bindings is better
3929 /// than the other based on what kind of bindings they are.
3930 static bool
3931 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3932                              const StandardConversionSequence &SCS2) {
3933   // C++0x [over.ics.rank]p3b4:
3934   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3935   //      implicit object parameter of a non-static member function declared
3936   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3937   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3938   //      lvalue reference to a function lvalue and S2 binds an rvalue
3939   //      reference*.
3940   //
3941   // FIXME: Rvalue references. We're going rogue with the above edits,
3942   // because the semantics in the current C++0x working paper (N3225 at the
3943   // time of this writing) break the standard definition of std::forward
3944   // and std::reference_wrapper when dealing with references to functions.
3945   // Proposed wording changes submitted to CWG for consideration.
3946   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3947       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3948     return false;
3949 
3950   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3951           SCS2.IsLvalueReference) ||
3952          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3953           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3954 }
3955 
3956 enum class FixedEnumPromotion {
3957   None,
3958   ToUnderlyingType,
3959   ToPromotedUnderlyingType
3960 };
3961 
3962 /// Returns kind of fixed enum promotion the \a SCS uses.
3963 static FixedEnumPromotion
3964 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
3965 
3966   if (SCS.Second != ICK_Integral_Promotion)
3967     return FixedEnumPromotion::None;
3968 
3969   QualType FromType = SCS.getFromType();
3970   if (!FromType->isEnumeralType())
3971     return FixedEnumPromotion::None;
3972 
3973   EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
3974   if (!Enum->isFixed())
3975     return FixedEnumPromotion::None;
3976 
3977   QualType UnderlyingType = Enum->getIntegerType();
3978   if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
3979     return FixedEnumPromotion::ToUnderlyingType;
3980 
3981   return FixedEnumPromotion::ToPromotedUnderlyingType;
3982 }
3983 
3984 /// CompareStandardConversionSequences - Compare two standard
3985 /// conversion sequences to determine whether one is better than the
3986 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3987 static ImplicitConversionSequence::CompareKind
3988 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3989                                    const StandardConversionSequence& SCS1,
3990                                    const StandardConversionSequence& SCS2)
3991 {
3992   // Standard conversion sequence S1 is a better conversion sequence
3993   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3994 
3995   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3996   //     sequences in the canonical form defined by 13.3.3.1.1,
3997   //     excluding any Lvalue Transformation; the identity conversion
3998   //     sequence is considered to be a subsequence of any
3999   //     non-identity conversion sequence) or, if not that,
4000   if (ImplicitConversionSequence::CompareKind CK
4001         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
4002     return CK;
4003 
4004   //  -- the rank of S1 is better than the rank of S2 (by the rules
4005   //     defined below), or, if not that,
4006   ImplicitConversionRank Rank1 = SCS1.getRank();
4007   ImplicitConversionRank Rank2 = SCS2.getRank();
4008   if (Rank1 < Rank2)
4009     return ImplicitConversionSequence::Better;
4010   else if (Rank2 < Rank1)
4011     return ImplicitConversionSequence::Worse;
4012 
4013   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4014   // are indistinguishable unless one of the following rules
4015   // applies:
4016 
4017   //   A conversion that is not a conversion of a pointer, or
4018   //   pointer to member, to bool is better than another conversion
4019   //   that is such a conversion.
4020   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4021     return SCS2.isPointerConversionToBool()
4022              ? ImplicitConversionSequence::Better
4023              : ImplicitConversionSequence::Worse;
4024 
4025   // C++14 [over.ics.rank]p4b2:
4026   // This is retroactively applied to C++11 by CWG 1601.
4027   //
4028   //   A conversion that promotes an enumeration whose underlying type is fixed
4029   //   to its underlying type is better than one that promotes to the promoted
4030   //   underlying type, if the two are different.
4031   FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
4032   FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
4033   if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4034       FEP1 != FEP2)
4035     return FEP1 == FixedEnumPromotion::ToUnderlyingType
4036                ? ImplicitConversionSequence::Better
4037                : ImplicitConversionSequence::Worse;
4038 
4039   // C++ [over.ics.rank]p4b2:
4040   //
4041   //   If class B is derived directly or indirectly from class A,
4042   //   conversion of B* to A* is better than conversion of B* to
4043   //   void*, and conversion of A* to void* is better than conversion
4044   //   of B* to void*.
4045   bool SCS1ConvertsToVoid
4046     = SCS1.isPointerConversionToVoidPointer(S.Context);
4047   bool SCS2ConvertsToVoid
4048     = SCS2.isPointerConversionToVoidPointer(S.Context);
4049   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4050     // Exactly one of the conversion sequences is a conversion to
4051     // a void pointer; it's the worse conversion.
4052     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4053                               : ImplicitConversionSequence::Worse;
4054   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4055     // Neither conversion sequence converts to a void pointer; compare
4056     // their derived-to-base conversions.
4057     if (ImplicitConversionSequence::CompareKind DerivedCK
4058           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4059       return DerivedCK;
4060   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4061              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4062     // Both conversion sequences are conversions to void
4063     // pointers. Compare the source types to determine if there's an
4064     // inheritance relationship in their sources.
4065     QualType FromType1 = SCS1.getFromType();
4066     QualType FromType2 = SCS2.getFromType();
4067 
4068     // Adjust the types we're converting from via the array-to-pointer
4069     // conversion, if we need to.
4070     if (SCS1.First == ICK_Array_To_Pointer)
4071       FromType1 = S.Context.getArrayDecayedType(FromType1);
4072     if (SCS2.First == ICK_Array_To_Pointer)
4073       FromType2 = S.Context.getArrayDecayedType(FromType2);
4074 
4075     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4076     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4077 
4078     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4079       return ImplicitConversionSequence::Better;
4080     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4081       return ImplicitConversionSequence::Worse;
4082 
4083     // Objective-C++: If one interface is more specific than the
4084     // other, it is the better one.
4085     const ObjCObjectPointerType* FromObjCPtr1
4086       = FromType1->getAs<ObjCObjectPointerType>();
4087     const ObjCObjectPointerType* FromObjCPtr2
4088       = FromType2->getAs<ObjCObjectPointerType>();
4089     if (FromObjCPtr1 && FromObjCPtr2) {
4090       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4091                                                           FromObjCPtr2);
4092       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4093                                                            FromObjCPtr1);
4094       if (AssignLeft != AssignRight) {
4095         return AssignLeft? ImplicitConversionSequence::Better
4096                          : ImplicitConversionSequence::Worse;
4097       }
4098     }
4099   }
4100 
4101   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4102     // Check for a better reference binding based on the kind of bindings.
4103     if (isBetterReferenceBindingKind(SCS1, SCS2))
4104       return ImplicitConversionSequence::Better;
4105     else if (isBetterReferenceBindingKind(SCS2, SCS1))
4106       return ImplicitConversionSequence::Worse;
4107   }
4108 
4109   // Compare based on qualification conversions (C++ 13.3.3.2p3,
4110   // bullet 3).
4111   if (ImplicitConversionSequence::CompareKind QualCK
4112         = CompareQualificationConversions(S, SCS1, SCS2))
4113     return QualCK;
4114 
4115   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4116     // C++ [over.ics.rank]p3b4:
4117     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
4118     //      which the references refer are the same type except for
4119     //      top-level cv-qualifiers, and the type to which the reference
4120     //      initialized by S2 refers is more cv-qualified than the type
4121     //      to which the reference initialized by S1 refers.
4122     QualType T1 = SCS1.getToType(2);
4123     QualType T2 = SCS2.getToType(2);
4124     T1 = S.Context.getCanonicalType(T1);
4125     T2 = S.Context.getCanonicalType(T2);
4126     Qualifiers T1Quals, T2Quals;
4127     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4128     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4129     if (UnqualT1 == UnqualT2) {
4130       // Objective-C++ ARC: If the references refer to objects with different
4131       // lifetimes, prefer bindings that don't change lifetime.
4132       if (SCS1.ObjCLifetimeConversionBinding !=
4133                                           SCS2.ObjCLifetimeConversionBinding) {
4134         return SCS1.ObjCLifetimeConversionBinding
4135                                            ? ImplicitConversionSequence::Worse
4136                                            : ImplicitConversionSequence::Better;
4137       }
4138 
4139       // If the type is an array type, promote the element qualifiers to the
4140       // type for comparison.
4141       if (isa<ArrayType>(T1) && T1Quals)
4142         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4143       if (isa<ArrayType>(T2) && T2Quals)
4144         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4145       if (T2.isMoreQualifiedThan(T1))
4146         return ImplicitConversionSequence::Better;
4147       if (T1.isMoreQualifiedThan(T2))
4148         return ImplicitConversionSequence::Worse;
4149     }
4150   }
4151 
4152   // In Microsoft mode (below 19.28), prefer an integral conversion to a
4153   // floating-to-integral conversion if the integral conversion
4154   // is between types of the same size.
4155   // For example:
4156   // void f(float);
4157   // void f(int);
4158   // int main {
4159   //    long a;
4160   //    f(a);
4161   // }
4162   // Here, MSVC will call f(int) instead of generating a compile error
4163   // as clang will do in standard mode.
4164   if (S.getLangOpts().MSVCCompat &&
4165       !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) &&
4166       SCS1.Second == ICK_Integral_Conversion &&
4167       SCS2.Second == ICK_Floating_Integral &&
4168       S.Context.getTypeSize(SCS1.getFromType()) ==
4169           S.Context.getTypeSize(SCS1.getToType(2)))
4170     return ImplicitConversionSequence::Better;
4171 
4172   // Prefer a compatible vector conversion over a lax vector conversion
4173   // For example:
4174   //
4175   // typedef float __v4sf __attribute__((__vector_size__(16)));
4176   // void f(vector float);
4177   // void f(vector signed int);
4178   // int main() {
4179   //   __v4sf a;
4180   //   f(a);
4181   // }
4182   // Here, we'd like to choose f(vector float) and not
4183   // report an ambiguous call error
4184   if (SCS1.Second == ICK_Vector_Conversion &&
4185       SCS2.Second == ICK_Vector_Conversion) {
4186     bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4187         SCS1.getFromType(), SCS1.getToType(2));
4188     bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4189         SCS2.getFromType(), SCS2.getToType(2));
4190 
4191     if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4192       return SCS1IsCompatibleVectorConversion
4193                  ? ImplicitConversionSequence::Better
4194                  : ImplicitConversionSequence::Worse;
4195   }
4196 
4197   if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4198       SCS2.Second == ICK_SVE_Vector_Conversion) {
4199     bool SCS1IsCompatibleSVEVectorConversion =
4200         S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4201     bool SCS2IsCompatibleSVEVectorConversion =
4202         S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4203 
4204     if (SCS1IsCompatibleSVEVectorConversion !=
4205         SCS2IsCompatibleSVEVectorConversion)
4206       return SCS1IsCompatibleSVEVectorConversion
4207                  ? ImplicitConversionSequence::Better
4208                  : ImplicitConversionSequence::Worse;
4209   }
4210 
4211   return ImplicitConversionSequence::Indistinguishable;
4212 }
4213 
4214 /// CompareQualificationConversions - Compares two standard conversion
4215 /// sequences to determine whether they can be ranked based on their
4216 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4217 static ImplicitConversionSequence::CompareKind
4218 CompareQualificationConversions(Sema &S,
4219                                 const StandardConversionSequence& SCS1,
4220                                 const StandardConversionSequence& SCS2) {
4221   // C++ [over.ics.rank]p3:
4222   //  -- S1 and S2 differ only in their qualification conversion and
4223   //     yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4224   // [C++98]
4225   //     [...] and the cv-qualification signature of type T1 is a proper subset
4226   //     of the cv-qualification signature of type T2, and S1 is not the
4227   //     deprecated string literal array-to-pointer conversion (4.2).
4228   // [C++2a]
4229   //     [...] where T1 can be converted to T2 by a qualification conversion.
4230   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4231       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4232     return ImplicitConversionSequence::Indistinguishable;
4233 
4234   // FIXME: the example in the standard doesn't use a qualification
4235   // conversion (!)
4236   QualType T1 = SCS1.getToType(2);
4237   QualType T2 = SCS2.getToType(2);
4238   T1 = S.Context.getCanonicalType(T1);
4239   T2 = S.Context.getCanonicalType(T2);
4240   assert(!T1->isReferenceType() && !T2->isReferenceType());
4241   Qualifiers T1Quals, T2Quals;
4242   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4243   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4244 
4245   // If the types are the same, we won't learn anything by unwrapping
4246   // them.
4247   if (UnqualT1 == UnqualT2)
4248     return ImplicitConversionSequence::Indistinguishable;
4249 
4250   // Don't ever prefer a standard conversion sequence that uses the deprecated
4251   // string literal array to pointer conversion.
4252   bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4253   bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4254 
4255   // Objective-C++ ARC:
4256   //   Prefer qualification conversions not involving a change in lifetime
4257   //   to qualification conversions that do change lifetime.
4258   if (SCS1.QualificationIncludesObjCLifetime &&
4259       !SCS2.QualificationIncludesObjCLifetime)
4260     CanPick1 = false;
4261   if (SCS2.QualificationIncludesObjCLifetime &&
4262       !SCS1.QualificationIncludesObjCLifetime)
4263     CanPick2 = false;
4264 
4265   bool ObjCLifetimeConversion;
4266   if (CanPick1 &&
4267       !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4268     CanPick1 = false;
4269   // FIXME: In Objective-C ARC, we can have qualification conversions in both
4270   // directions, so we can't short-cut this second check in general.
4271   if (CanPick2 &&
4272       !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4273     CanPick2 = false;
4274 
4275   if (CanPick1 != CanPick2)
4276     return CanPick1 ? ImplicitConversionSequence::Better
4277                     : ImplicitConversionSequence::Worse;
4278   return ImplicitConversionSequence::Indistinguishable;
4279 }
4280 
4281 /// CompareDerivedToBaseConversions - Compares two standard conversion
4282 /// sequences to determine whether they can be ranked based on their
4283 /// various kinds of derived-to-base conversions (C++
4284 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4285 /// conversions between Objective-C interface types.
4286 static ImplicitConversionSequence::CompareKind
4287 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4288                                 const StandardConversionSequence& SCS1,
4289                                 const StandardConversionSequence& SCS2) {
4290   QualType FromType1 = SCS1.getFromType();
4291   QualType ToType1 = SCS1.getToType(1);
4292   QualType FromType2 = SCS2.getFromType();
4293   QualType ToType2 = SCS2.getToType(1);
4294 
4295   // Adjust the types we're converting from via the array-to-pointer
4296   // conversion, if we need to.
4297   if (SCS1.First == ICK_Array_To_Pointer)
4298     FromType1 = S.Context.getArrayDecayedType(FromType1);
4299   if (SCS2.First == ICK_Array_To_Pointer)
4300     FromType2 = S.Context.getArrayDecayedType(FromType2);
4301 
4302   // Canonicalize all of the types.
4303   FromType1 = S.Context.getCanonicalType(FromType1);
4304   ToType1 = S.Context.getCanonicalType(ToType1);
4305   FromType2 = S.Context.getCanonicalType(FromType2);
4306   ToType2 = S.Context.getCanonicalType(ToType2);
4307 
4308   // C++ [over.ics.rank]p4b3:
4309   //
4310   //   If class B is derived directly or indirectly from class A and
4311   //   class C is derived directly or indirectly from B,
4312   //
4313   // Compare based on pointer conversions.
4314   if (SCS1.Second == ICK_Pointer_Conversion &&
4315       SCS2.Second == ICK_Pointer_Conversion &&
4316       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4317       FromType1->isPointerType() && FromType2->isPointerType() &&
4318       ToType1->isPointerType() && ToType2->isPointerType()) {
4319     QualType FromPointee1 =
4320         FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4321     QualType ToPointee1 =
4322         ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4323     QualType FromPointee2 =
4324         FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4325     QualType ToPointee2 =
4326         ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4327 
4328     //   -- conversion of C* to B* is better than conversion of C* to A*,
4329     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4330       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4331         return ImplicitConversionSequence::Better;
4332       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4333         return ImplicitConversionSequence::Worse;
4334     }
4335 
4336     //   -- conversion of B* to A* is better than conversion of C* to A*,
4337     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4338       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4339         return ImplicitConversionSequence::Better;
4340       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4341         return ImplicitConversionSequence::Worse;
4342     }
4343   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4344              SCS2.Second == ICK_Pointer_Conversion) {
4345     const ObjCObjectPointerType *FromPtr1
4346       = FromType1->getAs<ObjCObjectPointerType>();
4347     const ObjCObjectPointerType *FromPtr2
4348       = FromType2->getAs<ObjCObjectPointerType>();
4349     const ObjCObjectPointerType *ToPtr1
4350       = ToType1->getAs<ObjCObjectPointerType>();
4351     const ObjCObjectPointerType *ToPtr2
4352       = ToType2->getAs<ObjCObjectPointerType>();
4353 
4354     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4355       // Apply the same conversion ranking rules for Objective-C pointer types
4356       // that we do for C++ pointers to class types. However, we employ the
4357       // Objective-C pseudo-subtyping relationship used for assignment of
4358       // Objective-C pointer types.
4359       bool FromAssignLeft
4360         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4361       bool FromAssignRight
4362         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4363       bool ToAssignLeft
4364         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4365       bool ToAssignRight
4366         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4367 
4368       // A conversion to an a non-id object pointer type or qualified 'id'
4369       // type is better than a conversion to 'id'.
4370       if (ToPtr1->isObjCIdType() &&
4371           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4372         return ImplicitConversionSequence::Worse;
4373       if (ToPtr2->isObjCIdType() &&
4374           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4375         return ImplicitConversionSequence::Better;
4376 
4377       // A conversion to a non-id object pointer type is better than a
4378       // conversion to a qualified 'id' type
4379       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4380         return ImplicitConversionSequence::Worse;
4381       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4382         return ImplicitConversionSequence::Better;
4383 
4384       // A conversion to an a non-Class object pointer type or qualified 'Class'
4385       // type is better than a conversion to 'Class'.
4386       if (ToPtr1->isObjCClassType() &&
4387           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4388         return ImplicitConversionSequence::Worse;
4389       if (ToPtr2->isObjCClassType() &&
4390           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4391         return ImplicitConversionSequence::Better;
4392 
4393       // A conversion to a non-Class object pointer type is better than a
4394       // conversion to a qualified 'Class' type.
4395       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4396         return ImplicitConversionSequence::Worse;
4397       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4398         return ImplicitConversionSequence::Better;
4399 
4400       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4401       if (S.Context.hasSameType(FromType1, FromType2) &&
4402           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4403           (ToAssignLeft != ToAssignRight)) {
4404         if (FromPtr1->isSpecialized()) {
4405           // "conversion of B<A> * to B * is better than conversion of B * to
4406           // C *.
4407           bool IsFirstSame =
4408               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4409           bool IsSecondSame =
4410               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4411           if (IsFirstSame) {
4412             if (!IsSecondSame)
4413               return ImplicitConversionSequence::Better;
4414           } else if (IsSecondSame)
4415             return ImplicitConversionSequence::Worse;
4416         }
4417         return ToAssignLeft? ImplicitConversionSequence::Worse
4418                            : ImplicitConversionSequence::Better;
4419       }
4420 
4421       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4422       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4423           (FromAssignLeft != FromAssignRight))
4424         return FromAssignLeft? ImplicitConversionSequence::Better
4425         : ImplicitConversionSequence::Worse;
4426     }
4427   }
4428 
4429   // Ranking of member-pointer types.
4430   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4431       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4432       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4433     const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4434     const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4435     const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4436     const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4437     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4438     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4439     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4440     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4441     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4442     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4443     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4444     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4445     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4446     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4447       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4448         return ImplicitConversionSequence::Worse;
4449       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4450         return ImplicitConversionSequence::Better;
4451     }
4452     // conversion of B::* to C::* is better than conversion of A::* to C::*
4453     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4454       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4455         return ImplicitConversionSequence::Better;
4456       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4457         return ImplicitConversionSequence::Worse;
4458     }
4459   }
4460 
4461   if (SCS1.Second == ICK_Derived_To_Base) {
4462     //   -- conversion of C to B is better than conversion of C to A,
4463     //   -- binding of an expression of type C to a reference of type
4464     //      B& is better than binding an expression of type C to a
4465     //      reference of type A&,
4466     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4467         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4468       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4469         return ImplicitConversionSequence::Better;
4470       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4471         return ImplicitConversionSequence::Worse;
4472     }
4473 
4474     //   -- conversion of B to A is better than conversion of C to A.
4475     //   -- binding of an expression of type B to a reference of type
4476     //      A& is better than binding an expression of type C to a
4477     //      reference of type A&,
4478     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4479         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4480       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4481         return ImplicitConversionSequence::Better;
4482       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4483         return ImplicitConversionSequence::Worse;
4484     }
4485   }
4486 
4487   return ImplicitConversionSequence::Indistinguishable;
4488 }
4489 
4490 /// Determine whether the given type is valid, e.g., it is not an invalid
4491 /// C++ class.
4492 static bool isTypeValid(QualType T) {
4493   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4494     return !Record->isInvalidDecl();
4495 
4496   return true;
4497 }
4498 
4499 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4500   if (!T.getQualifiers().hasUnaligned())
4501     return T;
4502 
4503   Qualifiers Q;
4504   T = Ctx.getUnqualifiedArrayType(T, Q);
4505   Q.removeUnaligned();
4506   return Ctx.getQualifiedType(T, Q);
4507 }
4508 
4509 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4510 /// determine whether they are reference-compatible,
4511 /// reference-related, or incompatible, for use in C++ initialization by
4512 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4513 /// type, and the first type (T1) is the pointee type of the reference
4514 /// type being initialized.
4515 Sema::ReferenceCompareResult
4516 Sema::CompareReferenceRelationship(SourceLocation Loc,
4517                                    QualType OrigT1, QualType OrigT2,
4518                                    ReferenceConversions *ConvOut) {
4519   assert(!OrigT1->isReferenceType() &&
4520     "T1 must be the pointee type of the reference type");
4521   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4522 
4523   QualType T1 = Context.getCanonicalType(OrigT1);
4524   QualType T2 = Context.getCanonicalType(OrigT2);
4525   Qualifiers T1Quals, T2Quals;
4526   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4527   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4528 
4529   ReferenceConversions ConvTmp;
4530   ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4531   Conv = ReferenceConversions();
4532 
4533   // C++2a [dcl.init.ref]p4:
4534   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4535   //   reference-related to "cv2 T2" if T1 is similar to T2, or
4536   //   T1 is a base class of T2.
4537   //   "cv1 T1" is reference-compatible with "cv2 T2" if
4538   //   a prvalue of type "pointer to cv2 T2" can be converted to the type
4539   //   "pointer to cv1 T1" via a standard conversion sequence.
4540 
4541   // Check for standard conversions we can apply to pointers: derived-to-base
4542   // conversions, ObjC pointer conversions, and function pointer conversions.
4543   // (Qualification conversions are checked last.)
4544   QualType ConvertedT2;
4545   if (UnqualT1 == UnqualT2) {
4546     // Nothing to do.
4547   } else if (isCompleteType(Loc, OrigT2) &&
4548              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4549              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4550     Conv |= ReferenceConversions::DerivedToBase;
4551   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4552            UnqualT2->isObjCObjectOrInterfaceType() &&
4553            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4554     Conv |= ReferenceConversions::ObjC;
4555   else if (UnqualT2->isFunctionType() &&
4556            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4557     Conv |= ReferenceConversions::Function;
4558     // No need to check qualifiers; function types don't have them.
4559     return Ref_Compatible;
4560   }
4561   bool ConvertedReferent = Conv != 0;
4562 
4563   // We can have a qualification conversion. Compute whether the types are
4564   // similar at the same time.
4565   bool PreviousToQualsIncludeConst = true;
4566   bool TopLevel = true;
4567   do {
4568     if (T1 == T2)
4569       break;
4570 
4571     // We will need a qualification conversion.
4572     Conv |= ReferenceConversions::Qualification;
4573 
4574     // Track whether we performed a qualification conversion anywhere other
4575     // than the top level. This matters for ranking reference bindings in
4576     // overload resolution.
4577     if (!TopLevel)
4578       Conv |= ReferenceConversions::NestedQualification;
4579 
4580     // MS compiler ignores __unaligned qualifier for references; do the same.
4581     T1 = withoutUnaligned(Context, T1);
4582     T2 = withoutUnaligned(Context, T2);
4583 
4584     // If we find a qualifier mismatch, the types are not reference-compatible,
4585     // but are still be reference-related if they're similar.
4586     bool ObjCLifetimeConversion = false;
4587     if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4588                                        PreviousToQualsIncludeConst,
4589                                        ObjCLifetimeConversion))
4590       return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4591                  ? Ref_Related
4592                  : Ref_Incompatible;
4593 
4594     // FIXME: Should we track this for any level other than the first?
4595     if (ObjCLifetimeConversion)
4596       Conv |= ReferenceConversions::ObjCLifetime;
4597 
4598     TopLevel = false;
4599   } while (Context.UnwrapSimilarTypes(T1, T2));
4600 
4601   // At this point, if the types are reference-related, we must either have the
4602   // same inner type (ignoring qualifiers), or must have already worked out how
4603   // to convert the referent.
4604   return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4605              ? Ref_Compatible
4606              : Ref_Incompatible;
4607 }
4608 
4609 /// Look for a user-defined conversion to a value reference-compatible
4610 ///        with DeclType. Return true if something definite is found.
4611 static bool
4612 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4613                          QualType DeclType, SourceLocation DeclLoc,
4614                          Expr *Init, QualType T2, bool AllowRvalues,
4615                          bool AllowExplicit) {
4616   assert(T2->isRecordType() && "Can only find conversions of record types.");
4617   auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4618 
4619   OverloadCandidateSet CandidateSet(
4620       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4621   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4622   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4623     NamedDecl *D = *I;
4624     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4625     if (isa<UsingShadowDecl>(D))
4626       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4627 
4628     FunctionTemplateDecl *ConvTemplate
4629       = dyn_cast<FunctionTemplateDecl>(D);
4630     CXXConversionDecl *Conv;
4631     if (ConvTemplate)
4632       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4633     else
4634       Conv = cast<CXXConversionDecl>(D);
4635 
4636     if (AllowRvalues) {
4637       // If we are initializing an rvalue reference, don't permit conversion
4638       // functions that return lvalues.
4639       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4640         const ReferenceType *RefType
4641           = Conv->getConversionType()->getAs<LValueReferenceType>();
4642         if (RefType && !RefType->getPointeeType()->isFunctionType())
4643           continue;
4644       }
4645 
4646       if (!ConvTemplate &&
4647           S.CompareReferenceRelationship(
4648               DeclLoc,
4649               Conv->getConversionType()
4650                   .getNonReferenceType()
4651                   .getUnqualifiedType(),
4652               DeclType.getNonReferenceType().getUnqualifiedType()) ==
4653               Sema::Ref_Incompatible)
4654         continue;
4655     } else {
4656       // If the conversion function doesn't return a reference type,
4657       // it can't be considered for this conversion. An rvalue reference
4658       // is only acceptable if its referencee is a function type.
4659 
4660       const ReferenceType *RefType =
4661         Conv->getConversionType()->getAs<ReferenceType>();
4662       if (!RefType ||
4663           (!RefType->isLValueReferenceType() &&
4664            !RefType->getPointeeType()->isFunctionType()))
4665         continue;
4666     }
4667 
4668     if (ConvTemplate)
4669       S.AddTemplateConversionCandidate(
4670           ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4671           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4672     else
4673       S.AddConversionCandidate(
4674           Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4675           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4676   }
4677 
4678   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4679 
4680   OverloadCandidateSet::iterator Best;
4681   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4682   case OR_Success:
4683     // C++ [over.ics.ref]p1:
4684     //
4685     //   [...] If the parameter binds directly to the result of
4686     //   applying a conversion function to the argument
4687     //   expression, the implicit conversion sequence is a
4688     //   user-defined conversion sequence (13.3.3.1.2), with the
4689     //   second standard conversion sequence either an identity
4690     //   conversion or, if the conversion function returns an
4691     //   entity of a type that is a derived class of the parameter
4692     //   type, a derived-to-base Conversion.
4693     if (!Best->FinalConversion.DirectBinding)
4694       return false;
4695 
4696     ICS.setUserDefined();
4697     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4698     ICS.UserDefined.After = Best->FinalConversion;
4699     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4700     ICS.UserDefined.ConversionFunction = Best->Function;
4701     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4702     ICS.UserDefined.EllipsisConversion = false;
4703     assert(ICS.UserDefined.After.ReferenceBinding &&
4704            ICS.UserDefined.After.DirectBinding &&
4705            "Expected a direct reference binding!");
4706     return true;
4707 
4708   case OR_Ambiguous:
4709     ICS.setAmbiguous();
4710     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4711          Cand != CandidateSet.end(); ++Cand)
4712       if (Cand->Best)
4713         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4714     return true;
4715 
4716   case OR_No_Viable_Function:
4717   case OR_Deleted:
4718     // There was no suitable conversion, or we found a deleted
4719     // conversion; continue with other checks.
4720     return false;
4721   }
4722 
4723   llvm_unreachable("Invalid OverloadResult!");
4724 }
4725 
4726 /// Compute an implicit conversion sequence for reference
4727 /// initialization.
4728 static ImplicitConversionSequence
4729 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4730                  SourceLocation DeclLoc,
4731                  bool SuppressUserConversions,
4732                  bool AllowExplicit) {
4733   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4734 
4735   // Most paths end in a failed conversion.
4736   ImplicitConversionSequence ICS;
4737   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4738 
4739   QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4740   QualType T2 = Init->getType();
4741 
4742   // If the initializer is the address of an overloaded function, try
4743   // to resolve the overloaded function. If all goes well, T2 is the
4744   // type of the resulting function.
4745   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4746     DeclAccessPair Found;
4747     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4748                                                                 false, Found))
4749       T2 = Fn->getType();
4750   }
4751 
4752   // Compute some basic properties of the types and the initializer.
4753   bool isRValRef = DeclType->isRValueReferenceType();
4754   Expr::Classification InitCategory = Init->Classify(S.Context);
4755 
4756   Sema::ReferenceConversions RefConv;
4757   Sema::ReferenceCompareResult RefRelationship =
4758       S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4759 
4760   auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4761     ICS.setStandard();
4762     ICS.Standard.First = ICK_Identity;
4763     // FIXME: A reference binding can be a function conversion too. We should
4764     // consider that when ordering reference-to-function bindings.
4765     ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4766                               ? ICK_Derived_To_Base
4767                               : (RefConv & Sema::ReferenceConversions::ObjC)
4768                                     ? ICK_Compatible_Conversion
4769                                     : ICK_Identity;
4770     // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4771     // a reference binding that performs a non-top-level qualification
4772     // conversion as a qualification conversion, not as an identity conversion.
4773     ICS.Standard.Third = (RefConv &
4774                               Sema::ReferenceConversions::NestedQualification)
4775                              ? ICK_Qualification
4776                              : ICK_Identity;
4777     ICS.Standard.setFromType(T2);
4778     ICS.Standard.setToType(0, T2);
4779     ICS.Standard.setToType(1, T1);
4780     ICS.Standard.setToType(2, T1);
4781     ICS.Standard.ReferenceBinding = true;
4782     ICS.Standard.DirectBinding = BindsDirectly;
4783     ICS.Standard.IsLvalueReference = !isRValRef;
4784     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4785     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4786     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4787     ICS.Standard.ObjCLifetimeConversionBinding =
4788         (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4789     ICS.Standard.CopyConstructor = nullptr;
4790     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4791   };
4792 
4793   // C++0x [dcl.init.ref]p5:
4794   //   A reference to type "cv1 T1" is initialized by an expression
4795   //   of type "cv2 T2" as follows:
4796 
4797   //     -- If reference is an lvalue reference and the initializer expression
4798   if (!isRValRef) {
4799     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4800     //        reference-compatible with "cv2 T2," or
4801     //
4802     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4803     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4804       // C++ [over.ics.ref]p1:
4805       //   When a parameter of reference type binds directly (8.5.3)
4806       //   to an argument expression, the implicit conversion sequence
4807       //   is the identity conversion, unless the argument expression
4808       //   has a type that is a derived class of the parameter type,
4809       //   in which case the implicit conversion sequence is a
4810       //   derived-to-base Conversion (13.3.3.1).
4811       SetAsReferenceBinding(/*BindsDirectly=*/true);
4812 
4813       // Nothing more to do: the inaccessibility/ambiguity check for
4814       // derived-to-base conversions is suppressed when we're
4815       // computing the implicit conversion sequence (C++
4816       // [over.best.ics]p2).
4817       return ICS;
4818     }
4819 
4820     //       -- has a class type (i.e., T2 is a class type), where T1 is
4821     //          not reference-related to T2, and can be implicitly
4822     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4823     //          is reference-compatible with "cv3 T3" 92) (this
4824     //          conversion is selected by enumerating the applicable
4825     //          conversion functions (13.3.1.6) and choosing the best
4826     //          one through overload resolution (13.3)),
4827     if (!SuppressUserConversions && T2->isRecordType() &&
4828         S.isCompleteType(DeclLoc, T2) &&
4829         RefRelationship == Sema::Ref_Incompatible) {
4830       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4831                                    Init, T2, /*AllowRvalues=*/false,
4832                                    AllowExplicit))
4833         return ICS;
4834     }
4835   }
4836 
4837   //     -- Otherwise, the reference shall be an lvalue reference to a
4838   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4839   //        shall be an rvalue reference.
4840   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
4841     if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
4842       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4843     return ICS;
4844   }
4845 
4846   //       -- If the initializer expression
4847   //
4848   //            -- is an xvalue, class prvalue, array prvalue or function
4849   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4850   if (RefRelationship == Sema::Ref_Compatible &&
4851       (InitCategory.isXValue() ||
4852        (InitCategory.isPRValue() &&
4853           (T2->isRecordType() || T2->isArrayType())) ||
4854        (InitCategory.isLValue() && T2->isFunctionType()))) {
4855     // In C++11, this is always a direct binding. In C++98/03, it's a direct
4856     // binding unless we're binding to a class prvalue.
4857     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4858     // allow the use of rvalue references in C++98/03 for the benefit of
4859     // standard library implementors; therefore, we need the xvalue check here.
4860     SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4861                           !(InitCategory.isPRValue() || T2->isRecordType()));
4862     return ICS;
4863   }
4864 
4865   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4866   //               reference-related to T2, and can be implicitly converted to
4867   //               an xvalue, class prvalue, or function lvalue of type
4868   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4869   //               "cv3 T3",
4870   //
4871   //          then the reference is bound to the value of the initializer
4872   //          expression in the first case and to the result of the conversion
4873   //          in the second case (or, in either case, to an appropriate base
4874   //          class subobject).
4875   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4876       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4877       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4878                                Init, T2, /*AllowRvalues=*/true,
4879                                AllowExplicit)) {
4880     // In the second case, if the reference is an rvalue reference
4881     // and the second standard conversion sequence of the
4882     // user-defined conversion sequence includes an lvalue-to-rvalue
4883     // conversion, the program is ill-formed.
4884     if (ICS.isUserDefined() && isRValRef &&
4885         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4886       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4887 
4888     return ICS;
4889   }
4890 
4891   // A temporary of function type cannot be created; don't even try.
4892   if (T1->isFunctionType())
4893     return ICS;
4894 
4895   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4896   //          initialized from the initializer expression using the
4897   //          rules for a non-reference copy initialization (8.5). The
4898   //          reference is then bound to the temporary. If T1 is
4899   //          reference-related to T2, cv1 must be the same
4900   //          cv-qualification as, or greater cv-qualification than,
4901   //          cv2; otherwise, the program is ill-formed.
4902   if (RefRelationship == Sema::Ref_Related) {
4903     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4904     // we would be reference-compatible or reference-compatible with
4905     // added qualification. But that wasn't the case, so the reference
4906     // initialization fails.
4907     //
4908     // Note that we only want to check address spaces and cvr-qualifiers here.
4909     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4910     Qualifiers T1Quals = T1.getQualifiers();
4911     Qualifiers T2Quals = T2.getQualifiers();
4912     T1Quals.removeObjCGCAttr();
4913     T1Quals.removeObjCLifetime();
4914     T2Quals.removeObjCGCAttr();
4915     T2Quals.removeObjCLifetime();
4916     // MS compiler ignores __unaligned qualifier for references; do the same.
4917     T1Quals.removeUnaligned();
4918     T2Quals.removeUnaligned();
4919     if (!T1Quals.compatiblyIncludes(T2Quals))
4920       return ICS;
4921   }
4922 
4923   // If at least one of the types is a class type, the types are not
4924   // related, and we aren't allowed any user conversions, the
4925   // reference binding fails. This case is important for breaking
4926   // recursion, since TryImplicitConversion below will attempt to
4927   // create a temporary through the use of a copy constructor.
4928   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4929       (T1->isRecordType() || T2->isRecordType()))
4930     return ICS;
4931 
4932   // If T1 is reference-related to T2 and the reference is an rvalue
4933   // reference, the initializer expression shall not be an lvalue.
4934   if (RefRelationship >= Sema::Ref_Related && isRValRef &&
4935       Init->Classify(S.Context).isLValue()) {
4936     ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType);
4937     return ICS;
4938   }
4939 
4940   // C++ [over.ics.ref]p2:
4941   //   When a parameter of reference type is not bound directly to
4942   //   an argument expression, the conversion sequence is the one
4943   //   required to convert the argument expression to the
4944   //   underlying type of the reference according to
4945   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4946   //   to copy-initializing a temporary of the underlying type with
4947   //   the argument expression. Any difference in top-level
4948   //   cv-qualification is subsumed by the initialization itself
4949   //   and does not constitute a conversion.
4950   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4951                               AllowedExplicit::None,
4952                               /*InOverloadResolution=*/false,
4953                               /*CStyle=*/false,
4954                               /*AllowObjCWritebackConversion=*/false,
4955                               /*AllowObjCConversionOnExplicit=*/false);
4956 
4957   // Of course, that's still a reference binding.
4958   if (ICS.isStandard()) {
4959     ICS.Standard.ReferenceBinding = true;
4960     ICS.Standard.IsLvalueReference = !isRValRef;
4961     ICS.Standard.BindsToFunctionLvalue = false;
4962     ICS.Standard.BindsToRvalue = true;
4963     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4964     ICS.Standard.ObjCLifetimeConversionBinding = false;
4965   } else if (ICS.isUserDefined()) {
4966     const ReferenceType *LValRefType =
4967         ICS.UserDefined.ConversionFunction->getReturnType()
4968             ->getAs<LValueReferenceType>();
4969 
4970     // C++ [over.ics.ref]p3:
4971     //   Except for an implicit object parameter, for which see 13.3.1, a
4972     //   standard conversion sequence cannot be formed if it requires [...]
4973     //   binding an rvalue reference to an lvalue other than a function
4974     //   lvalue.
4975     // Note that the function case is not possible here.
4976     if (isRValRef && LValRefType) {
4977       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4978       return ICS;
4979     }
4980 
4981     ICS.UserDefined.After.ReferenceBinding = true;
4982     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4983     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4984     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4985     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4986     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4987   }
4988 
4989   return ICS;
4990 }
4991 
4992 static ImplicitConversionSequence
4993 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4994                       bool SuppressUserConversions,
4995                       bool InOverloadResolution,
4996                       bool AllowObjCWritebackConversion,
4997                       bool AllowExplicit = false);
4998 
4999 /// TryListConversion - Try to copy-initialize a value of type ToType from the
5000 /// initializer list From.
5001 static ImplicitConversionSequence
5002 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5003                   bool SuppressUserConversions,
5004                   bool InOverloadResolution,
5005                   bool AllowObjCWritebackConversion) {
5006   // C++11 [over.ics.list]p1:
5007   //   When an argument is an initializer list, it is not an expression and
5008   //   special rules apply for converting it to a parameter type.
5009 
5010   ImplicitConversionSequence Result;
5011   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5012 
5013   // We need a complete type for what follows.  With one C++20 exception,
5014   // incomplete types can never be initialized from init lists.
5015   QualType InitTy = ToType;
5016   const ArrayType *AT = S.Context.getAsArrayType(ToType);
5017   if (AT && S.getLangOpts().CPlusPlus20)
5018     if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5019       // C++20 allows list initialization of an incomplete array type.
5020       InitTy = IAT->getElementType();
5021   if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5022     return Result;
5023 
5024   // Per DR1467:
5025   //   If the parameter type is a class X and the initializer list has a single
5026   //   element of type cv U, where U is X or a class derived from X, the
5027   //   implicit conversion sequence is the one required to convert the element
5028   //   to the parameter type.
5029   //
5030   //   Otherwise, if the parameter type is a character array [... ]
5031   //   and the initializer list has a single element that is an
5032   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5033   //   implicit conversion sequence is the identity conversion.
5034   if (From->getNumInits() == 1) {
5035     if (ToType->isRecordType()) {
5036       QualType InitType = From->getInit(0)->getType();
5037       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5038           S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5039         return TryCopyInitialization(S, From->getInit(0), ToType,
5040                                      SuppressUserConversions,
5041                                      InOverloadResolution,
5042                                      AllowObjCWritebackConversion);
5043     }
5044 
5045     if (AT && S.IsStringInit(From->getInit(0), AT)) {
5046       InitializedEntity Entity =
5047           InitializedEntity::InitializeParameter(S.Context, ToType,
5048                                                  /*Consumed=*/false);
5049       if (S.CanPerformCopyInitialization(Entity, From)) {
5050         Result.setStandard();
5051         Result.Standard.setAsIdentityConversion();
5052         Result.Standard.setFromType(ToType);
5053         Result.Standard.setAllToTypes(ToType);
5054         return Result;
5055       }
5056     }
5057   }
5058 
5059   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5060   // C++11 [over.ics.list]p2:
5061   //   If the parameter type is std::initializer_list<X> or "array of X" and
5062   //   all the elements can be implicitly converted to X, the implicit
5063   //   conversion sequence is the worst conversion necessary to convert an
5064   //   element of the list to X.
5065   //
5066   // C++14 [over.ics.list]p3:
5067   //   Otherwise, if the parameter type is "array of N X", if the initializer
5068   //   list has exactly N elements or if it has fewer than N elements and X is
5069   //   default-constructible, and if all the elements of the initializer list
5070   //   can be implicitly converted to X, the implicit conversion sequence is
5071   //   the worst conversion necessary to convert an element of the list to X.
5072   if (AT || S.isStdInitializerList(ToType, &InitTy)) {
5073     unsigned e = From->getNumInits();
5074     ImplicitConversionSequence DfltElt;
5075     DfltElt.setBad(BadConversionSequence::no_conversion, QualType(),
5076                    QualType());
5077     QualType ContTy = ToType;
5078     bool IsUnbounded = false;
5079     if (AT) {
5080       InitTy = AT->getElementType();
5081       if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5082         if (CT->getSize().ult(e)) {
5083           // Too many inits, fatally bad
5084           Result.setBad(BadConversionSequence::too_many_initializers, From,
5085                         ToType);
5086           Result.setInitializerListContainerType(ContTy, IsUnbounded);
5087           return Result;
5088         }
5089         if (CT->getSize().ugt(e)) {
5090           // Need an init from empty {}, is there one?
5091           InitListExpr EmptyList(S.Context, From->getEndLoc(), None,
5092                                  From->getEndLoc());
5093           EmptyList.setType(S.Context.VoidTy);
5094           DfltElt = TryListConversion(
5095               S, &EmptyList, InitTy, SuppressUserConversions,
5096               InOverloadResolution, AllowObjCWritebackConversion);
5097           if (DfltElt.isBad()) {
5098             // No {} init, fatally bad
5099             Result.setBad(BadConversionSequence::too_few_initializers, From,
5100                           ToType);
5101             Result.setInitializerListContainerType(ContTy, IsUnbounded);
5102             return Result;
5103           }
5104         }
5105       } else {
5106         assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5107         IsUnbounded = true;
5108         if (!e) {
5109           // Cannot convert to zero-sized.
5110           Result.setBad(BadConversionSequence::too_few_initializers, From,
5111                         ToType);
5112           Result.setInitializerListContainerType(ContTy, IsUnbounded);
5113           return Result;
5114         }
5115         llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5116         ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5117                                                 ArrayType::Normal, 0);
5118       }
5119     }
5120 
5121     Result.setStandard();
5122     Result.Standard.setAsIdentityConversion();
5123     Result.Standard.setFromType(InitTy);
5124     Result.Standard.setAllToTypes(InitTy);
5125     for (unsigned i = 0; i < e; ++i) {
5126       Expr *Init = From->getInit(i);
5127       ImplicitConversionSequence ICS = TryCopyInitialization(
5128           S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5129           AllowObjCWritebackConversion);
5130 
5131       // Keep the worse conversion seen so far.
5132       // FIXME: Sequences are not totally ordered, so 'worse' can be
5133       // ambiguous. CWG has been informed.
5134       if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS,
5135                                              Result) ==
5136           ImplicitConversionSequence::Worse) {
5137         Result = ICS;
5138         // Bail as soon as we find something unconvertible.
5139         if (Result.isBad()) {
5140           Result.setInitializerListContainerType(ContTy, IsUnbounded);
5141           return Result;
5142         }
5143       }
5144     }
5145 
5146     // If we needed any implicit {} initialization, compare that now.
5147     // over.ics.list/6 indicates we should compare that conversion.  Again CWG
5148     // has been informed that this might not be the best thing.
5149     if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5150                                 S, From->getEndLoc(), DfltElt, Result) ==
5151                                 ImplicitConversionSequence::Worse)
5152       Result = DfltElt;
5153     // Record the type being initialized so that we may compare sequences
5154     Result.setInitializerListContainerType(ContTy, IsUnbounded);
5155     return Result;
5156   }
5157 
5158   // C++14 [over.ics.list]p4:
5159   // C++11 [over.ics.list]p3:
5160   //   Otherwise, if the parameter is a non-aggregate class X and overload
5161   //   resolution chooses a single best constructor [...] the implicit
5162   //   conversion sequence is a user-defined conversion sequence. If multiple
5163   //   constructors are viable but none is better than the others, the
5164   //   implicit conversion sequence is a user-defined conversion sequence.
5165   if (ToType->isRecordType() && !ToType->isAggregateType()) {
5166     // This function can deal with initializer lists.
5167     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5168                                     AllowedExplicit::None,
5169                                     InOverloadResolution, /*CStyle=*/false,
5170                                     AllowObjCWritebackConversion,
5171                                     /*AllowObjCConversionOnExplicit=*/false);
5172   }
5173 
5174   // C++14 [over.ics.list]p5:
5175   // C++11 [over.ics.list]p4:
5176   //   Otherwise, if the parameter has an aggregate type which can be
5177   //   initialized from the initializer list [...] the implicit conversion
5178   //   sequence is a user-defined conversion sequence.
5179   if (ToType->isAggregateType()) {
5180     // Type is an aggregate, argument is an init list. At this point it comes
5181     // down to checking whether the initialization works.
5182     // FIXME: Find out whether this parameter is consumed or not.
5183     InitializedEntity Entity =
5184         InitializedEntity::InitializeParameter(S.Context, ToType,
5185                                                /*Consumed=*/false);
5186     if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5187                                                                  From)) {
5188       Result.setUserDefined();
5189       Result.UserDefined.Before.setAsIdentityConversion();
5190       // Initializer lists don't have a type.
5191       Result.UserDefined.Before.setFromType(QualType());
5192       Result.UserDefined.Before.setAllToTypes(QualType());
5193 
5194       Result.UserDefined.After.setAsIdentityConversion();
5195       Result.UserDefined.After.setFromType(ToType);
5196       Result.UserDefined.After.setAllToTypes(ToType);
5197       Result.UserDefined.ConversionFunction = nullptr;
5198     }
5199     return Result;
5200   }
5201 
5202   // C++14 [over.ics.list]p6:
5203   // C++11 [over.ics.list]p5:
5204   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5205   if (ToType->isReferenceType()) {
5206     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5207     // mention initializer lists in any way. So we go by what list-
5208     // initialization would do and try to extrapolate from that.
5209 
5210     QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5211 
5212     // If the initializer list has a single element that is reference-related
5213     // to the parameter type, we initialize the reference from that.
5214     if (From->getNumInits() == 1) {
5215       Expr *Init = From->getInit(0);
5216 
5217       QualType T2 = Init->getType();
5218 
5219       // If the initializer is the address of an overloaded function, try
5220       // to resolve the overloaded function. If all goes well, T2 is the
5221       // type of the resulting function.
5222       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5223         DeclAccessPair Found;
5224         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5225                                    Init, ToType, false, Found))
5226           T2 = Fn->getType();
5227       }
5228 
5229       // Compute some basic properties of the types and the initializer.
5230       Sema::ReferenceCompareResult RefRelationship =
5231           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5232 
5233       if (RefRelationship >= Sema::Ref_Related) {
5234         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5235                                 SuppressUserConversions,
5236                                 /*AllowExplicit=*/false);
5237       }
5238     }
5239 
5240     // Otherwise, we bind the reference to a temporary created from the
5241     // initializer list.
5242     Result = TryListConversion(S, From, T1, SuppressUserConversions,
5243                                InOverloadResolution,
5244                                AllowObjCWritebackConversion);
5245     if (Result.isFailure())
5246       return Result;
5247     assert(!Result.isEllipsis() &&
5248            "Sub-initialization cannot result in ellipsis conversion.");
5249 
5250     // Can we even bind to a temporary?
5251     if (ToType->isRValueReferenceType() ||
5252         (T1.isConstQualified() && !T1.isVolatileQualified())) {
5253       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5254                                             Result.UserDefined.After;
5255       SCS.ReferenceBinding = true;
5256       SCS.IsLvalueReference = ToType->isLValueReferenceType();
5257       SCS.BindsToRvalue = true;
5258       SCS.BindsToFunctionLvalue = false;
5259       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5260       SCS.ObjCLifetimeConversionBinding = false;
5261     } else
5262       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5263                     From, ToType);
5264     return Result;
5265   }
5266 
5267   // C++14 [over.ics.list]p7:
5268   // C++11 [over.ics.list]p6:
5269   //   Otherwise, if the parameter type is not a class:
5270   if (!ToType->isRecordType()) {
5271     //    - if the initializer list has one element that is not itself an
5272     //      initializer list, the implicit conversion sequence is the one
5273     //      required to convert the element to the parameter type.
5274     unsigned NumInits = From->getNumInits();
5275     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5276       Result = TryCopyInitialization(S, From->getInit(0), ToType,
5277                                      SuppressUserConversions,
5278                                      InOverloadResolution,
5279                                      AllowObjCWritebackConversion);
5280     //    - if the initializer list has no elements, the implicit conversion
5281     //      sequence is the identity conversion.
5282     else if (NumInits == 0) {
5283       Result.setStandard();
5284       Result.Standard.setAsIdentityConversion();
5285       Result.Standard.setFromType(ToType);
5286       Result.Standard.setAllToTypes(ToType);
5287     }
5288     return Result;
5289   }
5290 
5291   // C++14 [over.ics.list]p8:
5292   // C++11 [over.ics.list]p7:
5293   //   In all cases other than those enumerated above, no conversion is possible
5294   return Result;
5295 }
5296 
5297 /// TryCopyInitialization - Try to copy-initialize a value of type
5298 /// ToType from the expression From. Return the implicit conversion
5299 /// sequence required to pass this argument, which may be a bad
5300 /// conversion sequence (meaning that the argument cannot be passed to
5301 /// a parameter of this type). If @p SuppressUserConversions, then we
5302 /// do not permit any user-defined conversion sequences.
5303 static ImplicitConversionSequence
5304 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5305                       bool SuppressUserConversions,
5306                       bool InOverloadResolution,
5307                       bool AllowObjCWritebackConversion,
5308                       bool AllowExplicit) {
5309   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5310     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5311                              InOverloadResolution,AllowObjCWritebackConversion);
5312 
5313   if (ToType->isReferenceType())
5314     return TryReferenceInit(S, From, ToType,
5315                             /*FIXME:*/ From->getBeginLoc(),
5316                             SuppressUserConversions, AllowExplicit);
5317 
5318   return TryImplicitConversion(S, From, ToType,
5319                                SuppressUserConversions,
5320                                AllowedExplicit::None,
5321                                InOverloadResolution,
5322                                /*CStyle=*/false,
5323                                AllowObjCWritebackConversion,
5324                                /*AllowObjCConversionOnExplicit=*/false);
5325 }
5326 
5327 static bool TryCopyInitialization(const CanQualType FromQTy,
5328                                   const CanQualType ToQTy,
5329                                   Sema &S,
5330                                   SourceLocation Loc,
5331                                   ExprValueKind FromVK) {
5332   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5333   ImplicitConversionSequence ICS =
5334     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5335 
5336   return !ICS.isBad();
5337 }
5338 
5339 /// TryObjectArgumentInitialization - Try to initialize the object
5340 /// parameter of the given member function (@c Method) from the
5341 /// expression @p From.
5342 static ImplicitConversionSequence
5343 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5344                                 Expr::Classification FromClassification,
5345                                 CXXMethodDecl *Method,
5346                                 CXXRecordDecl *ActingContext) {
5347   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5348   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5349   //                 const volatile object.
5350   Qualifiers Quals = Method->getMethodQualifiers();
5351   if (isa<CXXDestructorDecl>(Method)) {
5352     Quals.addConst();
5353     Quals.addVolatile();
5354   }
5355 
5356   QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5357 
5358   // Set up the conversion sequence as a "bad" conversion, to allow us
5359   // to exit early.
5360   ImplicitConversionSequence ICS;
5361 
5362   // We need to have an object of class type.
5363   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5364     FromType = PT->getPointeeType();
5365 
5366     // When we had a pointer, it's implicitly dereferenced, so we
5367     // better have an lvalue.
5368     assert(FromClassification.isLValue());
5369   }
5370 
5371   assert(FromType->isRecordType());
5372 
5373   // C++0x [over.match.funcs]p4:
5374   //   For non-static member functions, the type of the implicit object
5375   //   parameter is
5376   //
5377   //     - "lvalue reference to cv X" for functions declared without a
5378   //        ref-qualifier or with the & ref-qualifier
5379   //     - "rvalue reference to cv X" for functions declared with the &&
5380   //        ref-qualifier
5381   //
5382   // where X is the class of which the function is a member and cv is the
5383   // cv-qualification on the member function declaration.
5384   //
5385   // However, when finding an implicit conversion sequence for the argument, we
5386   // are not allowed to perform user-defined conversions
5387   // (C++ [over.match.funcs]p5). We perform a simplified version of
5388   // reference binding here, that allows class rvalues to bind to
5389   // non-constant references.
5390 
5391   // First check the qualifiers.
5392   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5393   if (ImplicitParamType.getCVRQualifiers()
5394                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5395       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5396     ICS.setBad(BadConversionSequence::bad_qualifiers,
5397                FromType, ImplicitParamType);
5398     return ICS;
5399   }
5400 
5401   if (FromTypeCanon.hasAddressSpace()) {
5402     Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5403     Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5404     if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5405       ICS.setBad(BadConversionSequence::bad_qualifiers,
5406                  FromType, ImplicitParamType);
5407       return ICS;
5408     }
5409   }
5410 
5411   // Check that we have either the same type or a derived type. It
5412   // affects the conversion rank.
5413   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5414   ImplicitConversionKind SecondKind;
5415   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5416     SecondKind = ICK_Identity;
5417   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5418     SecondKind = ICK_Derived_To_Base;
5419   else {
5420     ICS.setBad(BadConversionSequence::unrelated_class,
5421                FromType, ImplicitParamType);
5422     return ICS;
5423   }
5424 
5425   // Check the ref-qualifier.
5426   switch (Method->getRefQualifier()) {
5427   case RQ_None:
5428     // Do nothing; we don't care about lvalueness or rvalueness.
5429     break;
5430 
5431   case RQ_LValue:
5432     if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5433       // non-const lvalue reference cannot bind to an rvalue
5434       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5435                  ImplicitParamType);
5436       return ICS;
5437     }
5438     break;
5439 
5440   case RQ_RValue:
5441     if (!FromClassification.isRValue()) {
5442       // rvalue reference cannot bind to an lvalue
5443       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5444                  ImplicitParamType);
5445       return ICS;
5446     }
5447     break;
5448   }
5449 
5450   // Success. Mark this as a reference binding.
5451   ICS.setStandard();
5452   ICS.Standard.setAsIdentityConversion();
5453   ICS.Standard.Second = SecondKind;
5454   ICS.Standard.setFromType(FromType);
5455   ICS.Standard.setAllToTypes(ImplicitParamType);
5456   ICS.Standard.ReferenceBinding = true;
5457   ICS.Standard.DirectBinding = true;
5458   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5459   ICS.Standard.BindsToFunctionLvalue = false;
5460   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5461   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5462     = (Method->getRefQualifier() == RQ_None);
5463   return ICS;
5464 }
5465 
5466 /// PerformObjectArgumentInitialization - Perform initialization of
5467 /// the implicit object parameter for the given Method with the given
5468 /// expression.
5469 ExprResult
5470 Sema::PerformObjectArgumentInitialization(Expr *From,
5471                                           NestedNameSpecifier *Qualifier,
5472                                           NamedDecl *FoundDecl,
5473                                           CXXMethodDecl *Method) {
5474   QualType FromRecordType, DestType;
5475   QualType ImplicitParamRecordType  =
5476     Method->getThisType()->castAs<PointerType>()->getPointeeType();
5477 
5478   Expr::Classification FromClassification;
5479   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5480     FromRecordType = PT->getPointeeType();
5481     DestType = Method->getThisType();
5482     FromClassification = Expr::Classification::makeSimpleLValue();
5483   } else {
5484     FromRecordType = From->getType();
5485     DestType = ImplicitParamRecordType;
5486     FromClassification = From->Classify(Context);
5487 
5488     // When performing member access on a prvalue, materialize a temporary.
5489     if (From->isPRValue()) {
5490       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5491                                             Method->getRefQualifier() !=
5492                                                 RefQualifierKind::RQ_RValue);
5493     }
5494   }
5495 
5496   // Note that we always use the true parent context when performing
5497   // the actual argument initialization.
5498   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5499       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5500       Method->getParent());
5501   if (ICS.isBad()) {
5502     switch (ICS.Bad.Kind) {
5503     case BadConversionSequence::bad_qualifiers: {
5504       Qualifiers FromQs = FromRecordType.getQualifiers();
5505       Qualifiers ToQs = DestType.getQualifiers();
5506       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5507       if (CVR) {
5508         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5509             << Method->getDeclName() << FromRecordType << (CVR - 1)
5510             << From->getSourceRange();
5511         Diag(Method->getLocation(), diag::note_previous_decl)
5512           << Method->getDeclName();
5513         return ExprError();
5514       }
5515       break;
5516     }
5517 
5518     case BadConversionSequence::lvalue_ref_to_rvalue:
5519     case BadConversionSequence::rvalue_ref_to_lvalue: {
5520       bool IsRValueQualified =
5521         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5522       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5523           << Method->getDeclName() << FromClassification.isRValue()
5524           << IsRValueQualified;
5525       Diag(Method->getLocation(), diag::note_previous_decl)
5526         << Method->getDeclName();
5527       return ExprError();
5528     }
5529 
5530     case BadConversionSequence::no_conversion:
5531     case BadConversionSequence::unrelated_class:
5532       break;
5533 
5534     case BadConversionSequence::too_few_initializers:
5535     case BadConversionSequence::too_many_initializers:
5536       llvm_unreachable("Lists are not objects");
5537     }
5538 
5539     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5540            << ImplicitParamRecordType << FromRecordType
5541            << From->getSourceRange();
5542   }
5543 
5544   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5545     ExprResult FromRes =
5546       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5547     if (FromRes.isInvalid())
5548       return ExprError();
5549     From = FromRes.get();
5550   }
5551 
5552   if (!Context.hasSameType(From->getType(), DestType)) {
5553     CastKind CK;
5554     QualType PteeTy = DestType->getPointeeType();
5555     LangAS DestAS =
5556         PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5557     if (FromRecordType.getAddressSpace() != DestAS)
5558       CK = CK_AddressSpaceConversion;
5559     else
5560       CK = CK_NoOp;
5561     From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5562   }
5563   return From;
5564 }
5565 
5566 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5567 /// expression From to bool (C++0x [conv]p3).
5568 static ImplicitConversionSequence
5569 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5570   // C++ [dcl.init]/17.8:
5571   //   - Otherwise, if the initialization is direct-initialization, the source
5572   //     type is std::nullptr_t, and the destination type is bool, the initial
5573   //     value of the object being initialized is false.
5574   if (From->getType()->isNullPtrType())
5575     return ImplicitConversionSequence::getNullptrToBool(From->getType(),
5576                                                         S.Context.BoolTy,
5577                                                         From->isGLValue());
5578 
5579   // All other direct-initialization of bool is equivalent to an implicit
5580   // conversion to bool in which explicit conversions are permitted.
5581   return TryImplicitConversion(S, From, S.Context.BoolTy,
5582                                /*SuppressUserConversions=*/false,
5583                                AllowedExplicit::Conversions,
5584                                /*InOverloadResolution=*/false,
5585                                /*CStyle=*/false,
5586                                /*AllowObjCWritebackConversion=*/false,
5587                                /*AllowObjCConversionOnExplicit=*/false);
5588 }
5589 
5590 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5591 /// of the expression From to bool (C++0x [conv]p3).
5592 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5593   if (checkPlaceholderForOverload(*this, From))
5594     return ExprError();
5595 
5596   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5597   if (!ICS.isBad())
5598     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5599 
5600   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5601     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5602            << From->getType() << From->getSourceRange();
5603   return ExprError();
5604 }
5605 
5606 /// Check that the specified conversion is permitted in a converted constant
5607 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5608 /// is acceptable.
5609 static bool CheckConvertedConstantConversions(Sema &S,
5610                                               StandardConversionSequence &SCS) {
5611   // Since we know that the target type is an integral or unscoped enumeration
5612   // type, most conversion kinds are impossible. All possible First and Third
5613   // conversions are fine.
5614   switch (SCS.Second) {
5615   case ICK_Identity:
5616   case ICK_Integral_Promotion:
5617   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5618   case ICK_Zero_Queue_Conversion:
5619     return true;
5620 
5621   case ICK_Boolean_Conversion:
5622     // Conversion from an integral or unscoped enumeration type to bool is
5623     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5624     // conversion, so we allow it in a converted constant expression.
5625     //
5626     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5627     // a lot of popular code. We should at least add a warning for this
5628     // (non-conforming) extension.
5629     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5630            SCS.getToType(2)->isBooleanType();
5631 
5632   case ICK_Pointer_Conversion:
5633   case ICK_Pointer_Member:
5634     // C++1z: null pointer conversions and null member pointer conversions are
5635     // only permitted if the source type is std::nullptr_t.
5636     return SCS.getFromType()->isNullPtrType();
5637 
5638   case ICK_Floating_Promotion:
5639   case ICK_Complex_Promotion:
5640   case ICK_Floating_Conversion:
5641   case ICK_Complex_Conversion:
5642   case ICK_Floating_Integral:
5643   case ICK_Compatible_Conversion:
5644   case ICK_Derived_To_Base:
5645   case ICK_Vector_Conversion:
5646   case ICK_SVE_Vector_Conversion:
5647   case ICK_Vector_Splat:
5648   case ICK_Complex_Real:
5649   case ICK_Block_Pointer_Conversion:
5650   case ICK_TransparentUnionConversion:
5651   case ICK_Writeback_Conversion:
5652   case ICK_Zero_Event_Conversion:
5653   case ICK_C_Only_Conversion:
5654   case ICK_Incompatible_Pointer_Conversion:
5655     return false;
5656 
5657   case ICK_Lvalue_To_Rvalue:
5658   case ICK_Array_To_Pointer:
5659   case ICK_Function_To_Pointer:
5660     llvm_unreachable("found a first conversion kind in Second");
5661 
5662   case ICK_Function_Conversion:
5663   case ICK_Qualification:
5664     llvm_unreachable("found a third conversion kind in Second");
5665 
5666   case ICK_Num_Conversion_Kinds:
5667     break;
5668   }
5669 
5670   llvm_unreachable("unknown conversion kind");
5671 }
5672 
5673 /// CheckConvertedConstantExpression - Check that the expression From is a
5674 /// converted constant expression of type T, perform the conversion and produce
5675 /// the converted expression, per C++11 [expr.const]p3.
5676 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5677                                                    QualType T, APValue &Value,
5678                                                    Sema::CCEKind CCE,
5679                                                    bool RequireInt,
5680                                                    NamedDecl *Dest) {
5681   assert(S.getLangOpts().CPlusPlus11 &&
5682          "converted constant expression outside C++11");
5683 
5684   if (checkPlaceholderForOverload(S, From))
5685     return ExprError();
5686 
5687   // C++1z [expr.const]p3:
5688   //  A converted constant expression of type T is an expression,
5689   //  implicitly converted to type T, where the converted
5690   //  expression is a constant expression and the implicit conversion
5691   //  sequence contains only [... list of conversions ...].
5692   ImplicitConversionSequence ICS =
5693       (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept)
5694           ? TryContextuallyConvertToBool(S, From)
5695           : TryCopyInitialization(S, From, T,
5696                                   /*SuppressUserConversions=*/false,
5697                                   /*InOverloadResolution=*/false,
5698                                   /*AllowObjCWritebackConversion=*/false,
5699                                   /*AllowExplicit=*/false);
5700   StandardConversionSequence *SCS = nullptr;
5701   switch (ICS.getKind()) {
5702   case ImplicitConversionSequence::StandardConversion:
5703     SCS = &ICS.Standard;
5704     break;
5705   case ImplicitConversionSequence::UserDefinedConversion:
5706     if (T->isRecordType())
5707       SCS = &ICS.UserDefined.Before;
5708     else
5709       SCS = &ICS.UserDefined.After;
5710     break;
5711   case ImplicitConversionSequence::AmbiguousConversion:
5712   case ImplicitConversionSequence::BadConversion:
5713     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5714       return S.Diag(From->getBeginLoc(),
5715                     diag::err_typecheck_converted_constant_expression)
5716              << From->getType() << From->getSourceRange() << T;
5717     return ExprError();
5718 
5719   case ImplicitConversionSequence::EllipsisConversion:
5720     llvm_unreachable("ellipsis conversion in converted constant expression");
5721   }
5722 
5723   // Check that we would only use permitted conversions.
5724   if (!CheckConvertedConstantConversions(S, *SCS)) {
5725     return S.Diag(From->getBeginLoc(),
5726                   diag::err_typecheck_converted_constant_expression_disallowed)
5727            << From->getType() << From->getSourceRange() << T;
5728   }
5729   // [...] and where the reference binding (if any) binds directly.
5730   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5731     return S.Diag(From->getBeginLoc(),
5732                   diag::err_typecheck_converted_constant_expression_indirect)
5733            << From->getType() << From->getSourceRange() << T;
5734   }
5735 
5736   // Usually we can simply apply the ImplicitConversionSequence we formed
5737   // earlier, but that's not guaranteed to work when initializing an object of
5738   // class type.
5739   ExprResult Result;
5740   if (T->isRecordType()) {
5741     assert(CCE == Sema::CCEK_TemplateArg &&
5742            "unexpected class type converted constant expr");
5743     Result = S.PerformCopyInitialization(
5744         InitializedEntity::InitializeTemplateParameter(
5745             T, cast<NonTypeTemplateParmDecl>(Dest)),
5746         SourceLocation(), From);
5747   } else {
5748     Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5749   }
5750   if (Result.isInvalid())
5751     return Result;
5752 
5753   // C++2a [intro.execution]p5:
5754   //   A full-expression is [...] a constant-expression [...]
5755   Result =
5756       S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5757                             /*DiscardedValue=*/false, /*IsConstexpr=*/true);
5758   if (Result.isInvalid())
5759     return Result;
5760 
5761   // Check for a narrowing implicit conversion.
5762   bool ReturnPreNarrowingValue = false;
5763   APValue PreNarrowingValue;
5764   QualType PreNarrowingType;
5765   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5766                                 PreNarrowingType)) {
5767   case NK_Dependent_Narrowing:
5768     // Implicit conversion to a narrower type, but the expression is
5769     // value-dependent so we can't tell whether it's actually narrowing.
5770   case NK_Variable_Narrowing:
5771     // Implicit conversion to a narrower type, and the value is not a constant
5772     // expression. We'll diagnose this in a moment.
5773   case NK_Not_Narrowing:
5774     break;
5775 
5776   case NK_Constant_Narrowing:
5777     if (CCE == Sema::CCEK_ArrayBound &&
5778         PreNarrowingType->isIntegralOrEnumerationType() &&
5779         PreNarrowingValue.isInt()) {
5780       // Don't diagnose array bound narrowing here; we produce more precise
5781       // errors by allowing the un-narrowed value through.
5782       ReturnPreNarrowingValue = true;
5783       break;
5784     }
5785     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5786         << CCE << /*Constant*/ 1
5787         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5788     break;
5789 
5790   case NK_Type_Narrowing:
5791     // FIXME: It would be better to diagnose that the expression is not a
5792     // constant expression.
5793     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5794         << CCE << /*Constant*/ 0 << From->getType() << T;
5795     break;
5796   }
5797 
5798   if (Result.get()->isValueDependent()) {
5799     Value = APValue();
5800     return Result;
5801   }
5802 
5803   // Check the expression is a constant expression.
5804   SmallVector<PartialDiagnosticAt, 8> Notes;
5805   Expr::EvalResult Eval;
5806   Eval.Diag = &Notes;
5807 
5808   ConstantExprKind Kind;
5809   if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
5810     Kind = ConstantExprKind::ClassTemplateArgument;
5811   else if (CCE == Sema::CCEK_TemplateArg)
5812     Kind = ConstantExprKind::NonClassTemplateArgument;
5813   else
5814     Kind = ConstantExprKind::Normal;
5815 
5816   if (!Result.get()->EvaluateAsConstantExpr(Eval, S.Context, Kind) ||
5817       (RequireInt && !Eval.Val.isInt())) {
5818     // The expression can't be folded, so we can't keep it at this position in
5819     // the AST.
5820     Result = ExprError();
5821   } else {
5822     Value = Eval.Val;
5823 
5824     if (Notes.empty()) {
5825       // It's a constant expression.
5826       Expr *E = ConstantExpr::Create(S.Context, Result.get(), Value);
5827       if (ReturnPreNarrowingValue)
5828         Value = std::move(PreNarrowingValue);
5829       return E;
5830     }
5831   }
5832 
5833   // It's not a constant expression. Produce an appropriate diagnostic.
5834   if (Notes.size() == 1 &&
5835       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
5836     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5837   } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
5838                                    diag::note_constexpr_invalid_template_arg) {
5839     Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
5840     for (unsigned I = 0; I < Notes.size(); ++I)
5841       S.Diag(Notes[I].first, Notes[I].second);
5842   } else {
5843     S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5844         << CCE << From->getSourceRange();
5845     for (unsigned I = 0; I < Notes.size(); ++I)
5846       S.Diag(Notes[I].first, Notes[I].second);
5847   }
5848   return ExprError();
5849 }
5850 
5851 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5852                                                   APValue &Value, CCEKind CCE,
5853                                                   NamedDecl *Dest) {
5854   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
5855                                             Dest);
5856 }
5857 
5858 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5859                                                   llvm::APSInt &Value,
5860                                                   CCEKind CCE) {
5861   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5862 
5863   APValue V;
5864   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
5865                                               /*Dest=*/nullptr);
5866   if (!R.isInvalid() && !R.get()->isValueDependent())
5867     Value = V.getInt();
5868   return R;
5869 }
5870 
5871 
5872 /// dropPointerConversions - If the given standard conversion sequence
5873 /// involves any pointer conversions, remove them.  This may change
5874 /// the result type of the conversion sequence.
5875 static void dropPointerConversion(StandardConversionSequence &SCS) {
5876   if (SCS.Second == ICK_Pointer_Conversion) {
5877     SCS.Second = ICK_Identity;
5878     SCS.Third = ICK_Identity;
5879     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5880   }
5881 }
5882 
5883 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5884 /// convert the expression From to an Objective-C pointer type.
5885 static ImplicitConversionSequence
5886 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5887   // Do an implicit conversion to 'id'.
5888   QualType Ty = S.Context.getObjCIdType();
5889   ImplicitConversionSequence ICS
5890     = TryImplicitConversion(S, From, Ty,
5891                             // FIXME: Are these flags correct?
5892                             /*SuppressUserConversions=*/false,
5893                             AllowedExplicit::Conversions,
5894                             /*InOverloadResolution=*/false,
5895                             /*CStyle=*/false,
5896                             /*AllowObjCWritebackConversion=*/false,
5897                             /*AllowObjCConversionOnExplicit=*/true);
5898 
5899   // Strip off any final conversions to 'id'.
5900   switch (ICS.getKind()) {
5901   case ImplicitConversionSequence::BadConversion:
5902   case ImplicitConversionSequence::AmbiguousConversion:
5903   case ImplicitConversionSequence::EllipsisConversion:
5904     break;
5905 
5906   case ImplicitConversionSequence::UserDefinedConversion:
5907     dropPointerConversion(ICS.UserDefined.After);
5908     break;
5909 
5910   case ImplicitConversionSequence::StandardConversion:
5911     dropPointerConversion(ICS.Standard);
5912     break;
5913   }
5914 
5915   return ICS;
5916 }
5917 
5918 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5919 /// conversion of the expression From to an Objective-C pointer type.
5920 /// Returns a valid but null ExprResult if no conversion sequence exists.
5921 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5922   if (checkPlaceholderForOverload(*this, From))
5923     return ExprError();
5924 
5925   QualType Ty = Context.getObjCIdType();
5926   ImplicitConversionSequence ICS =
5927     TryContextuallyConvertToObjCPointer(*this, From);
5928   if (!ICS.isBad())
5929     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5930   return ExprResult();
5931 }
5932 
5933 /// Determine whether the provided type is an integral type, or an enumeration
5934 /// type of a permitted flavor.
5935 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5936   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5937                                  : T->isIntegralOrUnscopedEnumerationType();
5938 }
5939 
5940 static ExprResult
5941 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5942                             Sema::ContextualImplicitConverter &Converter,
5943                             QualType T, UnresolvedSetImpl &ViableConversions) {
5944 
5945   if (Converter.Suppress)
5946     return ExprError();
5947 
5948   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5949   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5950     CXXConversionDecl *Conv =
5951         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5952     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5953     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5954   }
5955   return From;
5956 }
5957 
5958 static bool
5959 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5960                            Sema::ContextualImplicitConverter &Converter,
5961                            QualType T, bool HadMultipleCandidates,
5962                            UnresolvedSetImpl &ExplicitConversions) {
5963   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5964     DeclAccessPair Found = ExplicitConversions[0];
5965     CXXConversionDecl *Conversion =
5966         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5967 
5968     // The user probably meant to invoke the given explicit
5969     // conversion; use it.
5970     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5971     std::string TypeStr;
5972     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5973 
5974     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5975         << FixItHint::CreateInsertion(From->getBeginLoc(),
5976                                       "static_cast<" + TypeStr + ">(")
5977         << FixItHint::CreateInsertion(
5978                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5979     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5980 
5981     // If we aren't in a SFINAE context, build a call to the
5982     // explicit conversion function.
5983     if (SemaRef.isSFINAEContext())
5984       return true;
5985 
5986     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5987     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5988                                                        HadMultipleCandidates);
5989     if (Result.isInvalid())
5990       return true;
5991     // Record usage of conversion in an implicit cast.
5992     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5993                                     CK_UserDefinedConversion, Result.get(),
5994                                     nullptr, Result.get()->getValueKind(),
5995                                     SemaRef.CurFPFeatureOverrides());
5996   }
5997   return false;
5998 }
5999 
6000 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6001                              Sema::ContextualImplicitConverter &Converter,
6002                              QualType T, bool HadMultipleCandidates,
6003                              DeclAccessPair &Found) {
6004   CXXConversionDecl *Conversion =
6005       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6006   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6007 
6008   QualType ToType = Conversion->getConversionType().getNonReferenceType();
6009   if (!Converter.SuppressConversion) {
6010     if (SemaRef.isSFINAEContext())
6011       return true;
6012 
6013     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6014         << From->getSourceRange();
6015   }
6016 
6017   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6018                                                      HadMultipleCandidates);
6019   if (Result.isInvalid())
6020     return true;
6021   // Record usage of conversion in an implicit cast.
6022   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6023                                   CK_UserDefinedConversion, Result.get(),
6024                                   nullptr, Result.get()->getValueKind(),
6025                                   SemaRef.CurFPFeatureOverrides());
6026   return false;
6027 }
6028 
6029 static ExprResult finishContextualImplicitConversion(
6030     Sema &SemaRef, SourceLocation Loc, Expr *From,
6031     Sema::ContextualImplicitConverter &Converter) {
6032   if (!Converter.match(From->getType()) && !Converter.Suppress)
6033     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6034         << From->getSourceRange();
6035 
6036   return SemaRef.DefaultLvalueConversion(From);
6037 }
6038 
6039 static void
6040 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
6041                                   UnresolvedSetImpl &ViableConversions,
6042                                   OverloadCandidateSet &CandidateSet) {
6043   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6044     DeclAccessPair FoundDecl = ViableConversions[I];
6045     NamedDecl *D = FoundDecl.getDecl();
6046     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6047     if (isa<UsingShadowDecl>(D))
6048       D = cast<UsingShadowDecl>(D)->getTargetDecl();
6049 
6050     CXXConversionDecl *Conv;
6051     FunctionTemplateDecl *ConvTemplate;
6052     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
6053       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6054     else
6055       Conv = cast<CXXConversionDecl>(D);
6056 
6057     if (ConvTemplate)
6058       SemaRef.AddTemplateConversionCandidate(
6059           ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6060           /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
6061     else
6062       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
6063                                      ToType, CandidateSet,
6064                                      /*AllowObjCConversionOnExplicit=*/false,
6065                                      /*AllowExplicit*/ true);
6066   }
6067 }
6068 
6069 /// Attempt to convert the given expression to a type which is accepted
6070 /// by the given converter.
6071 ///
6072 /// This routine will attempt to convert an expression of class type to a
6073 /// type accepted by the specified converter. In C++11 and before, the class
6074 /// must have a single non-explicit conversion function converting to a matching
6075 /// type. In C++1y, there can be multiple such conversion functions, but only
6076 /// one target type.
6077 ///
6078 /// \param Loc The source location of the construct that requires the
6079 /// conversion.
6080 ///
6081 /// \param From The expression we're converting from.
6082 ///
6083 /// \param Converter Used to control and diagnose the conversion process.
6084 ///
6085 /// \returns The expression, converted to an integral or enumeration type if
6086 /// successful.
6087 ExprResult Sema::PerformContextualImplicitConversion(
6088     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6089   // We can't perform any more checking for type-dependent expressions.
6090   if (From->isTypeDependent())
6091     return From;
6092 
6093   // Process placeholders immediately.
6094   if (From->hasPlaceholderType()) {
6095     ExprResult result = CheckPlaceholderExpr(From);
6096     if (result.isInvalid())
6097       return result;
6098     From = result.get();
6099   }
6100 
6101   // If the expression already has a matching type, we're golden.
6102   QualType T = From->getType();
6103   if (Converter.match(T))
6104     return DefaultLvalueConversion(From);
6105 
6106   // FIXME: Check for missing '()' if T is a function type?
6107 
6108   // We can only perform contextual implicit conversions on objects of class
6109   // type.
6110   const RecordType *RecordTy = T->getAs<RecordType>();
6111   if (!RecordTy || !getLangOpts().CPlusPlus) {
6112     if (!Converter.Suppress)
6113       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6114     return From;
6115   }
6116 
6117   // We must have a complete class type.
6118   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6119     ContextualImplicitConverter &Converter;
6120     Expr *From;
6121 
6122     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6123         : Converter(Converter), From(From) {}
6124 
6125     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6126       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6127     }
6128   } IncompleteDiagnoser(Converter, From);
6129 
6130   if (Converter.Suppress ? !isCompleteType(Loc, T)
6131                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6132     return From;
6133 
6134   // Look for a conversion to an integral or enumeration type.
6135   UnresolvedSet<4>
6136       ViableConversions; // These are *potentially* viable in C++1y.
6137   UnresolvedSet<4> ExplicitConversions;
6138   const auto &Conversions =
6139       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
6140 
6141   bool HadMultipleCandidates =
6142       (std::distance(Conversions.begin(), Conversions.end()) > 1);
6143 
6144   // To check that there is only one target type, in C++1y:
6145   QualType ToType;
6146   bool HasUniqueTargetType = true;
6147 
6148   // Collect explicit or viable (potentially in C++1y) conversions.
6149   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6150     NamedDecl *D = (*I)->getUnderlyingDecl();
6151     CXXConversionDecl *Conversion;
6152     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6153     if (ConvTemplate) {
6154       if (getLangOpts().CPlusPlus14)
6155         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6156       else
6157         continue; // C++11 does not consider conversion operator templates(?).
6158     } else
6159       Conversion = cast<CXXConversionDecl>(D);
6160 
6161     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6162            "Conversion operator templates are considered potentially "
6163            "viable in C++1y");
6164 
6165     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6166     if (Converter.match(CurToType) || ConvTemplate) {
6167 
6168       if (Conversion->isExplicit()) {
6169         // FIXME: For C++1y, do we need this restriction?
6170         // cf. diagnoseNoViableConversion()
6171         if (!ConvTemplate)
6172           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6173       } else {
6174         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6175           if (ToType.isNull())
6176             ToType = CurToType.getUnqualifiedType();
6177           else if (HasUniqueTargetType &&
6178                    (CurToType.getUnqualifiedType() != ToType))
6179             HasUniqueTargetType = false;
6180         }
6181         ViableConversions.addDecl(I.getDecl(), I.getAccess());
6182       }
6183     }
6184   }
6185 
6186   if (getLangOpts().CPlusPlus14) {
6187     // C++1y [conv]p6:
6188     // ... An expression e of class type E appearing in such a context
6189     // is said to be contextually implicitly converted to a specified
6190     // type T and is well-formed if and only if e can be implicitly
6191     // converted to a type T that is determined as follows: E is searched
6192     // for conversion functions whose return type is cv T or reference to
6193     // cv T such that T is allowed by the context. There shall be
6194     // exactly one such T.
6195 
6196     // If no unique T is found:
6197     if (ToType.isNull()) {
6198       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6199                                      HadMultipleCandidates,
6200                                      ExplicitConversions))
6201         return ExprError();
6202       return finishContextualImplicitConversion(*this, Loc, From, Converter);
6203     }
6204 
6205     // If more than one unique Ts are found:
6206     if (!HasUniqueTargetType)
6207       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6208                                          ViableConversions);
6209 
6210     // If one unique T is found:
6211     // First, build a candidate set from the previously recorded
6212     // potentially viable conversions.
6213     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6214     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6215                                       CandidateSet);
6216 
6217     // Then, perform overload resolution over the candidate set.
6218     OverloadCandidateSet::iterator Best;
6219     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6220     case OR_Success: {
6221       // Apply this conversion.
6222       DeclAccessPair Found =
6223           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6224       if (recordConversion(*this, Loc, From, Converter, T,
6225                            HadMultipleCandidates, Found))
6226         return ExprError();
6227       break;
6228     }
6229     case OR_Ambiguous:
6230       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6231                                          ViableConversions);
6232     case OR_No_Viable_Function:
6233       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6234                                      HadMultipleCandidates,
6235                                      ExplicitConversions))
6236         return ExprError();
6237       LLVM_FALLTHROUGH;
6238     case OR_Deleted:
6239       // We'll complain below about a non-integral condition type.
6240       break;
6241     }
6242   } else {
6243     switch (ViableConversions.size()) {
6244     case 0: {
6245       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6246                                      HadMultipleCandidates,
6247                                      ExplicitConversions))
6248         return ExprError();
6249 
6250       // We'll complain below about a non-integral condition type.
6251       break;
6252     }
6253     case 1: {
6254       // Apply this conversion.
6255       DeclAccessPair Found = ViableConversions[0];
6256       if (recordConversion(*this, Loc, From, Converter, T,
6257                            HadMultipleCandidates, Found))
6258         return ExprError();
6259       break;
6260     }
6261     default:
6262       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6263                                          ViableConversions);
6264     }
6265   }
6266 
6267   return finishContextualImplicitConversion(*this, Loc, From, Converter);
6268 }
6269 
6270 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6271 /// an acceptable non-member overloaded operator for a call whose
6272 /// arguments have types T1 (and, if non-empty, T2). This routine
6273 /// implements the check in C++ [over.match.oper]p3b2 concerning
6274 /// enumeration types.
6275 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6276                                                    FunctionDecl *Fn,
6277                                                    ArrayRef<Expr *> Args) {
6278   QualType T1 = Args[0]->getType();
6279   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6280 
6281   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6282     return true;
6283 
6284   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6285     return true;
6286 
6287   const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6288   if (Proto->getNumParams() < 1)
6289     return false;
6290 
6291   if (T1->isEnumeralType()) {
6292     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6293     if (Context.hasSameUnqualifiedType(T1, ArgType))
6294       return true;
6295   }
6296 
6297   if (Proto->getNumParams() < 2)
6298     return false;
6299 
6300   if (!T2.isNull() && T2->isEnumeralType()) {
6301     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6302     if (Context.hasSameUnqualifiedType(T2, ArgType))
6303       return true;
6304   }
6305 
6306   return false;
6307 }
6308 
6309 /// AddOverloadCandidate - Adds the given function to the set of
6310 /// candidate functions, using the given function call arguments.  If
6311 /// @p SuppressUserConversions, then don't allow user-defined
6312 /// conversions via constructors or conversion operators.
6313 ///
6314 /// \param PartialOverloading true if we are performing "partial" overloading
6315 /// based on an incomplete set of function arguments. This feature is used by
6316 /// code completion.
6317 void Sema::AddOverloadCandidate(
6318     FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6319     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6320     bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6321     ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6322     OverloadCandidateParamOrder PO) {
6323   const FunctionProtoType *Proto
6324     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6325   assert(Proto && "Functions without a prototype cannot be overloaded");
6326   assert(!Function->getDescribedFunctionTemplate() &&
6327          "Use AddTemplateOverloadCandidate for function templates");
6328 
6329   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6330     if (!isa<CXXConstructorDecl>(Method)) {
6331       // If we get here, it's because we're calling a member function
6332       // that is named without a member access expression (e.g.,
6333       // "this->f") that was either written explicitly or created
6334       // implicitly. This can happen with a qualified call to a member
6335       // function, e.g., X::f(). We use an empty type for the implied
6336       // object argument (C++ [over.call.func]p3), and the acting context
6337       // is irrelevant.
6338       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6339                          Expr::Classification::makeSimpleLValue(), Args,
6340                          CandidateSet, SuppressUserConversions,
6341                          PartialOverloading, EarlyConversions, PO);
6342       return;
6343     }
6344     // We treat a constructor like a non-member function, since its object
6345     // argument doesn't participate in overload resolution.
6346   }
6347 
6348   if (!CandidateSet.isNewCandidate(Function, PO))
6349     return;
6350 
6351   // C++11 [class.copy]p11: [DR1402]
6352   //   A defaulted move constructor that is defined as deleted is ignored by
6353   //   overload resolution.
6354   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6355   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6356       Constructor->isMoveConstructor())
6357     return;
6358 
6359   // Overload resolution is always an unevaluated context.
6360   EnterExpressionEvaluationContext Unevaluated(
6361       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6362 
6363   // C++ [over.match.oper]p3:
6364   //   if no operand has a class type, only those non-member functions in the
6365   //   lookup set that have a first parameter of type T1 or "reference to
6366   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6367   //   is a right operand) a second parameter of type T2 or "reference to
6368   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
6369   //   candidate functions.
6370   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6371       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6372     return;
6373 
6374   // Add this candidate
6375   OverloadCandidate &Candidate =
6376       CandidateSet.addCandidate(Args.size(), EarlyConversions);
6377   Candidate.FoundDecl = FoundDecl;
6378   Candidate.Function = Function;
6379   Candidate.Viable = true;
6380   Candidate.RewriteKind =
6381       CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6382   Candidate.IsSurrogate = false;
6383   Candidate.IsADLCandidate = IsADLCandidate;
6384   Candidate.IgnoreObjectArgument = false;
6385   Candidate.ExplicitCallArguments = Args.size();
6386 
6387   // Explicit functions are not actually candidates at all if we're not
6388   // allowing them in this context, but keep them around so we can point
6389   // to them in diagnostics.
6390   if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6391     Candidate.Viable = false;
6392     Candidate.FailureKind = ovl_fail_explicit;
6393     return;
6394   }
6395 
6396   if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6397       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6398     Candidate.Viable = false;
6399     Candidate.FailureKind = ovl_non_default_multiversion_function;
6400     return;
6401   }
6402 
6403   if (Constructor) {
6404     // C++ [class.copy]p3:
6405     //   A member function template is never instantiated to perform the copy
6406     //   of a class object to an object of its class type.
6407     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6408     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6409         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6410          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6411                        ClassType))) {
6412       Candidate.Viable = false;
6413       Candidate.FailureKind = ovl_fail_illegal_constructor;
6414       return;
6415     }
6416 
6417     // C++ [over.match.funcs]p8: (proposed DR resolution)
6418     //   A constructor inherited from class type C that has a first parameter
6419     //   of type "reference to P" (including such a constructor instantiated
6420     //   from a template) is excluded from the set of candidate functions when
6421     //   constructing an object of type cv D if the argument list has exactly
6422     //   one argument and D is reference-related to P and P is reference-related
6423     //   to C.
6424     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6425     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6426         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6427       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6428       QualType C = Context.getRecordType(Constructor->getParent());
6429       QualType D = Context.getRecordType(Shadow->getParent());
6430       SourceLocation Loc = Args.front()->getExprLoc();
6431       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6432           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6433         Candidate.Viable = false;
6434         Candidate.FailureKind = ovl_fail_inhctor_slice;
6435         return;
6436       }
6437     }
6438 
6439     // Check that the constructor is capable of constructing an object in the
6440     // destination address space.
6441     if (!Qualifiers::isAddressSpaceSupersetOf(
6442             Constructor->getMethodQualifiers().getAddressSpace(),
6443             CandidateSet.getDestAS())) {
6444       Candidate.Viable = false;
6445       Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6446     }
6447   }
6448 
6449   unsigned NumParams = Proto->getNumParams();
6450 
6451   // (C++ 13.3.2p2): A candidate function having fewer than m
6452   // parameters is viable only if it has an ellipsis in its parameter
6453   // list (8.3.5).
6454   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6455       !Proto->isVariadic() &&
6456       shouldEnforceArgLimit(PartialOverloading, Function)) {
6457     Candidate.Viable = false;
6458     Candidate.FailureKind = ovl_fail_too_many_arguments;
6459     return;
6460   }
6461 
6462   // (C++ 13.3.2p2): A candidate function having more than m parameters
6463   // is viable only if the (m+1)st parameter has a default argument
6464   // (8.3.6). For the purposes of overload resolution, the
6465   // parameter list is truncated on the right, so that there are
6466   // exactly m parameters.
6467   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6468   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6469     // Not enough arguments.
6470     Candidate.Viable = false;
6471     Candidate.FailureKind = ovl_fail_too_few_arguments;
6472     return;
6473   }
6474 
6475   // (CUDA B.1): Check for invalid calls between targets.
6476   if (getLangOpts().CUDA)
6477     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6478       // Skip the check for callers that are implicit members, because in this
6479       // case we may not yet know what the member's target is; the target is
6480       // inferred for the member automatically, based on the bases and fields of
6481       // the class.
6482       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6483         Candidate.Viable = false;
6484         Candidate.FailureKind = ovl_fail_bad_target;
6485         return;
6486       }
6487 
6488   if (Function->getTrailingRequiresClause()) {
6489     ConstraintSatisfaction Satisfaction;
6490     if (CheckFunctionConstraints(Function, Satisfaction) ||
6491         !Satisfaction.IsSatisfied) {
6492       Candidate.Viable = false;
6493       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6494       return;
6495     }
6496   }
6497 
6498   // Determine the implicit conversion sequences for each of the
6499   // arguments.
6500   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6501     unsigned ConvIdx =
6502         PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6503     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6504       // We already formed a conversion sequence for this parameter during
6505       // template argument deduction.
6506     } else if (ArgIdx < NumParams) {
6507       // (C++ 13.3.2p3): for F to be a viable function, there shall
6508       // exist for each argument an implicit conversion sequence
6509       // (13.3.3.1) that converts that argument to the corresponding
6510       // parameter of F.
6511       QualType ParamType = Proto->getParamType(ArgIdx);
6512       Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6513           *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6514           /*InOverloadResolution=*/true,
6515           /*AllowObjCWritebackConversion=*/
6516           getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6517       if (Candidate.Conversions[ConvIdx].isBad()) {
6518         Candidate.Viable = false;
6519         Candidate.FailureKind = ovl_fail_bad_conversion;
6520         return;
6521       }
6522     } else {
6523       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6524       // argument for which there is no corresponding parameter is
6525       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6526       Candidate.Conversions[ConvIdx].setEllipsis();
6527     }
6528   }
6529 
6530   if (EnableIfAttr *FailedAttr =
6531           CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
6532     Candidate.Viable = false;
6533     Candidate.FailureKind = ovl_fail_enable_if;
6534     Candidate.DeductionFailure.Data = FailedAttr;
6535     return;
6536   }
6537 }
6538 
6539 ObjCMethodDecl *
6540 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6541                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6542   if (Methods.size() <= 1)
6543     return nullptr;
6544 
6545   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6546     bool Match = true;
6547     ObjCMethodDecl *Method = Methods[b];
6548     unsigned NumNamedArgs = Sel.getNumArgs();
6549     // Method might have more arguments than selector indicates. This is due
6550     // to addition of c-style arguments in method.
6551     if (Method->param_size() > NumNamedArgs)
6552       NumNamedArgs = Method->param_size();
6553     if (Args.size() < NumNamedArgs)
6554       continue;
6555 
6556     for (unsigned i = 0; i < NumNamedArgs; i++) {
6557       // We can't do any type-checking on a type-dependent argument.
6558       if (Args[i]->isTypeDependent()) {
6559         Match = false;
6560         break;
6561       }
6562 
6563       ParmVarDecl *param = Method->parameters()[i];
6564       Expr *argExpr = Args[i];
6565       assert(argExpr && "SelectBestMethod(): missing expression");
6566 
6567       // Strip the unbridged-cast placeholder expression off unless it's
6568       // a consumed argument.
6569       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6570           !param->hasAttr<CFConsumedAttr>())
6571         argExpr = stripARCUnbridgedCast(argExpr);
6572 
6573       // If the parameter is __unknown_anytype, move on to the next method.
6574       if (param->getType() == Context.UnknownAnyTy) {
6575         Match = false;
6576         break;
6577       }
6578 
6579       ImplicitConversionSequence ConversionState
6580         = TryCopyInitialization(*this, argExpr, param->getType(),
6581                                 /*SuppressUserConversions*/false,
6582                                 /*InOverloadResolution=*/true,
6583                                 /*AllowObjCWritebackConversion=*/
6584                                 getLangOpts().ObjCAutoRefCount,
6585                                 /*AllowExplicit*/false);
6586       // This function looks for a reasonably-exact match, so we consider
6587       // incompatible pointer conversions to be a failure here.
6588       if (ConversionState.isBad() ||
6589           (ConversionState.isStandard() &&
6590            ConversionState.Standard.Second ==
6591                ICK_Incompatible_Pointer_Conversion)) {
6592         Match = false;
6593         break;
6594       }
6595     }
6596     // Promote additional arguments to variadic methods.
6597     if (Match && Method->isVariadic()) {
6598       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6599         if (Args[i]->isTypeDependent()) {
6600           Match = false;
6601           break;
6602         }
6603         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6604                                                           nullptr);
6605         if (Arg.isInvalid()) {
6606           Match = false;
6607           break;
6608         }
6609       }
6610     } else {
6611       // Check for extra arguments to non-variadic methods.
6612       if (Args.size() != NumNamedArgs)
6613         Match = false;
6614       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6615         // Special case when selectors have no argument. In this case, select
6616         // one with the most general result type of 'id'.
6617         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6618           QualType ReturnT = Methods[b]->getReturnType();
6619           if (ReturnT->isObjCIdType())
6620             return Methods[b];
6621         }
6622       }
6623     }
6624 
6625     if (Match)
6626       return Method;
6627   }
6628   return nullptr;
6629 }
6630 
6631 static bool convertArgsForAvailabilityChecks(
6632     Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
6633     ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
6634     Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
6635   if (ThisArg) {
6636     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6637     assert(!isa<CXXConstructorDecl>(Method) &&
6638            "Shouldn't have `this` for ctors!");
6639     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6640     ExprResult R = S.PerformObjectArgumentInitialization(
6641         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6642     if (R.isInvalid())
6643       return false;
6644     ConvertedThis = R.get();
6645   } else {
6646     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6647       (void)MD;
6648       assert((MissingImplicitThis || MD->isStatic() ||
6649               isa<CXXConstructorDecl>(MD)) &&
6650              "Expected `this` for non-ctor instance methods");
6651     }
6652     ConvertedThis = nullptr;
6653   }
6654 
6655   // Ignore any variadic arguments. Converting them is pointless, since the
6656   // user can't refer to them in the function condition.
6657   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6658 
6659   // Convert the arguments.
6660   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6661     ExprResult R;
6662     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6663                                         S.Context, Function->getParamDecl(I)),
6664                                     SourceLocation(), Args[I]);
6665 
6666     if (R.isInvalid())
6667       return false;
6668 
6669     ConvertedArgs.push_back(R.get());
6670   }
6671 
6672   if (Trap.hasErrorOccurred())
6673     return false;
6674 
6675   // Push default arguments if needed.
6676   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6677     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6678       ParmVarDecl *P = Function->getParamDecl(i);
6679       if (!P->hasDefaultArg())
6680         return false;
6681       ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
6682       if (R.isInvalid())
6683         return false;
6684       ConvertedArgs.push_back(R.get());
6685     }
6686 
6687     if (Trap.hasErrorOccurred())
6688       return false;
6689   }
6690   return true;
6691 }
6692 
6693 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
6694                                   SourceLocation CallLoc,
6695                                   ArrayRef<Expr *> Args,
6696                                   bool MissingImplicitThis) {
6697   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6698   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6699     return nullptr;
6700 
6701   SFINAETrap Trap(*this);
6702   SmallVector<Expr *, 16> ConvertedArgs;
6703   // FIXME: We should look into making enable_if late-parsed.
6704   Expr *DiscardedThis;
6705   if (!convertArgsForAvailabilityChecks(
6706           *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
6707           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6708     return *EnableIfAttrs.begin();
6709 
6710   for (auto *EIA : EnableIfAttrs) {
6711     APValue Result;
6712     // FIXME: This doesn't consider value-dependent cases, because doing so is
6713     // very difficult. Ideally, we should handle them more gracefully.
6714     if (EIA->getCond()->isValueDependent() ||
6715         !EIA->getCond()->EvaluateWithSubstitution(
6716             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6717       return EIA;
6718 
6719     if (!Result.isInt() || !Result.getInt().getBoolValue())
6720       return EIA;
6721   }
6722   return nullptr;
6723 }
6724 
6725 template <typename CheckFn>
6726 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6727                                         bool ArgDependent, SourceLocation Loc,
6728                                         CheckFn &&IsSuccessful) {
6729   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6730   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6731     if (ArgDependent == DIA->getArgDependent())
6732       Attrs.push_back(DIA);
6733   }
6734 
6735   // Common case: No diagnose_if attributes, so we can quit early.
6736   if (Attrs.empty())
6737     return false;
6738 
6739   auto WarningBegin = std::stable_partition(
6740       Attrs.begin(), Attrs.end(),
6741       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6742 
6743   // Note that diagnose_if attributes are late-parsed, so they appear in the
6744   // correct order (unlike enable_if attributes).
6745   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6746                                IsSuccessful);
6747   if (ErrAttr != WarningBegin) {
6748     const DiagnoseIfAttr *DIA = *ErrAttr;
6749     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6750     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6751         << DIA->getParent() << DIA->getCond()->getSourceRange();
6752     return true;
6753   }
6754 
6755   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6756     if (IsSuccessful(DIA)) {
6757       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6758       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6759           << DIA->getParent() << DIA->getCond()->getSourceRange();
6760     }
6761 
6762   return false;
6763 }
6764 
6765 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6766                                                const Expr *ThisArg,
6767                                                ArrayRef<const Expr *> Args,
6768                                                SourceLocation Loc) {
6769   return diagnoseDiagnoseIfAttrsWith(
6770       *this, Function, /*ArgDependent=*/true, Loc,
6771       [&](const DiagnoseIfAttr *DIA) {
6772         APValue Result;
6773         // It's sane to use the same Args for any redecl of this function, since
6774         // EvaluateWithSubstitution only cares about the position of each
6775         // argument in the arg list, not the ParmVarDecl* it maps to.
6776         if (!DIA->getCond()->EvaluateWithSubstitution(
6777                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6778           return false;
6779         return Result.isInt() && Result.getInt().getBoolValue();
6780       });
6781 }
6782 
6783 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6784                                                  SourceLocation Loc) {
6785   return diagnoseDiagnoseIfAttrsWith(
6786       *this, ND, /*ArgDependent=*/false, Loc,
6787       [&](const DiagnoseIfAttr *DIA) {
6788         bool Result;
6789         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6790                Result;
6791       });
6792 }
6793 
6794 /// Add all of the function declarations in the given function set to
6795 /// the overload candidate set.
6796 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6797                                  ArrayRef<Expr *> Args,
6798                                  OverloadCandidateSet &CandidateSet,
6799                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6800                                  bool SuppressUserConversions,
6801                                  bool PartialOverloading,
6802                                  bool FirstArgumentIsBase) {
6803   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6804     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6805     ArrayRef<Expr *> FunctionArgs = Args;
6806 
6807     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6808     FunctionDecl *FD =
6809         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6810 
6811     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6812       QualType ObjectType;
6813       Expr::Classification ObjectClassification;
6814       if (Args.size() > 0) {
6815         if (Expr *E = Args[0]) {
6816           // Use the explicit base to restrict the lookup:
6817           ObjectType = E->getType();
6818           // Pointers in the object arguments are implicitly dereferenced, so we
6819           // always classify them as l-values.
6820           if (!ObjectType.isNull() && ObjectType->isPointerType())
6821             ObjectClassification = Expr::Classification::makeSimpleLValue();
6822           else
6823             ObjectClassification = E->Classify(Context);
6824         } // .. else there is an implicit base.
6825         FunctionArgs = Args.slice(1);
6826       }
6827       if (FunTmpl) {
6828         AddMethodTemplateCandidate(
6829             FunTmpl, F.getPair(),
6830             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6831             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6832             FunctionArgs, CandidateSet, SuppressUserConversions,
6833             PartialOverloading);
6834       } else {
6835         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6836                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6837                            ObjectClassification, FunctionArgs, CandidateSet,
6838                            SuppressUserConversions, PartialOverloading);
6839       }
6840     } else {
6841       // This branch handles both standalone functions and static methods.
6842 
6843       // Slice the first argument (which is the base) when we access
6844       // static method as non-static.
6845       if (Args.size() > 0 &&
6846           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6847                         !isa<CXXConstructorDecl>(FD)))) {
6848         assert(cast<CXXMethodDecl>(FD)->isStatic());
6849         FunctionArgs = Args.slice(1);
6850       }
6851       if (FunTmpl) {
6852         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6853                                      ExplicitTemplateArgs, FunctionArgs,
6854                                      CandidateSet, SuppressUserConversions,
6855                                      PartialOverloading);
6856       } else {
6857         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6858                              SuppressUserConversions, PartialOverloading);
6859       }
6860     }
6861   }
6862 }
6863 
6864 /// AddMethodCandidate - Adds a named decl (which is some kind of
6865 /// method) as a method candidate to the given overload set.
6866 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
6867                               Expr::Classification ObjectClassification,
6868                               ArrayRef<Expr *> Args,
6869                               OverloadCandidateSet &CandidateSet,
6870                               bool SuppressUserConversions,
6871                               OverloadCandidateParamOrder PO) {
6872   NamedDecl *Decl = FoundDecl.getDecl();
6873   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6874 
6875   if (isa<UsingShadowDecl>(Decl))
6876     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6877 
6878   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6879     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6880            "Expected a member function template");
6881     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6882                                /*ExplicitArgs*/ nullptr, ObjectType,
6883                                ObjectClassification, Args, CandidateSet,
6884                                SuppressUserConversions, false, PO);
6885   } else {
6886     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6887                        ObjectType, ObjectClassification, Args, CandidateSet,
6888                        SuppressUserConversions, false, None, PO);
6889   }
6890 }
6891 
6892 /// AddMethodCandidate - Adds the given C++ member function to the set
6893 /// of candidate functions, using the given function call arguments
6894 /// and the object argument (@c Object). For example, in a call
6895 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6896 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6897 /// allow user-defined conversions via constructors or conversion
6898 /// operators.
6899 void
6900 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6901                          CXXRecordDecl *ActingContext, QualType ObjectType,
6902                          Expr::Classification ObjectClassification,
6903                          ArrayRef<Expr *> Args,
6904                          OverloadCandidateSet &CandidateSet,
6905                          bool SuppressUserConversions,
6906                          bool PartialOverloading,
6907                          ConversionSequenceList EarlyConversions,
6908                          OverloadCandidateParamOrder PO) {
6909   const FunctionProtoType *Proto
6910     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6911   assert(Proto && "Methods without a prototype cannot be overloaded");
6912   assert(!isa<CXXConstructorDecl>(Method) &&
6913          "Use AddOverloadCandidate for constructors");
6914 
6915   if (!CandidateSet.isNewCandidate(Method, PO))
6916     return;
6917 
6918   // C++11 [class.copy]p23: [DR1402]
6919   //   A defaulted move assignment operator that is defined as deleted is
6920   //   ignored by overload resolution.
6921   if (Method->isDefaulted() && Method->isDeleted() &&
6922       Method->isMoveAssignmentOperator())
6923     return;
6924 
6925   // Overload resolution is always an unevaluated context.
6926   EnterExpressionEvaluationContext Unevaluated(
6927       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6928 
6929   // Add this candidate
6930   OverloadCandidate &Candidate =
6931       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6932   Candidate.FoundDecl = FoundDecl;
6933   Candidate.Function = Method;
6934   Candidate.RewriteKind =
6935       CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
6936   Candidate.IsSurrogate = false;
6937   Candidate.IgnoreObjectArgument = false;
6938   Candidate.ExplicitCallArguments = Args.size();
6939 
6940   unsigned NumParams = Proto->getNumParams();
6941 
6942   // (C++ 13.3.2p2): A candidate function having fewer than m
6943   // parameters is viable only if it has an ellipsis in its parameter
6944   // list (8.3.5).
6945   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6946       !Proto->isVariadic() &&
6947       shouldEnforceArgLimit(PartialOverloading, Method)) {
6948     Candidate.Viable = false;
6949     Candidate.FailureKind = ovl_fail_too_many_arguments;
6950     return;
6951   }
6952 
6953   // (C++ 13.3.2p2): A candidate function having more than m parameters
6954   // is viable only if the (m+1)st parameter has a default argument
6955   // (8.3.6). For the purposes of overload resolution, the
6956   // parameter list is truncated on the right, so that there are
6957   // exactly m parameters.
6958   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6959   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6960     // Not enough arguments.
6961     Candidate.Viable = false;
6962     Candidate.FailureKind = ovl_fail_too_few_arguments;
6963     return;
6964   }
6965 
6966   Candidate.Viable = true;
6967 
6968   if (Method->isStatic() || ObjectType.isNull())
6969     // The implicit object argument is ignored.
6970     Candidate.IgnoreObjectArgument = true;
6971   else {
6972     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
6973     // Determine the implicit conversion sequence for the object
6974     // parameter.
6975     Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization(
6976         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6977         Method, ActingContext);
6978     if (Candidate.Conversions[ConvIdx].isBad()) {
6979       Candidate.Viable = false;
6980       Candidate.FailureKind = ovl_fail_bad_conversion;
6981       return;
6982     }
6983   }
6984 
6985   // (CUDA B.1): Check for invalid calls between targets.
6986   if (getLangOpts().CUDA)
6987     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6988       if (!IsAllowedCUDACall(Caller, Method)) {
6989         Candidate.Viable = false;
6990         Candidate.FailureKind = ovl_fail_bad_target;
6991         return;
6992       }
6993 
6994   if (Method->getTrailingRequiresClause()) {
6995     ConstraintSatisfaction Satisfaction;
6996     if (CheckFunctionConstraints(Method, Satisfaction) ||
6997         !Satisfaction.IsSatisfied) {
6998       Candidate.Viable = false;
6999       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7000       return;
7001     }
7002   }
7003 
7004   // Determine the implicit conversion sequences for each of the
7005   // arguments.
7006   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7007     unsigned ConvIdx =
7008         PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
7009     if (Candidate.Conversions[ConvIdx].isInitialized()) {
7010       // We already formed a conversion sequence for this parameter during
7011       // template argument deduction.
7012     } else if (ArgIdx < NumParams) {
7013       // (C++ 13.3.2p3): for F to be a viable function, there shall
7014       // exist for each argument an implicit conversion sequence
7015       // (13.3.3.1) that converts that argument to the corresponding
7016       // parameter of F.
7017       QualType ParamType = Proto->getParamType(ArgIdx);
7018       Candidate.Conversions[ConvIdx]
7019         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7020                                 SuppressUserConversions,
7021                                 /*InOverloadResolution=*/true,
7022                                 /*AllowObjCWritebackConversion=*/
7023                                   getLangOpts().ObjCAutoRefCount);
7024       if (Candidate.Conversions[ConvIdx].isBad()) {
7025         Candidate.Viable = false;
7026         Candidate.FailureKind = ovl_fail_bad_conversion;
7027         return;
7028       }
7029     } else {
7030       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7031       // argument for which there is no corresponding parameter is
7032       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7033       Candidate.Conversions[ConvIdx].setEllipsis();
7034     }
7035   }
7036 
7037   if (EnableIfAttr *FailedAttr =
7038           CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7039     Candidate.Viable = false;
7040     Candidate.FailureKind = ovl_fail_enable_if;
7041     Candidate.DeductionFailure.Data = FailedAttr;
7042     return;
7043   }
7044 
7045   if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
7046       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
7047     Candidate.Viable = false;
7048     Candidate.FailureKind = ovl_non_default_multiversion_function;
7049   }
7050 }
7051 
7052 /// Add a C++ member function template as a candidate to the candidate
7053 /// set, using template argument deduction to produce an appropriate member
7054 /// function template specialization.
7055 void Sema::AddMethodTemplateCandidate(
7056     FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7057     CXXRecordDecl *ActingContext,
7058     TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7059     Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7060     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7061     bool PartialOverloading, OverloadCandidateParamOrder PO) {
7062   if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7063     return;
7064 
7065   // C++ [over.match.funcs]p7:
7066   //   In each case where a candidate is a function template, candidate
7067   //   function template specializations are generated using template argument
7068   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
7069   //   candidate functions in the usual way.113) A given name can refer to one
7070   //   or more function templates and also to a set of overloaded non-template
7071   //   functions. In such a case, the candidate functions generated from each
7072   //   function template are combined with the set of non-template candidate
7073   //   functions.
7074   TemplateDeductionInfo Info(CandidateSet.getLocation());
7075   FunctionDecl *Specialization = nullptr;
7076   ConversionSequenceList Conversions;
7077   if (TemplateDeductionResult Result = DeduceTemplateArguments(
7078           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7079           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7080             return CheckNonDependentConversions(
7081                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7082                 SuppressUserConversions, ActingContext, ObjectType,
7083                 ObjectClassification, PO);
7084           })) {
7085     OverloadCandidate &Candidate =
7086         CandidateSet.addCandidate(Conversions.size(), Conversions);
7087     Candidate.FoundDecl = FoundDecl;
7088     Candidate.Function = MethodTmpl->getTemplatedDecl();
7089     Candidate.Viable = false;
7090     Candidate.RewriteKind =
7091       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7092     Candidate.IsSurrogate = false;
7093     Candidate.IgnoreObjectArgument =
7094         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
7095         ObjectType.isNull();
7096     Candidate.ExplicitCallArguments = Args.size();
7097     if (Result == TDK_NonDependentConversionFailure)
7098       Candidate.FailureKind = ovl_fail_bad_conversion;
7099     else {
7100       Candidate.FailureKind = ovl_fail_bad_deduction;
7101       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7102                                                             Info);
7103     }
7104     return;
7105   }
7106 
7107   // Add the function template specialization produced by template argument
7108   // deduction as a candidate.
7109   assert(Specialization && "Missing member function template specialization?");
7110   assert(isa<CXXMethodDecl>(Specialization) &&
7111          "Specialization is not a member function?");
7112   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
7113                      ActingContext, ObjectType, ObjectClassification, Args,
7114                      CandidateSet, SuppressUserConversions, PartialOverloading,
7115                      Conversions, PO);
7116 }
7117 
7118 /// Determine whether a given function template has a simple explicit specifier
7119 /// or a non-value-dependent explicit-specification that evaluates to true.
7120 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
7121   return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
7122 }
7123 
7124 /// Add a C++ function template specialization as a candidate
7125 /// in the candidate set, using template argument deduction to produce
7126 /// an appropriate function template specialization.
7127 void Sema::AddTemplateOverloadCandidate(
7128     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7129     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7130     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7131     bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7132     OverloadCandidateParamOrder PO) {
7133   if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
7134     return;
7135 
7136   // If the function template has a non-dependent explicit specification,
7137   // exclude it now if appropriate; we are not permitted to perform deduction
7138   // and substitution in this case.
7139   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7140     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7141     Candidate.FoundDecl = FoundDecl;
7142     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7143     Candidate.Viable = false;
7144     Candidate.FailureKind = ovl_fail_explicit;
7145     return;
7146   }
7147 
7148   // C++ [over.match.funcs]p7:
7149   //   In each case where a candidate is a function template, candidate
7150   //   function template specializations are generated using template argument
7151   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
7152   //   candidate functions in the usual way.113) A given name can refer to one
7153   //   or more function templates and also to a set of overloaded non-template
7154   //   functions. In such a case, the candidate functions generated from each
7155   //   function template are combined with the set of non-template candidate
7156   //   functions.
7157   TemplateDeductionInfo Info(CandidateSet.getLocation());
7158   FunctionDecl *Specialization = nullptr;
7159   ConversionSequenceList Conversions;
7160   if (TemplateDeductionResult Result = DeduceTemplateArguments(
7161           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7162           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7163             return CheckNonDependentConversions(
7164                 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7165                 SuppressUserConversions, nullptr, QualType(), {}, PO);
7166           })) {
7167     OverloadCandidate &Candidate =
7168         CandidateSet.addCandidate(Conversions.size(), Conversions);
7169     Candidate.FoundDecl = FoundDecl;
7170     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7171     Candidate.Viable = false;
7172     Candidate.RewriteKind =
7173       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7174     Candidate.IsSurrogate = false;
7175     Candidate.IsADLCandidate = IsADLCandidate;
7176     // Ignore the object argument if there is one, since we don't have an object
7177     // type.
7178     Candidate.IgnoreObjectArgument =
7179         isa<CXXMethodDecl>(Candidate.Function) &&
7180         !isa<CXXConstructorDecl>(Candidate.Function);
7181     Candidate.ExplicitCallArguments = Args.size();
7182     if (Result == TDK_NonDependentConversionFailure)
7183       Candidate.FailureKind = ovl_fail_bad_conversion;
7184     else {
7185       Candidate.FailureKind = ovl_fail_bad_deduction;
7186       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7187                                                             Info);
7188     }
7189     return;
7190   }
7191 
7192   // Add the function template specialization produced by template argument
7193   // deduction as a candidate.
7194   assert(Specialization && "Missing function template specialization?");
7195   AddOverloadCandidate(
7196       Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7197       PartialOverloading, AllowExplicit,
7198       /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO);
7199 }
7200 
7201 /// Check that implicit conversion sequences can be formed for each argument
7202 /// whose corresponding parameter has a non-dependent type, per DR1391's
7203 /// [temp.deduct.call]p10.
7204 bool Sema::CheckNonDependentConversions(
7205     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7206     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7207     ConversionSequenceList &Conversions, bool SuppressUserConversions,
7208     CXXRecordDecl *ActingContext, QualType ObjectType,
7209     Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7210   // FIXME: The cases in which we allow explicit conversions for constructor
7211   // arguments never consider calling a constructor template. It's not clear
7212   // that is correct.
7213   const bool AllowExplicit = false;
7214 
7215   auto *FD = FunctionTemplate->getTemplatedDecl();
7216   auto *Method = dyn_cast<CXXMethodDecl>(FD);
7217   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7218   unsigned ThisConversions = HasThisConversion ? 1 : 0;
7219 
7220   Conversions =
7221       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7222 
7223   // Overload resolution is always an unevaluated context.
7224   EnterExpressionEvaluationContext Unevaluated(
7225       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7226 
7227   // For a method call, check the 'this' conversion here too. DR1391 doesn't
7228   // require that, but this check should never result in a hard error, and
7229   // overload resolution is permitted to sidestep instantiations.
7230   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7231       !ObjectType.isNull()) {
7232     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7233     Conversions[ConvIdx] = TryObjectArgumentInitialization(
7234         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7235         Method, ActingContext);
7236     if (Conversions[ConvIdx].isBad())
7237       return true;
7238   }
7239 
7240   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
7241        ++I) {
7242     QualType ParamType = ParamTypes[I];
7243     if (!ParamType->isDependentType()) {
7244       unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
7245                              ? 0
7246                              : (ThisConversions + I);
7247       Conversions[ConvIdx]
7248         = TryCopyInitialization(*this, Args[I], ParamType,
7249                                 SuppressUserConversions,
7250                                 /*InOverloadResolution=*/true,
7251                                 /*AllowObjCWritebackConversion=*/
7252                                   getLangOpts().ObjCAutoRefCount,
7253                                 AllowExplicit);
7254       if (Conversions[ConvIdx].isBad())
7255         return true;
7256     }
7257   }
7258 
7259   return false;
7260 }
7261 
7262 /// Determine whether this is an allowable conversion from the result
7263 /// of an explicit conversion operator to the expected type, per C++
7264 /// [over.match.conv]p1 and [over.match.ref]p1.
7265 ///
7266 /// \param ConvType The return type of the conversion function.
7267 ///
7268 /// \param ToType The type we are converting to.
7269 ///
7270 /// \param AllowObjCPointerConversion Allow a conversion from one
7271 /// Objective-C pointer to another.
7272 ///
7273 /// \returns true if the conversion is allowable, false otherwise.
7274 static bool isAllowableExplicitConversion(Sema &S,
7275                                           QualType ConvType, QualType ToType,
7276                                           bool AllowObjCPointerConversion) {
7277   QualType ToNonRefType = ToType.getNonReferenceType();
7278 
7279   // Easy case: the types are the same.
7280   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7281     return true;
7282 
7283   // Allow qualification conversions.
7284   bool ObjCLifetimeConversion;
7285   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7286                                   ObjCLifetimeConversion))
7287     return true;
7288 
7289   // If we're not allowed to consider Objective-C pointer conversions,
7290   // we're done.
7291   if (!AllowObjCPointerConversion)
7292     return false;
7293 
7294   // Is this an Objective-C pointer conversion?
7295   bool IncompatibleObjC = false;
7296   QualType ConvertedType;
7297   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7298                                    IncompatibleObjC);
7299 }
7300 
7301 /// AddConversionCandidate - Add a C++ conversion function as a
7302 /// candidate in the candidate set (C++ [over.match.conv],
7303 /// C++ [over.match.copy]). From is the expression we're converting from,
7304 /// and ToType is the type that we're eventually trying to convert to
7305 /// (which may or may not be the same type as the type that the
7306 /// conversion function produces).
7307 void Sema::AddConversionCandidate(
7308     CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7309     CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7310     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7311     bool AllowExplicit, bool AllowResultConversion) {
7312   assert(!Conversion->getDescribedFunctionTemplate() &&
7313          "Conversion function templates use AddTemplateConversionCandidate");
7314   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7315   if (!CandidateSet.isNewCandidate(Conversion))
7316     return;
7317 
7318   // If the conversion function has an undeduced return type, trigger its
7319   // deduction now.
7320   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7321     if (DeduceReturnType(Conversion, From->getExprLoc()))
7322       return;
7323     ConvType = Conversion->getConversionType().getNonReferenceType();
7324   }
7325 
7326   // If we don't allow any conversion of the result type, ignore conversion
7327   // functions that don't convert to exactly (possibly cv-qualified) T.
7328   if (!AllowResultConversion &&
7329       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7330     return;
7331 
7332   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7333   // operator is only a candidate if its return type is the target type or
7334   // can be converted to the target type with a qualification conversion.
7335   //
7336   // FIXME: Include such functions in the candidate list and explain why we
7337   // can't select them.
7338   if (Conversion->isExplicit() &&
7339       !isAllowableExplicitConversion(*this, ConvType, ToType,
7340                                      AllowObjCConversionOnExplicit))
7341     return;
7342 
7343   // Overload resolution is always an unevaluated context.
7344   EnterExpressionEvaluationContext Unevaluated(
7345       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7346 
7347   // Add this candidate
7348   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7349   Candidate.FoundDecl = FoundDecl;
7350   Candidate.Function = Conversion;
7351   Candidate.IsSurrogate = false;
7352   Candidate.IgnoreObjectArgument = false;
7353   Candidate.FinalConversion.setAsIdentityConversion();
7354   Candidate.FinalConversion.setFromType(ConvType);
7355   Candidate.FinalConversion.setAllToTypes(ToType);
7356   Candidate.Viable = true;
7357   Candidate.ExplicitCallArguments = 1;
7358 
7359   // Explicit functions are not actually candidates at all if we're not
7360   // allowing them in this context, but keep them around so we can point
7361   // to them in diagnostics.
7362   if (!AllowExplicit && Conversion->isExplicit()) {
7363     Candidate.Viable = false;
7364     Candidate.FailureKind = ovl_fail_explicit;
7365     return;
7366   }
7367 
7368   // C++ [over.match.funcs]p4:
7369   //   For conversion functions, the function is considered to be a member of
7370   //   the class of the implicit implied object argument for the purpose of
7371   //   defining the type of the implicit object parameter.
7372   //
7373   // Determine the implicit conversion sequence for the implicit
7374   // object parameter.
7375   QualType ImplicitParamType = From->getType();
7376   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7377     ImplicitParamType = FromPtrType->getPointeeType();
7378   CXXRecordDecl *ConversionContext
7379     = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
7380 
7381   Candidate.Conversions[0] = TryObjectArgumentInitialization(
7382       *this, CandidateSet.getLocation(), From->getType(),
7383       From->Classify(Context), Conversion, ConversionContext);
7384 
7385   if (Candidate.Conversions[0].isBad()) {
7386     Candidate.Viable = false;
7387     Candidate.FailureKind = ovl_fail_bad_conversion;
7388     return;
7389   }
7390 
7391   if (Conversion->getTrailingRequiresClause()) {
7392     ConstraintSatisfaction Satisfaction;
7393     if (CheckFunctionConstraints(Conversion, Satisfaction) ||
7394         !Satisfaction.IsSatisfied) {
7395       Candidate.Viable = false;
7396       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7397       return;
7398     }
7399   }
7400 
7401   // We won't go through a user-defined type conversion function to convert a
7402   // derived to base as such conversions are given Conversion Rank. They only
7403   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7404   QualType FromCanon
7405     = Context.getCanonicalType(From->getType().getUnqualifiedType());
7406   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7407   if (FromCanon == ToCanon ||
7408       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7409     Candidate.Viable = false;
7410     Candidate.FailureKind = ovl_fail_trivial_conversion;
7411     return;
7412   }
7413 
7414   // To determine what the conversion from the result of calling the
7415   // conversion function to the type we're eventually trying to
7416   // convert to (ToType), we need to synthesize a call to the
7417   // conversion function and attempt copy initialization from it. This
7418   // makes sure that we get the right semantics with respect to
7419   // lvalues/rvalues and the type. Fortunately, we can allocate this
7420   // call on the stack and we don't need its arguments to be
7421   // well-formed.
7422   DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7423                             VK_LValue, From->getBeginLoc());
7424   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7425                                 Context.getPointerType(Conversion->getType()),
7426                                 CK_FunctionToPointerDecay, &ConversionRef,
7427                                 VK_PRValue, FPOptionsOverride());
7428 
7429   QualType ConversionType = Conversion->getConversionType();
7430   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7431     Candidate.Viable = false;
7432     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7433     return;
7434   }
7435 
7436   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7437 
7438   // Note that it is safe to allocate CallExpr on the stack here because
7439   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7440   // allocator).
7441   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7442 
7443   alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7444   CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7445       Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7446 
7447   ImplicitConversionSequence ICS =
7448       TryCopyInitialization(*this, TheTemporaryCall, ToType,
7449                             /*SuppressUserConversions=*/true,
7450                             /*InOverloadResolution=*/false,
7451                             /*AllowObjCWritebackConversion=*/false);
7452 
7453   switch (ICS.getKind()) {
7454   case ImplicitConversionSequence::StandardConversion:
7455     Candidate.FinalConversion = ICS.Standard;
7456 
7457     // C++ [over.ics.user]p3:
7458     //   If the user-defined conversion is specified by a specialization of a
7459     //   conversion function template, the second standard conversion sequence
7460     //   shall have exact match rank.
7461     if (Conversion->getPrimaryTemplate() &&
7462         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7463       Candidate.Viable = false;
7464       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7465       return;
7466     }
7467 
7468     // C++0x [dcl.init.ref]p5:
7469     //    In the second case, if the reference is an rvalue reference and
7470     //    the second standard conversion sequence of the user-defined
7471     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7472     //    program is ill-formed.
7473     if (ToType->isRValueReferenceType() &&
7474         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7475       Candidate.Viable = false;
7476       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7477       return;
7478     }
7479     break;
7480 
7481   case ImplicitConversionSequence::BadConversion:
7482     Candidate.Viable = false;
7483     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7484     return;
7485 
7486   default:
7487     llvm_unreachable(
7488            "Can only end up with a standard conversion sequence or failure");
7489   }
7490 
7491   if (EnableIfAttr *FailedAttr =
7492           CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7493     Candidate.Viable = false;
7494     Candidate.FailureKind = ovl_fail_enable_if;
7495     Candidate.DeductionFailure.Data = FailedAttr;
7496     return;
7497   }
7498 
7499   if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7500       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7501     Candidate.Viable = false;
7502     Candidate.FailureKind = ovl_non_default_multiversion_function;
7503   }
7504 }
7505 
7506 /// Adds a conversion function template specialization
7507 /// candidate to the overload set, using template argument deduction
7508 /// to deduce the template arguments of the conversion function
7509 /// template from the type that we are converting to (C++
7510 /// [temp.deduct.conv]).
7511 void Sema::AddTemplateConversionCandidate(
7512     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7513     CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7514     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7515     bool AllowExplicit, bool AllowResultConversion) {
7516   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7517          "Only conversion function templates permitted here");
7518 
7519   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7520     return;
7521 
7522   // If the function template has a non-dependent explicit specification,
7523   // exclude it now if appropriate; we are not permitted to perform deduction
7524   // and substitution in this case.
7525   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7526     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7527     Candidate.FoundDecl = FoundDecl;
7528     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7529     Candidate.Viable = false;
7530     Candidate.FailureKind = ovl_fail_explicit;
7531     return;
7532   }
7533 
7534   TemplateDeductionInfo Info(CandidateSet.getLocation());
7535   CXXConversionDecl *Specialization = nullptr;
7536   if (TemplateDeductionResult Result
7537         = DeduceTemplateArguments(FunctionTemplate, ToType,
7538                                   Specialization, Info)) {
7539     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7540     Candidate.FoundDecl = FoundDecl;
7541     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7542     Candidate.Viable = false;
7543     Candidate.FailureKind = ovl_fail_bad_deduction;
7544     Candidate.IsSurrogate = false;
7545     Candidate.IgnoreObjectArgument = false;
7546     Candidate.ExplicitCallArguments = 1;
7547     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7548                                                           Info);
7549     return;
7550   }
7551 
7552   // Add the conversion function template specialization produced by
7553   // template argument deduction as a candidate.
7554   assert(Specialization && "Missing function template specialization?");
7555   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7556                          CandidateSet, AllowObjCConversionOnExplicit,
7557                          AllowExplicit, AllowResultConversion);
7558 }
7559 
7560 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7561 /// converts the given @c Object to a function pointer via the
7562 /// conversion function @c Conversion, and then attempts to call it
7563 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7564 /// the type of function that we'll eventually be calling.
7565 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7566                                  DeclAccessPair FoundDecl,
7567                                  CXXRecordDecl *ActingContext,
7568                                  const FunctionProtoType *Proto,
7569                                  Expr *Object,
7570                                  ArrayRef<Expr *> Args,
7571                                  OverloadCandidateSet& CandidateSet) {
7572   if (!CandidateSet.isNewCandidate(Conversion))
7573     return;
7574 
7575   // Overload resolution is always an unevaluated context.
7576   EnterExpressionEvaluationContext Unevaluated(
7577       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7578 
7579   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7580   Candidate.FoundDecl = FoundDecl;
7581   Candidate.Function = nullptr;
7582   Candidate.Surrogate = Conversion;
7583   Candidate.Viable = true;
7584   Candidate.IsSurrogate = true;
7585   Candidate.IgnoreObjectArgument = false;
7586   Candidate.ExplicitCallArguments = Args.size();
7587 
7588   // Determine the implicit conversion sequence for the implicit
7589   // object parameter.
7590   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7591       *this, CandidateSet.getLocation(), Object->getType(),
7592       Object->Classify(Context), Conversion, ActingContext);
7593   if (ObjectInit.isBad()) {
7594     Candidate.Viable = false;
7595     Candidate.FailureKind = ovl_fail_bad_conversion;
7596     Candidate.Conversions[0] = ObjectInit;
7597     return;
7598   }
7599 
7600   // The first conversion is actually a user-defined conversion whose
7601   // first conversion is ObjectInit's standard conversion (which is
7602   // effectively a reference binding). Record it as such.
7603   Candidate.Conversions[0].setUserDefined();
7604   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7605   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7606   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7607   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7608   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7609   Candidate.Conversions[0].UserDefined.After
7610     = Candidate.Conversions[0].UserDefined.Before;
7611   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7612 
7613   // Find the
7614   unsigned NumParams = Proto->getNumParams();
7615 
7616   // (C++ 13.3.2p2): A candidate function having fewer than m
7617   // parameters is viable only if it has an ellipsis in its parameter
7618   // list (8.3.5).
7619   if (Args.size() > NumParams && !Proto->isVariadic()) {
7620     Candidate.Viable = false;
7621     Candidate.FailureKind = ovl_fail_too_many_arguments;
7622     return;
7623   }
7624 
7625   // Function types don't have any default arguments, so just check if
7626   // we have enough arguments.
7627   if (Args.size() < NumParams) {
7628     // Not enough arguments.
7629     Candidate.Viable = false;
7630     Candidate.FailureKind = ovl_fail_too_few_arguments;
7631     return;
7632   }
7633 
7634   // Determine the implicit conversion sequences for each of the
7635   // arguments.
7636   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7637     if (ArgIdx < NumParams) {
7638       // (C++ 13.3.2p3): for F to be a viable function, there shall
7639       // exist for each argument an implicit conversion sequence
7640       // (13.3.3.1) that converts that argument to the corresponding
7641       // parameter of F.
7642       QualType ParamType = Proto->getParamType(ArgIdx);
7643       Candidate.Conversions[ArgIdx + 1]
7644         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7645                                 /*SuppressUserConversions=*/false,
7646                                 /*InOverloadResolution=*/false,
7647                                 /*AllowObjCWritebackConversion=*/
7648                                   getLangOpts().ObjCAutoRefCount);
7649       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7650         Candidate.Viable = false;
7651         Candidate.FailureKind = ovl_fail_bad_conversion;
7652         return;
7653       }
7654     } else {
7655       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7656       // argument for which there is no corresponding parameter is
7657       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7658       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7659     }
7660   }
7661 
7662   if (EnableIfAttr *FailedAttr =
7663           CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7664     Candidate.Viable = false;
7665     Candidate.FailureKind = ovl_fail_enable_if;
7666     Candidate.DeductionFailure.Data = FailedAttr;
7667     return;
7668   }
7669 }
7670 
7671 /// Add all of the non-member operator function declarations in the given
7672 /// function set to the overload candidate set.
7673 void Sema::AddNonMemberOperatorCandidates(
7674     const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
7675     OverloadCandidateSet &CandidateSet,
7676     TemplateArgumentListInfo *ExplicitTemplateArgs) {
7677   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7678     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7679     ArrayRef<Expr *> FunctionArgs = Args;
7680 
7681     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7682     FunctionDecl *FD =
7683         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7684 
7685     // Don't consider rewritten functions if we're not rewriting.
7686     if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
7687       continue;
7688 
7689     assert(!isa<CXXMethodDecl>(FD) &&
7690            "unqualified operator lookup found a member function");
7691 
7692     if (FunTmpl) {
7693       AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
7694                                    FunctionArgs, CandidateSet);
7695       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7696         AddTemplateOverloadCandidate(
7697             FunTmpl, F.getPair(), ExplicitTemplateArgs,
7698             {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
7699             true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
7700     } else {
7701       if (ExplicitTemplateArgs)
7702         continue;
7703       AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
7704       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7705         AddOverloadCandidate(FD, F.getPair(),
7706                              {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
7707                              false, false, true, false, ADLCallKind::NotADL,
7708                              None, OverloadCandidateParamOrder::Reversed);
7709     }
7710   }
7711 }
7712 
7713 /// Add overload candidates for overloaded operators that are
7714 /// member functions.
7715 ///
7716 /// Add the overloaded operator candidates that are member functions
7717 /// for the operator Op that was used in an operator expression such
7718 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7719 /// CandidateSet will store the added overload candidates. (C++
7720 /// [over.match.oper]).
7721 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7722                                        SourceLocation OpLoc,
7723                                        ArrayRef<Expr *> Args,
7724                                        OverloadCandidateSet &CandidateSet,
7725                                        OverloadCandidateParamOrder PO) {
7726   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7727 
7728   // C++ [over.match.oper]p3:
7729   //   For a unary operator @ with an operand of a type whose
7730   //   cv-unqualified version is T1, and for a binary operator @ with
7731   //   a left operand of a type whose cv-unqualified version is T1 and
7732   //   a right operand of a type whose cv-unqualified version is T2,
7733   //   three sets of candidate functions, designated member
7734   //   candidates, non-member candidates and built-in candidates, are
7735   //   constructed as follows:
7736   QualType T1 = Args[0]->getType();
7737 
7738   //     -- If T1 is a complete class type or a class currently being
7739   //        defined, the set of member candidates is the result of the
7740   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7741   //        the set of member candidates is empty.
7742   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7743     // Complete the type if it can be completed.
7744     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7745       return;
7746     // If the type is neither complete nor being defined, bail out now.
7747     if (!T1Rec->getDecl()->getDefinition())
7748       return;
7749 
7750     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7751     LookupQualifiedName(Operators, T1Rec->getDecl());
7752     Operators.suppressDiagnostics();
7753 
7754     for (LookupResult::iterator Oper = Operators.begin(),
7755                              OperEnd = Operators.end();
7756          Oper != OperEnd;
7757          ++Oper)
7758       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7759                          Args[0]->Classify(Context), Args.slice(1),
7760                          CandidateSet, /*SuppressUserConversion=*/false, PO);
7761   }
7762 }
7763 
7764 /// AddBuiltinCandidate - Add a candidate for a built-in
7765 /// operator. ResultTy and ParamTys are the result and parameter types
7766 /// of the built-in candidate, respectively. Args and NumArgs are the
7767 /// arguments being passed to the candidate. IsAssignmentOperator
7768 /// should be true when this built-in candidate is an assignment
7769 /// operator. NumContextualBoolArguments is the number of arguments
7770 /// (at the beginning of the argument list) that will be contextually
7771 /// converted to bool.
7772 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7773                                OverloadCandidateSet& CandidateSet,
7774                                bool IsAssignmentOperator,
7775                                unsigned NumContextualBoolArguments) {
7776   // Overload resolution is always an unevaluated context.
7777   EnterExpressionEvaluationContext Unevaluated(
7778       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7779 
7780   // Add this candidate
7781   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7782   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7783   Candidate.Function = nullptr;
7784   Candidate.IsSurrogate = false;
7785   Candidate.IgnoreObjectArgument = false;
7786   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7787 
7788   // Determine the implicit conversion sequences for each of the
7789   // arguments.
7790   Candidate.Viable = true;
7791   Candidate.ExplicitCallArguments = Args.size();
7792   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7793     // C++ [over.match.oper]p4:
7794     //   For the built-in assignment operators, conversions of the
7795     //   left operand are restricted as follows:
7796     //     -- no temporaries are introduced to hold the left operand, and
7797     //     -- no user-defined conversions are applied to the left
7798     //        operand to achieve a type match with the left-most
7799     //        parameter of a built-in candidate.
7800     //
7801     // We block these conversions by turning off user-defined
7802     // conversions, since that is the only way that initialization of
7803     // a reference to a non-class type can occur from something that
7804     // is not of the same type.
7805     if (ArgIdx < NumContextualBoolArguments) {
7806       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7807              "Contextual conversion to bool requires bool type");
7808       Candidate.Conversions[ArgIdx]
7809         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7810     } else {
7811       Candidate.Conversions[ArgIdx]
7812         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7813                                 ArgIdx == 0 && IsAssignmentOperator,
7814                                 /*InOverloadResolution=*/false,
7815                                 /*AllowObjCWritebackConversion=*/
7816                                   getLangOpts().ObjCAutoRefCount);
7817     }
7818     if (Candidate.Conversions[ArgIdx].isBad()) {
7819       Candidate.Viable = false;
7820       Candidate.FailureKind = ovl_fail_bad_conversion;
7821       break;
7822     }
7823   }
7824 }
7825 
7826 namespace {
7827 
7828 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7829 /// candidate operator functions for built-in operators (C++
7830 /// [over.built]). The types are separated into pointer types and
7831 /// enumeration types.
7832 class BuiltinCandidateTypeSet  {
7833   /// TypeSet - A set of types.
7834   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7835                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7836 
7837   /// PointerTypes - The set of pointer types that will be used in the
7838   /// built-in candidates.
7839   TypeSet PointerTypes;
7840 
7841   /// MemberPointerTypes - The set of member pointer types that will be
7842   /// used in the built-in candidates.
7843   TypeSet MemberPointerTypes;
7844 
7845   /// EnumerationTypes - The set of enumeration types that will be
7846   /// used in the built-in candidates.
7847   TypeSet EnumerationTypes;
7848 
7849   /// The set of vector types that will be used in the built-in
7850   /// candidates.
7851   TypeSet VectorTypes;
7852 
7853   /// The set of matrix types that will be used in the built-in
7854   /// candidates.
7855   TypeSet MatrixTypes;
7856 
7857   /// A flag indicating non-record types are viable candidates
7858   bool HasNonRecordTypes;
7859 
7860   /// A flag indicating whether either arithmetic or enumeration types
7861   /// were present in the candidate set.
7862   bool HasArithmeticOrEnumeralTypes;
7863 
7864   /// A flag indicating whether the nullptr type was present in the
7865   /// candidate set.
7866   bool HasNullPtrType;
7867 
7868   /// Sema - The semantic analysis instance where we are building the
7869   /// candidate type set.
7870   Sema &SemaRef;
7871 
7872   /// Context - The AST context in which we will build the type sets.
7873   ASTContext &Context;
7874 
7875   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7876                                                const Qualifiers &VisibleQuals);
7877   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7878 
7879 public:
7880   /// iterator - Iterates through the types that are part of the set.
7881   typedef TypeSet::iterator iterator;
7882 
7883   BuiltinCandidateTypeSet(Sema &SemaRef)
7884     : HasNonRecordTypes(false),
7885       HasArithmeticOrEnumeralTypes(false),
7886       HasNullPtrType(false),
7887       SemaRef(SemaRef),
7888       Context(SemaRef.Context) { }
7889 
7890   void AddTypesConvertedFrom(QualType Ty,
7891                              SourceLocation Loc,
7892                              bool AllowUserConversions,
7893                              bool AllowExplicitConversions,
7894                              const Qualifiers &VisibleTypeConversionsQuals);
7895 
7896   llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
7897   llvm::iterator_range<iterator> member_pointer_types() {
7898     return MemberPointerTypes;
7899   }
7900   llvm::iterator_range<iterator> enumeration_types() {
7901     return EnumerationTypes;
7902   }
7903   llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
7904   llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
7905 
7906   bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
7907   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7908   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7909   bool hasNullPtrType() const { return HasNullPtrType; }
7910 };
7911 
7912 } // end anonymous namespace
7913 
7914 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7915 /// the set of pointer types along with any more-qualified variants of
7916 /// that type. For example, if @p Ty is "int const *", this routine
7917 /// will add "int const *", "int const volatile *", "int const
7918 /// restrict *", and "int const volatile restrict *" to the set of
7919 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7920 /// false otherwise.
7921 ///
7922 /// FIXME: what to do about extended qualifiers?
7923 bool
7924 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7925                                              const Qualifiers &VisibleQuals) {
7926 
7927   // Insert this type.
7928   if (!PointerTypes.insert(Ty))
7929     return false;
7930 
7931   QualType PointeeTy;
7932   const PointerType *PointerTy = Ty->getAs<PointerType>();
7933   bool buildObjCPtr = false;
7934   if (!PointerTy) {
7935     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7936     PointeeTy = PTy->getPointeeType();
7937     buildObjCPtr = true;
7938   } else {
7939     PointeeTy = PointerTy->getPointeeType();
7940   }
7941 
7942   // Don't add qualified variants of arrays. For one, they're not allowed
7943   // (the qualifier would sink to the element type), and for another, the
7944   // only overload situation where it matters is subscript or pointer +- int,
7945   // and those shouldn't have qualifier variants anyway.
7946   if (PointeeTy->isArrayType())
7947     return true;
7948 
7949   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7950   bool hasVolatile = VisibleQuals.hasVolatile();
7951   bool hasRestrict = VisibleQuals.hasRestrict();
7952 
7953   // Iterate through all strict supersets of BaseCVR.
7954   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7955     if ((CVR | BaseCVR) != CVR) continue;
7956     // Skip over volatile if no volatile found anywhere in the types.
7957     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7958 
7959     // Skip over restrict if no restrict found anywhere in the types, or if
7960     // the type cannot be restrict-qualified.
7961     if ((CVR & Qualifiers::Restrict) &&
7962         (!hasRestrict ||
7963          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7964       continue;
7965 
7966     // Build qualified pointee type.
7967     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7968 
7969     // Build qualified pointer type.
7970     QualType QPointerTy;
7971     if (!buildObjCPtr)
7972       QPointerTy = Context.getPointerType(QPointeeTy);
7973     else
7974       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7975 
7976     // Insert qualified pointer type.
7977     PointerTypes.insert(QPointerTy);
7978   }
7979 
7980   return true;
7981 }
7982 
7983 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7984 /// to the set of pointer types along with any more-qualified variants of
7985 /// that type. For example, if @p Ty is "int const *", this routine
7986 /// will add "int const *", "int const volatile *", "int const
7987 /// restrict *", and "int const volatile restrict *" to the set of
7988 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7989 /// false otherwise.
7990 ///
7991 /// FIXME: what to do about extended qualifiers?
7992 bool
7993 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7994     QualType Ty) {
7995   // Insert this type.
7996   if (!MemberPointerTypes.insert(Ty))
7997     return false;
7998 
7999   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8000   assert(PointerTy && "type was not a member pointer type!");
8001 
8002   QualType PointeeTy = PointerTy->getPointeeType();
8003   // Don't add qualified variants of arrays. For one, they're not allowed
8004   // (the qualifier would sink to the element type), and for another, the
8005   // only overload situation where it matters is subscript or pointer +- int,
8006   // and those shouldn't have qualifier variants anyway.
8007   if (PointeeTy->isArrayType())
8008     return true;
8009   const Type *ClassTy = PointerTy->getClass();
8010 
8011   // Iterate through all strict supersets of the pointee type's CVR
8012   // qualifiers.
8013   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8014   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8015     if ((CVR | BaseCVR) != CVR) continue;
8016 
8017     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8018     MemberPointerTypes.insert(
8019       Context.getMemberPointerType(QPointeeTy, ClassTy));
8020   }
8021 
8022   return true;
8023 }
8024 
8025 /// AddTypesConvertedFrom - Add each of the types to which the type @p
8026 /// Ty can be implicit converted to the given set of @p Types. We're
8027 /// primarily interested in pointer types and enumeration types. We also
8028 /// take member pointer types, for the conditional operator.
8029 /// AllowUserConversions is true if we should look at the conversion
8030 /// functions of a class type, and AllowExplicitConversions if we
8031 /// should also include the explicit conversion functions of a class
8032 /// type.
8033 void
8034 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
8035                                                SourceLocation Loc,
8036                                                bool AllowUserConversions,
8037                                                bool AllowExplicitConversions,
8038                                                const Qualifiers &VisibleQuals) {
8039   // Only deal with canonical types.
8040   Ty = Context.getCanonicalType(Ty);
8041 
8042   // Look through reference types; they aren't part of the type of an
8043   // expression for the purposes of conversions.
8044   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
8045     Ty = RefTy->getPointeeType();
8046 
8047   // If we're dealing with an array type, decay to the pointer.
8048   if (Ty->isArrayType())
8049     Ty = SemaRef.Context.getArrayDecayedType(Ty);
8050 
8051   // Otherwise, we don't care about qualifiers on the type.
8052   Ty = Ty.getLocalUnqualifiedType();
8053 
8054   // Flag if we ever add a non-record type.
8055   const RecordType *TyRec = Ty->getAs<RecordType>();
8056   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
8057 
8058   // Flag if we encounter an arithmetic type.
8059   HasArithmeticOrEnumeralTypes =
8060     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
8061 
8062   if (Ty->isObjCIdType() || Ty->isObjCClassType())
8063     PointerTypes.insert(Ty);
8064   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
8065     // Insert our type, and its more-qualified variants, into the set
8066     // of types.
8067     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
8068       return;
8069   } else if (Ty->isMemberPointerType()) {
8070     // Member pointers are far easier, since the pointee can't be converted.
8071     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
8072       return;
8073   } else if (Ty->isEnumeralType()) {
8074     HasArithmeticOrEnumeralTypes = true;
8075     EnumerationTypes.insert(Ty);
8076   } else if (Ty->isVectorType()) {
8077     // We treat vector types as arithmetic types in many contexts as an
8078     // extension.
8079     HasArithmeticOrEnumeralTypes = true;
8080     VectorTypes.insert(Ty);
8081   } else if (Ty->isMatrixType()) {
8082     // Similar to vector types, we treat vector types as arithmetic types in
8083     // many contexts as an extension.
8084     HasArithmeticOrEnumeralTypes = true;
8085     MatrixTypes.insert(Ty);
8086   } else if (Ty->isNullPtrType()) {
8087     HasNullPtrType = true;
8088   } else if (AllowUserConversions && TyRec) {
8089     // No conversion functions in incomplete types.
8090     if (!SemaRef.isCompleteType(Loc, Ty))
8091       return;
8092 
8093     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8094     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8095       if (isa<UsingShadowDecl>(D))
8096         D = cast<UsingShadowDecl>(D)->getTargetDecl();
8097 
8098       // Skip conversion function templates; they don't tell us anything
8099       // about which builtin types we can convert to.
8100       if (isa<FunctionTemplateDecl>(D))
8101         continue;
8102 
8103       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
8104       if (AllowExplicitConversions || !Conv->isExplicit()) {
8105         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
8106                               VisibleQuals);
8107       }
8108     }
8109   }
8110 }
8111 /// Helper function for adjusting address spaces for the pointer or reference
8112 /// operands of builtin operators depending on the argument.
8113 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
8114                                                         Expr *Arg) {
8115   return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
8116 }
8117 
8118 /// Helper function for AddBuiltinOperatorCandidates() that adds
8119 /// the volatile- and non-volatile-qualified assignment operators for the
8120 /// given type to the candidate set.
8121 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
8122                                                    QualType T,
8123                                                    ArrayRef<Expr *> Args,
8124                                     OverloadCandidateSet &CandidateSet) {
8125   QualType ParamTypes[2];
8126 
8127   // T& operator=(T&, T)
8128   ParamTypes[0] = S.Context.getLValueReferenceType(
8129       AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
8130   ParamTypes[1] = T;
8131   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8132                         /*IsAssignmentOperator=*/true);
8133 
8134   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
8135     // volatile T& operator=(volatile T&, T)
8136     ParamTypes[0] = S.Context.getLValueReferenceType(
8137         AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
8138                                                 Args[0]));
8139     ParamTypes[1] = T;
8140     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8141                           /*IsAssignmentOperator=*/true);
8142   }
8143 }
8144 
8145 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8146 /// if any, found in visible type conversion functions found in ArgExpr's type.
8147 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8148     Qualifiers VRQuals;
8149     const RecordType *TyRec;
8150     if (const MemberPointerType *RHSMPType =
8151         ArgExpr->getType()->getAs<MemberPointerType>())
8152       TyRec = RHSMPType->getClass()->getAs<RecordType>();
8153     else
8154       TyRec = ArgExpr->getType()->getAs<RecordType>();
8155     if (!TyRec) {
8156       // Just to be safe, assume the worst case.
8157       VRQuals.addVolatile();
8158       VRQuals.addRestrict();
8159       return VRQuals;
8160     }
8161 
8162     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8163     if (!ClassDecl->hasDefinition())
8164       return VRQuals;
8165 
8166     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8167       if (isa<UsingShadowDecl>(D))
8168         D = cast<UsingShadowDecl>(D)->getTargetDecl();
8169       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8170         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8171         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8172           CanTy = ResTypeRef->getPointeeType();
8173         // Need to go down the pointer/mempointer chain and add qualifiers
8174         // as see them.
8175         bool done = false;
8176         while (!done) {
8177           if (CanTy.isRestrictQualified())
8178             VRQuals.addRestrict();
8179           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8180             CanTy = ResTypePtr->getPointeeType();
8181           else if (const MemberPointerType *ResTypeMPtr =
8182                 CanTy->getAs<MemberPointerType>())
8183             CanTy = ResTypeMPtr->getPointeeType();
8184           else
8185             done = true;
8186           if (CanTy.isVolatileQualified())
8187             VRQuals.addVolatile();
8188           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8189             return VRQuals;
8190         }
8191       }
8192     }
8193     return VRQuals;
8194 }
8195 
8196 namespace {
8197 
8198 /// Helper class to manage the addition of builtin operator overload
8199 /// candidates. It provides shared state and utility methods used throughout
8200 /// the process, as well as a helper method to add each group of builtin
8201 /// operator overloads from the standard to a candidate set.
8202 class BuiltinOperatorOverloadBuilder {
8203   // Common instance state available to all overload candidate addition methods.
8204   Sema &S;
8205   ArrayRef<Expr *> Args;
8206   Qualifiers VisibleTypeConversionsQuals;
8207   bool HasArithmeticOrEnumeralCandidateType;
8208   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8209   OverloadCandidateSet &CandidateSet;
8210 
8211   static constexpr int ArithmeticTypesCap = 24;
8212   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8213 
8214   // Define some indices used to iterate over the arithmetic types in
8215   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
8216   // types are that preserved by promotion (C++ [over.built]p2).
8217   unsigned FirstIntegralType,
8218            LastIntegralType;
8219   unsigned FirstPromotedIntegralType,
8220            LastPromotedIntegralType;
8221   unsigned FirstPromotedArithmeticType,
8222            LastPromotedArithmeticType;
8223   unsigned NumArithmeticTypes;
8224 
8225   void InitArithmeticTypes() {
8226     // Start of promoted types.
8227     FirstPromotedArithmeticType = 0;
8228     ArithmeticTypes.push_back(S.Context.FloatTy);
8229     ArithmeticTypes.push_back(S.Context.DoubleTy);
8230     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8231     if (S.Context.getTargetInfo().hasFloat128Type())
8232       ArithmeticTypes.push_back(S.Context.Float128Ty);
8233     if (S.Context.getTargetInfo().hasIbm128Type())
8234       ArithmeticTypes.push_back(S.Context.Ibm128Ty);
8235 
8236     // Start of integral types.
8237     FirstIntegralType = ArithmeticTypes.size();
8238     FirstPromotedIntegralType = ArithmeticTypes.size();
8239     ArithmeticTypes.push_back(S.Context.IntTy);
8240     ArithmeticTypes.push_back(S.Context.LongTy);
8241     ArithmeticTypes.push_back(S.Context.LongLongTy);
8242     if (S.Context.getTargetInfo().hasInt128Type() ||
8243         (S.Context.getAuxTargetInfo() &&
8244          S.Context.getAuxTargetInfo()->hasInt128Type()))
8245       ArithmeticTypes.push_back(S.Context.Int128Ty);
8246     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8247     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8248     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8249     if (S.Context.getTargetInfo().hasInt128Type() ||
8250         (S.Context.getAuxTargetInfo() &&
8251          S.Context.getAuxTargetInfo()->hasInt128Type()))
8252       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8253     LastPromotedIntegralType = ArithmeticTypes.size();
8254     LastPromotedArithmeticType = ArithmeticTypes.size();
8255     // End of promoted types.
8256 
8257     ArithmeticTypes.push_back(S.Context.BoolTy);
8258     ArithmeticTypes.push_back(S.Context.CharTy);
8259     ArithmeticTypes.push_back(S.Context.WCharTy);
8260     if (S.Context.getLangOpts().Char8)
8261       ArithmeticTypes.push_back(S.Context.Char8Ty);
8262     ArithmeticTypes.push_back(S.Context.Char16Ty);
8263     ArithmeticTypes.push_back(S.Context.Char32Ty);
8264     ArithmeticTypes.push_back(S.Context.SignedCharTy);
8265     ArithmeticTypes.push_back(S.Context.ShortTy);
8266     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8267     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8268     LastIntegralType = ArithmeticTypes.size();
8269     NumArithmeticTypes = ArithmeticTypes.size();
8270     // End of integral types.
8271     // FIXME: What about complex? What about half?
8272 
8273     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
8274            "Enough inline storage for all arithmetic types.");
8275   }
8276 
8277   /// Helper method to factor out the common pattern of adding overloads
8278   /// for '++' and '--' builtin operators.
8279   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8280                                            bool HasVolatile,
8281                                            bool HasRestrict) {
8282     QualType ParamTypes[2] = {
8283       S.Context.getLValueReferenceType(CandidateTy),
8284       S.Context.IntTy
8285     };
8286 
8287     // Non-volatile version.
8288     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8289 
8290     // Use a heuristic to reduce number of builtin candidates in the set:
8291     // add volatile version only if there are conversions to a volatile type.
8292     if (HasVolatile) {
8293       ParamTypes[0] =
8294         S.Context.getLValueReferenceType(
8295           S.Context.getVolatileType(CandidateTy));
8296       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8297     }
8298 
8299     // Add restrict version only if there are conversions to a restrict type
8300     // and our candidate type is a non-restrict-qualified pointer.
8301     if (HasRestrict && CandidateTy->isAnyPointerType() &&
8302         !CandidateTy.isRestrictQualified()) {
8303       ParamTypes[0]
8304         = S.Context.getLValueReferenceType(
8305             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8306       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8307 
8308       if (HasVolatile) {
8309         ParamTypes[0]
8310           = S.Context.getLValueReferenceType(
8311               S.Context.getCVRQualifiedType(CandidateTy,
8312                                             (Qualifiers::Volatile |
8313                                              Qualifiers::Restrict)));
8314         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8315       }
8316     }
8317 
8318   }
8319 
8320   /// Helper to add an overload candidate for a binary builtin with types \p L
8321   /// and \p R.
8322   void AddCandidate(QualType L, QualType R) {
8323     QualType LandR[2] = {L, R};
8324     S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8325   }
8326 
8327 public:
8328   BuiltinOperatorOverloadBuilder(
8329     Sema &S, ArrayRef<Expr *> Args,
8330     Qualifiers VisibleTypeConversionsQuals,
8331     bool HasArithmeticOrEnumeralCandidateType,
8332     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8333     OverloadCandidateSet &CandidateSet)
8334     : S(S), Args(Args),
8335       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8336       HasArithmeticOrEnumeralCandidateType(
8337         HasArithmeticOrEnumeralCandidateType),
8338       CandidateTypes(CandidateTypes),
8339       CandidateSet(CandidateSet) {
8340 
8341     InitArithmeticTypes();
8342   }
8343 
8344   // Increment is deprecated for bool since C++17.
8345   //
8346   // C++ [over.built]p3:
8347   //
8348   //   For every pair (T, VQ), where T is an arithmetic type other
8349   //   than bool, and VQ is either volatile or empty, there exist
8350   //   candidate operator functions of the form
8351   //
8352   //       VQ T&      operator++(VQ T&);
8353   //       T          operator++(VQ T&, int);
8354   //
8355   // C++ [over.built]p4:
8356   //
8357   //   For every pair (T, VQ), where T is an arithmetic type other
8358   //   than bool, and VQ is either volatile or empty, there exist
8359   //   candidate operator functions of the form
8360   //
8361   //       VQ T&      operator--(VQ T&);
8362   //       T          operator--(VQ T&, int);
8363   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8364     if (!HasArithmeticOrEnumeralCandidateType)
8365       return;
8366 
8367     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8368       const auto TypeOfT = ArithmeticTypes[Arith];
8369       if (TypeOfT == S.Context.BoolTy) {
8370         if (Op == OO_MinusMinus)
8371           continue;
8372         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8373           continue;
8374       }
8375       addPlusPlusMinusMinusStyleOverloads(
8376         TypeOfT,
8377         VisibleTypeConversionsQuals.hasVolatile(),
8378         VisibleTypeConversionsQuals.hasRestrict());
8379     }
8380   }
8381 
8382   // C++ [over.built]p5:
8383   //
8384   //   For every pair (T, VQ), where T is a cv-qualified or
8385   //   cv-unqualified object type, and VQ is either volatile or
8386   //   empty, there exist candidate operator functions of the form
8387   //
8388   //       T*VQ&      operator++(T*VQ&);
8389   //       T*VQ&      operator--(T*VQ&);
8390   //       T*         operator++(T*VQ&, int);
8391   //       T*         operator--(T*VQ&, int);
8392   void addPlusPlusMinusMinusPointerOverloads() {
8393     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
8394       // Skip pointer types that aren't pointers to object types.
8395       if (!PtrTy->getPointeeType()->isObjectType())
8396         continue;
8397 
8398       addPlusPlusMinusMinusStyleOverloads(
8399           PtrTy,
8400           (!PtrTy.isVolatileQualified() &&
8401            VisibleTypeConversionsQuals.hasVolatile()),
8402           (!PtrTy.isRestrictQualified() &&
8403            VisibleTypeConversionsQuals.hasRestrict()));
8404     }
8405   }
8406 
8407   // C++ [over.built]p6:
8408   //   For every cv-qualified or cv-unqualified object type T, there
8409   //   exist candidate operator functions of the form
8410   //
8411   //       T&         operator*(T*);
8412   //
8413   // C++ [over.built]p7:
8414   //   For every function type T that does not have cv-qualifiers or a
8415   //   ref-qualifier, there exist candidate operator functions of the form
8416   //       T&         operator*(T*);
8417   void addUnaryStarPointerOverloads() {
8418     for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
8419       QualType PointeeTy = ParamTy->getPointeeType();
8420       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8421         continue;
8422 
8423       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8424         if (Proto->getMethodQuals() || Proto->getRefQualifier())
8425           continue;
8426 
8427       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8428     }
8429   }
8430 
8431   // C++ [over.built]p9:
8432   //  For every promoted arithmetic type T, there exist candidate
8433   //  operator functions of the form
8434   //
8435   //       T         operator+(T);
8436   //       T         operator-(T);
8437   void addUnaryPlusOrMinusArithmeticOverloads() {
8438     if (!HasArithmeticOrEnumeralCandidateType)
8439       return;
8440 
8441     for (unsigned Arith = FirstPromotedArithmeticType;
8442          Arith < LastPromotedArithmeticType; ++Arith) {
8443       QualType ArithTy = ArithmeticTypes[Arith];
8444       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8445     }
8446 
8447     // Extension: We also add these operators for vector types.
8448     for (QualType VecTy : CandidateTypes[0].vector_types())
8449       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8450   }
8451 
8452   // C++ [over.built]p8:
8453   //   For every type T, there exist candidate operator functions of
8454   //   the form
8455   //
8456   //       T*         operator+(T*);
8457   void addUnaryPlusPointerOverloads() {
8458     for (QualType ParamTy : CandidateTypes[0].pointer_types())
8459       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8460   }
8461 
8462   // C++ [over.built]p10:
8463   //   For every promoted integral type T, there exist candidate
8464   //   operator functions of the form
8465   //
8466   //        T         operator~(T);
8467   void addUnaryTildePromotedIntegralOverloads() {
8468     if (!HasArithmeticOrEnumeralCandidateType)
8469       return;
8470 
8471     for (unsigned Int = FirstPromotedIntegralType;
8472          Int < LastPromotedIntegralType; ++Int) {
8473       QualType IntTy = ArithmeticTypes[Int];
8474       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8475     }
8476 
8477     // Extension: We also add this operator for vector types.
8478     for (QualType VecTy : CandidateTypes[0].vector_types())
8479       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8480   }
8481 
8482   // C++ [over.match.oper]p16:
8483   //   For every pointer to member type T or type std::nullptr_t, there
8484   //   exist candidate operator functions of the form
8485   //
8486   //        bool operator==(T,T);
8487   //        bool operator!=(T,T);
8488   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8489     /// Set of (canonical) types that we've already handled.
8490     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8491 
8492     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8493       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
8494         // Don't add the same builtin candidate twice.
8495         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
8496           continue;
8497 
8498         QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
8499         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8500       }
8501 
8502       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8503         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8504         if (AddedTypes.insert(NullPtrTy).second) {
8505           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8506           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8507         }
8508       }
8509     }
8510   }
8511 
8512   // C++ [over.built]p15:
8513   //
8514   //   For every T, where T is an enumeration type or a pointer type,
8515   //   there exist candidate operator functions of the form
8516   //
8517   //        bool       operator<(T, T);
8518   //        bool       operator>(T, T);
8519   //        bool       operator<=(T, T);
8520   //        bool       operator>=(T, T);
8521   //        bool       operator==(T, T);
8522   //        bool       operator!=(T, T);
8523   //           R       operator<=>(T, T)
8524   void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
8525     // C++ [over.match.oper]p3:
8526     //   [...]the built-in candidates include all of the candidate operator
8527     //   functions defined in 13.6 that, compared to the given operator, [...]
8528     //   do not have the same parameter-type-list as any non-template non-member
8529     //   candidate.
8530     //
8531     // Note that in practice, this only affects enumeration types because there
8532     // aren't any built-in candidates of record type, and a user-defined operator
8533     // must have an operand of record or enumeration type. Also, the only other
8534     // overloaded operator with enumeration arguments, operator=,
8535     // cannot be overloaded for enumeration types, so this is the only place
8536     // where we must suppress candidates like this.
8537     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8538       UserDefinedBinaryOperators;
8539 
8540     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8541       if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
8542         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8543                                          CEnd = CandidateSet.end();
8544              C != CEnd; ++C) {
8545           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8546             continue;
8547 
8548           if (C->Function->isFunctionTemplateSpecialization())
8549             continue;
8550 
8551           // We interpret "same parameter-type-list" as applying to the
8552           // "synthesized candidate, with the order of the two parameters
8553           // reversed", not to the original function.
8554           bool Reversed = C->isReversed();
8555           QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
8556                                         ->getType()
8557                                         .getUnqualifiedType();
8558           QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
8559                                          ->getType()
8560                                          .getUnqualifiedType();
8561 
8562           // Skip if either parameter isn't of enumeral type.
8563           if (!FirstParamType->isEnumeralType() ||
8564               !SecondParamType->isEnumeralType())
8565             continue;
8566 
8567           // Add this operator to the set of known user-defined operators.
8568           UserDefinedBinaryOperators.insert(
8569             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8570                            S.Context.getCanonicalType(SecondParamType)));
8571         }
8572       }
8573     }
8574 
8575     /// Set of (canonical) types that we've already handled.
8576     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8577 
8578     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8579       for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
8580         // Don't add the same builtin candidate twice.
8581         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8582           continue;
8583         if (IsSpaceship && PtrTy->isFunctionPointerType())
8584           continue;
8585 
8586         QualType ParamTypes[2] = {PtrTy, PtrTy};
8587         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8588       }
8589       for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
8590         CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
8591 
8592         // Don't add the same builtin candidate twice, or if a user defined
8593         // candidate exists.
8594         if (!AddedTypes.insert(CanonType).second ||
8595             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8596                                                             CanonType)))
8597           continue;
8598         QualType ParamTypes[2] = {EnumTy, EnumTy};
8599         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8600       }
8601     }
8602   }
8603 
8604   // C++ [over.built]p13:
8605   //
8606   //   For every cv-qualified or cv-unqualified object type T
8607   //   there exist candidate operator functions of the form
8608   //
8609   //      T*         operator+(T*, ptrdiff_t);
8610   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8611   //      T*         operator-(T*, ptrdiff_t);
8612   //      T*         operator+(ptrdiff_t, T*);
8613   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8614   //
8615   // C++ [over.built]p14:
8616   //
8617   //   For every T, where T is a pointer to object type, there
8618   //   exist candidate operator functions of the form
8619   //
8620   //      ptrdiff_t  operator-(T, T);
8621   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8622     /// Set of (canonical) types that we've already handled.
8623     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8624 
8625     for (int Arg = 0; Arg < 2; ++Arg) {
8626       QualType AsymmetricParamTypes[2] = {
8627         S.Context.getPointerDiffType(),
8628         S.Context.getPointerDiffType(),
8629       };
8630       for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
8631         QualType PointeeTy = PtrTy->getPointeeType();
8632         if (!PointeeTy->isObjectType())
8633           continue;
8634 
8635         AsymmetricParamTypes[Arg] = PtrTy;
8636         if (Arg == 0 || Op == OO_Plus) {
8637           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8638           // T* operator+(ptrdiff_t, T*);
8639           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8640         }
8641         if (Op == OO_Minus) {
8642           // ptrdiff_t operator-(T, T);
8643           if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8644             continue;
8645 
8646           QualType ParamTypes[2] = {PtrTy, PtrTy};
8647           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8648         }
8649       }
8650     }
8651   }
8652 
8653   // C++ [over.built]p12:
8654   //
8655   //   For every pair of promoted arithmetic types L and R, there
8656   //   exist candidate operator functions of the form
8657   //
8658   //        LR         operator*(L, R);
8659   //        LR         operator/(L, R);
8660   //        LR         operator+(L, R);
8661   //        LR         operator-(L, R);
8662   //        bool       operator<(L, R);
8663   //        bool       operator>(L, R);
8664   //        bool       operator<=(L, R);
8665   //        bool       operator>=(L, R);
8666   //        bool       operator==(L, R);
8667   //        bool       operator!=(L, R);
8668   //
8669   //   where LR is the result of the usual arithmetic conversions
8670   //   between types L and R.
8671   //
8672   // C++ [over.built]p24:
8673   //
8674   //   For every pair of promoted arithmetic types L and R, there exist
8675   //   candidate operator functions of the form
8676   //
8677   //        LR       operator?(bool, L, R);
8678   //
8679   //   where LR is the result of the usual arithmetic conversions
8680   //   between types L and R.
8681   // Our candidates ignore the first parameter.
8682   void addGenericBinaryArithmeticOverloads() {
8683     if (!HasArithmeticOrEnumeralCandidateType)
8684       return;
8685 
8686     for (unsigned Left = FirstPromotedArithmeticType;
8687          Left < LastPromotedArithmeticType; ++Left) {
8688       for (unsigned Right = FirstPromotedArithmeticType;
8689            Right < LastPromotedArithmeticType; ++Right) {
8690         QualType LandR[2] = { ArithmeticTypes[Left],
8691                               ArithmeticTypes[Right] };
8692         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8693       }
8694     }
8695 
8696     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8697     // conditional operator for vector types.
8698     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8699       for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
8700         QualType LandR[2] = {Vec1Ty, Vec2Ty};
8701         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8702       }
8703   }
8704 
8705   /// Add binary operator overloads for each candidate matrix type M1, M2:
8706   ///  * (M1, M1) -> M1
8707   ///  * (M1, M1.getElementType()) -> M1
8708   ///  * (M2.getElementType(), M2) -> M2
8709   ///  * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
8710   void addMatrixBinaryArithmeticOverloads() {
8711     if (!HasArithmeticOrEnumeralCandidateType)
8712       return;
8713 
8714     for (QualType M1 : CandidateTypes[0].matrix_types()) {
8715       AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
8716       AddCandidate(M1, M1);
8717     }
8718 
8719     for (QualType M2 : CandidateTypes[1].matrix_types()) {
8720       AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
8721       if (!CandidateTypes[0].containsMatrixType(M2))
8722         AddCandidate(M2, M2);
8723     }
8724   }
8725 
8726   // C++2a [over.built]p14:
8727   //
8728   //   For every integral type T there exists a candidate operator function
8729   //   of the form
8730   //
8731   //        std::strong_ordering operator<=>(T, T)
8732   //
8733   // C++2a [over.built]p15:
8734   //
8735   //   For every pair of floating-point types L and R, there exists a candidate
8736   //   operator function of the form
8737   //
8738   //       std::partial_ordering operator<=>(L, R);
8739   //
8740   // FIXME: The current specification for integral types doesn't play nice with
8741   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8742   // comparisons. Under the current spec this can lead to ambiguity during
8743   // overload resolution. For example:
8744   //
8745   //   enum A : int {a};
8746   //   auto x = (a <=> (long)42);
8747   //
8748   //   error: call is ambiguous for arguments 'A' and 'long'.
8749   //   note: candidate operator<=>(int, int)
8750   //   note: candidate operator<=>(long, long)
8751   //
8752   // To avoid this error, this function deviates from the specification and adds
8753   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8754   // arithmetic types (the same as the generic relational overloads).
8755   //
8756   // For now this function acts as a placeholder.
8757   void addThreeWayArithmeticOverloads() {
8758     addGenericBinaryArithmeticOverloads();
8759   }
8760 
8761   // C++ [over.built]p17:
8762   //
8763   //   For every pair of promoted integral types L and R, there
8764   //   exist candidate operator functions of the form
8765   //
8766   //      LR         operator%(L, R);
8767   //      LR         operator&(L, R);
8768   //      LR         operator^(L, R);
8769   //      LR         operator|(L, R);
8770   //      L          operator<<(L, R);
8771   //      L          operator>>(L, R);
8772   //
8773   //   where LR is the result of the usual arithmetic conversions
8774   //   between types L and R.
8775   void addBinaryBitwiseArithmeticOverloads() {
8776     if (!HasArithmeticOrEnumeralCandidateType)
8777       return;
8778 
8779     for (unsigned Left = FirstPromotedIntegralType;
8780          Left < LastPromotedIntegralType; ++Left) {
8781       for (unsigned Right = FirstPromotedIntegralType;
8782            Right < LastPromotedIntegralType; ++Right) {
8783         QualType LandR[2] = { ArithmeticTypes[Left],
8784                               ArithmeticTypes[Right] };
8785         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8786       }
8787     }
8788   }
8789 
8790   // C++ [over.built]p20:
8791   //
8792   //   For every pair (T, VQ), where T is an enumeration or
8793   //   pointer to member type and VQ is either volatile or
8794   //   empty, there exist candidate operator functions of the form
8795   //
8796   //        VQ T&      operator=(VQ T&, T);
8797   void addAssignmentMemberPointerOrEnumeralOverloads() {
8798     /// Set of (canonical) types that we've already handled.
8799     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8800 
8801     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8802       for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
8803         if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
8804           continue;
8805 
8806         AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
8807       }
8808 
8809       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
8810         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
8811           continue;
8812 
8813         AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
8814       }
8815     }
8816   }
8817 
8818   // C++ [over.built]p19:
8819   //
8820   //   For every pair (T, VQ), where T is any type and VQ is either
8821   //   volatile or empty, there exist candidate operator functions
8822   //   of the form
8823   //
8824   //        T*VQ&      operator=(T*VQ&, T*);
8825   //
8826   // C++ [over.built]p21:
8827   //
8828   //   For every pair (T, VQ), where T is a cv-qualified or
8829   //   cv-unqualified object type and VQ is either volatile or
8830   //   empty, there exist candidate operator functions of the form
8831   //
8832   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8833   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8834   void addAssignmentPointerOverloads(bool isEqualOp) {
8835     /// Set of (canonical) types that we've already handled.
8836     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8837 
8838     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
8839       // If this is operator=, keep track of the builtin candidates we added.
8840       if (isEqualOp)
8841         AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
8842       else if (!PtrTy->getPointeeType()->isObjectType())
8843         continue;
8844 
8845       // non-volatile version
8846       QualType ParamTypes[2] = {
8847           S.Context.getLValueReferenceType(PtrTy),
8848           isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
8849       };
8850       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8851                             /*IsAssignmentOperator=*/ isEqualOp);
8852 
8853       bool NeedVolatile = !PtrTy.isVolatileQualified() &&
8854                           VisibleTypeConversionsQuals.hasVolatile();
8855       if (NeedVolatile) {
8856         // volatile version
8857         ParamTypes[0] =
8858             S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy));
8859         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8860                               /*IsAssignmentOperator=*/isEqualOp);
8861       }
8862 
8863       if (!PtrTy.isRestrictQualified() &&
8864           VisibleTypeConversionsQuals.hasRestrict()) {
8865         // restrict version
8866         ParamTypes[0] =
8867             S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy));
8868         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8869                               /*IsAssignmentOperator=*/isEqualOp);
8870 
8871         if (NeedVolatile) {
8872           // volatile restrict version
8873           ParamTypes[0] =
8874               S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
8875                   PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
8876           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8877                                 /*IsAssignmentOperator=*/isEqualOp);
8878         }
8879       }
8880     }
8881 
8882     if (isEqualOp) {
8883       for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
8884         // Make sure we don't add the same candidate twice.
8885         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8886           continue;
8887 
8888         QualType ParamTypes[2] = {
8889             S.Context.getLValueReferenceType(PtrTy),
8890             PtrTy,
8891         };
8892 
8893         // non-volatile version
8894         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8895                               /*IsAssignmentOperator=*/true);
8896 
8897         bool NeedVolatile = !PtrTy.isVolatileQualified() &&
8898                             VisibleTypeConversionsQuals.hasVolatile();
8899         if (NeedVolatile) {
8900           // volatile version
8901           ParamTypes[0] = S.Context.getLValueReferenceType(
8902               S.Context.getVolatileType(PtrTy));
8903           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8904                                 /*IsAssignmentOperator=*/true);
8905         }
8906 
8907         if (!PtrTy.isRestrictQualified() &&
8908             VisibleTypeConversionsQuals.hasRestrict()) {
8909           // restrict version
8910           ParamTypes[0] = S.Context.getLValueReferenceType(
8911               S.Context.getRestrictType(PtrTy));
8912           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8913                                 /*IsAssignmentOperator=*/true);
8914 
8915           if (NeedVolatile) {
8916             // volatile restrict version
8917             ParamTypes[0] =
8918                 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
8919                     PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
8920             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8921                                   /*IsAssignmentOperator=*/true);
8922           }
8923         }
8924       }
8925     }
8926   }
8927 
8928   // C++ [over.built]p18:
8929   //
8930   //   For every triple (L, VQ, R), where L is an arithmetic type,
8931   //   VQ is either volatile or empty, and R is a promoted
8932   //   arithmetic type, there exist candidate operator functions of
8933   //   the form
8934   //
8935   //        VQ L&      operator=(VQ L&, R);
8936   //        VQ L&      operator*=(VQ L&, R);
8937   //        VQ L&      operator/=(VQ L&, R);
8938   //        VQ L&      operator+=(VQ L&, R);
8939   //        VQ L&      operator-=(VQ L&, R);
8940   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8941     if (!HasArithmeticOrEnumeralCandidateType)
8942       return;
8943 
8944     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8945       for (unsigned Right = FirstPromotedArithmeticType;
8946            Right < LastPromotedArithmeticType; ++Right) {
8947         QualType ParamTypes[2];
8948         ParamTypes[1] = ArithmeticTypes[Right];
8949         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8950             S, ArithmeticTypes[Left], Args[0]);
8951         // Add this built-in operator as a candidate (VQ is empty).
8952         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8953         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8954                               /*IsAssignmentOperator=*/isEqualOp);
8955 
8956         // Add this built-in operator as a candidate (VQ is 'volatile').
8957         if (VisibleTypeConversionsQuals.hasVolatile()) {
8958           ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy);
8959           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8960           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8961                                 /*IsAssignmentOperator=*/isEqualOp);
8962         }
8963       }
8964     }
8965 
8966     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8967     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8968       for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
8969         QualType ParamTypes[2];
8970         ParamTypes[1] = Vec2Ty;
8971         // Add this built-in operator as a candidate (VQ is empty).
8972         ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
8973         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8974                               /*IsAssignmentOperator=*/isEqualOp);
8975 
8976         // Add this built-in operator as a candidate (VQ is 'volatile').
8977         if (VisibleTypeConversionsQuals.hasVolatile()) {
8978           ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
8979           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8980           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8981                                 /*IsAssignmentOperator=*/isEqualOp);
8982         }
8983       }
8984   }
8985 
8986   // C++ [over.built]p22:
8987   //
8988   //   For every triple (L, VQ, R), where L is an integral type, VQ
8989   //   is either volatile or empty, and R is a promoted integral
8990   //   type, there exist candidate operator functions of the form
8991   //
8992   //        VQ L&       operator%=(VQ L&, R);
8993   //        VQ L&       operator<<=(VQ L&, R);
8994   //        VQ L&       operator>>=(VQ L&, R);
8995   //        VQ L&       operator&=(VQ L&, R);
8996   //        VQ L&       operator^=(VQ L&, R);
8997   //        VQ L&       operator|=(VQ L&, R);
8998   void addAssignmentIntegralOverloads() {
8999     if (!HasArithmeticOrEnumeralCandidateType)
9000       return;
9001 
9002     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
9003       for (unsigned Right = FirstPromotedIntegralType;
9004            Right < LastPromotedIntegralType; ++Right) {
9005         QualType ParamTypes[2];
9006         ParamTypes[1] = ArithmeticTypes[Right];
9007         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
9008             S, ArithmeticTypes[Left], Args[0]);
9009         // Add this built-in operator as a candidate (VQ is empty).
9010         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
9011         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9012         if (VisibleTypeConversionsQuals.hasVolatile()) {
9013           // Add this built-in operator as a candidate (VQ is 'volatile').
9014           ParamTypes[0] = LeftBaseTy;
9015           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
9016           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
9017           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9018         }
9019       }
9020     }
9021   }
9022 
9023   // C++ [over.operator]p23:
9024   //
9025   //   There also exist candidate operator functions of the form
9026   //
9027   //        bool        operator!(bool);
9028   //        bool        operator&&(bool, bool);
9029   //        bool        operator||(bool, bool);
9030   void addExclaimOverload() {
9031     QualType ParamTy = S.Context.BoolTy;
9032     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
9033                           /*IsAssignmentOperator=*/false,
9034                           /*NumContextualBoolArguments=*/1);
9035   }
9036   void addAmpAmpOrPipePipeOverload() {
9037     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
9038     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9039                           /*IsAssignmentOperator=*/false,
9040                           /*NumContextualBoolArguments=*/2);
9041   }
9042 
9043   // C++ [over.built]p13:
9044   //
9045   //   For every cv-qualified or cv-unqualified object type T there
9046   //   exist candidate operator functions of the form
9047   //
9048   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
9049   //        T&         operator[](T*, ptrdiff_t);
9050   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
9051   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
9052   //        T&         operator[](ptrdiff_t, T*);
9053   void addSubscriptOverloads() {
9054     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9055       QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
9056       QualType PointeeType = PtrTy->getPointeeType();
9057       if (!PointeeType->isObjectType())
9058         continue;
9059 
9060       // T& operator[](T*, ptrdiff_t)
9061       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9062     }
9063 
9064     for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9065       QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
9066       QualType PointeeType = PtrTy->getPointeeType();
9067       if (!PointeeType->isObjectType())
9068         continue;
9069 
9070       // T& operator[](ptrdiff_t, T*)
9071       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9072     }
9073   }
9074 
9075   // C++ [over.built]p11:
9076   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9077   //    C1 is the same type as C2 or is a derived class of C2, T is an object
9078   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9079   //    there exist candidate operator functions of the form
9080   //
9081   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9082   //
9083   //    where CV12 is the union of CV1 and CV2.
9084   void addArrowStarOverloads() {
9085     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9086       QualType C1Ty = PtrTy;
9087       QualType C1;
9088       QualifierCollector Q1;
9089       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
9090       if (!isa<RecordType>(C1))
9091         continue;
9092       // heuristic to reduce number of builtin candidates in the set.
9093       // Add volatile/restrict version only if there are conversions to a
9094       // volatile/restrict type.
9095       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9096         continue;
9097       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9098         continue;
9099       for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
9100         const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
9101         QualType C2 = QualType(mptr->getClass(), 0);
9102         C2 = C2.getUnqualifiedType();
9103         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9104           break;
9105         QualType ParamTypes[2] = {PtrTy, MemPtrTy};
9106         // build CV12 T&
9107         QualType T = mptr->getPointeeType();
9108         if (!VisibleTypeConversionsQuals.hasVolatile() &&
9109             T.isVolatileQualified())
9110           continue;
9111         if (!VisibleTypeConversionsQuals.hasRestrict() &&
9112             T.isRestrictQualified())
9113           continue;
9114         T = Q1.apply(S.Context, T);
9115         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9116       }
9117     }
9118   }
9119 
9120   // Note that we don't consider the first argument, since it has been
9121   // contextually converted to bool long ago. The candidates below are
9122   // therefore added as binary.
9123   //
9124   // C++ [over.built]p25:
9125   //   For every type T, where T is a pointer, pointer-to-member, or scoped
9126   //   enumeration type, there exist candidate operator functions of the form
9127   //
9128   //        T        operator?(bool, T, T);
9129   //
9130   void addConditionalOperatorOverloads() {
9131     /// Set of (canonical) types that we've already handled.
9132     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9133 
9134     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9135       for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9136         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9137           continue;
9138 
9139         QualType ParamTypes[2] = {PtrTy, PtrTy};
9140         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9141       }
9142 
9143       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9144         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9145           continue;
9146 
9147         QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9148         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9149       }
9150 
9151       if (S.getLangOpts().CPlusPlus11) {
9152         for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9153           if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
9154             continue;
9155 
9156           if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9157             continue;
9158 
9159           QualType ParamTypes[2] = {EnumTy, EnumTy};
9160           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9161         }
9162       }
9163     }
9164   }
9165 };
9166 
9167 } // end anonymous namespace
9168 
9169 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
9170 /// operator overloads to the candidate set (C++ [over.built]), based
9171 /// on the operator @p Op and the arguments given. For example, if the
9172 /// operator is a binary '+', this routine might add "int
9173 /// operator+(int, int)" to cover integer addition.
9174 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9175                                         SourceLocation OpLoc,
9176                                         ArrayRef<Expr *> Args,
9177                                         OverloadCandidateSet &CandidateSet) {
9178   // Find all of the types that the arguments can convert to, but only
9179   // if the operator we're looking at has built-in operator candidates
9180   // that make use of these types. Also record whether we encounter non-record
9181   // candidate types or either arithmetic or enumeral candidate types.
9182   Qualifiers VisibleTypeConversionsQuals;
9183   VisibleTypeConversionsQuals.addConst();
9184   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
9185     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9186 
9187   bool HasNonRecordCandidateType = false;
9188   bool HasArithmeticOrEnumeralCandidateType = false;
9189   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9190   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9191     CandidateTypes.emplace_back(*this);
9192     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9193                                                  OpLoc,
9194                                                  true,
9195                                                  (Op == OO_Exclaim ||
9196                                                   Op == OO_AmpAmp ||
9197                                                   Op == OO_PipePipe),
9198                                                  VisibleTypeConversionsQuals);
9199     HasNonRecordCandidateType = HasNonRecordCandidateType ||
9200         CandidateTypes[ArgIdx].hasNonRecordTypes();
9201     HasArithmeticOrEnumeralCandidateType =
9202         HasArithmeticOrEnumeralCandidateType ||
9203         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9204   }
9205 
9206   // Exit early when no non-record types have been added to the candidate set
9207   // for any of the arguments to the operator.
9208   //
9209   // We can't exit early for !, ||, or &&, since there we have always have
9210   // 'bool' overloads.
9211   if (!HasNonRecordCandidateType &&
9212       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9213     return;
9214 
9215   // Setup an object to manage the common state for building overloads.
9216   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9217                                            VisibleTypeConversionsQuals,
9218                                            HasArithmeticOrEnumeralCandidateType,
9219                                            CandidateTypes, CandidateSet);
9220 
9221   // Dispatch over the operation to add in only those overloads which apply.
9222   switch (Op) {
9223   case OO_None:
9224   case NUM_OVERLOADED_OPERATORS:
9225     llvm_unreachable("Expected an overloaded operator");
9226 
9227   case OO_New:
9228   case OO_Delete:
9229   case OO_Array_New:
9230   case OO_Array_Delete:
9231   case OO_Call:
9232     llvm_unreachable(
9233                     "Special operators don't use AddBuiltinOperatorCandidates");
9234 
9235   case OO_Comma:
9236   case OO_Arrow:
9237   case OO_Coawait:
9238     // C++ [over.match.oper]p3:
9239     //   -- For the operator ',', the unary operator '&', the
9240     //      operator '->', or the operator 'co_await', the
9241     //      built-in candidates set is empty.
9242     break;
9243 
9244   case OO_Plus: // '+' is either unary or binary
9245     if (Args.size() == 1)
9246       OpBuilder.addUnaryPlusPointerOverloads();
9247     LLVM_FALLTHROUGH;
9248 
9249   case OO_Minus: // '-' is either unary or binary
9250     if (Args.size() == 1) {
9251       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9252     } else {
9253       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9254       OpBuilder.addGenericBinaryArithmeticOverloads();
9255       OpBuilder.addMatrixBinaryArithmeticOverloads();
9256     }
9257     break;
9258 
9259   case OO_Star: // '*' is either unary or binary
9260     if (Args.size() == 1)
9261       OpBuilder.addUnaryStarPointerOverloads();
9262     else {
9263       OpBuilder.addGenericBinaryArithmeticOverloads();
9264       OpBuilder.addMatrixBinaryArithmeticOverloads();
9265     }
9266     break;
9267 
9268   case OO_Slash:
9269     OpBuilder.addGenericBinaryArithmeticOverloads();
9270     break;
9271 
9272   case OO_PlusPlus:
9273   case OO_MinusMinus:
9274     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9275     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9276     break;
9277 
9278   case OO_EqualEqual:
9279   case OO_ExclaimEqual:
9280     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9281     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9282     OpBuilder.addGenericBinaryArithmeticOverloads();
9283     break;
9284 
9285   case OO_Less:
9286   case OO_Greater:
9287   case OO_LessEqual:
9288   case OO_GreaterEqual:
9289     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9290     OpBuilder.addGenericBinaryArithmeticOverloads();
9291     break;
9292 
9293   case OO_Spaceship:
9294     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
9295     OpBuilder.addThreeWayArithmeticOverloads();
9296     break;
9297 
9298   case OO_Percent:
9299   case OO_Caret:
9300   case OO_Pipe:
9301   case OO_LessLess:
9302   case OO_GreaterGreater:
9303     OpBuilder.addBinaryBitwiseArithmeticOverloads();
9304     break;
9305 
9306   case OO_Amp: // '&' is either unary or binary
9307     if (Args.size() == 1)
9308       // C++ [over.match.oper]p3:
9309       //   -- For the operator ',', the unary operator '&', or the
9310       //      operator '->', the built-in candidates set is empty.
9311       break;
9312 
9313     OpBuilder.addBinaryBitwiseArithmeticOverloads();
9314     break;
9315 
9316   case OO_Tilde:
9317     OpBuilder.addUnaryTildePromotedIntegralOverloads();
9318     break;
9319 
9320   case OO_Equal:
9321     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9322     LLVM_FALLTHROUGH;
9323 
9324   case OO_PlusEqual:
9325   case OO_MinusEqual:
9326     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9327     LLVM_FALLTHROUGH;
9328 
9329   case OO_StarEqual:
9330   case OO_SlashEqual:
9331     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9332     break;
9333 
9334   case OO_PercentEqual:
9335   case OO_LessLessEqual:
9336   case OO_GreaterGreaterEqual:
9337   case OO_AmpEqual:
9338   case OO_CaretEqual:
9339   case OO_PipeEqual:
9340     OpBuilder.addAssignmentIntegralOverloads();
9341     break;
9342 
9343   case OO_Exclaim:
9344     OpBuilder.addExclaimOverload();
9345     break;
9346 
9347   case OO_AmpAmp:
9348   case OO_PipePipe:
9349     OpBuilder.addAmpAmpOrPipePipeOverload();
9350     break;
9351 
9352   case OO_Subscript:
9353     if (Args.size() == 2)
9354       OpBuilder.addSubscriptOverloads();
9355     break;
9356 
9357   case OO_ArrowStar:
9358     OpBuilder.addArrowStarOverloads();
9359     break;
9360 
9361   case OO_Conditional:
9362     OpBuilder.addConditionalOperatorOverloads();
9363     OpBuilder.addGenericBinaryArithmeticOverloads();
9364     break;
9365   }
9366 }
9367 
9368 /// Add function candidates found via argument-dependent lookup
9369 /// to the set of overloading candidates.
9370 ///
9371 /// This routine performs argument-dependent name lookup based on the
9372 /// given function name (which may also be an operator name) and adds
9373 /// all of the overload candidates found by ADL to the overload
9374 /// candidate set (C++ [basic.lookup.argdep]).
9375 void
9376 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9377                                            SourceLocation Loc,
9378                                            ArrayRef<Expr *> Args,
9379                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
9380                                            OverloadCandidateSet& CandidateSet,
9381                                            bool PartialOverloading) {
9382   ADLResult Fns;
9383 
9384   // FIXME: This approach for uniquing ADL results (and removing
9385   // redundant candidates from the set) relies on pointer-equality,
9386   // which means we need to key off the canonical decl.  However,
9387   // always going back to the canonical decl might not get us the
9388   // right set of default arguments.  What default arguments are
9389   // we supposed to consider on ADL candidates, anyway?
9390 
9391   // FIXME: Pass in the explicit template arguments?
9392   ArgumentDependentLookup(Name, Loc, Args, Fns);
9393 
9394   // Erase all of the candidates we already knew about.
9395   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9396                                    CandEnd = CandidateSet.end();
9397        Cand != CandEnd; ++Cand)
9398     if (Cand->Function) {
9399       Fns.erase(Cand->Function);
9400       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9401         Fns.erase(FunTmpl);
9402     }
9403 
9404   // For each of the ADL candidates we found, add it to the overload
9405   // set.
9406   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9407     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9408 
9409     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9410       if (ExplicitTemplateArgs)
9411         continue;
9412 
9413       AddOverloadCandidate(
9414           FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
9415           PartialOverloading, /*AllowExplicit=*/true,
9416           /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
9417       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) {
9418         AddOverloadCandidate(
9419             FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
9420             /*SuppressUserConversions=*/false, PartialOverloading,
9421             /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
9422             ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed);
9423       }
9424     } else {
9425       auto *FTD = cast<FunctionTemplateDecl>(*I);
9426       AddTemplateOverloadCandidate(
9427           FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
9428           /*SuppressUserConversions=*/false, PartialOverloading,
9429           /*AllowExplicit=*/true, ADLCallKind::UsesADL);
9430       if (CandidateSet.getRewriteInfo().shouldAddReversed(
9431               Context, FTD->getTemplatedDecl())) {
9432         AddTemplateOverloadCandidate(
9433             FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
9434             CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
9435             /*AllowExplicit=*/true, ADLCallKind::UsesADL,
9436             OverloadCandidateParamOrder::Reversed);
9437       }
9438     }
9439   }
9440 }
9441 
9442 namespace {
9443 enum class Comparison { Equal, Better, Worse };
9444 }
9445 
9446 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9447 /// overload resolution.
9448 ///
9449 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9450 /// Cand1's first N enable_if attributes have precisely the same conditions as
9451 /// Cand2's first N enable_if attributes (where N = the number of enable_if
9452 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9453 ///
9454 /// Note that you can have a pair of candidates such that Cand1's enable_if
9455 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9456 /// worse than Cand1's.
9457 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9458                                        const FunctionDecl *Cand2) {
9459   // Common case: One (or both) decls don't have enable_if attrs.
9460   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9461   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9462   if (!Cand1Attr || !Cand2Attr) {
9463     if (Cand1Attr == Cand2Attr)
9464       return Comparison::Equal;
9465     return Cand1Attr ? Comparison::Better : Comparison::Worse;
9466   }
9467 
9468   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9469   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9470 
9471   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9472   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9473     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9474     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9475 
9476     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9477     // has fewer enable_if attributes than Cand2, and vice versa.
9478     if (!Cand1A)
9479       return Comparison::Worse;
9480     if (!Cand2A)
9481       return Comparison::Better;
9482 
9483     Cand1ID.clear();
9484     Cand2ID.clear();
9485 
9486     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9487     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9488     if (Cand1ID != Cand2ID)
9489       return Comparison::Worse;
9490   }
9491 
9492   return Comparison::Equal;
9493 }
9494 
9495 static Comparison
9496 isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9497                               const OverloadCandidate &Cand2) {
9498   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9499       !Cand2.Function->isMultiVersion())
9500     return Comparison::Equal;
9501 
9502   // If both are invalid, they are equal. If one of them is invalid, the other
9503   // is better.
9504   if (Cand1.Function->isInvalidDecl()) {
9505     if (Cand2.Function->isInvalidDecl())
9506       return Comparison::Equal;
9507     return Comparison::Worse;
9508   }
9509   if (Cand2.Function->isInvalidDecl())
9510     return Comparison::Better;
9511 
9512   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9513   // cpu_dispatch, else arbitrarily based on the identifiers.
9514   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9515   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9516   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9517   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9518 
9519   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9520     return Comparison::Equal;
9521 
9522   if (Cand1CPUDisp && !Cand2CPUDisp)
9523     return Comparison::Better;
9524   if (Cand2CPUDisp && !Cand1CPUDisp)
9525     return Comparison::Worse;
9526 
9527   if (Cand1CPUSpec && Cand2CPUSpec) {
9528     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9529       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
9530                  ? Comparison::Better
9531                  : Comparison::Worse;
9532 
9533     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9534         FirstDiff = std::mismatch(
9535             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9536             Cand2CPUSpec->cpus_begin(),
9537             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9538               return LHS->getName() == RHS->getName();
9539             });
9540 
9541     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9542            "Two different cpu-specific versions should not have the same "
9543            "identifier list, otherwise they'd be the same decl!");
9544     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
9545                ? Comparison::Better
9546                : Comparison::Worse;
9547   }
9548   llvm_unreachable("No way to get here unless both had cpu_dispatch");
9549 }
9550 
9551 /// Compute the type of the implicit object parameter for the given function,
9552 /// if any. Returns None if there is no implicit object parameter, and a null
9553 /// QualType if there is a 'matches anything' implicit object parameter.
9554 static Optional<QualType> getImplicitObjectParamType(ASTContext &Context,
9555                                                      const FunctionDecl *F) {
9556   if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
9557     return llvm::None;
9558 
9559   auto *M = cast<CXXMethodDecl>(F);
9560   // Static member functions' object parameters match all types.
9561   if (M->isStatic())
9562     return QualType();
9563 
9564   QualType T = M->getThisObjectType();
9565   if (M->getRefQualifier() == RQ_RValue)
9566     return Context.getRValueReferenceType(T);
9567   return Context.getLValueReferenceType(T);
9568 }
9569 
9570 static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1,
9571                                    const FunctionDecl *F2, unsigned NumParams) {
9572   if (declaresSameEntity(F1, F2))
9573     return true;
9574 
9575   auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
9576     if (First) {
9577       if (Optional<QualType> T = getImplicitObjectParamType(Context, F))
9578         return *T;
9579     }
9580     assert(I < F->getNumParams());
9581     return F->getParamDecl(I++)->getType();
9582   };
9583 
9584   unsigned I1 = 0, I2 = 0;
9585   for (unsigned I = 0; I != NumParams; ++I) {
9586     QualType T1 = NextParam(F1, I1, I == 0);
9587     QualType T2 = NextParam(F2, I2, I == 0);
9588     assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
9589     if (!Context.hasSameUnqualifiedType(T1, T2))
9590       return false;
9591   }
9592   return true;
9593 }
9594 
9595 /// isBetterOverloadCandidate - Determines whether the first overload
9596 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9597 bool clang::isBetterOverloadCandidate(
9598     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9599     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9600   // Define viable functions to be better candidates than non-viable
9601   // functions.
9602   if (!Cand2.Viable)
9603     return Cand1.Viable;
9604   else if (!Cand1.Viable)
9605     return false;
9606 
9607   // [CUDA] A function with 'never' preference is marked not viable, therefore
9608   // is never shown up here. The worst preference shown up here is 'wrong side',
9609   // e.g. an H function called by a HD function in device compilation. This is
9610   // valid AST as long as the HD function is not emitted, e.g. it is an inline
9611   // function which is called only by an H function. A deferred diagnostic will
9612   // be triggered if it is emitted. However a wrong-sided function is still
9613   // a viable candidate here.
9614   //
9615   // If Cand1 can be emitted and Cand2 cannot be emitted in the current
9616   // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
9617   // can be emitted, Cand1 is not better than Cand2. This rule should have
9618   // precedence over other rules.
9619   //
9620   // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
9621   // other rules should be used to determine which is better. This is because
9622   // host/device based overloading resolution is mostly for determining
9623   // viability of a function. If two functions are both viable, other factors
9624   // should take precedence in preference, e.g. the standard-defined preferences
9625   // like argument conversion ranks or enable_if partial-ordering. The
9626   // preference for pass-object-size parameters is probably most similar to a
9627   // type-based-overloading decision and so should take priority.
9628   //
9629   // If other rules cannot determine which is better, CUDA preference will be
9630   // used again to determine which is better.
9631   //
9632   // TODO: Currently IdentifyCUDAPreference does not return correct values
9633   // for functions called in global variable initializers due to missing
9634   // correct context about device/host. Therefore we can only enforce this
9635   // rule when there is a caller. We should enforce this rule for functions
9636   // in global variable initializers once proper context is added.
9637   //
9638   // TODO: We can only enable the hostness based overloading resolution when
9639   // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
9640   // overloading resolution diagnostics.
9641   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
9642       S.getLangOpts().GPUExcludeWrongSideOverloads) {
9643     if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) {
9644       bool IsCallerImplicitHD = Sema::isCUDAImplicitHostDeviceFunction(Caller);
9645       bool IsCand1ImplicitHD =
9646           Sema::isCUDAImplicitHostDeviceFunction(Cand1.Function);
9647       bool IsCand2ImplicitHD =
9648           Sema::isCUDAImplicitHostDeviceFunction(Cand2.Function);
9649       auto P1 = S.IdentifyCUDAPreference(Caller, Cand1.Function);
9650       auto P2 = S.IdentifyCUDAPreference(Caller, Cand2.Function);
9651       assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never);
9652       // The implicit HD function may be a function in a system header which
9653       // is forced by pragma. In device compilation, if we prefer HD candidates
9654       // over wrong-sided candidates, overloading resolution may change, which
9655       // may result in non-deferrable diagnostics. As a workaround, we let
9656       // implicit HD candidates take equal preference as wrong-sided candidates.
9657       // This will preserve the overloading resolution.
9658       // TODO: We still need special handling of implicit HD functions since
9659       // they may incur other diagnostics to be deferred. We should make all
9660       // host/device related diagnostics deferrable and remove special handling
9661       // of implicit HD functions.
9662       auto EmitThreshold =
9663           (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
9664            (IsCand1ImplicitHD || IsCand2ImplicitHD))
9665               ? Sema::CFP_Never
9666               : Sema::CFP_WrongSide;
9667       auto Cand1Emittable = P1 > EmitThreshold;
9668       auto Cand2Emittable = P2 > EmitThreshold;
9669       if (Cand1Emittable && !Cand2Emittable)
9670         return true;
9671       if (!Cand1Emittable && Cand2Emittable)
9672         return false;
9673     }
9674   }
9675 
9676   // C++ [over.match.best]p1:
9677   //
9678   //   -- if F is a static member function, ICS1(F) is defined such
9679   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9680   //      any function G, and, symmetrically, ICS1(G) is neither
9681   //      better nor worse than ICS1(F).
9682   unsigned StartArg = 0;
9683   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9684     StartArg = 1;
9685 
9686   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9687     // We don't allow incompatible pointer conversions in C++.
9688     if (!S.getLangOpts().CPlusPlus)
9689       return ICS.isStandard() &&
9690              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9691 
9692     // The only ill-formed conversion we allow in C++ is the string literal to
9693     // char* conversion, which is only considered ill-formed after C++11.
9694     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9695            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9696   };
9697 
9698   // Define functions that don't require ill-formed conversions for a given
9699   // argument to be better candidates than functions that do.
9700   unsigned NumArgs = Cand1.Conversions.size();
9701   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9702   bool HasBetterConversion = false;
9703   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9704     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9705     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9706     if (Cand1Bad != Cand2Bad) {
9707       if (Cand1Bad)
9708         return false;
9709       HasBetterConversion = true;
9710     }
9711   }
9712 
9713   if (HasBetterConversion)
9714     return true;
9715 
9716   // C++ [over.match.best]p1:
9717   //   A viable function F1 is defined to be a better function than another
9718   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9719   //   conversion sequence than ICSi(F2), and then...
9720   bool HasWorseConversion = false;
9721   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9722     switch (CompareImplicitConversionSequences(S, Loc,
9723                                                Cand1.Conversions[ArgIdx],
9724                                                Cand2.Conversions[ArgIdx])) {
9725     case ImplicitConversionSequence::Better:
9726       // Cand1 has a better conversion sequence.
9727       HasBetterConversion = true;
9728       break;
9729 
9730     case ImplicitConversionSequence::Worse:
9731       if (Cand1.Function && Cand2.Function &&
9732           Cand1.isReversed() != Cand2.isReversed() &&
9733           haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function,
9734                                  NumArgs)) {
9735         // Work around large-scale breakage caused by considering reversed
9736         // forms of operator== in C++20:
9737         //
9738         // When comparing a function against a reversed function with the same
9739         // parameter types, if we have a better conversion for one argument and
9740         // a worse conversion for the other, the implicit conversion sequences
9741         // are treated as being equally good.
9742         //
9743         // This prevents a comparison function from being considered ambiguous
9744         // with a reversed form that is written in the same way.
9745         //
9746         // We diagnose this as an extension from CreateOverloadedBinOp.
9747         HasWorseConversion = true;
9748         break;
9749       }
9750 
9751       // Cand1 can't be better than Cand2.
9752       return false;
9753 
9754     case ImplicitConversionSequence::Indistinguishable:
9755       // Do nothing.
9756       break;
9757     }
9758   }
9759 
9760   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9761   //       ICSj(F2), or, if not that,
9762   if (HasBetterConversion && !HasWorseConversion)
9763     return true;
9764 
9765   //   -- the context is an initialization by user-defined conversion
9766   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9767   //      from the return type of F1 to the destination type (i.e.,
9768   //      the type of the entity being initialized) is a better
9769   //      conversion sequence than the standard conversion sequence
9770   //      from the return type of F2 to the destination type.
9771   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9772       Cand1.Function && Cand2.Function &&
9773       isa<CXXConversionDecl>(Cand1.Function) &&
9774       isa<CXXConversionDecl>(Cand2.Function)) {
9775     // First check whether we prefer one of the conversion functions over the
9776     // other. This only distinguishes the results in non-standard, extension
9777     // cases such as the conversion from a lambda closure type to a function
9778     // pointer or block.
9779     ImplicitConversionSequence::CompareKind Result =
9780         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9781     if (Result == ImplicitConversionSequence::Indistinguishable)
9782       Result = CompareStandardConversionSequences(S, Loc,
9783                                                   Cand1.FinalConversion,
9784                                                   Cand2.FinalConversion);
9785 
9786     if (Result != ImplicitConversionSequence::Indistinguishable)
9787       return Result == ImplicitConversionSequence::Better;
9788 
9789     // FIXME: Compare kind of reference binding if conversion functions
9790     // convert to a reference type used in direct reference binding, per
9791     // C++14 [over.match.best]p1 section 2 bullet 3.
9792   }
9793 
9794   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9795   // as combined with the resolution to CWG issue 243.
9796   //
9797   // When the context is initialization by constructor ([over.match.ctor] or
9798   // either phase of [over.match.list]), a constructor is preferred over
9799   // a conversion function.
9800   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9801       Cand1.Function && Cand2.Function &&
9802       isa<CXXConstructorDecl>(Cand1.Function) !=
9803           isa<CXXConstructorDecl>(Cand2.Function))
9804     return isa<CXXConstructorDecl>(Cand1.Function);
9805 
9806   //    -- F1 is a non-template function and F2 is a function template
9807   //       specialization, or, if not that,
9808   bool Cand1IsSpecialization = Cand1.Function &&
9809                                Cand1.Function->getPrimaryTemplate();
9810   bool Cand2IsSpecialization = Cand2.Function &&
9811                                Cand2.Function->getPrimaryTemplate();
9812   if (Cand1IsSpecialization != Cand2IsSpecialization)
9813     return Cand2IsSpecialization;
9814 
9815   //   -- F1 and F2 are function template specializations, and the function
9816   //      template for F1 is more specialized than the template for F2
9817   //      according to the partial ordering rules described in 14.5.5.2, or,
9818   //      if not that,
9819   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9820     if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
9821             Cand1.Function->getPrimaryTemplate(),
9822             Cand2.Function->getPrimaryTemplate(), Loc,
9823             isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
9824                                                    : TPOC_Call,
9825             Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments,
9826             Cand1.isReversed() ^ Cand2.isReversed()))
9827       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9828   }
9829 
9830   //   -— F1 and F2 are non-template functions with the same
9831   //      parameter-type-lists, and F1 is more constrained than F2 [...],
9832   if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization &&
9833       !Cand2IsSpecialization && Cand1.Function->hasPrototype() &&
9834       Cand2.Function->hasPrototype()) {
9835     auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType());
9836     auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType());
9837     if (PT1->getNumParams() == PT2->getNumParams() &&
9838         PT1->isVariadic() == PT2->isVariadic() &&
9839         S.FunctionParamTypesAreEqual(PT1, PT2)) {
9840       Expr *RC1 = Cand1.Function->getTrailingRequiresClause();
9841       Expr *RC2 = Cand2.Function->getTrailingRequiresClause();
9842       if (RC1 && RC2) {
9843         bool AtLeastAsConstrained1, AtLeastAsConstrained2;
9844         if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function,
9845                                      {RC2}, AtLeastAsConstrained1) ||
9846             S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function,
9847                                      {RC1}, AtLeastAsConstrained2))
9848           return false;
9849         if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
9850           return AtLeastAsConstrained1;
9851       } else if (RC1 || RC2) {
9852         return RC1 != nullptr;
9853       }
9854     }
9855   }
9856 
9857   //   -- F1 is a constructor for a class D, F2 is a constructor for a base
9858   //      class B of D, and for all arguments the corresponding parameters of
9859   //      F1 and F2 have the same type.
9860   // FIXME: Implement the "all parameters have the same type" check.
9861   bool Cand1IsInherited =
9862       isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9863   bool Cand2IsInherited =
9864       isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9865   if (Cand1IsInherited != Cand2IsInherited)
9866     return Cand2IsInherited;
9867   else if (Cand1IsInherited) {
9868     assert(Cand2IsInherited);
9869     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9870     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9871     if (Cand1Class->isDerivedFrom(Cand2Class))
9872       return true;
9873     if (Cand2Class->isDerivedFrom(Cand1Class))
9874       return false;
9875     // Inherited from sibling base classes: still ambiguous.
9876   }
9877 
9878   //   -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
9879   //   -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
9880   //      with reversed order of parameters and F1 is not
9881   //
9882   // We rank reversed + different operator as worse than just reversed, but
9883   // that comparison can never happen, because we only consider reversing for
9884   // the maximally-rewritten operator (== or <=>).
9885   if (Cand1.RewriteKind != Cand2.RewriteKind)
9886     return Cand1.RewriteKind < Cand2.RewriteKind;
9887 
9888   // Check C++17 tie-breakers for deduction guides.
9889   {
9890     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9891     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9892     if (Guide1 && Guide2) {
9893       //  -- F1 is generated from a deduction-guide and F2 is not
9894       if (Guide1->isImplicit() != Guide2->isImplicit())
9895         return Guide2->isImplicit();
9896 
9897       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9898       if (Guide1->isCopyDeductionCandidate())
9899         return true;
9900     }
9901   }
9902 
9903   // Check for enable_if value-based overload resolution.
9904   if (Cand1.Function && Cand2.Function) {
9905     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9906     if (Cmp != Comparison::Equal)
9907       return Cmp == Comparison::Better;
9908   }
9909 
9910   bool HasPS1 = Cand1.Function != nullptr &&
9911                 functionHasPassObjectSizeParams(Cand1.Function);
9912   bool HasPS2 = Cand2.Function != nullptr &&
9913                 functionHasPassObjectSizeParams(Cand2.Function);
9914   if (HasPS1 != HasPS2 && HasPS1)
9915     return true;
9916 
9917   auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
9918   if (MV == Comparison::Better)
9919     return true;
9920   if (MV == Comparison::Worse)
9921     return false;
9922 
9923   // If other rules cannot determine which is better, CUDA preference is used
9924   // to determine which is better.
9925   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9926     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9927     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9928            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9929   }
9930 
9931   // General member function overloading is handled above, so this only handles
9932   // constructors with address spaces.
9933   // This only handles address spaces since C++ has no other
9934   // qualifier that can be used with constructors.
9935   const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
9936   const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
9937   if (CD1 && CD2) {
9938     LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
9939     LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
9940     if (AS1 != AS2) {
9941       if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
9942         return true;
9943       if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
9944         return false;
9945     }
9946   }
9947 
9948   return false;
9949 }
9950 
9951 /// Determine whether two declarations are "equivalent" for the purposes of
9952 /// name lookup and overload resolution. This applies when the same internal/no
9953 /// linkage entity is defined by two modules (probably by textually including
9954 /// the same header). In such a case, we don't consider the declarations to
9955 /// declare the same entity, but we also don't want lookups with both
9956 /// declarations visible to be ambiguous in some cases (this happens when using
9957 /// a modularized libstdc++).
9958 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9959                                                   const NamedDecl *B) {
9960   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9961   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9962   if (!VA || !VB)
9963     return false;
9964 
9965   // The declarations must be declaring the same name as an internal linkage
9966   // entity in different modules.
9967   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9968           VB->getDeclContext()->getRedeclContext()) ||
9969       getOwningModule(VA) == getOwningModule(VB) ||
9970       VA->isExternallyVisible() || VB->isExternallyVisible())
9971     return false;
9972 
9973   // Check that the declarations appear to be equivalent.
9974   //
9975   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9976   // For constants and functions, we should check the initializer or body is
9977   // the same. For non-constant variables, we shouldn't allow it at all.
9978   if (Context.hasSameType(VA->getType(), VB->getType()))
9979     return true;
9980 
9981   // Enum constants within unnamed enumerations will have different types, but
9982   // may still be similar enough to be interchangeable for our purposes.
9983   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9984     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9985       // Only handle anonymous enums. If the enumerations were named and
9986       // equivalent, they would have been merged to the same type.
9987       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9988       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9989       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9990           !Context.hasSameType(EnumA->getIntegerType(),
9991                                EnumB->getIntegerType()))
9992         return false;
9993       // Allow this only if the value is the same for both enumerators.
9994       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9995     }
9996   }
9997 
9998   // Nothing else is sufficiently similar.
9999   return false;
10000 }
10001 
10002 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
10003     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
10004   assert(D && "Unknown declaration");
10005   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
10006 
10007   Module *M = getOwningModule(D);
10008   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
10009       << !M << (M ? M->getFullModuleName() : "");
10010 
10011   for (auto *E : Equiv) {
10012     Module *M = getOwningModule(E);
10013     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
10014         << !M << (M ? M->getFullModuleName() : "");
10015   }
10016 }
10017 
10018 /// Computes the best viable function (C++ 13.3.3)
10019 /// within an overload candidate set.
10020 ///
10021 /// \param Loc The location of the function name (or operator symbol) for
10022 /// which overload resolution occurs.
10023 ///
10024 /// \param Best If overload resolution was successful or found a deleted
10025 /// function, \p Best points to the candidate function found.
10026 ///
10027 /// \returns The result of overload resolution.
10028 OverloadingResult
10029 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
10030                                          iterator &Best) {
10031   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
10032   std::transform(begin(), end(), std::back_inserter(Candidates),
10033                  [](OverloadCandidate &Cand) { return &Cand; });
10034 
10035   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
10036   // are accepted by both clang and NVCC. However, during a particular
10037   // compilation mode only one call variant is viable. We need to
10038   // exclude non-viable overload candidates from consideration based
10039   // only on their host/device attributes. Specifically, if one
10040   // candidate call is WrongSide and the other is SameSide, we ignore
10041   // the WrongSide candidate.
10042   // We only need to remove wrong-sided candidates here if
10043   // -fgpu-exclude-wrong-side-overloads is off. When
10044   // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
10045   // uniformly in isBetterOverloadCandidate.
10046   if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) {
10047     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
10048     bool ContainsSameSideCandidate =
10049         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
10050           // Check viable function only.
10051           return Cand->Viable && Cand->Function &&
10052                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
10053                      Sema::CFP_SameSide;
10054         });
10055     if (ContainsSameSideCandidate) {
10056       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
10057         // Check viable function only to avoid unnecessary data copying/moving.
10058         return Cand->Viable && Cand->Function &&
10059                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
10060                    Sema::CFP_WrongSide;
10061       };
10062       llvm::erase_if(Candidates, IsWrongSideCandidate);
10063     }
10064   }
10065 
10066   // Find the best viable function.
10067   Best = end();
10068   for (auto *Cand : Candidates) {
10069     Cand->Best = false;
10070     if (Cand->Viable)
10071       if (Best == end() ||
10072           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
10073         Best = Cand;
10074   }
10075 
10076   // If we didn't find any viable functions, abort.
10077   if (Best == end())
10078     return OR_No_Viable_Function;
10079 
10080   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
10081 
10082   llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
10083   PendingBest.push_back(&*Best);
10084   Best->Best = true;
10085 
10086   // Make sure that this function is better than every other viable
10087   // function. If not, we have an ambiguity.
10088   while (!PendingBest.empty()) {
10089     auto *Curr = PendingBest.pop_back_val();
10090     for (auto *Cand : Candidates) {
10091       if (Cand->Viable && !Cand->Best &&
10092           !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
10093         PendingBest.push_back(Cand);
10094         Cand->Best = true;
10095 
10096         if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
10097                                                      Curr->Function))
10098           EquivalentCands.push_back(Cand->Function);
10099         else
10100           Best = end();
10101       }
10102     }
10103   }
10104 
10105   // If we found more than one best candidate, this is ambiguous.
10106   if (Best == end())
10107     return OR_Ambiguous;
10108 
10109   // Best is the best viable function.
10110   if (Best->Function && Best->Function->isDeleted())
10111     return OR_Deleted;
10112 
10113   if (!EquivalentCands.empty())
10114     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
10115                                                     EquivalentCands);
10116 
10117   return OR_Success;
10118 }
10119 
10120 namespace {
10121 
10122 enum OverloadCandidateKind {
10123   oc_function,
10124   oc_method,
10125   oc_reversed_binary_operator,
10126   oc_constructor,
10127   oc_implicit_default_constructor,
10128   oc_implicit_copy_constructor,
10129   oc_implicit_move_constructor,
10130   oc_implicit_copy_assignment,
10131   oc_implicit_move_assignment,
10132   oc_implicit_equality_comparison,
10133   oc_inherited_constructor
10134 };
10135 
10136 enum OverloadCandidateSelect {
10137   ocs_non_template,
10138   ocs_template,
10139   ocs_described_template,
10140 };
10141 
10142 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
10143 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
10144                           OverloadCandidateRewriteKind CRK,
10145                           std::string &Description) {
10146 
10147   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
10148   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
10149     isTemplate = true;
10150     Description = S.getTemplateArgumentBindingsText(
10151         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
10152   }
10153 
10154   OverloadCandidateSelect Select = [&]() {
10155     if (!Description.empty())
10156       return ocs_described_template;
10157     return isTemplate ? ocs_template : ocs_non_template;
10158   }();
10159 
10160   OverloadCandidateKind Kind = [&]() {
10161     if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
10162       return oc_implicit_equality_comparison;
10163 
10164     if (CRK & CRK_Reversed)
10165       return oc_reversed_binary_operator;
10166 
10167     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
10168       if (!Ctor->isImplicit()) {
10169         if (isa<ConstructorUsingShadowDecl>(Found))
10170           return oc_inherited_constructor;
10171         else
10172           return oc_constructor;
10173       }
10174 
10175       if (Ctor->isDefaultConstructor())
10176         return oc_implicit_default_constructor;
10177 
10178       if (Ctor->isMoveConstructor())
10179         return oc_implicit_move_constructor;
10180 
10181       assert(Ctor->isCopyConstructor() &&
10182              "unexpected sort of implicit constructor");
10183       return oc_implicit_copy_constructor;
10184     }
10185 
10186     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
10187       // This actually gets spelled 'candidate function' for now, but
10188       // it doesn't hurt to split it out.
10189       if (!Meth->isImplicit())
10190         return oc_method;
10191 
10192       if (Meth->isMoveAssignmentOperator())
10193         return oc_implicit_move_assignment;
10194 
10195       if (Meth->isCopyAssignmentOperator())
10196         return oc_implicit_copy_assignment;
10197 
10198       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
10199       return oc_method;
10200     }
10201 
10202     return oc_function;
10203   }();
10204 
10205   return std::make_pair(Kind, Select);
10206 }
10207 
10208 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
10209   // FIXME: It'd be nice to only emit a note once per using-decl per overload
10210   // set.
10211   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
10212     S.Diag(FoundDecl->getLocation(),
10213            diag::note_ovl_candidate_inherited_constructor)
10214       << Shadow->getNominatedBaseClass();
10215 }
10216 
10217 } // end anonymous namespace
10218 
10219 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
10220                                     const FunctionDecl *FD) {
10221   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
10222     bool AlwaysTrue;
10223     if (EnableIf->getCond()->isValueDependent() ||
10224         !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
10225       return false;
10226     if (!AlwaysTrue)
10227       return false;
10228   }
10229   return true;
10230 }
10231 
10232 /// Returns true if we can take the address of the function.
10233 ///
10234 /// \param Complain - If true, we'll emit a diagnostic
10235 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
10236 ///   we in overload resolution?
10237 /// \param Loc - The location of the statement we're complaining about. Ignored
10238 ///   if we're not complaining, or if we're in overload resolution.
10239 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
10240                                               bool Complain,
10241                                               bool InOverloadResolution,
10242                                               SourceLocation Loc) {
10243   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
10244     if (Complain) {
10245       if (InOverloadResolution)
10246         S.Diag(FD->getBeginLoc(),
10247                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
10248       else
10249         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
10250     }
10251     return false;
10252   }
10253 
10254   if (FD->getTrailingRequiresClause()) {
10255     ConstraintSatisfaction Satisfaction;
10256     if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
10257       return false;
10258     if (!Satisfaction.IsSatisfied) {
10259       if (Complain) {
10260         if (InOverloadResolution)
10261           S.Diag(FD->getBeginLoc(),
10262                  diag::note_ovl_candidate_unsatisfied_constraints);
10263         else
10264           S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
10265               << FD;
10266         S.DiagnoseUnsatisfiedConstraint(Satisfaction);
10267       }
10268       return false;
10269     }
10270   }
10271 
10272   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
10273     return P->hasAttr<PassObjectSizeAttr>();
10274   });
10275   if (I == FD->param_end())
10276     return true;
10277 
10278   if (Complain) {
10279     // Add one to ParamNo because it's user-facing
10280     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
10281     if (InOverloadResolution)
10282       S.Diag(FD->getLocation(),
10283              diag::note_ovl_candidate_has_pass_object_size_params)
10284           << ParamNo;
10285     else
10286       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
10287           << FD << ParamNo;
10288   }
10289   return false;
10290 }
10291 
10292 static bool checkAddressOfCandidateIsAvailable(Sema &S,
10293                                                const FunctionDecl *FD) {
10294   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
10295                                            /*InOverloadResolution=*/true,
10296                                            /*Loc=*/SourceLocation());
10297 }
10298 
10299 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10300                                              bool Complain,
10301                                              SourceLocation Loc) {
10302   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
10303                                              /*InOverloadResolution=*/false,
10304                                              Loc);
10305 }
10306 
10307 // Don't print candidates other than the one that matches the calling
10308 // convention of the call operator, since that is guaranteed to exist.
10309 static bool shouldSkipNotingLambdaConversionDecl(FunctionDecl *Fn) {
10310   const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
10311 
10312   if (!ConvD)
10313     return false;
10314   const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
10315   if (!RD->isLambda())
10316     return false;
10317 
10318   CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
10319   CallingConv CallOpCC =
10320       CallOp->getType()->castAs<FunctionType>()->getCallConv();
10321   QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
10322   CallingConv ConvToCC =
10323       ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
10324 
10325   return ConvToCC != CallOpCC;
10326 }
10327 
10328 // Notes the location of an overload candidate.
10329 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
10330                                  OverloadCandidateRewriteKind RewriteKind,
10331                                  QualType DestType, bool TakingAddress) {
10332   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
10333     return;
10334   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
10335       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
10336     return;
10337   if (shouldSkipNotingLambdaConversionDecl(Fn))
10338     return;
10339 
10340   std::string FnDesc;
10341   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
10342       ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
10343   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
10344                          << (unsigned)KSPair.first << (unsigned)KSPair.second
10345                          << Fn << FnDesc;
10346 
10347   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
10348   Diag(Fn->getLocation(), PD);
10349   MaybeEmitInheritedConstructorNote(*this, Found);
10350 }
10351 
10352 static void
10353 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
10354   // Perhaps the ambiguity was caused by two atomic constraints that are
10355   // 'identical' but not equivalent:
10356   //
10357   // void foo() requires (sizeof(T) > 4) { } // #1
10358   // void foo() requires (sizeof(T) > 4) && T::value { } // #2
10359   //
10360   // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
10361   // #2 to subsume #1, but these constraint are not considered equivalent
10362   // according to the subsumption rules because they are not the same
10363   // source-level construct. This behavior is quite confusing and we should try
10364   // to help the user figure out what happened.
10365 
10366   SmallVector<const Expr *, 3> FirstAC, SecondAC;
10367   FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
10368   for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10369     if (!I->Function)
10370       continue;
10371     SmallVector<const Expr *, 3> AC;
10372     if (auto *Template = I->Function->getPrimaryTemplate())
10373       Template->getAssociatedConstraints(AC);
10374     else
10375       I->Function->getAssociatedConstraints(AC);
10376     if (AC.empty())
10377       continue;
10378     if (FirstCand == nullptr) {
10379       FirstCand = I->Function;
10380       FirstAC = AC;
10381     } else if (SecondCand == nullptr) {
10382       SecondCand = I->Function;
10383       SecondAC = AC;
10384     } else {
10385       // We have more than one pair of constrained functions - this check is
10386       // expensive and we'd rather not try to diagnose it.
10387       return;
10388     }
10389   }
10390   if (!SecondCand)
10391     return;
10392   // The diagnostic can only happen if there are associated constraints on
10393   // both sides (there needs to be some identical atomic constraint).
10394   if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
10395                                                       SecondCand, SecondAC))
10396     // Just show the user one diagnostic, they'll probably figure it out
10397     // from here.
10398     return;
10399 }
10400 
10401 // Notes the location of all overload candidates designated through
10402 // OverloadedExpr
10403 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
10404                                      bool TakingAddress) {
10405   assert(OverloadedExpr->getType() == Context.OverloadTy);
10406 
10407   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
10408   OverloadExpr *OvlExpr = Ovl.Expression;
10409 
10410   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10411                             IEnd = OvlExpr->decls_end();
10412        I != IEnd; ++I) {
10413     if (FunctionTemplateDecl *FunTmpl =
10414                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
10415       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
10416                             TakingAddress);
10417     } else if (FunctionDecl *Fun
10418                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
10419       NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
10420     }
10421   }
10422 }
10423 
10424 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
10425 /// "lead" diagnostic; it will be given two arguments, the source and
10426 /// target types of the conversion.
10427 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
10428                                  Sema &S,
10429                                  SourceLocation CaretLoc,
10430                                  const PartialDiagnostic &PDiag) const {
10431   S.Diag(CaretLoc, PDiag)
10432     << Ambiguous.getFromType() << Ambiguous.getToType();
10433   unsigned CandsShown = 0;
10434   AmbiguousConversionSequence::const_iterator I, E;
10435   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
10436     if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
10437       break;
10438     ++CandsShown;
10439     S.NoteOverloadCandidate(I->first, I->second);
10440   }
10441   S.Diags.overloadCandidatesShown(CandsShown);
10442   if (I != E)
10443     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
10444 }
10445 
10446 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
10447                                   unsigned I, bool TakingCandidateAddress) {
10448   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
10449   assert(Conv.isBad());
10450   assert(Cand->Function && "for now, candidate must be a function");
10451   FunctionDecl *Fn = Cand->Function;
10452 
10453   // There's a conversion slot for the object argument if this is a
10454   // non-constructor method.  Note that 'I' corresponds the
10455   // conversion-slot index.
10456   bool isObjectArgument = false;
10457   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
10458     if (I == 0)
10459       isObjectArgument = true;
10460     else
10461       I--;
10462   }
10463 
10464   std::string FnDesc;
10465   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10466       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
10467                                 FnDesc);
10468 
10469   Expr *FromExpr = Conv.Bad.FromExpr;
10470   QualType FromTy = Conv.Bad.getFromType();
10471   QualType ToTy = Conv.Bad.getToType();
10472 
10473   if (FromTy == S.Context.OverloadTy) {
10474     assert(FromExpr && "overload set argument came from implicit argument?");
10475     Expr *E = FromExpr->IgnoreParens();
10476     if (isa<UnaryOperator>(E))
10477       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
10478     DeclarationName Name = cast<OverloadExpr>(E)->getName();
10479 
10480     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
10481         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10482         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
10483         << Name << I + 1;
10484     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10485     return;
10486   }
10487 
10488   // Do some hand-waving analysis to see if the non-viability is due
10489   // to a qualifier mismatch.
10490   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
10491   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
10492   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
10493     CToTy = RT->getPointeeType();
10494   else {
10495     // TODO: detect and diagnose the full richness of const mismatches.
10496     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
10497       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
10498         CFromTy = FromPT->getPointeeType();
10499         CToTy = ToPT->getPointeeType();
10500       }
10501   }
10502 
10503   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
10504       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
10505     Qualifiers FromQs = CFromTy.getQualifiers();
10506     Qualifiers ToQs = CToTy.getQualifiers();
10507 
10508     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
10509       if (isObjectArgument)
10510         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
10511             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10512             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10513             << FromQs.getAddressSpace() << ToQs.getAddressSpace();
10514       else
10515         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
10516             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10517             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10518             << FromQs.getAddressSpace() << ToQs.getAddressSpace()
10519             << ToTy->isReferenceType() << I + 1;
10520       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10521       return;
10522     }
10523 
10524     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10525       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
10526           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10527           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10528           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
10529           << (unsigned)isObjectArgument << I + 1;
10530       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10531       return;
10532     }
10533 
10534     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
10535       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
10536           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10537           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10538           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
10539           << (unsigned)isObjectArgument << I + 1;
10540       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10541       return;
10542     }
10543 
10544     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
10545       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
10546           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10547           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10548           << FromQs.hasUnaligned() << I + 1;
10549       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10550       return;
10551     }
10552 
10553     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
10554     assert(CVR && "expected qualifiers mismatch");
10555 
10556     if (isObjectArgument) {
10557       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
10558           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10559           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10560           << (CVR - 1);
10561     } else {
10562       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
10563           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10564           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10565           << (CVR - 1) << I + 1;
10566     }
10567     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10568     return;
10569   }
10570 
10571   if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
10572       Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
10573     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
10574         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10575         << (unsigned)isObjectArgument << I + 1
10576         << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
10577         << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
10578     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10579     return;
10580   }
10581 
10582   // Special diagnostic for failure to convert an initializer list, since
10583   // telling the user that it has type void is not useful.
10584   if (FromExpr && isa<InitListExpr>(FromExpr)) {
10585     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
10586         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10587         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10588         << ToTy << (unsigned)isObjectArgument << I + 1
10589         << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1
10590             : Conv.Bad.Kind == BadConversionSequence::too_many_initializers
10591                 ? 2
10592                 : 0);
10593     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10594     return;
10595   }
10596 
10597   // Diagnose references or pointers to incomplete types differently,
10598   // since it's far from impossible that the incompleteness triggered
10599   // the failure.
10600   QualType TempFromTy = FromTy.getNonReferenceType();
10601   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
10602     TempFromTy = PTy->getPointeeType();
10603   if (TempFromTy->isIncompleteType()) {
10604     // Emit the generic diagnostic and, optionally, add the hints to it.
10605     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
10606         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10607         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10608         << ToTy << (unsigned)isObjectArgument << I + 1
10609         << (unsigned)(Cand->Fix.Kind);
10610 
10611     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10612     return;
10613   }
10614 
10615   // Diagnose base -> derived pointer conversions.
10616   unsigned BaseToDerivedConversion = 0;
10617   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
10618     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
10619       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10620                                                FromPtrTy->getPointeeType()) &&
10621           !FromPtrTy->getPointeeType()->isIncompleteType() &&
10622           !ToPtrTy->getPointeeType()->isIncompleteType() &&
10623           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
10624                           FromPtrTy->getPointeeType()))
10625         BaseToDerivedConversion = 1;
10626     }
10627   } else if (const ObjCObjectPointerType *FromPtrTy
10628                                     = FromTy->getAs<ObjCObjectPointerType>()) {
10629     if (const ObjCObjectPointerType *ToPtrTy
10630                                         = ToTy->getAs<ObjCObjectPointerType>())
10631       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
10632         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
10633           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10634                                                 FromPtrTy->getPointeeType()) &&
10635               FromIface->isSuperClassOf(ToIface))
10636             BaseToDerivedConversion = 2;
10637   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
10638     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
10639         !FromTy->isIncompleteType() &&
10640         !ToRefTy->getPointeeType()->isIncompleteType() &&
10641         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
10642       BaseToDerivedConversion = 3;
10643     }
10644   }
10645 
10646   if (BaseToDerivedConversion) {
10647     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
10648         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10649         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10650         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
10651     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10652     return;
10653   }
10654 
10655   if (isa<ObjCObjectPointerType>(CFromTy) &&
10656       isa<PointerType>(CToTy)) {
10657       Qualifiers FromQs = CFromTy.getQualifiers();
10658       Qualifiers ToQs = CToTy.getQualifiers();
10659       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10660         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
10661             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10662             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10663             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
10664         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10665         return;
10666       }
10667   }
10668 
10669   if (TakingCandidateAddress &&
10670       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
10671     return;
10672 
10673   // Emit the generic diagnostic and, optionally, add the hints to it.
10674   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
10675   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10676         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10677         << ToTy << (unsigned)isObjectArgument << I + 1
10678         << (unsigned)(Cand->Fix.Kind);
10679 
10680   // If we can fix the conversion, suggest the FixIts.
10681   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
10682        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
10683     FDiag << *HI;
10684   S.Diag(Fn->getLocation(), FDiag);
10685 
10686   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10687 }
10688 
10689 /// Additional arity mismatch diagnosis specific to a function overload
10690 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
10691 /// over a candidate in any candidate set.
10692 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
10693                                unsigned NumArgs) {
10694   FunctionDecl *Fn = Cand->Function;
10695   unsigned MinParams = Fn->getMinRequiredArguments();
10696 
10697   // With invalid overloaded operators, it's possible that we think we
10698   // have an arity mismatch when in fact it looks like we have the
10699   // right number of arguments, because only overloaded operators have
10700   // the weird behavior of overloading member and non-member functions.
10701   // Just don't report anything.
10702   if (Fn->isInvalidDecl() &&
10703       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
10704     return true;
10705 
10706   if (NumArgs < MinParams) {
10707     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
10708            (Cand->FailureKind == ovl_fail_bad_deduction &&
10709             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
10710   } else {
10711     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
10712            (Cand->FailureKind == ovl_fail_bad_deduction &&
10713             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
10714   }
10715 
10716   return false;
10717 }
10718 
10719 /// General arity mismatch diagnosis over a candidate in a candidate set.
10720 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
10721                                   unsigned NumFormalArgs) {
10722   assert(isa<FunctionDecl>(D) &&
10723       "The templated declaration should at least be a function"
10724       " when diagnosing bad template argument deduction due to too many"
10725       " or too few arguments");
10726 
10727   FunctionDecl *Fn = cast<FunctionDecl>(D);
10728 
10729   // TODO: treat calls to a missing default constructor as a special case
10730   const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
10731   unsigned MinParams = Fn->getMinRequiredArguments();
10732 
10733   // at least / at most / exactly
10734   unsigned mode, modeCount;
10735   if (NumFormalArgs < MinParams) {
10736     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
10737         FnTy->isTemplateVariadic())
10738       mode = 0; // "at least"
10739     else
10740       mode = 2; // "exactly"
10741     modeCount = MinParams;
10742   } else {
10743     if (MinParams != FnTy->getNumParams())
10744       mode = 1; // "at most"
10745     else
10746       mode = 2; // "exactly"
10747     modeCount = FnTy->getNumParams();
10748   }
10749 
10750   std::string Description;
10751   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10752       ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
10753 
10754   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10755     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10756         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10757         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
10758   else
10759     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
10760         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10761         << Description << mode << modeCount << NumFormalArgs;
10762 
10763   MaybeEmitInheritedConstructorNote(S, Found);
10764 }
10765 
10766 /// Arity mismatch diagnosis specific to a function overload candidate.
10767 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
10768                                   unsigned NumFormalArgs) {
10769   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
10770     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10771 }
10772 
10773 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10774   if (TemplateDecl *TD = Templated->getDescribedTemplate())
10775     return TD;
10776   llvm_unreachable("Unsupported: Getting the described template declaration"
10777                    " for bad deduction diagnosis");
10778 }
10779 
10780 /// Diagnose a failed template-argument deduction.
10781 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10782                                  DeductionFailureInfo &DeductionFailure,
10783                                  unsigned NumArgs,
10784                                  bool TakingCandidateAddress) {
10785   TemplateParameter Param = DeductionFailure.getTemplateParameter();
10786   NamedDecl *ParamD;
10787   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10788   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10789   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10790   switch (DeductionFailure.Result) {
10791   case Sema::TDK_Success:
10792     llvm_unreachable("TDK_success while diagnosing bad deduction");
10793 
10794   case Sema::TDK_Incomplete: {
10795     assert(ParamD && "no parameter found for incomplete deduction result");
10796     S.Diag(Templated->getLocation(),
10797            diag::note_ovl_candidate_incomplete_deduction)
10798         << ParamD->getDeclName();
10799     MaybeEmitInheritedConstructorNote(S, Found);
10800     return;
10801   }
10802 
10803   case Sema::TDK_IncompletePack: {
10804     assert(ParamD && "no parameter found for incomplete deduction result");
10805     S.Diag(Templated->getLocation(),
10806            diag::note_ovl_candidate_incomplete_deduction_pack)
10807         << ParamD->getDeclName()
10808         << (DeductionFailure.getFirstArg()->pack_size() + 1)
10809         << *DeductionFailure.getFirstArg();
10810     MaybeEmitInheritedConstructorNote(S, Found);
10811     return;
10812   }
10813 
10814   case Sema::TDK_Underqualified: {
10815     assert(ParamD && "no parameter found for bad qualifiers deduction result");
10816     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10817 
10818     QualType Param = DeductionFailure.getFirstArg()->getAsType();
10819 
10820     // Param will have been canonicalized, but it should just be a
10821     // qualified version of ParamD, so move the qualifiers to that.
10822     QualifierCollector Qs;
10823     Qs.strip(Param);
10824     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10825     assert(S.Context.hasSameType(Param, NonCanonParam));
10826 
10827     // Arg has also been canonicalized, but there's nothing we can do
10828     // about that.  It also doesn't matter as much, because it won't
10829     // have any template parameters in it (because deduction isn't
10830     // done on dependent types).
10831     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10832 
10833     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10834         << ParamD->getDeclName() << Arg << NonCanonParam;
10835     MaybeEmitInheritedConstructorNote(S, Found);
10836     return;
10837   }
10838 
10839   case Sema::TDK_Inconsistent: {
10840     assert(ParamD && "no parameter found for inconsistent deduction result");
10841     int which = 0;
10842     if (isa<TemplateTypeParmDecl>(ParamD))
10843       which = 0;
10844     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10845       // Deduction might have failed because we deduced arguments of two
10846       // different types for a non-type template parameter.
10847       // FIXME: Use a different TDK value for this.
10848       QualType T1 =
10849           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10850       QualType T2 =
10851           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10852       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10853         S.Diag(Templated->getLocation(),
10854                diag::note_ovl_candidate_inconsistent_deduction_types)
10855           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10856           << *DeductionFailure.getSecondArg() << T2;
10857         MaybeEmitInheritedConstructorNote(S, Found);
10858         return;
10859       }
10860 
10861       which = 1;
10862     } else {
10863       which = 2;
10864     }
10865 
10866     // Tweak the diagnostic if the problem is that we deduced packs of
10867     // different arities. We'll print the actual packs anyway in case that
10868     // includes additional useful information.
10869     if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
10870         DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
10871         DeductionFailure.getFirstArg()->pack_size() !=
10872             DeductionFailure.getSecondArg()->pack_size()) {
10873       which = 3;
10874     }
10875 
10876     S.Diag(Templated->getLocation(),
10877            diag::note_ovl_candidate_inconsistent_deduction)
10878         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10879         << *DeductionFailure.getSecondArg();
10880     MaybeEmitInheritedConstructorNote(S, Found);
10881     return;
10882   }
10883 
10884   case Sema::TDK_InvalidExplicitArguments:
10885     assert(ParamD && "no parameter found for invalid explicit arguments");
10886     if (ParamD->getDeclName())
10887       S.Diag(Templated->getLocation(),
10888              diag::note_ovl_candidate_explicit_arg_mismatch_named)
10889           << ParamD->getDeclName();
10890     else {
10891       int index = 0;
10892       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10893         index = TTP->getIndex();
10894       else if (NonTypeTemplateParmDecl *NTTP
10895                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10896         index = NTTP->getIndex();
10897       else
10898         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10899       S.Diag(Templated->getLocation(),
10900              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10901           << (index + 1);
10902     }
10903     MaybeEmitInheritedConstructorNote(S, Found);
10904     return;
10905 
10906   case Sema::TDK_ConstraintsNotSatisfied: {
10907     // Format the template argument list into the argument string.
10908     SmallString<128> TemplateArgString;
10909     TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
10910     TemplateArgString = " ";
10911     TemplateArgString += S.getTemplateArgumentBindingsText(
10912         getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10913     if (TemplateArgString.size() == 1)
10914       TemplateArgString.clear();
10915     S.Diag(Templated->getLocation(),
10916            diag::note_ovl_candidate_unsatisfied_constraints)
10917         << TemplateArgString;
10918 
10919     S.DiagnoseUnsatisfiedConstraint(
10920         static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
10921     return;
10922   }
10923   case Sema::TDK_TooManyArguments:
10924   case Sema::TDK_TooFewArguments:
10925     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10926     return;
10927 
10928   case Sema::TDK_InstantiationDepth:
10929     S.Diag(Templated->getLocation(),
10930            diag::note_ovl_candidate_instantiation_depth);
10931     MaybeEmitInheritedConstructorNote(S, Found);
10932     return;
10933 
10934   case Sema::TDK_SubstitutionFailure: {
10935     // Format the template argument list into the argument string.
10936     SmallString<128> TemplateArgString;
10937     if (TemplateArgumentList *Args =
10938             DeductionFailure.getTemplateArgumentList()) {
10939       TemplateArgString = " ";
10940       TemplateArgString += S.getTemplateArgumentBindingsText(
10941           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10942       if (TemplateArgString.size() == 1)
10943         TemplateArgString.clear();
10944     }
10945 
10946     // If this candidate was disabled by enable_if, say so.
10947     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10948     if (PDiag && PDiag->second.getDiagID() ==
10949           diag::err_typename_nested_not_found_enable_if) {
10950       // FIXME: Use the source range of the condition, and the fully-qualified
10951       //        name of the enable_if template. These are both present in PDiag.
10952       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10953         << "'enable_if'" << TemplateArgString;
10954       return;
10955     }
10956 
10957     // We found a specific requirement that disabled the enable_if.
10958     if (PDiag && PDiag->second.getDiagID() ==
10959         diag::err_typename_nested_not_found_requirement) {
10960       S.Diag(Templated->getLocation(),
10961              diag::note_ovl_candidate_disabled_by_requirement)
10962         << PDiag->second.getStringArg(0) << TemplateArgString;
10963       return;
10964     }
10965 
10966     // Format the SFINAE diagnostic into the argument string.
10967     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10968     //        formatted message in another diagnostic.
10969     SmallString<128> SFINAEArgString;
10970     SourceRange R;
10971     if (PDiag) {
10972       SFINAEArgString = ": ";
10973       R = SourceRange(PDiag->first, PDiag->first);
10974       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10975     }
10976 
10977     S.Diag(Templated->getLocation(),
10978            diag::note_ovl_candidate_substitution_failure)
10979         << TemplateArgString << SFINAEArgString << R;
10980     MaybeEmitInheritedConstructorNote(S, Found);
10981     return;
10982   }
10983 
10984   case Sema::TDK_DeducedMismatch:
10985   case Sema::TDK_DeducedMismatchNested: {
10986     // Format the template argument list into the argument string.
10987     SmallString<128> TemplateArgString;
10988     if (TemplateArgumentList *Args =
10989             DeductionFailure.getTemplateArgumentList()) {
10990       TemplateArgString = " ";
10991       TemplateArgString += S.getTemplateArgumentBindingsText(
10992           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10993       if (TemplateArgString.size() == 1)
10994         TemplateArgString.clear();
10995     }
10996 
10997     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10998         << (*DeductionFailure.getCallArgIndex() + 1)
10999         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
11000         << TemplateArgString
11001         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
11002     break;
11003   }
11004 
11005   case Sema::TDK_NonDeducedMismatch: {
11006     // FIXME: Provide a source location to indicate what we couldn't match.
11007     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
11008     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
11009     if (FirstTA.getKind() == TemplateArgument::Template &&
11010         SecondTA.getKind() == TemplateArgument::Template) {
11011       TemplateName FirstTN = FirstTA.getAsTemplate();
11012       TemplateName SecondTN = SecondTA.getAsTemplate();
11013       if (FirstTN.getKind() == TemplateName::Template &&
11014           SecondTN.getKind() == TemplateName::Template) {
11015         if (FirstTN.getAsTemplateDecl()->getName() ==
11016             SecondTN.getAsTemplateDecl()->getName()) {
11017           // FIXME: This fixes a bad diagnostic where both templates are named
11018           // the same.  This particular case is a bit difficult since:
11019           // 1) It is passed as a string to the diagnostic printer.
11020           // 2) The diagnostic printer only attempts to find a better
11021           //    name for types, not decls.
11022           // Ideally, this should folded into the diagnostic printer.
11023           S.Diag(Templated->getLocation(),
11024                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
11025               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
11026           return;
11027         }
11028       }
11029     }
11030 
11031     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
11032         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
11033       return;
11034 
11035     // FIXME: For generic lambda parameters, check if the function is a lambda
11036     // call operator, and if so, emit a prettier and more informative
11037     // diagnostic that mentions 'auto' and lambda in addition to
11038     // (or instead of?) the canonical template type parameters.
11039     S.Diag(Templated->getLocation(),
11040            diag::note_ovl_candidate_non_deduced_mismatch)
11041         << FirstTA << SecondTA;
11042     return;
11043   }
11044   // TODO: diagnose these individually, then kill off
11045   // note_ovl_candidate_bad_deduction, which is uselessly vague.
11046   case Sema::TDK_MiscellaneousDeductionFailure:
11047     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
11048     MaybeEmitInheritedConstructorNote(S, Found);
11049     return;
11050   case Sema::TDK_CUDATargetMismatch:
11051     S.Diag(Templated->getLocation(),
11052            diag::note_cuda_ovl_candidate_target_mismatch);
11053     return;
11054   }
11055 }
11056 
11057 /// Diagnose a failed template-argument deduction, for function calls.
11058 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
11059                                  unsigned NumArgs,
11060                                  bool TakingCandidateAddress) {
11061   unsigned TDK = Cand->DeductionFailure.Result;
11062   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
11063     if (CheckArityMismatch(S, Cand, NumArgs))
11064       return;
11065   }
11066   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
11067                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
11068 }
11069 
11070 /// CUDA: diagnose an invalid call across targets.
11071 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
11072   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
11073   FunctionDecl *Callee = Cand->Function;
11074 
11075   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
11076                            CalleeTarget = S.IdentifyCUDATarget(Callee);
11077 
11078   std::string FnDesc;
11079   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11080       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
11081                                 Cand->getRewriteKind(), FnDesc);
11082 
11083   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
11084       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11085       << FnDesc /* Ignored */
11086       << CalleeTarget << CallerTarget;
11087 
11088   // This could be an implicit constructor for which we could not infer the
11089   // target due to a collsion. Diagnose that case.
11090   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
11091   if (Meth != nullptr && Meth->isImplicit()) {
11092     CXXRecordDecl *ParentClass = Meth->getParent();
11093     Sema::CXXSpecialMember CSM;
11094 
11095     switch (FnKindPair.first) {
11096     default:
11097       return;
11098     case oc_implicit_default_constructor:
11099       CSM = Sema::CXXDefaultConstructor;
11100       break;
11101     case oc_implicit_copy_constructor:
11102       CSM = Sema::CXXCopyConstructor;
11103       break;
11104     case oc_implicit_move_constructor:
11105       CSM = Sema::CXXMoveConstructor;
11106       break;
11107     case oc_implicit_copy_assignment:
11108       CSM = Sema::CXXCopyAssignment;
11109       break;
11110     case oc_implicit_move_assignment:
11111       CSM = Sema::CXXMoveAssignment;
11112       break;
11113     };
11114 
11115     bool ConstRHS = false;
11116     if (Meth->getNumParams()) {
11117       if (const ReferenceType *RT =
11118               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
11119         ConstRHS = RT->getPointeeType().isConstQualified();
11120       }
11121     }
11122 
11123     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
11124                                               /* ConstRHS */ ConstRHS,
11125                                               /* Diagnose */ true);
11126   }
11127 }
11128 
11129 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
11130   FunctionDecl *Callee = Cand->Function;
11131   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
11132 
11133   S.Diag(Callee->getLocation(),
11134          diag::note_ovl_candidate_disabled_by_function_cond_attr)
11135       << Attr->getCond()->getSourceRange() << Attr->getMessage();
11136 }
11137 
11138 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
11139   ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function);
11140   assert(ES.isExplicit() && "not an explicit candidate");
11141 
11142   unsigned Kind;
11143   switch (Cand->Function->getDeclKind()) {
11144   case Decl::Kind::CXXConstructor:
11145     Kind = 0;
11146     break;
11147   case Decl::Kind::CXXConversion:
11148     Kind = 1;
11149     break;
11150   case Decl::Kind::CXXDeductionGuide:
11151     Kind = Cand->Function->isImplicit() ? 0 : 2;
11152     break;
11153   default:
11154     llvm_unreachable("invalid Decl");
11155   }
11156 
11157   // Note the location of the first (in-class) declaration; a redeclaration
11158   // (particularly an out-of-class definition) will typically lack the
11159   // 'explicit' specifier.
11160   // FIXME: This is probably a good thing to do for all 'candidate' notes.
11161   FunctionDecl *First = Cand->Function->getFirstDecl();
11162   if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
11163     First = Pattern->getFirstDecl();
11164 
11165   S.Diag(First->getLocation(),
11166          diag::note_ovl_candidate_explicit)
11167       << Kind << (ES.getExpr() ? 1 : 0)
11168       << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
11169 }
11170 
11171 /// Generates a 'note' diagnostic for an overload candidate.  We've
11172 /// already generated a primary error at the call site.
11173 ///
11174 /// It really does need to be a single diagnostic with its caret
11175 /// pointed at the candidate declaration.  Yes, this creates some
11176 /// major challenges of technical writing.  Yes, this makes pointing
11177 /// out problems with specific arguments quite awkward.  It's still
11178 /// better than generating twenty screens of text for every failed
11179 /// overload.
11180 ///
11181 /// It would be great to be able to express per-candidate problems
11182 /// more richly for those diagnostic clients that cared, but we'd
11183 /// still have to be just as careful with the default diagnostics.
11184 /// \param CtorDestAS Addr space of object being constructed (for ctor
11185 /// candidates only).
11186 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
11187                                   unsigned NumArgs,
11188                                   bool TakingCandidateAddress,
11189                                   LangAS CtorDestAS = LangAS::Default) {
11190   FunctionDecl *Fn = Cand->Function;
11191   if (shouldSkipNotingLambdaConversionDecl(Fn))
11192     return;
11193 
11194   // Note deleted candidates, but only if they're viable.
11195   if (Cand->Viable) {
11196     if (Fn->isDeleted()) {
11197       std::string FnDesc;
11198       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11199           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11200                                     Cand->getRewriteKind(), FnDesc);
11201 
11202       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
11203           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11204           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
11205       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11206       return;
11207     }
11208 
11209     // We don't really have anything else to say about viable candidates.
11210     S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11211     return;
11212   }
11213 
11214   switch (Cand->FailureKind) {
11215   case ovl_fail_too_many_arguments:
11216   case ovl_fail_too_few_arguments:
11217     return DiagnoseArityMismatch(S, Cand, NumArgs);
11218 
11219   case ovl_fail_bad_deduction:
11220     return DiagnoseBadDeduction(S, Cand, NumArgs,
11221                                 TakingCandidateAddress);
11222 
11223   case ovl_fail_illegal_constructor: {
11224     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
11225       << (Fn->getPrimaryTemplate() ? 1 : 0);
11226     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11227     return;
11228   }
11229 
11230   case ovl_fail_object_addrspace_mismatch: {
11231     Qualifiers QualsForPrinting;
11232     QualsForPrinting.setAddressSpace(CtorDestAS);
11233     S.Diag(Fn->getLocation(),
11234            diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
11235         << QualsForPrinting;
11236     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11237     return;
11238   }
11239 
11240   case ovl_fail_trivial_conversion:
11241   case ovl_fail_bad_final_conversion:
11242   case ovl_fail_final_conversion_not_exact:
11243     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11244 
11245   case ovl_fail_bad_conversion: {
11246     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
11247     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
11248       if (Cand->Conversions[I].isBad())
11249         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
11250 
11251     // FIXME: this currently happens when we're called from SemaInit
11252     // when user-conversion overload fails.  Figure out how to handle
11253     // those conditions and diagnose them well.
11254     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11255   }
11256 
11257   case ovl_fail_bad_target:
11258     return DiagnoseBadTarget(S, Cand);
11259 
11260   case ovl_fail_enable_if:
11261     return DiagnoseFailedEnableIfAttr(S, Cand);
11262 
11263   case ovl_fail_explicit:
11264     return DiagnoseFailedExplicitSpec(S, Cand);
11265 
11266   case ovl_fail_inhctor_slice:
11267     // It's generally not interesting to note copy/move constructors here.
11268     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
11269       return;
11270     S.Diag(Fn->getLocation(),
11271            diag::note_ovl_candidate_inherited_constructor_slice)
11272       << (Fn->getPrimaryTemplate() ? 1 : 0)
11273       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
11274     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11275     return;
11276 
11277   case ovl_fail_addr_not_available: {
11278     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
11279     (void)Available;
11280     assert(!Available);
11281     break;
11282   }
11283   case ovl_non_default_multiversion_function:
11284     // Do nothing, these should simply be ignored.
11285     break;
11286 
11287   case ovl_fail_constraints_not_satisfied: {
11288     std::string FnDesc;
11289     std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11290         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11291                                   Cand->getRewriteKind(), FnDesc);
11292 
11293     S.Diag(Fn->getLocation(),
11294            diag::note_ovl_candidate_constraints_not_satisfied)
11295         << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11296         << FnDesc /* Ignored */;
11297     ConstraintSatisfaction Satisfaction;
11298     if (S.CheckFunctionConstraints(Fn, Satisfaction))
11299       break;
11300     S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11301   }
11302   }
11303 }
11304 
11305 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
11306   if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate))
11307     return;
11308 
11309   // Desugar the type of the surrogate down to a function type,
11310   // retaining as many typedefs as possible while still showing
11311   // the function type (and, therefore, its parameter types).
11312   QualType FnType = Cand->Surrogate->getConversionType();
11313   bool isLValueReference = false;
11314   bool isRValueReference = false;
11315   bool isPointer = false;
11316   if (const LValueReferenceType *FnTypeRef =
11317         FnType->getAs<LValueReferenceType>()) {
11318     FnType = FnTypeRef->getPointeeType();
11319     isLValueReference = true;
11320   } else if (const RValueReferenceType *FnTypeRef =
11321                FnType->getAs<RValueReferenceType>()) {
11322     FnType = FnTypeRef->getPointeeType();
11323     isRValueReference = true;
11324   }
11325   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
11326     FnType = FnTypePtr->getPointeeType();
11327     isPointer = true;
11328   }
11329   // Desugar down to a function type.
11330   FnType = QualType(FnType->getAs<FunctionType>(), 0);
11331   // Reconstruct the pointer/reference as appropriate.
11332   if (isPointer) FnType = S.Context.getPointerType(FnType);
11333   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
11334   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
11335 
11336   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
11337     << FnType;
11338 }
11339 
11340 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
11341                                          SourceLocation OpLoc,
11342                                          OverloadCandidate *Cand) {
11343   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
11344   std::string TypeStr("operator");
11345   TypeStr += Opc;
11346   TypeStr += "(";
11347   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
11348   if (Cand->Conversions.size() == 1) {
11349     TypeStr += ")";
11350     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11351   } else {
11352     TypeStr += ", ";
11353     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
11354     TypeStr += ")";
11355     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11356   }
11357 }
11358 
11359 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
11360                                          OverloadCandidate *Cand) {
11361   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
11362     if (ICS.isBad()) break; // all meaningless after first invalid
11363     if (!ICS.isAmbiguous()) continue;
11364 
11365     ICS.DiagnoseAmbiguousConversion(
11366         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
11367   }
11368 }
11369 
11370 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
11371   if (Cand->Function)
11372     return Cand->Function->getLocation();
11373   if (Cand->IsSurrogate)
11374     return Cand->Surrogate->getLocation();
11375   return SourceLocation();
11376 }
11377 
11378 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
11379   switch ((Sema::TemplateDeductionResult)DFI.Result) {
11380   case Sema::TDK_Success:
11381   case Sema::TDK_NonDependentConversionFailure:
11382     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
11383 
11384   case Sema::TDK_Invalid:
11385   case Sema::TDK_Incomplete:
11386   case Sema::TDK_IncompletePack:
11387     return 1;
11388 
11389   case Sema::TDK_Underqualified:
11390   case Sema::TDK_Inconsistent:
11391     return 2;
11392 
11393   case Sema::TDK_SubstitutionFailure:
11394   case Sema::TDK_DeducedMismatch:
11395   case Sema::TDK_ConstraintsNotSatisfied:
11396   case Sema::TDK_DeducedMismatchNested:
11397   case Sema::TDK_NonDeducedMismatch:
11398   case Sema::TDK_MiscellaneousDeductionFailure:
11399   case Sema::TDK_CUDATargetMismatch:
11400     return 3;
11401 
11402   case Sema::TDK_InstantiationDepth:
11403     return 4;
11404 
11405   case Sema::TDK_InvalidExplicitArguments:
11406     return 5;
11407 
11408   case Sema::TDK_TooManyArguments:
11409   case Sema::TDK_TooFewArguments:
11410     return 6;
11411   }
11412   llvm_unreachable("Unhandled deduction result");
11413 }
11414 
11415 namespace {
11416 struct CompareOverloadCandidatesForDisplay {
11417   Sema &S;
11418   SourceLocation Loc;
11419   size_t NumArgs;
11420   OverloadCandidateSet::CandidateSetKind CSK;
11421 
11422   CompareOverloadCandidatesForDisplay(
11423       Sema &S, SourceLocation Loc, size_t NArgs,
11424       OverloadCandidateSet::CandidateSetKind CSK)
11425       : S(S), NumArgs(NArgs), CSK(CSK) {}
11426 
11427   OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
11428     // If there are too many or too few arguments, that's the high-order bit we
11429     // want to sort by, even if the immediate failure kind was something else.
11430     if (C->FailureKind == ovl_fail_too_many_arguments ||
11431         C->FailureKind == ovl_fail_too_few_arguments)
11432       return static_cast<OverloadFailureKind>(C->FailureKind);
11433 
11434     if (C->Function) {
11435       if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
11436         return ovl_fail_too_many_arguments;
11437       if (NumArgs < C->Function->getMinRequiredArguments())
11438         return ovl_fail_too_few_arguments;
11439     }
11440 
11441     return static_cast<OverloadFailureKind>(C->FailureKind);
11442   }
11443 
11444   bool operator()(const OverloadCandidate *L,
11445                   const OverloadCandidate *R) {
11446     // Fast-path this check.
11447     if (L == R) return false;
11448 
11449     // Order first by viability.
11450     if (L->Viable) {
11451       if (!R->Viable) return true;
11452 
11453       // TODO: introduce a tri-valued comparison for overload
11454       // candidates.  Would be more worthwhile if we had a sort
11455       // that could exploit it.
11456       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
11457         return true;
11458       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
11459         return false;
11460     } else if (R->Viable)
11461       return false;
11462 
11463     assert(L->Viable == R->Viable);
11464 
11465     // Criteria by which we can sort non-viable candidates:
11466     if (!L->Viable) {
11467       OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
11468       OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
11469 
11470       // 1. Arity mismatches come after other candidates.
11471       if (LFailureKind == ovl_fail_too_many_arguments ||
11472           LFailureKind == ovl_fail_too_few_arguments) {
11473         if (RFailureKind == ovl_fail_too_many_arguments ||
11474             RFailureKind == ovl_fail_too_few_arguments) {
11475           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
11476           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
11477           if (LDist == RDist) {
11478             if (LFailureKind == RFailureKind)
11479               // Sort non-surrogates before surrogates.
11480               return !L->IsSurrogate && R->IsSurrogate;
11481             // Sort candidates requiring fewer parameters than there were
11482             // arguments given after candidates requiring more parameters
11483             // than there were arguments given.
11484             return LFailureKind == ovl_fail_too_many_arguments;
11485           }
11486           return LDist < RDist;
11487         }
11488         return false;
11489       }
11490       if (RFailureKind == ovl_fail_too_many_arguments ||
11491           RFailureKind == ovl_fail_too_few_arguments)
11492         return true;
11493 
11494       // 2. Bad conversions come first and are ordered by the number
11495       // of bad conversions and quality of good conversions.
11496       if (LFailureKind == ovl_fail_bad_conversion) {
11497         if (RFailureKind != ovl_fail_bad_conversion)
11498           return true;
11499 
11500         // The conversion that can be fixed with a smaller number of changes,
11501         // comes first.
11502         unsigned numLFixes = L->Fix.NumConversionsFixed;
11503         unsigned numRFixes = R->Fix.NumConversionsFixed;
11504         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
11505         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
11506         if (numLFixes != numRFixes) {
11507           return numLFixes < numRFixes;
11508         }
11509 
11510         // If there's any ordering between the defined conversions...
11511         // FIXME: this might not be transitive.
11512         assert(L->Conversions.size() == R->Conversions.size());
11513 
11514         int leftBetter = 0;
11515         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
11516         for (unsigned E = L->Conversions.size(); I != E; ++I) {
11517           switch (CompareImplicitConversionSequences(S, Loc,
11518                                                      L->Conversions[I],
11519                                                      R->Conversions[I])) {
11520           case ImplicitConversionSequence::Better:
11521             leftBetter++;
11522             break;
11523 
11524           case ImplicitConversionSequence::Worse:
11525             leftBetter--;
11526             break;
11527 
11528           case ImplicitConversionSequence::Indistinguishable:
11529             break;
11530           }
11531         }
11532         if (leftBetter > 0) return true;
11533         if (leftBetter < 0) return false;
11534 
11535       } else if (RFailureKind == ovl_fail_bad_conversion)
11536         return false;
11537 
11538       if (LFailureKind == ovl_fail_bad_deduction) {
11539         if (RFailureKind != ovl_fail_bad_deduction)
11540           return true;
11541 
11542         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11543           return RankDeductionFailure(L->DeductionFailure)
11544                < RankDeductionFailure(R->DeductionFailure);
11545       } else if (RFailureKind == ovl_fail_bad_deduction)
11546         return false;
11547 
11548       // TODO: others?
11549     }
11550 
11551     // Sort everything else by location.
11552     SourceLocation LLoc = GetLocationForCandidate(L);
11553     SourceLocation RLoc = GetLocationForCandidate(R);
11554 
11555     // Put candidates without locations (e.g. builtins) at the end.
11556     if (LLoc.isInvalid()) return false;
11557     if (RLoc.isInvalid()) return true;
11558 
11559     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11560   }
11561 };
11562 }
11563 
11564 /// CompleteNonViableCandidate - Normally, overload resolution only
11565 /// computes up to the first bad conversion. Produces the FixIt set if
11566 /// possible.
11567 static void
11568 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
11569                            ArrayRef<Expr *> Args,
11570                            OverloadCandidateSet::CandidateSetKind CSK) {
11571   assert(!Cand->Viable);
11572 
11573   // Don't do anything on failures other than bad conversion.
11574   if (Cand->FailureKind != ovl_fail_bad_conversion)
11575     return;
11576 
11577   // We only want the FixIts if all the arguments can be corrected.
11578   bool Unfixable = false;
11579   // Use a implicit copy initialization to check conversion fixes.
11580   Cand->Fix.setConversionChecker(TryCopyInitialization);
11581 
11582   // Attempt to fix the bad conversion.
11583   unsigned ConvCount = Cand->Conversions.size();
11584   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
11585        ++ConvIdx) {
11586     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
11587     if (Cand->Conversions[ConvIdx].isInitialized() &&
11588         Cand->Conversions[ConvIdx].isBad()) {
11589       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11590       break;
11591     }
11592   }
11593 
11594   // FIXME: this should probably be preserved from the overload
11595   // operation somehow.
11596   bool SuppressUserConversions = false;
11597 
11598   unsigned ConvIdx = 0;
11599   unsigned ArgIdx = 0;
11600   ArrayRef<QualType> ParamTypes;
11601   bool Reversed = Cand->isReversed();
11602 
11603   if (Cand->IsSurrogate) {
11604     QualType ConvType
11605       = Cand->Surrogate->getConversionType().getNonReferenceType();
11606     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11607       ConvType = ConvPtrType->getPointeeType();
11608     ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
11609     // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11610     ConvIdx = 1;
11611   } else if (Cand->Function) {
11612     ParamTypes =
11613         Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
11614     if (isa<CXXMethodDecl>(Cand->Function) &&
11615         !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
11616       // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11617       ConvIdx = 1;
11618       if (CSK == OverloadCandidateSet::CSK_Operator &&
11619           Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
11620           Cand->Function->getDeclName().getCXXOverloadedOperator() !=
11621               OO_Subscript)
11622         // Argument 0 is 'this', which doesn't have a corresponding parameter.
11623         ArgIdx = 1;
11624     }
11625   } else {
11626     // Builtin operator.
11627     assert(ConvCount <= 3);
11628     ParamTypes = Cand->BuiltinParamTypes;
11629   }
11630 
11631   // Fill in the rest of the conversions.
11632   for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
11633        ConvIdx != ConvCount;
11634        ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
11635     assert(ArgIdx < Args.size() && "no argument for this arg conversion");
11636     if (Cand->Conversions[ConvIdx].isInitialized()) {
11637       // We've already checked this conversion.
11638     } else if (ParamIdx < ParamTypes.size()) {
11639       if (ParamTypes[ParamIdx]->isDependentType())
11640         Cand->Conversions[ConvIdx].setAsIdentityConversion(
11641             Args[ArgIdx]->getType());
11642       else {
11643         Cand->Conversions[ConvIdx] =
11644             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
11645                                   SuppressUserConversions,
11646                                   /*InOverloadResolution=*/true,
11647                                   /*AllowObjCWritebackConversion=*/
11648                                   S.getLangOpts().ObjCAutoRefCount);
11649         // Store the FixIt in the candidate if it exists.
11650         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
11651           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11652       }
11653     } else
11654       Cand->Conversions[ConvIdx].setEllipsis();
11655   }
11656 }
11657 
11658 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
11659     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11660     SourceLocation OpLoc,
11661     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11662   // Sort the candidates by viability and position.  Sorting directly would
11663   // be prohibitive, so we make a set of pointers and sort those.
11664   SmallVector<OverloadCandidate*, 32> Cands;
11665   if (OCD == OCD_AllCandidates) Cands.reserve(size());
11666   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11667     if (!Filter(*Cand))
11668       continue;
11669     switch (OCD) {
11670     case OCD_AllCandidates:
11671       if (!Cand->Viable) {
11672         if (!Cand->Function && !Cand->IsSurrogate) {
11673           // This a non-viable builtin candidate.  We do not, in general,
11674           // want to list every possible builtin candidate.
11675           continue;
11676         }
11677         CompleteNonViableCandidate(S, Cand, Args, Kind);
11678       }
11679       break;
11680 
11681     case OCD_ViableCandidates:
11682       if (!Cand->Viable)
11683         continue;
11684       break;
11685 
11686     case OCD_AmbiguousCandidates:
11687       if (!Cand->Best)
11688         continue;
11689       break;
11690     }
11691 
11692     Cands.push_back(Cand);
11693   }
11694 
11695   llvm::stable_sort(
11696       Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
11697 
11698   return Cands;
11699 }
11700 
11701 bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
11702                                             SourceLocation OpLoc) {
11703   bool DeferHint = false;
11704   if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
11705     // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
11706     // host device candidates.
11707     auto WrongSidedCands =
11708         CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
11709           return (Cand.Viable == false &&
11710                   Cand.FailureKind == ovl_fail_bad_target) ||
11711                  (Cand.Function &&
11712                   Cand.Function->template hasAttr<CUDAHostAttr>() &&
11713                   Cand.Function->template hasAttr<CUDADeviceAttr>());
11714         });
11715     DeferHint = !WrongSidedCands.empty();
11716   }
11717   return DeferHint;
11718 }
11719 
11720 /// When overload resolution fails, prints diagnostic messages containing the
11721 /// candidates in the candidate set.
11722 void OverloadCandidateSet::NoteCandidates(
11723     PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
11724     ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
11725     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11726 
11727   auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
11728 
11729   S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
11730 
11731   NoteCandidates(S, Args, Cands, Opc, OpLoc);
11732 
11733   if (OCD == OCD_AmbiguousCandidates)
11734     MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
11735 }
11736 
11737 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
11738                                           ArrayRef<OverloadCandidate *> Cands,
11739                                           StringRef Opc, SourceLocation OpLoc) {
11740   bool ReportedAmbiguousConversions = false;
11741 
11742   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11743   unsigned CandsShown = 0;
11744   auto I = Cands.begin(), E = Cands.end();
11745   for (; I != E; ++I) {
11746     OverloadCandidate *Cand = *I;
11747 
11748     if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
11749         ShowOverloads == Ovl_Best) {
11750       break;
11751     }
11752     ++CandsShown;
11753 
11754     if (Cand->Function)
11755       NoteFunctionCandidate(S, Cand, Args.size(),
11756                             /*TakingCandidateAddress=*/false, DestAS);
11757     else if (Cand->IsSurrogate)
11758       NoteSurrogateCandidate(S, Cand);
11759     else {
11760       assert(Cand->Viable &&
11761              "Non-viable built-in candidates are not added to Cands.");
11762       // Generally we only see ambiguities including viable builtin
11763       // operators if overload resolution got screwed up by an
11764       // ambiguous user-defined conversion.
11765       //
11766       // FIXME: It's quite possible for different conversions to see
11767       // different ambiguities, though.
11768       if (!ReportedAmbiguousConversions) {
11769         NoteAmbiguousUserConversions(S, OpLoc, Cand);
11770         ReportedAmbiguousConversions = true;
11771       }
11772 
11773       // If this is a viable builtin, print it.
11774       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
11775     }
11776   }
11777 
11778   // Inform S.Diags that we've shown an overload set with N elements.  This may
11779   // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
11780   S.Diags.overloadCandidatesShown(CandsShown);
11781 
11782   if (I != E)
11783     S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
11784            shouldDeferDiags(S, Args, OpLoc))
11785         << int(E - I);
11786 }
11787 
11788 static SourceLocation
11789 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
11790   return Cand->Specialization ? Cand->Specialization->getLocation()
11791                               : SourceLocation();
11792 }
11793 
11794 namespace {
11795 struct CompareTemplateSpecCandidatesForDisplay {
11796   Sema &S;
11797   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
11798 
11799   bool operator()(const TemplateSpecCandidate *L,
11800                   const TemplateSpecCandidate *R) {
11801     // Fast-path this check.
11802     if (L == R)
11803       return false;
11804 
11805     // Assuming that both candidates are not matches...
11806 
11807     // Sort by the ranking of deduction failures.
11808     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11809       return RankDeductionFailure(L->DeductionFailure) <
11810              RankDeductionFailure(R->DeductionFailure);
11811 
11812     // Sort everything else by location.
11813     SourceLocation LLoc = GetLocationForCandidate(L);
11814     SourceLocation RLoc = GetLocationForCandidate(R);
11815 
11816     // Put candidates without locations (e.g. builtins) at the end.
11817     if (LLoc.isInvalid())
11818       return false;
11819     if (RLoc.isInvalid())
11820       return true;
11821 
11822     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11823   }
11824 };
11825 }
11826 
11827 /// Diagnose a template argument deduction failure.
11828 /// We are treating these failures as overload failures due to bad
11829 /// deductions.
11830 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
11831                                                  bool ForTakingAddress) {
11832   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
11833                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
11834 }
11835 
11836 void TemplateSpecCandidateSet::destroyCandidates() {
11837   for (iterator i = begin(), e = end(); i != e; ++i) {
11838     i->DeductionFailure.Destroy();
11839   }
11840 }
11841 
11842 void TemplateSpecCandidateSet::clear() {
11843   destroyCandidates();
11844   Candidates.clear();
11845 }
11846 
11847 /// NoteCandidates - When no template specialization match is found, prints
11848 /// diagnostic messages containing the non-matching specializations that form
11849 /// the candidate set.
11850 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
11851 /// OCD == OCD_AllCandidates and Cand->Viable == false.
11852 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
11853   // Sort the candidates by position (assuming no candidate is a match).
11854   // Sorting directly would be prohibitive, so we make a set of pointers
11855   // and sort those.
11856   SmallVector<TemplateSpecCandidate *, 32> Cands;
11857   Cands.reserve(size());
11858   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11859     if (Cand->Specialization)
11860       Cands.push_back(Cand);
11861     // Otherwise, this is a non-matching builtin candidate.  We do not,
11862     // in general, want to list every possible builtin candidate.
11863   }
11864 
11865   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
11866 
11867   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
11868   // for generalization purposes (?).
11869   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11870 
11871   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
11872   unsigned CandsShown = 0;
11873   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11874     TemplateSpecCandidate *Cand = *I;
11875 
11876     // Set an arbitrary limit on the number of candidates we'll spam
11877     // the user with.  FIXME: This limit should depend on details of the
11878     // candidate list.
11879     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
11880       break;
11881     ++CandsShown;
11882 
11883     assert(Cand->Specialization &&
11884            "Non-matching built-in candidates are not added to Cands.");
11885     Cand->NoteDeductionFailure(S, ForTakingAddress);
11886   }
11887 
11888   if (I != E)
11889     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
11890 }
11891 
11892 // [PossiblyAFunctionType]  -->   [Return]
11893 // NonFunctionType --> NonFunctionType
11894 // R (A) --> R(A)
11895 // R (*)(A) --> R (A)
11896 // R (&)(A) --> R (A)
11897 // R (S::*)(A) --> R (A)
11898 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
11899   QualType Ret = PossiblyAFunctionType;
11900   if (const PointerType *ToTypePtr =
11901     PossiblyAFunctionType->getAs<PointerType>())
11902     Ret = ToTypePtr->getPointeeType();
11903   else if (const ReferenceType *ToTypeRef =
11904     PossiblyAFunctionType->getAs<ReferenceType>())
11905     Ret = ToTypeRef->getPointeeType();
11906   else if (const MemberPointerType *MemTypePtr =
11907     PossiblyAFunctionType->getAs<MemberPointerType>())
11908     Ret = MemTypePtr->getPointeeType();
11909   Ret =
11910     Context.getCanonicalType(Ret).getUnqualifiedType();
11911   return Ret;
11912 }
11913 
11914 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
11915                                  bool Complain = true) {
11916   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
11917       S.DeduceReturnType(FD, Loc, Complain))
11918     return true;
11919 
11920   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
11921   if (S.getLangOpts().CPlusPlus17 &&
11922       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
11923       !S.ResolveExceptionSpec(Loc, FPT))
11924     return true;
11925 
11926   return false;
11927 }
11928 
11929 namespace {
11930 // A helper class to help with address of function resolution
11931 // - allows us to avoid passing around all those ugly parameters
11932 class AddressOfFunctionResolver {
11933   Sema& S;
11934   Expr* SourceExpr;
11935   const QualType& TargetType;
11936   QualType TargetFunctionType; // Extracted function type from target type
11937 
11938   bool Complain;
11939   //DeclAccessPair& ResultFunctionAccessPair;
11940   ASTContext& Context;
11941 
11942   bool TargetTypeIsNonStaticMemberFunction;
11943   bool FoundNonTemplateFunction;
11944   bool StaticMemberFunctionFromBoundPointer;
11945   bool HasComplained;
11946 
11947   OverloadExpr::FindResult OvlExprInfo;
11948   OverloadExpr *OvlExpr;
11949   TemplateArgumentListInfo OvlExplicitTemplateArgs;
11950   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
11951   TemplateSpecCandidateSet FailedCandidates;
11952 
11953 public:
11954   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
11955                             const QualType &TargetType, bool Complain)
11956       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
11957         Complain(Complain), Context(S.getASTContext()),
11958         TargetTypeIsNonStaticMemberFunction(
11959             !!TargetType->getAs<MemberPointerType>()),
11960         FoundNonTemplateFunction(false),
11961         StaticMemberFunctionFromBoundPointer(false),
11962         HasComplained(false),
11963         OvlExprInfo(OverloadExpr::find(SourceExpr)),
11964         OvlExpr(OvlExprInfo.Expression),
11965         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
11966     ExtractUnqualifiedFunctionTypeFromTargetType();
11967 
11968     if (TargetFunctionType->isFunctionType()) {
11969       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
11970         if (!UME->isImplicitAccess() &&
11971             !S.ResolveSingleFunctionTemplateSpecialization(UME))
11972           StaticMemberFunctionFromBoundPointer = true;
11973     } else if (OvlExpr->hasExplicitTemplateArgs()) {
11974       DeclAccessPair dap;
11975       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
11976               OvlExpr, false, &dap)) {
11977         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
11978           if (!Method->isStatic()) {
11979             // If the target type is a non-function type and the function found
11980             // is a non-static member function, pretend as if that was the
11981             // target, it's the only possible type to end up with.
11982             TargetTypeIsNonStaticMemberFunction = true;
11983 
11984             // And skip adding the function if its not in the proper form.
11985             // We'll diagnose this due to an empty set of functions.
11986             if (!OvlExprInfo.HasFormOfMemberPointer)
11987               return;
11988           }
11989 
11990         Matches.push_back(std::make_pair(dap, Fn));
11991       }
11992       return;
11993     }
11994 
11995     if (OvlExpr->hasExplicitTemplateArgs())
11996       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
11997 
11998     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
11999       // C++ [over.over]p4:
12000       //   If more than one function is selected, [...]
12001       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
12002         if (FoundNonTemplateFunction)
12003           EliminateAllTemplateMatches();
12004         else
12005           EliminateAllExceptMostSpecializedTemplate();
12006       }
12007     }
12008 
12009     if (S.getLangOpts().CUDA && Matches.size() > 1)
12010       EliminateSuboptimalCudaMatches();
12011   }
12012 
12013   bool hasComplained() const { return HasComplained; }
12014 
12015 private:
12016   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
12017     QualType Discard;
12018     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
12019            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
12020   }
12021 
12022   /// \return true if A is considered a better overload candidate for the
12023   /// desired type than B.
12024   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
12025     // If A doesn't have exactly the correct type, we don't want to classify it
12026     // as "better" than anything else. This way, the user is required to
12027     // disambiguate for us if there are multiple candidates and no exact match.
12028     return candidateHasExactlyCorrectType(A) &&
12029            (!candidateHasExactlyCorrectType(B) ||
12030             compareEnableIfAttrs(S, A, B) == Comparison::Better);
12031   }
12032 
12033   /// \return true if we were able to eliminate all but one overload candidate,
12034   /// false otherwise.
12035   bool eliminiateSuboptimalOverloadCandidates() {
12036     // Same algorithm as overload resolution -- one pass to pick the "best",
12037     // another pass to be sure that nothing is better than the best.
12038     auto Best = Matches.begin();
12039     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
12040       if (isBetterCandidate(I->second, Best->second))
12041         Best = I;
12042 
12043     const FunctionDecl *BestFn = Best->second;
12044     auto IsBestOrInferiorToBest = [this, BestFn](
12045         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
12046       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
12047     };
12048 
12049     // Note: We explicitly leave Matches unmodified if there isn't a clear best
12050     // option, so we can potentially give the user a better error
12051     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
12052       return false;
12053     Matches[0] = *Best;
12054     Matches.resize(1);
12055     return true;
12056   }
12057 
12058   bool isTargetTypeAFunction() const {
12059     return TargetFunctionType->isFunctionType();
12060   }
12061 
12062   // [ToType]     [Return]
12063 
12064   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
12065   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
12066   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
12067   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
12068     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
12069   }
12070 
12071   // return true if any matching specializations were found
12072   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
12073                                    const DeclAccessPair& CurAccessFunPair) {
12074     if (CXXMethodDecl *Method
12075               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
12076       // Skip non-static function templates when converting to pointer, and
12077       // static when converting to member pointer.
12078       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
12079         return false;
12080     }
12081     else if (TargetTypeIsNonStaticMemberFunction)
12082       return false;
12083 
12084     // C++ [over.over]p2:
12085     //   If the name is a function template, template argument deduction is
12086     //   done (14.8.2.2), and if the argument deduction succeeds, the
12087     //   resulting template argument list is used to generate a single
12088     //   function template specialization, which is added to the set of
12089     //   overloaded functions considered.
12090     FunctionDecl *Specialization = nullptr;
12091     TemplateDeductionInfo Info(FailedCandidates.getLocation());
12092     if (Sema::TemplateDeductionResult Result
12093           = S.DeduceTemplateArguments(FunctionTemplate,
12094                                       &OvlExplicitTemplateArgs,
12095                                       TargetFunctionType, Specialization,
12096                                       Info, /*IsAddressOfFunction*/true)) {
12097       // Make a note of the failed deduction for diagnostics.
12098       FailedCandidates.addCandidate()
12099           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
12100                MakeDeductionFailureInfo(Context, Result, Info));
12101       return false;
12102     }
12103 
12104     // Template argument deduction ensures that we have an exact match or
12105     // compatible pointer-to-function arguments that would be adjusted by ICS.
12106     // This function template specicalization works.
12107     assert(S.isSameOrCompatibleFunctionType(
12108               Context.getCanonicalType(Specialization->getType()),
12109               Context.getCanonicalType(TargetFunctionType)));
12110 
12111     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
12112       return false;
12113 
12114     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
12115     return true;
12116   }
12117 
12118   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
12119                                       const DeclAccessPair& CurAccessFunPair) {
12120     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12121       // Skip non-static functions when converting to pointer, and static
12122       // when converting to member pointer.
12123       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
12124         return false;
12125     }
12126     else if (TargetTypeIsNonStaticMemberFunction)
12127       return false;
12128 
12129     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
12130       if (S.getLangOpts().CUDA)
12131         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
12132           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
12133             return false;
12134       if (FunDecl->isMultiVersion()) {
12135         const auto *TA = FunDecl->getAttr<TargetAttr>();
12136         if (TA && !TA->isDefaultVersion())
12137           return false;
12138       }
12139 
12140       // If any candidate has a placeholder return type, trigger its deduction
12141       // now.
12142       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
12143                                Complain)) {
12144         HasComplained |= Complain;
12145         return false;
12146       }
12147 
12148       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
12149         return false;
12150 
12151       // If we're in C, we need to support types that aren't exactly identical.
12152       if (!S.getLangOpts().CPlusPlus ||
12153           candidateHasExactlyCorrectType(FunDecl)) {
12154         Matches.push_back(std::make_pair(
12155             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
12156         FoundNonTemplateFunction = true;
12157         return true;
12158       }
12159     }
12160 
12161     return false;
12162   }
12163 
12164   bool FindAllFunctionsThatMatchTargetTypeExactly() {
12165     bool Ret = false;
12166 
12167     // If the overload expression doesn't have the form of a pointer to
12168     // member, don't try to convert it to a pointer-to-member type.
12169     if (IsInvalidFormOfPointerToMemberFunction())
12170       return false;
12171 
12172     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12173                                E = OvlExpr->decls_end();
12174          I != E; ++I) {
12175       // Look through any using declarations to find the underlying function.
12176       NamedDecl *Fn = (*I)->getUnderlyingDecl();
12177 
12178       // C++ [over.over]p3:
12179       //   Non-member functions and static member functions match
12180       //   targets of type "pointer-to-function" or "reference-to-function."
12181       //   Nonstatic member functions match targets of
12182       //   type "pointer-to-member-function."
12183       // Note that according to DR 247, the containing class does not matter.
12184       if (FunctionTemplateDecl *FunctionTemplate
12185                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
12186         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
12187           Ret = true;
12188       }
12189       // If we have explicit template arguments supplied, skip non-templates.
12190       else if (!OvlExpr->hasExplicitTemplateArgs() &&
12191                AddMatchingNonTemplateFunction(Fn, I.getPair()))
12192         Ret = true;
12193     }
12194     assert(Ret || Matches.empty());
12195     return Ret;
12196   }
12197 
12198   void EliminateAllExceptMostSpecializedTemplate() {
12199     //   [...] and any given function template specialization F1 is
12200     //   eliminated if the set contains a second function template
12201     //   specialization whose function template is more specialized
12202     //   than the function template of F1 according to the partial
12203     //   ordering rules of 14.5.5.2.
12204 
12205     // The algorithm specified above is quadratic. We instead use a
12206     // two-pass algorithm (similar to the one used to identify the
12207     // best viable function in an overload set) that identifies the
12208     // best function template (if it exists).
12209 
12210     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
12211     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
12212       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
12213 
12214     // TODO: It looks like FailedCandidates does not serve much purpose
12215     // here, since the no_viable diagnostic has index 0.
12216     UnresolvedSetIterator Result = S.getMostSpecialized(
12217         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
12218         SourceExpr->getBeginLoc(), S.PDiag(),
12219         S.PDiag(diag::err_addr_ovl_ambiguous)
12220             << Matches[0].second->getDeclName(),
12221         S.PDiag(diag::note_ovl_candidate)
12222             << (unsigned)oc_function << (unsigned)ocs_described_template,
12223         Complain, TargetFunctionType);
12224 
12225     if (Result != MatchesCopy.end()) {
12226       // Make it the first and only element
12227       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
12228       Matches[0].second = cast<FunctionDecl>(*Result);
12229       Matches.resize(1);
12230     } else
12231       HasComplained |= Complain;
12232   }
12233 
12234   void EliminateAllTemplateMatches() {
12235     //   [...] any function template specializations in the set are
12236     //   eliminated if the set also contains a non-template function, [...]
12237     for (unsigned I = 0, N = Matches.size(); I != N; ) {
12238       if (Matches[I].second->getPrimaryTemplate() == nullptr)
12239         ++I;
12240       else {
12241         Matches[I] = Matches[--N];
12242         Matches.resize(N);
12243       }
12244     }
12245   }
12246 
12247   void EliminateSuboptimalCudaMatches() {
12248     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
12249   }
12250 
12251 public:
12252   void ComplainNoMatchesFound() const {
12253     assert(Matches.empty());
12254     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
12255         << OvlExpr->getName() << TargetFunctionType
12256         << OvlExpr->getSourceRange();
12257     if (FailedCandidates.empty())
12258       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12259                                   /*TakingAddress=*/true);
12260     else {
12261       // We have some deduction failure messages. Use them to diagnose
12262       // the function templates, and diagnose the non-template candidates
12263       // normally.
12264       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12265                                  IEnd = OvlExpr->decls_end();
12266            I != IEnd; ++I)
12267         if (FunctionDecl *Fun =
12268                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
12269           if (!functionHasPassObjectSizeParams(Fun))
12270             S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
12271                                     /*TakingAddress=*/true);
12272       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
12273     }
12274   }
12275 
12276   bool IsInvalidFormOfPointerToMemberFunction() const {
12277     return TargetTypeIsNonStaticMemberFunction &&
12278       !OvlExprInfo.HasFormOfMemberPointer;
12279   }
12280 
12281   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
12282       // TODO: Should we condition this on whether any functions might
12283       // have matched, or is it more appropriate to do that in callers?
12284       // TODO: a fixit wouldn't hurt.
12285       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
12286         << TargetType << OvlExpr->getSourceRange();
12287   }
12288 
12289   bool IsStaticMemberFunctionFromBoundPointer() const {
12290     return StaticMemberFunctionFromBoundPointer;
12291   }
12292 
12293   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
12294     S.Diag(OvlExpr->getBeginLoc(),
12295            diag::err_invalid_form_pointer_member_function)
12296         << OvlExpr->getSourceRange();
12297   }
12298 
12299   void ComplainOfInvalidConversion() const {
12300     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
12301         << OvlExpr->getName() << TargetType;
12302   }
12303 
12304   void ComplainMultipleMatchesFound() const {
12305     assert(Matches.size() > 1);
12306     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
12307         << OvlExpr->getName() << OvlExpr->getSourceRange();
12308     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12309                                 /*TakingAddress=*/true);
12310   }
12311 
12312   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
12313 
12314   int getNumMatches() const { return Matches.size(); }
12315 
12316   FunctionDecl* getMatchingFunctionDecl() const {
12317     if (Matches.size() != 1) return nullptr;
12318     return Matches[0].second;
12319   }
12320 
12321   const DeclAccessPair* getMatchingFunctionAccessPair() const {
12322     if (Matches.size() != 1) return nullptr;
12323     return &Matches[0].first;
12324   }
12325 };
12326 }
12327 
12328 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
12329 /// an overloaded function (C++ [over.over]), where @p From is an
12330 /// expression with overloaded function type and @p ToType is the type
12331 /// we're trying to resolve to. For example:
12332 ///
12333 /// @code
12334 /// int f(double);
12335 /// int f(int);
12336 ///
12337 /// int (*pfd)(double) = f; // selects f(double)
12338 /// @endcode
12339 ///
12340 /// This routine returns the resulting FunctionDecl if it could be
12341 /// resolved, and NULL otherwise. When @p Complain is true, this
12342 /// routine will emit diagnostics if there is an error.
12343 FunctionDecl *
12344 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
12345                                          QualType TargetType,
12346                                          bool Complain,
12347                                          DeclAccessPair &FoundResult,
12348                                          bool *pHadMultipleCandidates) {
12349   assert(AddressOfExpr->getType() == Context.OverloadTy);
12350 
12351   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
12352                                      Complain);
12353   int NumMatches = Resolver.getNumMatches();
12354   FunctionDecl *Fn = nullptr;
12355   bool ShouldComplain = Complain && !Resolver.hasComplained();
12356   if (NumMatches == 0 && ShouldComplain) {
12357     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
12358       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
12359     else
12360       Resolver.ComplainNoMatchesFound();
12361   }
12362   else if (NumMatches > 1 && ShouldComplain)
12363     Resolver.ComplainMultipleMatchesFound();
12364   else if (NumMatches == 1) {
12365     Fn = Resolver.getMatchingFunctionDecl();
12366     assert(Fn);
12367     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
12368       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
12369     FoundResult = *Resolver.getMatchingFunctionAccessPair();
12370     if (Complain) {
12371       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
12372         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
12373       else
12374         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
12375     }
12376   }
12377 
12378   if (pHadMultipleCandidates)
12379     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
12380   return Fn;
12381 }
12382 
12383 /// Given an expression that refers to an overloaded function, try to
12384 /// resolve that function to a single function that can have its address taken.
12385 /// This will modify `Pair` iff it returns non-null.
12386 ///
12387 /// This routine can only succeed if from all of the candidates in the overload
12388 /// set for SrcExpr that can have their addresses taken, there is one candidate
12389 /// that is more constrained than the rest.
12390 FunctionDecl *
12391 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
12392   OverloadExpr::FindResult R = OverloadExpr::find(E);
12393   OverloadExpr *Ovl = R.Expression;
12394   bool IsResultAmbiguous = false;
12395   FunctionDecl *Result = nullptr;
12396   DeclAccessPair DAP;
12397   SmallVector<FunctionDecl *, 2> AmbiguousDecls;
12398 
12399   auto CheckMoreConstrained =
12400       [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> {
12401         SmallVector<const Expr *, 1> AC1, AC2;
12402         FD1->getAssociatedConstraints(AC1);
12403         FD2->getAssociatedConstraints(AC2);
12404         bool AtLeastAsConstrained1, AtLeastAsConstrained2;
12405         if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
12406           return None;
12407         if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
12408           return None;
12409         if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
12410           return None;
12411         return AtLeastAsConstrained1;
12412       };
12413 
12414   // Don't use the AddressOfResolver because we're specifically looking for
12415   // cases where we have one overload candidate that lacks
12416   // enable_if/pass_object_size/...
12417   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
12418     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
12419     if (!FD)
12420       return nullptr;
12421 
12422     if (!checkAddressOfFunctionIsAvailable(FD))
12423       continue;
12424 
12425     // We have more than one result - see if it is more constrained than the
12426     // previous one.
12427     if (Result) {
12428       Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD,
12429                                                                         Result);
12430       if (!MoreConstrainedThanPrevious) {
12431         IsResultAmbiguous = true;
12432         AmbiguousDecls.push_back(FD);
12433         continue;
12434       }
12435       if (!*MoreConstrainedThanPrevious)
12436         continue;
12437       // FD is more constrained - replace Result with it.
12438     }
12439     IsResultAmbiguous = false;
12440     DAP = I.getPair();
12441     Result = FD;
12442   }
12443 
12444   if (IsResultAmbiguous)
12445     return nullptr;
12446 
12447   if (Result) {
12448     SmallVector<const Expr *, 1> ResultAC;
12449     // We skipped over some ambiguous declarations which might be ambiguous with
12450     // the selected result.
12451     for (FunctionDecl *Skipped : AmbiguousDecls)
12452       if (!CheckMoreConstrained(Skipped, Result).hasValue())
12453         return nullptr;
12454     Pair = DAP;
12455   }
12456   return Result;
12457 }
12458 
12459 /// Given an overloaded function, tries to turn it into a non-overloaded
12460 /// function reference using resolveAddressOfSingleOverloadCandidate. This
12461 /// will perform access checks, diagnose the use of the resultant decl, and, if
12462 /// requested, potentially perform a function-to-pointer decay.
12463 ///
12464 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
12465 /// Otherwise, returns true. This may emit diagnostics and return true.
12466 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
12467     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
12468   Expr *E = SrcExpr.get();
12469   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
12470 
12471   DeclAccessPair DAP;
12472   FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
12473   if (!Found || Found->isCPUDispatchMultiVersion() ||
12474       Found->isCPUSpecificMultiVersion())
12475     return false;
12476 
12477   // Emitting multiple diagnostics for a function that is both inaccessible and
12478   // unavailable is consistent with our behavior elsewhere. So, always check
12479   // for both.
12480   DiagnoseUseOfDecl(Found, E->getExprLoc());
12481   CheckAddressOfMemberAccess(E, DAP);
12482   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
12483   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
12484     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
12485   else
12486     SrcExpr = Fixed;
12487   return true;
12488 }
12489 
12490 /// Given an expression that refers to an overloaded function, try to
12491 /// resolve that overloaded function expression down to a single function.
12492 ///
12493 /// This routine can only resolve template-ids that refer to a single function
12494 /// template, where that template-id refers to a single template whose template
12495 /// arguments are either provided by the template-id or have defaults,
12496 /// as described in C++0x [temp.arg.explicit]p3.
12497 ///
12498 /// If no template-ids are found, no diagnostics are emitted and NULL is
12499 /// returned.
12500 FunctionDecl *
12501 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
12502                                                   bool Complain,
12503                                                   DeclAccessPair *FoundResult) {
12504   // C++ [over.over]p1:
12505   //   [...] [Note: any redundant set of parentheses surrounding the
12506   //   overloaded function name is ignored (5.1). ]
12507   // C++ [over.over]p1:
12508   //   [...] The overloaded function name can be preceded by the &
12509   //   operator.
12510 
12511   // If we didn't actually find any template-ids, we're done.
12512   if (!ovl->hasExplicitTemplateArgs())
12513     return nullptr;
12514 
12515   TemplateArgumentListInfo ExplicitTemplateArgs;
12516   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
12517   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
12518 
12519   // Look through all of the overloaded functions, searching for one
12520   // whose type matches exactly.
12521   FunctionDecl *Matched = nullptr;
12522   for (UnresolvedSetIterator I = ovl->decls_begin(),
12523          E = ovl->decls_end(); I != E; ++I) {
12524     // C++0x [temp.arg.explicit]p3:
12525     //   [...] In contexts where deduction is done and fails, or in contexts
12526     //   where deduction is not done, if a template argument list is
12527     //   specified and it, along with any default template arguments,
12528     //   identifies a single function template specialization, then the
12529     //   template-id is an lvalue for the function template specialization.
12530     FunctionTemplateDecl *FunctionTemplate
12531       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
12532 
12533     // C++ [over.over]p2:
12534     //   If the name is a function template, template argument deduction is
12535     //   done (14.8.2.2), and if the argument deduction succeeds, the
12536     //   resulting template argument list is used to generate a single
12537     //   function template specialization, which is added to the set of
12538     //   overloaded functions considered.
12539     FunctionDecl *Specialization = nullptr;
12540     TemplateDeductionInfo Info(FailedCandidates.getLocation());
12541     if (TemplateDeductionResult Result
12542           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
12543                                     Specialization, Info,
12544                                     /*IsAddressOfFunction*/true)) {
12545       // Make a note of the failed deduction for diagnostics.
12546       // TODO: Actually use the failed-deduction info?
12547       FailedCandidates.addCandidate()
12548           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
12549                MakeDeductionFailureInfo(Context, Result, Info));
12550       continue;
12551     }
12552 
12553     assert(Specialization && "no specialization and no error?");
12554 
12555     // Multiple matches; we can't resolve to a single declaration.
12556     if (Matched) {
12557       if (Complain) {
12558         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
12559           << ovl->getName();
12560         NoteAllOverloadCandidates(ovl);
12561       }
12562       return nullptr;
12563     }
12564 
12565     Matched = Specialization;
12566     if (FoundResult) *FoundResult = I.getPair();
12567   }
12568 
12569   if (Matched &&
12570       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
12571     return nullptr;
12572 
12573   return Matched;
12574 }
12575 
12576 // Resolve and fix an overloaded expression that can be resolved
12577 // because it identifies a single function template specialization.
12578 //
12579 // Last three arguments should only be supplied if Complain = true
12580 //
12581 // Return true if it was logically possible to so resolve the
12582 // expression, regardless of whether or not it succeeded.  Always
12583 // returns true if 'complain' is set.
12584 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
12585                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
12586                       bool complain, SourceRange OpRangeForComplaining,
12587                                            QualType DestTypeForComplaining,
12588                                             unsigned DiagIDForComplaining) {
12589   assert(SrcExpr.get()->getType() == Context.OverloadTy);
12590 
12591   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
12592 
12593   DeclAccessPair found;
12594   ExprResult SingleFunctionExpression;
12595   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
12596                            ovl.Expression, /*complain*/ false, &found)) {
12597     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
12598       SrcExpr = ExprError();
12599       return true;
12600     }
12601 
12602     // It is only correct to resolve to an instance method if we're
12603     // resolving a form that's permitted to be a pointer to member.
12604     // Otherwise we'll end up making a bound member expression, which
12605     // is illegal in all the contexts we resolve like this.
12606     if (!ovl.HasFormOfMemberPointer &&
12607         isa<CXXMethodDecl>(fn) &&
12608         cast<CXXMethodDecl>(fn)->isInstance()) {
12609       if (!complain) return false;
12610 
12611       Diag(ovl.Expression->getExprLoc(),
12612            diag::err_bound_member_function)
12613         << 0 << ovl.Expression->getSourceRange();
12614 
12615       // TODO: I believe we only end up here if there's a mix of
12616       // static and non-static candidates (otherwise the expression
12617       // would have 'bound member' type, not 'overload' type).
12618       // Ideally we would note which candidate was chosen and why
12619       // the static candidates were rejected.
12620       SrcExpr = ExprError();
12621       return true;
12622     }
12623 
12624     // Fix the expression to refer to 'fn'.
12625     SingleFunctionExpression =
12626         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
12627 
12628     // If desired, do function-to-pointer decay.
12629     if (doFunctionPointerConverion) {
12630       SingleFunctionExpression =
12631         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
12632       if (SingleFunctionExpression.isInvalid()) {
12633         SrcExpr = ExprError();
12634         return true;
12635       }
12636     }
12637   }
12638 
12639   if (!SingleFunctionExpression.isUsable()) {
12640     if (complain) {
12641       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
12642         << ovl.Expression->getName()
12643         << DestTypeForComplaining
12644         << OpRangeForComplaining
12645         << ovl.Expression->getQualifierLoc().getSourceRange();
12646       NoteAllOverloadCandidates(SrcExpr.get());
12647 
12648       SrcExpr = ExprError();
12649       return true;
12650     }
12651 
12652     return false;
12653   }
12654 
12655   SrcExpr = SingleFunctionExpression;
12656   return true;
12657 }
12658 
12659 /// Add a single candidate to the overload set.
12660 static void AddOverloadedCallCandidate(Sema &S,
12661                                        DeclAccessPair FoundDecl,
12662                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
12663                                        ArrayRef<Expr *> Args,
12664                                        OverloadCandidateSet &CandidateSet,
12665                                        bool PartialOverloading,
12666                                        bool KnownValid) {
12667   NamedDecl *Callee = FoundDecl.getDecl();
12668   if (isa<UsingShadowDecl>(Callee))
12669     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
12670 
12671   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
12672     if (ExplicitTemplateArgs) {
12673       assert(!KnownValid && "Explicit template arguments?");
12674       return;
12675     }
12676     // Prevent ill-formed function decls to be added as overload candidates.
12677     if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
12678       return;
12679 
12680     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
12681                            /*SuppressUserConversions=*/false,
12682                            PartialOverloading);
12683     return;
12684   }
12685 
12686   if (FunctionTemplateDecl *FuncTemplate
12687       = dyn_cast<FunctionTemplateDecl>(Callee)) {
12688     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
12689                                    ExplicitTemplateArgs, Args, CandidateSet,
12690                                    /*SuppressUserConversions=*/false,
12691                                    PartialOverloading);
12692     return;
12693   }
12694 
12695   assert(!KnownValid && "unhandled case in overloaded call candidate");
12696 }
12697 
12698 /// Add the overload candidates named by callee and/or found by argument
12699 /// dependent lookup to the given overload set.
12700 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
12701                                        ArrayRef<Expr *> Args,
12702                                        OverloadCandidateSet &CandidateSet,
12703                                        bool PartialOverloading) {
12704 
12705 #ifndef NDEBUG
12706   // Verify that ArgumentDependentLookup is consistent with the rules
12707   // in C++0x [basic.lookup.argdep]p3:
12708   //
12709   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
12710   //   and let Y be the lookup set produced by argument dependent
12711   //   lookup (defined as follows). If X contains
12712   //
12713   //     -- a declaration of a class member, or
12714   //
12715   //     -- a block-scope function declaration that is not a
12716   //        using-declaration, or
12717   //
12718   //     -- a declaration that is neither a function or a function
12719   //        template
12720   //
12721   //   then Y is empty.
12722 
12723   if (ULE->requiresADL()) {
12724     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12725            E = ULE->decls_end(); I != E; ++I) {
12726       assert(!(*I)->getDeclContext()->isRecord());
12727       assert(isa<UsingShadowDecl>(*I) ||
12728              !(*I)->getDeclContext()->isFunctionOrMethod());
12729       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
12730     }
12731   }
12732 #endif
12733 
12734   // It would be nice to avoid this copy.
12735   TemplateArgumentListInfo TABuffer;
12736   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12737   if (ULE->hasExplicitTemplateArgs()) {
12738     ULE->copyTemplateArgumentsInto(TABuffer);
12739     ExplicitTemplateArgs = &TABuffer;
12740   }
12741 
12742   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12743          E = ULE->decls_end(); I != E; ++I)
12744     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12745                                CandidateSet, PartialOverloading,
12746                                /*KnownValid*/ true);
12747 
12748   if (ULE->requiresADL())
12749     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
12750                                          Args, ExplicitTemplateArgs,
12751                                          CandidateSet, PartialOverloading);
12752 }
12753 
12754 /// Add the call candidates from the given set of lookup results to the given
12755 /// overload set. Non-function lookup results are ignored.
12756 void Sema::AddOverloadedCallCandidates(
12757     LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
12758     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
12759   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12760     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12761                                CandidateSet, false, /*KnownValid*/ false);
12762 }
12763 
12764 /// Determine whether a declaration with the specified name could be moved into
12765 /// a different namespace.
12766 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
12767   switch (Name.getCXXOverloadedOperator()) {
12768   case OO_New: case OO_Array_New:
12769   case OO_Delete: case OO_Array_Delete:
12770     return false;
12771 
12772   default:
12773     return true;
12774   }
12775 }
12776 
12777 /// Attempt to recover from an ill-formed use of a non-dependent name in a
12778 /// template, where the non-dependent name was declared after the template
12779 /// was defined. This is common in code written for a compilers which do not
12780 /// correctly implement two-stage name lookup.
12781 ///
12782 /// Returns true if a viable candidate was found and a diagnostic was issued.
12783 static bool DiagnoseTwoPhaseLookup(
12784     Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
12785     LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
12786     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
12787     CXXRecordDecl **FoundInClass = nullptr) {
12788   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
12789     return false;
12790 
12791   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
12792     if (DC->isTransparentContext())
12793       continue;
12794 
12795     SemaRef.LookupQualifiedName(R, DC);
12796 
12797     if (!R.empty()) {
12798       R.suppressDiagnostics();
12799 
12800       OverloadCandidateSet Candidates(FnLoc, CSK);
12801       SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
12802                                           Candidates);
12803 
12804       OverloadCandidateSet::iterator Best;
12805       OverloadingResult OR =
12806           Candidates.BestViableFunction(SemaRef, FnLoc, Best);
12807 
12808       if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
12809         // We either found non-function declarations or a best viable function
12810         // at class scope. A class-scope lookup result disables ADL. Don't
12811         // look past this, but let the caller know that we found something that
12812         // either is, or might be, usable in this class.
12813         if (FoundInClass) {
12814           *FoundInClass = RD;
12815           if (OR == OR_Success) {
12816             R.clear();
12817             R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
12818             R.resolveKind();
12819           }
12820         }
12821         return false;
12822       }
12823 
12824       if (OR != OR_Success) {
12825         // There wasn't a unique best function or function template.
12826         return false;
12827       }
12828 
12829       // Find the namespaces where ADL would have looked, and suggest
12830       // declaring the function there instead.
12831       Sema::AssociatedNamespaceSet AssociatedNamespaces;
12832       Sema::AssociatedClassSet AssociatedClasses;
12833       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
12834                                                  AssociatedNamespaces,
12835                                                  AssociatedClasses);
12836       Sema::AssociatedNamespaceSet SuggestedNamespaces;
12837       if (canBeDeclaredInNamespace(R.getLookupName())) {
12838         DeclContext *Std = SemaRef.getStdNamespace();
12839         for (Sema::AssociatedNamespaceSet::iterator
12840                it = AssociatedNamespaces.begin(),
12841                end = AssociatedNamespaces.end(); it != end; ++it) {
12842           // Never suggest declaring a function within namespace 'std'.
12843           if (Std && Std->Encloses(*it))
12844             continue;
12845 
12846           // Never suggest declaring a function within a namespace with a
12847           // reserved name, like __gnu_cxx.
12848           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
12849           if (NS &&
12850               NS->getQualifiedNameAsString().find("__") != std::string::npos)
12851             continue;
12852 
12853           SuggestedNamespaces.insert(*it);
12854         }
12855       }
12856 
12857       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
12858         << R.getLookupName();
12859       if (SuggestedNamespaces.empty()) {
12860         SemaRef.Diag(Best->Function->getLocation(),
12861                      diag::note_not_found_by_two_phase_lookup)
12862           << R.getLookupName() << 0;
12863       } else if (SuggestedNamespaces.size() == 1) {
12864         SemaRef.Diag(Best->Function->getLocation(),
12865                      diag::note_not_found_by_two_phase_lookup)
12866           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
12867       } else {
12868         // FIXME: It would be useful to list the associated namespaces here,
12869         // but the diagnostics infrastructure doesn't provide a way to produce
12870         // a localized representation of a list of items.
12871         SemaRef.Diag(Best->Function->getLocation(),
12872                      diag::note_not_found_by_two_phase_lookup)
12873           << R.getLookupName() << 2;
12874       }
12875 
12876       // Try to recover by calling this function.
12877       return true;
12878     }
12879 
12880     R.clear();
12881   }
12882 
12883   return false;
12884 }
12885 
12886 /// Attempt to recover from ill-formed use of a non-dependent operator in a
12887 /// template, where the non-dependent operator was declared after the template
12888 /// was defined.
12889 ///
12890 /// Returns true if a viable candidate was found and a diagnostic was issued.
12891 static bool
12892 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
12893                                SourceLocation OpLoc,
12894                                ArrayRef<Expr *> Args) {
12895   DeclarationName OpName =
12896     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
12897   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
12898   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
12899                                 OverloadCandidateSet::CSK_Operator,
12900                                 /*ExplicitTemplateArgs=*/nullptr, Args);
12901 }
12902 
12903 namespace {
12904 class BuildRecoveryCallExprRAII {
12905   Sema &SemaRef;
12906 public:
12907   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
12908     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
12909     SemaRef.IsBuildingRecoveryCallExpr = true;
12910   }
12911 
12912   ~BuildRecoveryCallExprRAII() {
12913     SemaRef.IsBuildingRecoveryCallExpr = false;
12914   }
12915 };
12916 
12917 }
12918 
12919 /// Attempts to recover from a call where no functions were found.
12920 ///
12921 /// This function will do one of three things:
12922 ///  * Diagnose, recover, and return a recovery expression.
12923 ///  * Diagnose, fail to recover, and return ExprError().
12924 ///  * Do not diagnose, do not recover, and return ExprResult(). The caller is
12925 ///    expected to diagnose as appropriate.
12926 static ExprResult
12927 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12928                       UnresolvedLookupExpr *ULE,
12929                       SourceLocation LParenLoc,
12930                       MutableArrayRef<Expr *> Args,
12931                       SourceLocation RParenLoc,
12932                       bool EmptyLookup, bool AllowTypoCorrection) {
12933   // Do not try to recover if it is already building a recovery call.
12934   // This stops infinite loops for template instantiations like
12935   //
12936   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
12937   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
12938   if (SemaRef.IsBuildingRecoveryCallExpr)
12939     return ExprResult();
12940   BuildRecoveryCallExprRAII RCE(SemaRef);
12941 
12942   CXXScopeSpec SS;
12943   SS.Adopt(ULE->getQualifierLoc());
12944   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
12945 
12946   TemplateArgumentListInfo TABuffer;
12947   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12948   if (ULE->hasExplicitTemplateArgs()) {
12949     ULE->copyTemplateArgumentsInto(TABuffer);
12950     ExplicitTemplateArgs = &TABuffer;
12951   }
12952 
12953   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
12954                  Sema::LookupOrdinaryName);
12955   CXXRecordDecl *FoundInClass = nullptr;
12956   if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
12957                              OverloadCandidateSet::CSK_Normal,
12958                              ExplicitTemplateArgs, Args, &FoundInClass)) {
12959     // OK, diagnosed a two-phase lookup issue.
12960   } else if (EmptyLookup) {
12961     // Try to recover from an empty lookup with typo correction.
12962     R.clear();
12963     NoTypoCorrectionCCC NoTypoValidator{};
12964     FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
12965                                                 ExplicitTemplateArgs != nullptr,
12966                                                 dyn_cast<MemberExpr>(Fn));
12967     CorrectionCandidateCallback &Validator =
12968         AllowTypoCorrection
12969             ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
12970             : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
12971     if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
12972                                     Args))
12973       return ExprError();
12974   } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
12975     // We found a usable declaration of the name in a dependent base of some
12976     // enclosing class.
12977     // FIXME: We should also explain why the candidates found by name lookup
12978     // were not viable.
12979     if (SemaRef.DiagnoseDependentMemberLookup(R))
12980       return ExprError();
12981   } else {
12982     // We had viable candidates and couldn't recover; let the caller diagnose
12983     // this.
12984     return ExprResult();
12985   }
12986 
12987   // If we get here, we should have issued a diagnostic and formed a recovery
12988   // lookup result.
12989   assert(!R.empty() && "lookup results empty despite recovery");
12990 
12991   // If recovery created an ambiguity, just bail out.
12992   if (R.isAmbiguous()) {
12993     R.suppressDiagnostics();
12994     return ExprError();
12995   }
12996 
12997   // Build an implicit member call if appropriate.  Just drop the
12998   // casts and such from the call, we don't really care.
12999   ExprResult NewFn = ExprError();
13000   if ((*R.begin())->isCXXClassMember())
13001     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
13002                                                     ExplicitTemplateArgs, S);
13003   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
13004     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
13005                                         ExplicitTemplateArgs);
13006   else
13007     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
13008 
13009   if (NewFn.isInvalid())
13010     return ExprError();
13011 
13012   // This shouldn't cause an infinite loop because we're giving it
13013   // an expression with viable lookup results, which should never
13014   // end up here.
13015   return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
13016                                MultiExprArg(Args.data(), Args.size()),
13017                                RParenLoc);
13018 }
13019 
13020 /// Constructs and populates an OverloadedCandidateSet from
13021 /// the given function.
13022 /// \returns true when an the ExprResult output parameter has been set.
13023 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
13024                                   UnresolvedLookupExpr *ULE,
13025                                   MultiExprArg Args,
13026                                   SourceLocation RParenLoc,
13027                                   OverloadCandidateSet *CandidateSet,
13028                                   ExprResult *Result) {
13029 #ifndef NDEBUG
13030   if (ULE->requiresADL()) {
13031     // To do ADL, we must have found an unqualified name.
13032     assert(!ULE->getQualifier() && "qualified name with ADL");
13033 
13034     // We don't perform ADL for implicit declarations of builtins.
13035     // Verify that this was correctly set up.
13036     FunctionDecl *F;
13037     if (ULE->decls_begin() != ULE->decls_end() &&
13038         ULE->decls_begin() + 1 == ULE->decls_end() &&
13039         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
13040         F->getBuiltinID() && F->isImplicit())
13041       llvm_unreachable("performing ADL for builtin");
13042 
13043     // We don't perform ADL in C.
13044     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
13045   }
13046 #endif
13047 
13048   UnbridgedCastsSet UnbridgedCasts;
13049   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
13050     *Result = ExprError();
13051     return true;
13052   }
13053 
13054   // Add the functions denoted by the callee to the set of candidate
13055   // functions, including those from argument-dependent lookup.
13056   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
13057 
13058   if (getLangOpts().MSVCCompat &&
13059       CurContext->isDependentContext() && !isSFINAEContext() &&
13060       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
13061 
13062     OverloadCandidateSet::iterator Best;
13063     if (CandidateSet->empty() ||
13064         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
13065             OR_No_Viable_Function) {
13066       // In Microsoft mode, if we are inside a template class member function
13067       // then create a type dependent CallExpr. The goal is to postpone name
13068       // lookup to instantiation time to be able to search into type dependent
13069       // base classes.
13070       CallExpr *CE =
13071           CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
13072                            RParenLoc, CurFPFeatureOverrides());
13073       CE->markDependentForPostponedNameLookup();
13074       *Result = CE;
13075       return true;
13076     }
13077   }
13078 
13079   if (CandidateSet->empty())
13080     return false;
13081 
13082   UnbridgedCasts.restore();
13083   return false;
13084 }
13085 
13086 // Guess at what the return type for an unresolvable overload should be.
13087 static QualType chooseRecoveryType(OverloadCandidateSet &CS,
13088                                    OverloadCandidateSet::iterator *Best) {
13089   llvm::Optional<QualType> Result;
13090   // Adjust Type after seeing a candidate.
13091   auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
13092     if (!Candidate.Function)
13093       return;
13094     if (Candidate.Function->isInvalidDecl())
13095       return;
13096     QualType T = Candidate.Function->getReturnType();
13097     if (T.isNull())
13098       return;
13099     if (!Result)
13100       Result = T;
13101     else if (Result != T)
13102       Result = QualType();
13103   };
13104 
13105   // Look for an unambiguous type from a progressively larger subset.
13106   // e.g. if types disagree, but all *viable* overloads return int, choose int.
13107   //
13108   // First, consider only the best candidate.
13109   if (Best && *Best != CS.end())
13110     ConsiderCandidate(**Best);
13111   // Next, consider only viable candidates.
13112   if (!Result)
13113     for (const auto &C : CS)
13114       if (C.Viable)
13115         ConsiderCandidate(C);
13116   // Finally, consider all candidates.
13117   if (!Result)
13118     for (const auto &C : CS)
13119       ConsiderCandidate(C);
13120 
13121   if (!Result)
13122     return QualType();
13123   auto Value = Result.getValue();
13124   if (Value.isNull() || Value->isUndeducedType())
13125     return QualType();
13126   return Value;
13127 }
13128 
13129 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
13130 /// the completed call expression. If overload resolution fails, emits
13131 /// diagnostics and returns ExprError()
13132 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
13133                                            UnresolvedLookupExpr *ULE,
13134                                            SourceLocation LParenLoc,
13135                                            MultiExprArg Args,
13136                                            SourceLocation RParenLoc,
13137                                            Expr *ExecConfig,
13138                                            OverloadCandidateSet *CandidateSet,
13139                                            OverloadCandidateSet::iterator *Best,
13140                                            OverloadingResult OverloadResult,
13141                                            bool AllowTypoCorrection) {
13142   switch (OverloadResult) {
13143   case OR_Success: {
13144     FunctionDecl *FDecl = (*Best)->Function;
13145     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
13146     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
13147       return ExprError();
13148     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13149     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
13150                                          ExecConfig, /*IsExecConfig=*/false,
13151                                          (*Best)->IsADLCandidate);
13152   }
13153 
13154   case OR_No_Viable_Function: {
13155     // Try to recover by looking for viable functions which the user might
13156     // have meant to call.
13157     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
13158                                                 Args, RParenLoc,
13159                                                 CandidateSet->empty(),
13160                                                 AllowTypoCorrection);
13161     if (Recovery.isInvalid() || Recovery.isUsable())
13162       return Recovery;
13163 
13164     // If the user passes in a function that we can't take the address of, we
13165     // generally end up emitting really bad error messages. Here, we attempt to
13166     // emit better ones.
13167     for (const Expr *Arg : Args) {
13168       if (!Arg->getType()->isFunctionType())
13169         continue;
13170       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
13171         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13172         if (FD &&
13173             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13174                                                        Arg->getExprLoc()))
13175           return ExprError();
13176       }
13177     }
13178 
13179     CandidateSet->NoteCandidates(
13180         PartialDiagnosticAt(
13181             Fn->getBeginLoc(),
13182             SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
13183                 << ULE->getName() << Fn->getSourceRange()),
13184         SemaRef, OCD_AllCandidates, Args);
13185     break;
13186   }
13187 
13188   case OR_Ambiguous:
13189     CandidateSet->NoteCandidates(
13190         PartialDiagnosticAt(Fn->getBeginLoc(),
13191                             SemaRef.PDiag(diag::err_ovl_ambiguous_call)
13192                                 << ULE->getName() << Fn->getSourceRange()),
13193         SemaRef, OCD_AmbiguousCandidates, Args);
13194     break;
13195 
13196   case OR_Deleted: {
13197     CandidateSet->NoteCandidates(
13198         PartialDiagnosticAt(Fn->getBeginLoc(),
13199                             SemaRef.PDiag(diag::err_ovl_deleted_call)
13200                                 << ULE->getName() << Fn->getSourceRange()),
13201         SemaRef, OCD_AllCandidates, Args);
13202 
13203     // We emitted an error for the unavailable/deleted function call but keep
13204     // the call in the AST.
13205     FunctionDecl *FDecl = (*Best)->Function;
13206     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13207     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
13208                                          ExecConfig, /*IsExecConfig=*/false,
13209                                          (*Best)->IsADLCandidate);
13210   }
13211   }
13212 
13213   // Overload resolution failed, try to recover.
13214   SmallVector<Expr *, 8> SubExprs = {Fn};
13215   SubExprs.append(Args.begin(), Args.end());
13216   return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
13217                                     chooseRecoveryType(*CandidateSet, Best));
13218 }
13219 
13220 static void markUnaddressableCandidatesUnviable(Sema &S,
13221                                                 OverloadCandidateSet &CS) {
13222   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
13223     if (I->Viable &&
13224         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
13225       I->Viable = false;
13226       I->FailureKind = ovl_fail_addr_not_available;
13227     }
13228   }
13229 }
13230 
13231 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
13232 /// (which eventually refers to the declaration Func) and the call
13233 /// arguments Args/NumArgs, attempt to resolve the function call down
13234 /// to a specific function. If overload resolution succeeds, returns
13235 /// the call expression produced by overload resolution.
13236 /// Otherwise, emits diagnostics and returns ExprError.
13237 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
13238                                          UnresolvedLookupExpr *ULE,
13239                                          SourceLocation LParenLoc,
13240                                          MultiExprArg Args,
13241                                          SourceLocation RParenLoc,
13242                                          Expr *ExecConfig,
13243                                          bool AllowTypoCorrection,
13244                                          bool CalleesAddressIsTaken) {
13245   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
13246                                     OverloadCandidateSet::CSK_Normal);
13247   ExprResult result;
13248 
13249   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
13250                              &result))
13251     return result;
13252 
13253   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
13254   // functions that aren't addressible are considered unviable.
13255   if (CalleesAddressIsTaken)
13256     markUnaddressableCandidatesUnviable(*this, CandidateSet);
13257 
13258   OverloadCandidateSet::iterator Best;
13259   OverloadingResult OverloadResult =
13260       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
13261 
13262   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
13263                                   ExecConfig, &CandidateSet, &Best,
13264                                   OverloadResult, AllowTypoCorrection);
13265 }
13266 
13267 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
13268   return Functions.size() > 1 ||
13269          (Functions.size() == 1 &&
13270           isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl()));
13271 }
13272 
13273 ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
13274                                             NestedNameSpecifierLoc NNSLoc,
13275                                             DeclarationNameInfo DNI,
13276                                             const UnresolvedSetImpl &Fns,
13277                                             bool PerformADL) {
13278   return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI,
13279                                       PerformADL, IsOverloaded(Fns),
13280                                       Fns.begin(), Fns.end());
13281 }
13282 
13283 /// Create a unary operation that may resolve to an overloaded
13284 /// operator.
13285 ///
13286 /// \param OpLoc The location of the operator itself (e.g., '*').
13287 ///
13288 /// \param Opc The UnaryOperatorKind that describes this operator.
13289 ///
13290 /// \param Fns The set of non-member functions that will be
13291 /// considered by overload resolution. The caller needs to build this
13292 /// set based on the context using, e.g.,
13293 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13294 /// set should not contain any member functions; those will be added
13295 /// by CreateOverloadedUnaryOp().
13296 ///
13297 /// \param Input The input argument.
13298 ExprResult
13299 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
13300                               const UnresolvedSetImpl &Fns,
13301                               Expr *Input, bool PerformADL) {
13302   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
13303   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
13304   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13305   // TODO: provide better source location info.
13306   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13307 
13308   if (checkPlaceholderForOverload(*this, Input))
13309     return ExprError();
13310 
13311   Expr *Args[2] = { Input, nullptr };
13312   unsigned NumArgs = 1;
13313 
13314   // For post-increment and post-decrement, add the implicit '0' as
13315   // the second argument, so that we know this is a post-increment or
13316   // post-decrement.
13317   if (Opc == UO_PostInc || Opc == UO_PostDec) {
13318     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13319     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
13320                                      SourceLocation());
13321     NumArgs = 2;
13322   }
13323 
13324   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
13325 
13326   if (Input->isTypeDependent()) {
13327     if (Fns.empty())
13328       return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy,
13329                                    VK_PRValue, OK_Ordinary, OpLoc, false,
13330                                    CurFPFeatureOverrides());
13331 
13332     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13333     ExprResult Fn = CreateUnresolvedLookupExpr(
13334         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
13335     if (Fn.isInvalid())
13336       return ExprError();
13337     return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
13338                                        Context.DependentTy, VK_PRValue, OpLoc,
13339                                        CurFPFeatureOverrides());
13340   }
13341 
13342   // Build an empty overload set.
13343   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
13344 
13345   // Add the candidates from the given function set.
13346   AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
13347 
13348   // Add operator candidates that are member functions.
13349   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13350 
13351   // Add candidates from ADL.
13352   if (PerformADL) {
13353     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
13354                                          /*ExplicitTemplateArgs*/nullptr,
13355                                          CandidateSet);
13356   }
13357 
13358   // Add builtin operator candidates.
13359   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13360 
13361   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13362 
13363   // Perform overload resolution.
13364   OverloadCandidateSet::iterator Best;
13365   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13366   case OR_Success: {
13367     // We found a built-in operator or an overloaded operator.
13368     FunctionDecl *FnDecl = Best->Function;
13369 
13370     if (FnDecl) {
13371       Expr *Base = nullptr;
13372       // We matched an overloaded operator. Build a call to that
13373       // operator.
13374 
13375       // Convert the arguments.
13376       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13377         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
13378 
13379         ExprResult InputRes =
13380           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
13381                                               Best->FoundDecl, Method);
13382         if (InputRes.isInvalid())
13383           return ExprError();
13384         Base = Input = InputRes.get();
13385       } else {
13386         // Convert the arguments.
13387         ExprResult InputInit
13388           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13389                                                       Context,
13390                                                       FnDecl->getParamDecl(0)),
13391                                       SourceLocation(),
13392                                       Input);
13393         if (InputInit.isInvalid())
13394           return ExprError();
13395         Input = InputInit.get();
13396       }
13397 
13398       // Build the actual expression node.
13399       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
13400                                                 Base, HadMultipleCandidates,
13401                                                 OpLoc);
13402       if (FnExpr.isInvalid())
13403         return ExprError();
13404 
13405       // Determine the result type.
13406       QualType ResultTy = FnDecl->getReturnType();
13407       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13408       ResultTy = ResultTy.getNonLValueExprType(Context);
13409 
13410       Args[0] = Input;
13411       CallExpr *TheCall = CXXOperatorCallExpr::Create(
13412           Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
13413           CurFPFeatureOverrides(), Best->IsADLCandidate);
13414 
13415       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
13416         return ExprError();
13417 
13418       if (CheckFunctionCall(FnDecl, TheCall,
13419                             FnDecl->getType()->castAs<FunctionProtoType>()))
13420         return ExprError();
13421       return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
13422     } else {
13423       // We matched a built-in operator. Convert the arguments, then
13424       // break out so that we will build the appropriate built-in
13425       // operator node.
13426       ExprResult InputRes = PerformImplicitConversion(
13427           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
13428           CCK_ForBuiltinOverloadedOp);
13429       if (InputRes.isInvalid())
13430         return ExprError();
13431       Input = InputRes.get();
13432       break;
13433     }
13434   }
13435 
13436   case OR_No_Viable_Function:
13437     // This is an erroneous use of an operator which can be overloaded by
13438     // a non-member function. Check for non-member operators which were
13439     // defined too late to be candidates.
13440     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
13441       // FIXME: Recover by calling the found function.
13442       return ExprError();
13443 
13444     // No viable function; fall through to handling this as a
13445     // built-in operator, which will produce an error message for us.
13446     break;
13447 
13448   case OR_Ambiguous:
13449     CandidateSet.NoteCandidates(
13450         PartialDiagnosticAt(OpLoc,
13451                             PDiag(diag::err_ovl_ambiguous_oper_unary)
13452                                 << UnaryOperator::getOpcodeStr(Opc)
13453                                 << Input->getType() << Input->getSourceRange()),
13454         *this, OCD_AmbiguousCandidates, ArgsArray,
13455         UnaryOperator::getOpcodeStr(Opc), OpLoc);
13456     return ExprError();
13457 
13458   case OR_Deleted:
13459     CandidateSet.NoteCandidates(
13460         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
13461                                        << UnaryOperator::getOpcodeStr(Opc)
13462                                        << Input->getSourceRange()),
13463         *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
13464         OpLoc);
13465     return ExprError();
13466   }
13467 
13468   // Either we found no viable overloaded operator or we matched a
13469   // built-in operator. In either case, fall through to trying to
13470   // build a built-in operation.
13471   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13472 }
13473 
13474 /// Perform lookup for an overloaded binary operator.
13475 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
13476                                  OverloadedOperatorKind Op,
13477                                  const UnresolvedSetImpl &Fns,
13478                                  ArrayRef<Expr *> Args, bool PerformADL) {
13479   SourceLocation OpLoc = CandidateSet.getLocation();
13480 
13481   OverloadedOperatorKind ExtraOp =
13482       CandidateSet.getRewriteInfo().AllowRewrittenCandidates
13483           ? getRewrittenOverloadedOperator(Op)
13484           : OO_None;
13485 
13486   // Add the candidates from the given function set. This also adds the
13487   // rewritten candidates using these functions if necessary.
13488   AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
13489 
13490   // Add operator candidates that are member functions.
13491   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13492   if (CandidateSet.getRewriteInfo().shouldAddReversed(Op))
13493     AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
13494                                 OverloadCandidateParamOrder::Reversed);
13495 
13496   // In C++20, also add any rewritten member candidates.
13497   if (ExtraOp) {
13498     AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
13499     if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp))
13500       AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
13501                                   CandidateSet,
13502                                   OverloadCandidateParamOrder::Reversed);
13503   }
13504 
13505   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
13506   // performed for an assignment operator (nor for operator[] nor operator->,
13507   // which don't get here).
13508   if (Op != OO_Equal && PerformADL) {
13509     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13510     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
13511                                          /*ExplicitTemplateArgs*/ nullptr,
13512                                          CandidateSet);
13513     if (ExtraOp) {
13514       DeclarationName ExtraOpName =
13515           Context.DeclarationNames.getCXXOperatorName(ExtraOp);
13516       AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
13517                                            /*ExplicitTemplateArgs*/ nullptr,
13518                                            CandidateSet);
13519     }
13520   }
13521 
13522   // Add builtin operator candidates.
13523   //
13524   // FIXME: We don't add any rewritten candidates here. This is strictly
13525   // incorrect; a builtin candidate could be hidden by a non-viable candidate,
13526   // resulting in our selecting a rewritten builtin candidate. For example:
13527   //
13528   //   enum class E { e };
13529   //   bool operator!=(E, E) requires false;
13530   //   bool k = E::e != E::e;
13531   //
13532   // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
13533   // it seems unreasonable to consider rewritten builtin candidates. A core
13534   // issue has been filed proposing to removed this requirement.
13535   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13536 }
13537 
13538 /// Create a binary operation that may resolve to an overloaded
13539 /// operator.
13540 ///
13541 /// \param OpLoc The location of the operator itself (e.g., '+').
13542 ///
13543 /// \param Opc The BinaryOperatorKind that describes this operator.
13544 ///
13545 /// \param Fns The set of non-member functions that will be
13546 /// considered by overload resolution. The caller needs to build this
13547 /// set based on the context using, e.g.,
13548 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13549 /// set should not contain any member functions; those will be added
13550 /// by CreateOverloadedBinOp().
13551 ///
13552 /// \param LHS Left-hand argument.
13553 /// \param RHS Right-hand argument.
13554 /// \param PerformADL Whether to consider operator candidates found by ADL.
13555 /// \param AllowRewrittenCandidates Whether to consider candidates found by
13556 ///        C++20 operator rewrites.
13557 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
13558 ///        the function in question. Such a function is never a candidate in
13559 ///        our overload resolution. This also enables synthesizing a three-way
13560 ///        comparison from < and == as described in C++20 [class.spaceship]p1.
13561 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
13562                                        BinaryOperatorKind Opc,
13563                                        const UnresolvedSetImpl &Fns, Expr *LHS,
13564                                        Expr *RHS, bool PerformADL,
13565                                        bool AllowRewrittenCandidates,
13566                                        FunctionDecl *DefaultedFn) {
13567   Expr *Args[2] = { LHS, RHS };
13568   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
13569 
13570   if (!getLangOpts().CPlusPlus20)
13571     AllowRewrittenCandidates = false;
13572 
13573   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
13574 
13575   // If either side is type-dependent, create an appropriate dependent
13576   // expression.
13577   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13578     if (Fns.empty()) {
13579       // If there are no functions to store, just build a dependent
13580       // BinaryOperator or CompoundAssignment.
13581       if (BinaryOperator::isCompoundAssignmentOp(Opc))
13582         return CompoundAssignOperator::Create(
13583             Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
13584             OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
13585             Context.DependentTy);
13586       return BinaryOperator::Create(
13587           Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
13588           OK_Ordinary, OpLoc, CurFPFeatureOverrides());
13589     }
13590 
13591     // FIXME: save results of ADL from here?
13592     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13593     // TODO: provide better source location info in DNLoc component.
13594     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13595     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13596     ExprResult Fn = CreateUnresolvedLookupExpr(
13597         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
13598     if (Fn.isInvalid())
13599       return ExprError();
13600     return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
13601                                        Context.DependentTy, VK_PRValue, OpLoc,
13602                                        CurFPFeatureOverrides());
13603   }
13604 
13605   // Always do placeholder-like conversions on the RHS.
13606   if (checkPlaceholderForOverload(*this, Args[1]))
13607     return ExprError();
13608 
13609   // Do placeholder-like conversion on the LHS; note that we should
13610   // not get here with a PseudoObject LHS.
13611   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
13612   if (checkPlaceholderForOverload(*this, Args[0]))
13613     return ExprError();
13614 
13615   // If this is the assignment operator, we only perform overload resolution
13616   // if the left-hand side is a class or enumeration type. This is actually
13617   // a hack. The standard requires that we do overload resolution between the
13618   // various built-in candidates, but as DR507 points out, this can lead to
13619   // problems. So we do it this way, which pretty much follows what GCC does.
13620   // Note that we go the traditional code path for compound assignment forms.
13621   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
13622     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13623 
13624   // If this is the .* operator, which is not overloadable, just
13625   // create a built-in binary operator.
13626   if (Opc == BO_PtrMemD)
13627     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13628 
13629   // Build the overload set.
13630   OverloadCandidateSet CandidateSet(
13631       OpLoc, OverloadCandidateSet::CSK_Operator,
13632       OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates));
13633   if (DefaultedFn)
13634     CandidateSet.exclude(DefaultedFn);
13635   LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
13636 
13637   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13638 
13639   // Perform overload resolution.
13640   OverloadCandidateSet::iterator Best;
13641   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13642     case OR_Success: {
13643       // We found a built-in operator or an overloaded operator.
13644       FunctionDecl *FnDecl = Best->Function;
13645 
13646       bool IsReversed = Best->isReversed();
13647       if (IsReversed)
13648         std::swap(Args[0], Args[1]);
13649 
13650       if (FnDecl) {
13651         Expr *Base = nullptr;
13652         // We matched an overloaded operator. Build a call to that
13653         // operator.
13654 
13655         OverloadedOperatorKind ChosenOp =
13656             FnDecl->getDeclName().getCXXOverloadedOperator();
13657 
13658         // C++2a [over.match.oper]p9:
13659         //   If a rewritten operator== candidate is selected by overload
13660         //   resolution for an operator@, its return type shall be cv bool
13661         if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
13662             !FnDecl->getReturnType()->isBooleanType()) {
13663           bool IsExtension =
13664               FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
13665           Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
13666                                   : diag::err_ovl_rewrite_equalequal_not_bool)
13667               << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
13668               << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13669           Diag(FnDecl->getLocation(), diag::note_declared_at);
13670           if (!IsExtension)
13671             return ExprError();
13672         }
13673 
13674         if (AllowRewrittenCandidates && !IsReversed &&
13675             CandidateSet.getRewriteInfo().isReversible()) {
13676           // We could have reversed this operator, but didn't. Check if some
13677           // reversed form was a viable candidate, and if so, if it had a
13678           // better conversion for either parameter. If so, this call is
13679           // formally ambiguous, and allowing it is an extension.
13680           llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
13681           for (OverloadCandidate &Cand : CandidateSet) {
13682             if (Cand.Viable && Cand.Function && Cand.isReversed() &&
13683                 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) {
13684               for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
13685                 if (CompareImplicitConversionSequences(
13686                         *this, OpLoc, Cand.Conversions[ArgIdx],
13687                         Best->Conversions[ArgIdx]) ==
13688                     ImplicitConversionSequence::Better) {
13689                   AmbiguousWith.push_back(Cand.Function);
13690                   break;
13691                 }
13692               }
13693             }
13694           }
13695 
13696           if (!AmbiguousWith.empty()) {
13697             bool AmbiguousWithSelf =
13698                 AmbiguousWith.size() == 1 &&
13699                 declaresSameEntity(AmbiguousWith.front(), FnDecl);
13700             Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
13701                 << BinaryOperator::getOpcodeStr(Opc)
13702                 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
13703                 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13704             if (AmbiguousWithSelf) {
13705               Diag(FnDecl->getLocation(),
13706                    diag::note_ovl_ambiguous_oper_binary_reversed_self);
13707             } else {
13708               Diag(FnDecl->getLocation(),
13709                    diag::note_ovl_ambiguous_oper_binary_selected_candidate);
13710               for (auto *F : AmbiguousWith)
13711                 Diag(F->getLocation(),
13712                      diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
13713             }
13714           }
13715         }
13716 
13717         // Convert the arguments.
13718         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13719           // Best->Access is only meaningful for class members.
13720           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
13721 
13722           ExprResult Arg1 =
13723             PerformCopyInitialization(
13724               InitializedEntity::InitializeParameter(Context,
13725                                                      FnDecl->getParamDecl(0)),
13726               SourceLocation(), Args[1]);
13727           if (Arg1.isInvalid())
13728             return ExprError();
13729 
13730           ExprResult Arg0 =
13731             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13732                                                 Best->FoundDecl, Method);
13733           if (Arg0.isInvalid())
13734             return ExprError();
13735           Base = Args[0] = Arg0.getAs<Expr>();
13736           Args[1] = RHS = Arg1.getAs<Expr>();
13737         } else {
13738           // Convert the arguments.
13739           ExprResult Arg0 = PerformCopyInitialization(
13740             InitializedEntity::InitializeParameter(Context,
13741                                                    FnDecl->getParamDecl(0)),
13742             SourceLocation(), Args[0]);
13743           if (Arg0.isInvalid())
13744             return ExprError();
13745 
13746           ExprResult Arg1 =
13747             PerformCopyInitialization(
13748               InitializedEntity::InitializeParameter(Context,
13749                                                      FnDecl->getParamDecl(1)),
13750               SourceLocation(), Args[1]);
13751           if (Arg1.isInvalid())
13752             return ExprError();
13753           Args[0] = LHS = Arg0.getAs<Expr>();
13754           Args[1] = RHS = Arg1.getAs<Expr>();
13755         }
13756 
13757         // Build the actual expression node.
13758         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13759                                                   Best->FoundDecl, Base,
13760                                                   HadMultipleCandidates, OpLoc);
13761         if (FnExpr.isInvalid())
13762           return ExprError();
13763 
13764         // Determine the result type.
13765         QualType ResultTy = FnDecl->getReturnType();
13766         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13767         ResultTy = ResultTy.getNonLValueExprType(Context);
13768 
13769         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13770             Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
13771             CurFPFeatureOverrides(), Best->IsADLCandidate);
13772 
13773         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
13774                                 FnDecl))
13775           return ExprError();
13776 
13777         ArrayRef<const Expr *> ArgsArray(Args, 2);
13778         const Expr *ImplicitThis = nullptr;
13779         // Cut off the implicit 'this'.
13780         if (isa<CXXMethodDecl>(FnDecl)) {
13781           ImplicitThis = ArgsArray[0];
13782           ArgsArray = ArgsArray.slice(1);
13783         }
13784 
13785         // Check for a self move.
13786         if (Op == OO_Equal)
13787           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
13788 
13789         if (ImplicitThis) {
13790           QualType ThisType = Context.getPointerType(ImplicitThis->getType());
13791           QualType ThisTypeFromDecl = Context.getPointerType(
13792               cast<CXXMethodDecl>(FnDecl)->getThisObjectType());
13793 
13794           CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
13795                             ThisTypeFromDecl);
13796         }
13797 
13798         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
13799                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
13800                   VariadicDoesNotApply);
13801 
13802         ExprResult R = MaybeBindToTemporary(TheCall);
13803         if (R.isInvalid())
13804           return ExprError();
13805 
13806         R = CheckForImmediateInvocation(R, FnDecl);
13807         if (R.isInvalid())
13808           return ExprError();
13809 
13810         // For a rewritten candidate, we've already reversed the arguments
13811         // if needed. Perform the rest of the rewrite now.
13812         if ((Best->RewriteKind & CRK_DifferentOperator) ||
13813             (Op == OO_Spaceship && IsReversed)) {
13814           if (Op == OO_ExclaimEqual) {
13815             assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
13816             R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
13817           } else {
13818             assert(ChosenOp == OO_Spaceship && "unexpected operator name");
13819             llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13820             Expr *ZeroLiteral =
13821                 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
13822 
13823             Sema::CodeSynthesisContext Ctx;
13824             Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
13825             Ctx.Entity = FnDecl;
13826             pushCodeSynthesisContext(Ctx);
13827 
13828             R = CreateOverloadedBinOp(
13829                 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
13830                 IsReversed ? R.get() : ZeroLiteral, PerformADL,
13831                 /*AllowRewrittenCandidates=*/false);
13832 
13833             popCodeSynthesisContext();
13834           }
13835           if (R.isInvalid())
13836             return ExprError();
13837         } else {
13838           assert(ChosenOp == Op && "unexpected operator name");
13839         }
13840 
13841         // Make a note in the AST if we did any rewriting.
13842         if (Best->RewriteKind != CRK_None)
13843           R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
13844 
13845         return R;
13846       } else {
13847         // We matched a built-in operator. Convert the arguments, then
13848         // break out so that we will build the appropriate built-in
13849         // operator node.
13850         ExprResult ArgsRes0 = PerformImplicitConversion(
13851             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13852             AA_Passing, CCK_ForBuiltinOverloadedOp);
13853         if (ArgsRes0.isInvalid())
13854           return ExprError();
13855         Args[0] = ArgsRes0.get();
13856 
13857         ExprResult ArgsRes1 = PerformImplicitConversion(
13858             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13859             AA_Passing, CCK_ForBuiltinOverloadedOp);
13860         if (ArgsRes1.isInvalid())
13861           return ExprError();
13862         Args[1] = ArgsRes1.get();
13863         break;
13864       }
13865     }
13866 
13867     case OR_No_Viable_Function: {
13868       // C++ [over.match.oper]p9:
13869       //   If the operator is the operator , [...] and there are no
13870       //   viable functions, then the operator is assumed to be the
13871       //   built-in operator and interpreted according to clause 5.
13872       if (Opc == BO_Comma)
13873         break;
13874 
13875       // When defaulting an 'operator<=>', we can try to synthesize a three-way
13876       // compare result using '==' and '<'.
13877       if (DefaultedFn && Opc == BO_Cmp) {
13878         ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
13879                                                           Args[1], DefaultedFn);
13880         if (E.isInvalid() || E.isUsable())
13881           return E;
13882       }
13883 
13884       // For class as left operand for assignment or compound assignment
13885       // operator do not fall through to handling in built-in, but report that
13886       // no overloaded assignment operator found
13887       ExprResult Result = ExprError();
13888       StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
13889       auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
13890                                                    Args, OpLoc);
13891       DeferDiagsRAII DDR(*this,
13892                          CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
13893       if (Args[0]->getType()->isRecordType() &&
13894           Opc >= BO_Assign && Opc <= BO_OrAssign) {
13895         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
13896              << BinaryOperator::getOpcodeStr(Opc)
13897              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13898         if (Args[0]->getType()->isIncompleteType()) {
13899           Diag(OpLoc, diag::note_assign_lhs_incomplete)
13900             << Args[0]->getType()
13901             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13902         }
13903       } else {
13904         // This is an erroneous use of an operator which can be overloaded by
13905         // a non-member function. Check for non-member operators which were
13906         // defined too late to be candidates.
13907         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
13908           // FIXME: Recover by calling the found function.
13909           return ExprError();
13910 
13911         // No viable function; try to create a built-in operation, which will
13912         // produce an error. Then, show the non-viable candidates.
13913         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13914       }
13915       assert(Result.isInvalid() &&
13916              "C++ binary operator overloading is missing candidates!");
13917       CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
13918       return Result;
13919     }
13920 
13921     case OR_Ambiguous:
13922       CandidateSet.NoteCandidates(
13923           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13924                                          << BinaryOperator::getOpcodeStr(Opc)
13925                                          << Args[0]->getType()
13926                                          << Args[1]->getType()
13927                                          << Args[0]->getSourceRange()
13928                                          << Args[1]->getSourceRange()),
13929           *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13930           OpLoc);
13931       return ExprError();
13932 
13933     case OR_Deleted:
13934       if (isImplicitlyDeleted(Best->Function)) {
13935         FunctionDecl *DeletedFD = Best->Function;
13936         DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
13937         if (DFK.isSpecialMember()) {
13938           Diag(OpLoc, diag::err_ovl_deleted_special_oper)
13939             << Args[0]->getType() << DFK.asSpecialMember();
13940         } else {
13941           assert(DFK.isComparison());
13942           Diag(OpLoc, diag::err_ovl_deleted_comparison)
13943             << Args[0]->getType() << DeletedFD;
13944         }
13945 
13946         // The user probably meant to call this special member. Just
13947         // explain why it's deleted.
13948         NoteDeletedFunction(DeletedFD);
13949         return ExprError();
13950       }
13951       CandidateSet.NoteCandidates(
13952           PartialDiagnosticAt(
13953               OpLoc, PDiag(diag::err_ovl_deleted_oper)
13954                          << getOperatorSpelling(Best->Function->getDeclName()
13955                                                     .getCXXOverloadedOperator())
13956                          << Args[0]->getSourceRange()
13957                          << Args[1]->getSourceRange()),
13958           *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13959           OpLoc);
13960       return ExprError();
13961   }
13962 
13963   // We matched a built-in operator; build it.
13964   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13965 }
13966 
13967 ExprResult Sema::BuildSynthesizedThreeWayComparison(
13968     SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
13969     FunctionDecl *DefaultedFn) {
13970   const ComparisonCategoryInfo *Info =
13971       Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
13972   // If we're not producing a known comparison category type, we can't
13973   // synthesize a three-way comparison. Let the caller diagnose this.
13974   if (!Info)
13975     return ExprResult((Expr*)nullptr);
13976 
13977   // If we ever want to perform this synthesis more generally, we will need to
13978   // apply the temporary materialization conversion to the operands.
13979   assert(LHS->isGLValue() && RHS->isGLValue() &&
13980          "cannot use prvalue expressions more than once");
13981   Expr *OrigLHS = LHS;
13982   Expr *OrigRHS = RHS;
13983 
13984   // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
13985   // each of them multiple times below.
13986   LHS = new (Context)
13987       OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
13988                       LHS->getObjectKind(), LHS);
13989   RHS = new (Context)
13990       OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
13991                       RHS->getObjectKind(), RHS);
13992 
13993   ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
13994                                         DefaultedFn);
13995   if (Eq.isInvalid())
13996     return ExprError();
13997 
13998   ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
13999                                           true, DefaultedFn);
14000   if (Less.isInvalid())
14001     return ExprError();
14002 
14003   ExprResult Greater;
14004   if (Info->isPartial()) {
14005     Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
14006                                     DefaultedFn);
14007     if (Greater.isInvalid())
14008       return ExprError();
14009   }
14010 
14011   // Form the list of comparisons we're going to perform.
14012   struct Comparison {
14013     ExprResult Cmp;
14014     ComparisonCategoryResult Result;
14015   } Comparisons[4] =
14016   { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
14017                           : ComparisonCategoryResult::Equivalent},
14018     {Less, ComparisonCategoryResult::Less},
14019     {Greater, ComparisonCategoryResult::Greater},
14020     {ExprResult(), ComparisonCategoryResult::Unordered},
14021   };
14022 
14023   int I = Info->isPartial() ? 3 : 2;
14024 
14025   // Combine the comparisons with suitable conditional expressions.
14026   ExprResult Result;
14027   for (; I >= 0; --I) {
14028     // Build a reference to the comparison category constant.
14029     auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
14030     // FIXME: Missing a constant for a comparison category. Diagnose this?
14031     if (!VI)
14032       return ExprResult((Expr*)nullptr);
14033     ExprResult ThisResult =
14034         BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
14035     if (ThisResult.isInvalid())
14036       return ExprError();
14037 
14038     // Build a conditional unless this is the final case.
14039     if (Result.get()) {
14040       Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
14041                                   ThisResult.get(), Result.get());
14042       if (Result.isInvalid())
14043         return ExprError();
14044     } else {
14045       Result = ThisResult;
14046     }
14047   }
14048 
14049   // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
14050   // bind the OpaqueValueExprs before they're (repeatedly) used.
14051   Expr *SyntacticForm = BinaryOperator::Create(
14052       Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
14053       Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
14054       CurFPFeatureOverrides());
14055   Expr *SemanticForm[] = {LHS, RHS, Result.get()};
14056   return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
14057 }
14058 
14059 static bool PrepareArgumentsForCallToObjectOfClassType(
14060     Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
14061     MultiExprArg Args, SourceLocation LParenLoc) {
14062 
14063   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14064   unsigned NumParams = Proto->getNumParams();
14065   unsigned NumArgsSlots =
14066       MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
14067   // Build the full argument list for the method call (the implicit object
14068   // parameter is placed at the beginning of the list).
14069   MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
14070   bool IsError = false;
14071   // Initialize the implicit object parameter.
14072   // Check the argument types.
14073   for (unsigned i = 0; i != NumParams; i++) {
14074     Expr *Arg;
14075     if (i < Args.size()) {
14076       Arg = Args[i];
14077       ExprResult InputInit =
14078           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
14079                                           S.Context, Method->getParamDecl(i)),
14080                                       SourceLocation(), Arg);
14081       IsError |= InputInit.isInvalid();
14082       Arg = InputInit.getAs<Expr>();
14083     } else {
14084       ExprResult DefArg =
14085           S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14086       if (DefArg.isInvalid()) {
14087         IsError = true;
14088         break;
14089       }
14090       Arg = DefArg.getAs<Expr>();
14091     }
14092 
14093     MethodArgs.push_back(Arg);
14094   }
14095   return IsError;
14096 }
14097 
14098 ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
14099                                                     SourceLocation RLoc,
14100                                                     Expr *Base,
14101                                                     MultiExprArg ArgExpr) {
14102   SmallVector<Expr *, 2> Args;
14103   Args.push_back(Base);
14104   for (auto e : ArgExpr) {
14105     Args.push_back(e);
14106   }
14107   DeclarationName OpName =
14108       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
14109 
14110   SourceRange Range = ArgExpr.empty()
14111                           ? SourceRange{}
14112                           : SourceRange(ArgExpr.front()->getBeginLoc(),
14113                                         ArgExpr.back()->getEndLoc());
14114 
14115   // If either side is type-dependent, create an appropriate dependent
14116   // expression.
14117   if (Expr::hasAnyTypeDependentArguments(Args)) {
14118 
14119     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14120     // CHECKME: no 'operator' keyword?
14121     DeclarationNameInfo OpNameInfo(OpName, LLoc);
14122     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
14123     ExprResult Fn = CreateUnresolvedLookupExpr(
14124         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
14125     if (Fn.isInvalid())
14126       return ExprError();
14127     // Can't add any actual overloads yet
14128 
14129     return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
14130                                        Context.DependentTy, VK_PRValue, RLoc,
14131                                        CurFPFeatureOverrides());
14132   }
14133 
14134   // Handle placeholders
14135   UnbridgedCastsSet UnbridgedCasts;
14136   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14137     return ExprError();
14138   }
14139   // Build an empty overload set.
14140   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
14141 
14142   // Subscript can only be overloaded as a member function.
14143 
14144   // Add operator candidates that are member functions.
14145   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
14146 
14147   // Add builtin operator candidates.
14148   if (Args.size() == 2)
14149     AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
14150 
14151   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14152 
14153   // Perform overload resolution.
14154   OverloadCandidateSet::iterator Best;
14155   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
14156     case OR_Success: {
14157       // We found a built-in operator or an overloaded operator.
14158       FunctionDecl *FnDecl = Best->Function;
14159 
14160       if (FnDecl) {
14161         // We matched an overloaded operator. Build a call to that
14162         // operator.
14163 
14164         CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
14165 
14166         // Convert the arguments.
14167         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
14168         SmallVector<Expr *, 2> MethodArgs;
14169         ExprResult Arg0 = PerformObjectArgumentInitialization(
14170             Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14171         if (Arg0.isInvalid())
14172           return ExprError();
14173 
14174         MethodArgs.push_back(Arg0.get());
14175         bool IsError = PrepareArgumentsForCallToObjectOfClassType(
14176             *this, MethodArgs, Method, ArgExpr, LLoc);
14177         if (IsError)
14178           return ExprError();
14179 
14180         // Build the actual expression node.
14181         DeclarationNameInfo OpLocInfo(OpName, LLoc);
14182         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
14183         ExprResult FnExpr = CreateFunctionRefExpr(
14184             *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
14185             OpLocInfo.getLoc(), OpLocInfo.getInfo());
14186         if (FnExpr.isInvalid())
14187           return ExprError();
14188 
14189         // Determine the result type
14190         QualType ResultTy = FnDecl->getReturnType();
14191         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14192         ResultTy = ResultTy.getNonLValueExprType(Context);
14193 
14194         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14195             Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
14196             CurFPFeatureOverrides());
14197         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
14198           return ExprError();
14199 
14200         if (CheckFunctionCall(Method, TheCall,
14201                               Method->getType()->castAs<FunctionProtoType>()))
14202           return ExprError();
14203 
14204         return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14205                                            FnDecl);
14206       } else {
14207         // We matched a built-in operator. Convert the arguments, then
14208         // break out so that we will build the appropriate built-in
14209         // operator node.
14210         ExprResult ArgsRes0 = PerformImplicitConversion(
14211             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
14212             AA_Passing, CCK_ForBuiltinOverloadedOp);
14213         if (ArgsRes0.isInvalid())
14214           return ExprError();
14215         Args[0] = ArgsRes0.get();
14216 
14217         ExprResult ArgsRes1 = PerformImplicitConversion(
14218             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
14219             AA_Passing, CCK_ForBuiltinOverloadedOp);
14220         if (ArgsRes1.isInvalid())
14221           return ExprError();
14222         Args[1] = ArgsRes1.get();
14223 
14224         break;
14225       }
14226     }
14227 
14228     case OR_No_Viable_Function: {
14229       PartialDiagnostic PD =
14230           CandidateSet.empty()
14231               ? (PDiag(diag::err_ovl_no_oper)
14232                  << Args[0]->getType() << /*subscript*/ 0
14233                  << Args[0]->getSourceRange() << Range)
14234               : (PDiag(diag::err_ovl_no_viable_subscript)
14235                  << Args[0]->getType() << Args[0]->getSourceRange() << Range);
14236       CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
14237                                   OCD_AllCandidates, ArgExpr, "[]", LLoc);
14238       return ExprError();
14239     }
14240 
14241     case OR_Ambiguous:
14242       if (Args.size() == 2) {
14243         CandidateSet.NoteCandidates(
14244             PartialDiagnosticAt(
14245                 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
14246                           << "[]" << Args[0]->getType() << Args[1]->getType()
14247                           << Args[0]->getSourceRange() << Range),
14248             *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
14249       } else {
14250         CandidateSet.NoteCandidates(
14251             PartialDiagnosticAt(LLoc,
14252                                 PDiag(diag::err_ovl_ambiguous_subscript_call)
14253                                     << Args[0]->getType()
14254                                     << Args[0]->getSourceRange() << Range),
14255             *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
14256       }
14257       return ExprError();
14258 
14259     case OR_Deleted:
14260       CandidateSet.NoteCandidates(
14261           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
14262                                         << "[]" << Args[0]->getSourceRange()
14263                                         << Range),
14264           *this, OCD_AllCandidates, Args, "[]", LLoc);
14265       return ExprError();
14266     }
14267 
14268   // We matched a built-in operator; build it.
14269   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
14270 }
14271 
14272 /// BuildCallToMemberFunction - Build a call to a member
14273 /// function. MemExpr is the expression that refers to the member
14274 /// function (and includes the object parameter), Args/NumArgs are the
14275 /// arguments to the function call (not including the object
14276 /// parameter). The caller needs to validate that the member
14277 /// expression refers to a non-static member function or an overloaded
14278 /// member function.
14279 ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
14280                                            SourceLocation LParenLoc,
14281                                            MultiExprArg Args,
14282                                            SourceLocation RParenLoc,
14283                                            Expr *ExecConfig, bool IsExecConfig,
14284                                            bool AllowRecovery) {
14285   assert(MemExprE->getType() == Context.BoundMemberTy ||
14286          MemExprE->getType() == Context.OverloadTy);
14287 
14288   // Dig out the member expression. This holds both the object
14289   // argument and the member function we're referring to.
14290   Expr *NakedMemExpr = MemExprE->IgnoreParens();
14291 
14292   // Determine whether this is a call to a pointer-to-member function.
14293   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
14294     assert(op->getType() == Context.BoundMemberTy);
14295     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
14296 
14297     QualType fnType =
14298       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
14299 
14300     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
14301     QualType resultType = proto->getCallResultType(Context);
14302     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
14303 
14304     // Check that the object type isn't more qualified than the
14305     // member function we're calling.
14306     Qualifiers funcQuals = proto->getMethodQuals();
14307 
14308     QualType objectType = op->getLHS()->getType();
14309     if (op->getOpcode() == BO_PtrMemI)
14310       objectType = objectType->castAs<PointerType>()->getPointeeType();
14311     Qualifiers objectQuals = objectType.getQualifiers();
14312 
14313     Qualifiers difference = objectQuals - funcQuals;
14314     difference.removeObjCGCAttr();
14315     difference.removeAddressSpace();
14316     if (difference) {
14317       std::string qualsString = difference.getAsString();
14318       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
14319         << fnType.getUnqualifiedType()
14320         << qualsString
14321         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
14322     }
14323 
14324     CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
14325         Context, MemExprE, Args, resultType, valueKind, RParenLoc,
14326         CurFPFeatureOverrides(), proto->getNumParams());
14327 
14328     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
14329                             call, nullptr))
14330       return ExprError();
14331 
14332     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
14333       return ExprError();
14334 
14335     if (CheckOtherCall(call, proto))
14336       return ExprError();
14337 
14338     return MaybeBindToTemporary(call);
14339   }
14340 
14341   // We only try to build a recovery expr at this level if we can preserve
14342   // the return type, otherwise we return ExprError() and let the caller
14343   // recover.
14344   auto BuildRecoveryExpr = [&](QualType Type) {
14345     if (!AllowRecovery)
14346       return ExprError();
14347     std::vector<Expr *> SubExprs = {MemExprE};
14348     llvm::for_each(Args, [&SubExprs](Expr *E) { SubExprs.push_back(E); });
14349     return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
14350                               Type);
14351   };
14352   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
14353     return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
14354                             RParenLoc, CurFPFeatureOverrides());
14355 
14356   UnbridgedCastsSet UnbridgedCasts;
14357   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14358     return ExprError();
14359 
14360   MemberExpr *MemExpr;
14361   CXXMethodDecl *Method = nullptr;
14362   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
14363   NestedNameSpecifier *Qualifier = nullptr;
14364   if (isa<MemberExpr>(NakedMemExpr)) {
14365     MemExpr = cast<MemberExpr>(NakedMemExpr);
14366     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
14367     FoundDecl = MemExpr->getFoundDecl();
14368     Qualifier = MemExpr->getQualifier();
14369     UnbridgedCasts.restore();
14370   } else {
14371     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
14372     Qualifier = UnresExpr->getQualifier();
14373 
14374     QualType ObjectType = UnresExpr->getBaseType();
14375     Expr::Classification ObjectClassification
14376       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
14377                             : UnresExpr->getBase()->Classify(Context);
14378 
14379     // Add overload candidates
14380     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
14381                                       OverloadCandidateSet::CSK_Normal);
14382 
14383     // FIXME: avoid copy.
14384     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14385     if (UnresExpr->hasExplicitTemplateArgs()) {
14386       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14387       TemplateArgs = &TemplateArgsBuffer;
14388     }
14389 
14390     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
14391            E = UnresExpr->decls_end(); I != E; ++I) {
14392 
14393       NamedDecl *Func = *I;
14394       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
14395       if (isa<UsingShadowDecl>(Func))
14396         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
14397 
14398 
14399       // Microsoft supports direct constructor calls.
14400       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
14401         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
14402                              CandidateSet,
14403                              /*SuppressUserConversions*/ false);
14404       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
14405         // If explicit template arguments were provided, we can't call a
14406         // non-template member function.
14407         if (TemplateArgs)
14408           continue;
14409 
14410         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
14411                            ObjectClassification, Args, CandidateSet,
14412                            /*SuppressUserConversions=*/false);
14413       } else {
14414         AddMethodTemplateCandidate(
14415             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
14416             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
14417             /*SuppressUserConversions=*/false);
14418       }
14419     }
14420 
14421     DeclarationName DeclName = UnresExpr->getMemberName();
14422 
14423     UnbridgedCasts.restore();
14424 
14425     OverloadCandidateSet::iterator Best;
14426     bool Succeeded = false;
14427     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
14428                                             Best)) {
14429     case OR_Success:
14430       Method = cast<CXXMethodDecl>(Best->Function);
14431       FoundDecl = Best->FoundDecl;
14432       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
14433       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
14434         break;
14435       // If FoundDecl is different from Method (such as if one is a template
14436       // and the other a specialization), make sure DiagnoseUseOfDecl is
14437       // called on both.
14438       // FIXME: This would be more comprehensively addressed by modifying
14439       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
14440       // being used.
14441       if (Method != FoundDecl.getDecl() &&
14442                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
14443         break;
14444       Succeeded = true;
14445       break;
14446 
14447     case OR_No_Viable_Function:
14448       CandidateSet.NoteCandidates(
14449           PartialDiagnosticAt(
14450               UnresExpr->getMemberLoc(),
14451               PDiag(diag::err_ovl_no_viable_member_function_in_call)
14452                   << DeclName << MemExprE->getSourceRange()),
14453           *this, OCD_AllCandidates, Args);
14454       break;
14455     case OR_Ambiguous:
14456       CandidateSet.NoteCandidates(
14457           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14458                               PDiag(diag::err_ovl_ambiguous_member_call)
14459                                   << DeclName << MemExprE->getSourceRange()),
14460           *this, OCD_AmbiguousCandidates, Args);
14461       break;
14462     case OR_Deleted:
14463       CandidateSet.NoteCandidates(
14464           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14465                               PDiag(diag::err_ovl_deleted_member_call)
14466                                   << DeclName << MemExprE->getSourceRange()),
14467           *this, OCD_AllCandidates, Args);
14468       break;
14469     }
14470     // Overload resolution fails, try to recover.
14471     if (!Succeeded)
14472       return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
14473 
14474     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
14475 
14476     // If overload resolution picked a static member, build a
14477     // non-member call based on that function.
14478     if (Method->isStatic()) {
14479       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
14480                                    ExecConfig, IsExecConfig);
14481     }
14482 
14483     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
14484   }
14485 
14486   QualType ResultType = Method->getReturnType();
14487   ExprValueKind VK = Expr::getValueKindForType(ResultType);
14488   ResultType = ResultType.getNonLValueExprType(Context);
14489 
14490   assert(Method && "Member call to something that isn't a method?");
14491   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14492   CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create(
14493       Context, MemExprE, Args, ResultType, VK, RParenLoc,
14494       CurFPFeatureOverrides(), Proto->getNumParams());
14495 
14496   // Check for a valid return type.
14497   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
14498                           TheCall, Method))
14499     return BuildRecoveryExpr(ResultType);
14500 
14501   // Convert the object argument (for a non-static member function call).
14502   // We only need to do this if there was actually an overload; otherwise
14503   // it was done at lookup.
14504   if (!Method->isStatic()) {
14505     ExprResult ObjectArg =
14506       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
14507                                           FoundDecl, Method);
14508     if (ObjectArg.isInvalid())
14509       return ExprError();
14510     MemExpr->setBase(ObjectArg.get());
14511   }
14512 
14513   // Convert the rest of the arguments
14514   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
14515                               RParenLoc))
14516     return BuildRecoveryExpr(ResultType);
14517 
14518   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14519 
14520   if (CheckFunctionCall(Method, TheCall, Proto))
14521     return ExprError();
14522 
14523   // In the case the method to call was not selected by the overloading
14524   // resolution process, we still need to handle the enable_if attribute. Do
14525   // that here, so it will not hide previous -- and more relevant -- errors.
14526   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
14527     if (const EnableIfAttr *Attr =
14528             CheckEnableIf(Method, LParenLoc, Args, true)) {
14529       Diag(MemE->getMemberLoc(),
14530            diag::err_ovl_no_viable_member_function_in_call)
14531           << Method << Method->getSourceRange();
14532       Diag(Method->getLocation(),
14533            diag::note_ovl_candidate_disabled_by_function_cond_attr)
14534           << Attr->getCond()->getSourceRange() << Attr->getMessage();
14535       return ExprError();
14536     }
14537   }
14538 
14539   if ((isa<CXXConstructorDecl>(CurContext) ||
14540        isa<CXXDestructorDecl>(CurContext)) &&
14541       TheCall->getMethodDecl()->isPure()) {
14542     const CXXMethodDecl *MD = TheCall->getMethodDecl();
14543 
14544     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
14545         MemExpr->performsVirtualDispatch(getLangOpts())) {
14546       Diag(MemExpr->getBeginLoc(),
14547            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
14548           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
14549           << MD->getParent();
14550 
14551       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
14552       if (getLangOpts().AppleKext)
14553         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
14554             << MD->getParent() << MD->getDeclName();
14555     }
14556   }
14557 
14558   if (CXXDestructorDecl *DD =
14559           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
14560     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
14561     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
14562     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
14563                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
14564                          MemExpr->getMemberLoc());
14565   }
14566 
14567   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14568                                      TheCall->getMethodDecl());
14569 }
14570 
14571 /// BuildCallToObjectOfClassType - Build a call to an object of class
14572 /// type (C++ [over.call.object]), which can end up invoking an
14573 /// overloaded function call operator (@c operator()) or performing a
14574 /// user-defined conversion on the object argument.
14575 ExprResult
14576 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
14577                                    SourceLocation LParenLoc,
14578                                    MultiExprArg Args,
14579                                    SourceLocation RParenLoc) {
14580   if (checkPlaceholderForOverload(*this, Obj))
14581     return ExprError();
14582   ExprResult Object = Obj;
14583 
14584   UnbridgedCastsSet UnbridgedCasts;
14585   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14586     return ExprError();
14587 
14588   assert(Object.get()->getType()->isRecordType() &&
14589          "Requires object type argument");
14590 
14591   // C++ [over.call.object]p1:
14592   //  If the primary-expression E in the function call syntax
14593   //  evaluates to a class object of type "cv T", then the set of
14594   //  candidate functions includes at least the function call
14595   //  operators of T. The function call operators of T are obtained by
14596   //  ordinary lookup of the name operator() in the context of
14597   //  (E).operator().
14598   OverloadCandidateSet CandidateSet(LParenLoc,
14599                                     OverloadCandidateSet::CSK_Operator);
14600   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
14601 
14602   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
14603                           diag::err_incomplete_object_call, Object.get()))
14604     return true;
14605 
14606   const auto *Record = Object.get()->getType()->castAs<RecordType>();
14607   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
14608   LookupQualifiedName(R, Record->getDecl());
14609   R.suppressDiagnostics();
14610 
14611   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14612        Oper != OperEnd; ++Oper) {
14613     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
14614                        Object.get()->Classify(Context), Args, CandidateSet,
14615                        /*SuppressUserConversion=*/false);
14616   }
14617 
14618   // C++ [over.call.object]p2:
14619   //   In addition, for each (non-explicit in C++0x) conversion function
14620   //   declared in T of the form
14621   //
14622   //        operator conversion-type-id () cv-qualifier;
14623   //
14624   //   where cv-qualifier is the same cv-qualification as, or a
14625   //   greater cv-qualification than, cv, and where conversion-type-id
14626   //   denotes the type "pointer to function of (P1,...,Pn) returning
14627   //   R", or the type "reference to pointer to function of
14628   //   (P1,...,Pn) returning R", or the type "reference to function
14629   //   of (P1,...,Pn) returning R", a surrogate call function [...]
14630   //   is also considered as a candidate function. Similarly,
14631   //   surrogate call functions are added to the set of candidate
14632   //   functions for each conversion function declared in an
14633   //   accessible base class provided the function is not hidden
14634   //   within T by another intervening declaration.
14635   const auto &Conversions =
14636       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
14637   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
14638     NamedDecl *D = *I;
14639     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
14640     if (isa<UsingShadowDecl>(D))
14641       D = cast<UsingShadowDecl>(D)->getTargetDecl();
14642 
14643     // Skip over templated conversion functions; they aren't
14644     // surrogates.
14645     if (isa<FunctionTemplateDecl>(D))
14646       continue;
14647 
14648     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
14649     if (!Conv->isExplicit()) {
14650       // Strip the reference type (if any) and then the pointer type (if
14651       // any) to get down to what might be a function type.
14652       QualType ConvType = Conv->getConversionType().getNonReferenceType();
14653       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
14654         ConvType = ConvPtrType->getPointeeType();
14655 
14656       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
14657       {
14658         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
14659                               Object.get(), Args, CandidateSet);
14660       }
14661     }
14662   }
14663 
14664   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14665 
14666   // Perform overload resolution.
14667   OverloadCandidateSet::iterator Best;
14668   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
14669                                           Best)) {
14670   case OR_Success:
14671     // Overload resolution succeeded; we'll build the appropriate call
14672     // below.
14673     break;
14674 
14675   case OR_No_Viable_Function: {
14676     PartialDiagnostic PD =
14677         CandidateSet.empty()
14678             ? (PDiag(diag::err_ovl_no_oper)
14679                << Object.get()->getType() << /*call*/ 1
14680                << Object.get()->getSourceRange())
14681             : (PDiag(diag::err_ovl_no_viable_object_call)
14682                << Object.get()->getType() << Object.get()->getSourceRange());
14683     CandidateSet.NoteCandidates(
14684         PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
14685         OCD_AllCandidates, Args);
14686     break;
14687   }
14688   case OR_Ambiguous:
14689     CandidateSet.NoteCandidates(
14690         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14691                             PDiag(diag::err_ovl_ambiguous_object_call)
14692                                 << Object.get()->getType()
14693                                 << Object.get()->getSourceRange()),
14694         *this, OCD_AmbiguousCandidates, Args);
14695     break;
14696 
14697   case OR_Deleted:
14698     CandidateSet.NoteCandidates(
14699         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14700                             PDiag(diag::err_ovl_deleted_object_call)
14701                                 << Object.get()->getType()
14702                                 << Object.get()->getSourceRange()),
14703         *this, OCD_AllCandidates, Args);
14704     break;
14705   }
14706 
14707   if (Best == CandidateSet.end())
14708     return true;
14709 
14710   UnbridgedCasts.restore();
14711 
14712   if (Best->Function == nullptr) {
14713     // Since there is no function declaration, this is one of the
14714     // surrogate candidates. Dig out the conversion function.
14715     CXXConversionDecl *Conv
14716       = cast<CXXConversionDecl>(
14717                          Best->Conversions[0].UserDefined.ConversionFunction);
14718 
14719     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
14720                               Best->FoundDecl);
14721     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
14722       return ExprError();
14723     assert(Conv == Best->FoundDecl.getDecl() &&
14724              "Found Decl & conversion-to-functionptr should be same, right?!");
14725     // We selected one of the surrogate functions that converts the
14726     // object parameter to a function pointer. Perform the conversion
14727     // on the object argument, then let BuildCallExpr finish the job.
14728 
14729     // Create an implicit member expr to refer to the conversion operator.
14730     // and then call it.
14731     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
14732                                              Conv, HadMultipleCandidates);
14733     if (Call.isInvalid())
14734       return ExprError();
14735     // Record usage of conversion in an implicit cast.
14736     Call = ImplicitCastExpr::Create(
14737         Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
14738         nullptr, VK_PRValue, CurFPFeatureOverrides());
14739 
14740     return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
14741   }
14742 
14743   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
14744 
14745   // We found an overloaded operator(). Build a CXXOperatorCallExpr
14746   // that calls this method, using Object for the implicit object
14747   // parameter and passing along the remaining arguments.
14748   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14749 
14750   // An error diagnostic has already been printed when parsing the declaration.
14751   if (Method->isInvalidDecl())
14752     return ExprError();
14753 
14754   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14755   unsigned NumParams = Proto->getNumParams();
14756 
14757   DeclarationNameInfo OpLocInfo(
14758                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
14759   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
14760   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14761                                            Obj, HadMultipleCandidates,
14762                                            OpLocInfo.getLoc(),
14763                                            OpLocInfo.getInfo());
14764   if (NewFn.isInvalid())
14765     return true;
14766 
14767   SmallVector<Expr *, 8> MethodArgs;
14768   MethodArgs.reserve(NumParams + 1);
14769 
14770   bool IsError = false;
14771 
14772   // Initialize the implicit object parameter.
14773   ExprResult ObjRes =
14774     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
14775                                         Best->FoundDecl, Method);
14776   if (ObjRes.isInvalid())
14777     IsError = true;
14778   else
14779     Object = ObjRes;
14780   MethodArgs.push_back(Object.get());
14781 
14782   IsError |= PrepareArgumentsForCallToObjectOfClassType(
14783       *this, MethodArgs, Method, Args, LParenLoc);
14784 
14785   // If this is a variadic call, handle args passed through "...".
14786   if (Proto->isVariadic()) {
14787     // Promote the arguments (C99 6.5.2.2p7).
14788     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
14789       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
14790                                                         nullptr);
14791       IsError |= Arg.isInvalid();
14792       MethodArgs.push_back(Arg.get());
14793     }
14794   }
14795 
14796   if (IsError)
14797     return true;
14798 
14799   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14800 
14801   // Once we've built TheCall, all of the expressions are properly owned.
14802   QualType ResultTy = Method->getReturnType();
14803   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14804   ResultTy = ResultTy.getNonLValueExprType(Context);
14805 
14806   CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14807       Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
14808       CurFPFeatureOverrides());
14809 
14810   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
14811     return true;
14812 
14813   if (CheckFunctionCall(Method, TheCall, Proto))
14814     return true;
14815 
14816   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
14817 }
14818 
14819 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
14820 ///  (if one exists), where @c Base is an expression of class type and
14821 /// @c Member is the name of the member we're trying to find.
14822 ExprResult
14823 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
14824                                bool *NoArrowOperatorFound) {
14825   assert(Base->getType()->isRecordType() &&
14826          "left-hand side must have class type");
14827 
14828   if (checkPlaceholderForOverload(*this, Base))
14829     return ExprError();
14830 
14831   SourceLocation Loc = Base->getExprLoc();
14832 
14833   // C++ [over.ref]p1:
14834   //
14835   //   [...] An expression x->m is interpreted as (x.operator->())->m
14836   //   for a class object x of type T if T::operator->() exists and if
14837   //   the operator is selected as the best match function by the
14838   //   overload resolution mechanism (13.3).
14839   DeclarationName OpName =
14840     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
14841   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
14842 
14843   if (RequireCompleteType(Loc, Base->getType(),
14844                           diag::err_typecheck_incomplete_tag, Base))
14845     return ExprError();
14846 
14847   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
14848   LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
14849   R.suppressDiagnostics();
14850 
14851   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14852        Oper != OperEnd; ++Oper) {
14853     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
14854                        None, CandidateSet, /*SuppressUserConversion=*/false);
14855   }
14856 
14857   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14858 
14859   // Perform overload resolution.
14860   OverloadCandidateSet::iterator Best;
14861   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14862   case OR_Success:
14863     // Overload resolution succeeded; we'll build the call below.
14864     break;
14865 
14866   case OR_No_Viable_Function: {
14867     auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
14868     if (CandidateSet.empty()) {
14869       QualType BaseType = Base->getType();
14870       if (NoArrowOperatorFound) {
14871         // Report this specific error to the caller instead of emitting a
14872         // diagnostic, as requested.
14873         *NoArrowOperatorFound = true;
14874         return ExprError();
14875       }
14876       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
14877         << BaseType << Base->getSourceRange();
14878       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
14879         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
14880           << FixItHint::CreateReplacement(OpLoc, ".");
14881       }
14882     } else
14883       Diag(OpLoc, diag::err_ovl_no_viable_oper)
14884         << "operator->" << Base->getSourceRange();
14885     CandidateSet.NoteCandidates(*this, Base, Cands);
14886     return ExprError();
14887   }
14888   case OR_Ambiguous:
14889     CandidateSet.NoteCandidates(
14890         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
14891                                        << "->" << Base->getType()
14892                                        << Base->getSourceRange()),
14893         *this, OCD_AmbiguousCandidates, Base);
14894     return ExprError();
14895 
14896   case OR_Deleted:
14897     CandidateSet.NoteCandidates(
14898         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14899                                        << "->" << Base->getSourceRange()),
14900         *this, OCD_AllCandidates, Base);
14901     return ExprError();
14902   }
14903 
14904   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
14905 
14906   // Convert the object parameter.
14907   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14908   ExprResult BaseResult =
14909     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
14910                                         Best->FoundDecl, Method);
14911   if (BaseResult.isInvalid())
14912     return ExprError();
14913   Base = BaseResult.get();
14914 
14915   // Build the operator call.
14916   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14917                                             Base, HadMultipleCandidates, OpLoc);
14918   if (FnExpr.isInvalid())
14919     return ExprError();
14920 
14921   QualType ResultTy = Method->getReturnType();
14922   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14923   ResultTy = ResultTy.getNonLValueExprType(Context);
14924   CXXOperatorCallExpr *TheCall =
14925       CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
14926                                   ResultTy, VK, OpLoc, CurFPFeatureOverrides());
14927 
14928   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
14929     return ExprError();
14930 
14931   if (CheckFunctionCall(Method, TheCall,
14932                         Method->getType()->castAs<FunctionProtoType>()))
14933     return ExprError();
14934 
14935   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
14936 }
14937 
14938 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
14939 /// a literal operator described by the provided lookup results.
14940 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
14941                                           DeclarationNameInfo &SuffixInfo,
14942                                           ArrayRef<Expr*> Args,
14943                                           SourceLocation LitEndLoc,
14944                                        TemplateArgumentListInfo *TemplateArgs) {
14945   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
14946 
14947   OverloadCandidateSet CandidateSet(UDSuffixLoc,
14948                                     OverloadCandidateSet::CSK_Normal);
14949   AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
14950                                  TemplateArgs);
14951 
14952   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14953 
14954   // Perform overload resolution. This will usually be trivial, but might need
14955   // to perform substitutions for a literal operator template.
14956   OverloadCandidateSet::iterator Best;
14957   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
14958   case OR_Success:
14959   case OR_Deleted:
14960     break;
14961 
14962   case OR_No_Viable_Function:
14963     CandidateSet.NoteCandidates(
14964         PartialDiagnosticAt(UDSuffixLoc,
14965                             PDiag(diag::err_ovl_no_viable_function_in_call)
14966                                 << R.getLookupName()),
14967         *this, OCD_AllCandidates, Args);
14968     return ExprError();
14969 
14970   case OR_Ambiguous:
14971     CandidateSet.NoteCandidates(
14972         PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
14973                                                 << R.getLookupName()),
14974         *this, OCD_AmbiguousCandidates, Args);
14975     return ExprError();
14976   }
14977 
14978   FunctionDecl *FD = Best->Function;
14979   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
14980                                         nullptr, HadMultipleCandidates,
14981                                         SuffixInfo.getLoc(),
14982                                         SuffixInfo.getInfo());
14983   if (Fn.isInvalid())
14984     return true;
14985 
14986   // Check the argument types. This should almost always be a no-op, except
14987   // that array-to-pointer decay is applied to string literals.
14988   Expr *ConvArgs[2];
14989   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
14990     ExprResult InputInit = PerformCopyInitialization(
14991       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
14992       SourceLocation(), Args[ArgIdx]);
14993     if (InputInit.isInvalid())
14994       return true;
14995     ConvArgs[ArgIdx] = InputInit.get();
14996   }
14997 
14998   QualType ResultTy = FD->getReturnType();
14999   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15000   ResultTy = ResultTy.getNonLValueExprType(Context);
15001 
15002   UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
15003       Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
15004       VK, LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
15005 
15006   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
15007     return ExprError();
15008 
15009   if (CheckFunctionCall(FD, UDL, nullptr))
15010     return ExprError();
15011 
15012   return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
15013 }
15014 
15015 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
15016 /// given LookupResult is non-empty, it is assumed to describe a member which
15017 /// will be invoked. Otherwise, the function will be found via argument
15018 /// dependent lookup.
15019 /// CallExpr is set to a valid expression and FRS_Success returned on success,
15020 /// otherwise CallExpr is set to ExprError() and some non-success value
15021 /// is returned.
15022 Sema::ForRangeStatus
15023 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
15024                                 SourceLocation RangeLoc,
15025                                 const DeclarationNameInfo &NameInfo,
15026                                 LookupResult &MemberLookup,
15027                                 OverloadCandidateSet *CandidateSet,
15028                                 Expr *Range, ExprResult *CallExpr) {
15029   Scope *S = nullptr;
15030 
15031   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
15032   if (!MemberLookup.empty()) {
15033     ExprResult MemberRef =
15034         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
15035                                  /*IsPtr=*/false, CXXScopeSpec(),
15036                                  /*TemplateKWLoc=*/SourceLocation(),
15037                                  /*FirstQualifierInScope=*/nullptr,
15038                                  MemberLookup,
15039                                  /*TemplateArgs=*/nullptr, S);
15040     if (MemberRef.isInvalid()) {
15041       *CallExpr = ExprError();
15042       return FRS_DiagnosticIssued;
15043     }
15044     *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
15045     if (CallExpr->isInvalid()) {
15046       *CallExpr = ExprError();
15047       return FRS_DiagnosticIssued;
15048     }
15049   } else {
15050     ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
15051                                                 NestedNameSpecifierLoc(),
15052                                                 NameInfo, UnresolvedSet<0>());
15053     if (FnR.isInvalid())
15054       return FRS_DiagnosticIssued;
15055     UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
15056 
15057     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
15058                                                     CandidateSet, CallExpr);
15059     if (CandidateSet->empty() || CandidateSetError) {
15060       *CallExpr = ExprError();
15061       return FRS_NoViableFunction;
15062     }
15063     OverloadCandidateSet::iterator Best;
15064     OverloadingResult OverloadResult =
15065         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
15066 
15067     if (OverloadResult == OR_No_Viable_Function) {
15068       *CallExpr = ExprError();
15069       return FRS_NoViableFunction;
15070     }
15071     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
15072                                          Loc, nullptr, CandidateSet, &Best,
15073                                          OverloadResult,
15074                                          /*AllowTypoCorrection=*/false);
15075     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
15076       *CallExpr = ExprError();
15077       return FRS_DiagnosticIssued;
15078     }
15079   }
15080   return FRS_Success;
15081 }
15082 
15083 
15084 /// FixOverloadedFunctionReference - E is an expression that refers to
15085 /// a C++ overloaded function (possibly with some parentheses and
15086 /// perhaps a '&' around it). We have resolved the overloaded function
15087 /// to the function declaration Fn, so patch up the expression E to
15088 /// refer (possibly indirectly) to Fn. Returns the new expr.
15089 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
15090                                            FunctionDecl *Fn) {
15091   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
15092     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
15093                                                    Found, Fn);
15094     if (SubExpr == PE->getSubExpr())
15095       return PE;
15096 
15097     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
15098   }
15099 
15100   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
15101     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
15102                                                    Found, Fn);
15103     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
15104                                SubExpr->getType()) &&
15105            "Implicit cast type cannot be determined from overload");
15106     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
15107     if (SubExpr == ICE->getSubExpr())
15108       return ICE;
15109 
15110     return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
15111                                     SubExpr, nullptr, ICE->getValueKind(),
15112                                     CurFPFeatureOverrides());
15113   }
15114 
15115   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
15116     if (!GSE->isResultDependent()) {
15117       Expr *SubExpr =
15118           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
15119       if (SubExpr == GSE->getResultExpr())
15120         return GSE;
15121 
15122       // Replace the resulting type information before rebuilding the generic
15123       // selection expression.
15124       ArrayRef<Expr *> A = GSE->getAssocExprs();
15125       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
15126       unsigned ResultIdx = GSE->getResultIndex();
15127       AssocExprs[ResultIdx] = SubExpr;
15128 
15129       return GenericSelectionExpr::Create(
15130           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
15131           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
15132           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
15133           ResultIdx);
15134     }
15135     // Rather than fall through to the unreachable, return the original generic
15136     // selection expression.
15137     return GSE;
15138   }
15139 
15140   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
15141     assert(UnOp->getOpcode() == UO_AddrOf &&
15142            "Can only take the address of an overloaded function");
15143     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
15144       if (Method->isStatic()) {
15145         // Do nothing: static member functions aren't any different
15146         // from non-member functions.
15147       } else {
15148         // Fix the subexpression, which really has to be an
15149         // UnresolvedLookupExpr holding an overloaded member function
15150         // or template.
15151         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
15152                                                        Found, Fn);
15153         if (SubExpr == UnOp->getSubExpr())
15154           return UnOp;
15155 
15156         assert(isa<DeclRefExpr>(SubExpr)
15157                && "fixed to something other than a decl ref");
15158         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
15159                && "fixed to a member ref with no nested name qualifier");
15160 
15161         // We have taken the address of a pointer to member
15162         // function. Perform the computation here so that we get the
15163         // appropriate pointer to member type.
15164         QualType ClassType
15165           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
15166         QualType MemPtrType
15167           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
15168         // Under the MS ABI, lock down the inheritance model now.
15169         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15170           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
15171 
15172         return UnaryOperator::Create(
15173             Context, SubExpr, UO_AddrOf, MemPtrType, VK_PRValue, OK_Ordinary,
15174             UnOp->getOperatorLoc(), false, CurFPFeatureOverrides());
15175       }
15176     }
15177     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
15178                                                    Found, Fn);
15179     if (SubExpr == UnOp->getSubExpr())
15180       return UnOp;
15181 
15182     return UnaryOperator::Create(
15183         Context, SubExpr, UO_AddrOf, Context.getPointerType(SubExpr->getType()),
15184         VK_PRValue, OK_Ordinary, UnOp->getOperatorLoc(), false,
15185         CurFPFeatureOverrides());
15186   }
15187 
15188   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15189     // FIXME: avoid copy.
15190     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15191     if (ULE->hasExplicitTemplateArgs()) {
15192       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
15193       TemplateArgs = &TemplateArgsBuffer;
15194     }
15195 
15196     DeclRefExpr *DRE =
15197         BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(),
15198                          ULE->getQualifierLoc(), Found.getDecl(),
15199                          ULE->getTemplateKeywordLoc(), TemplateArgs);
15200     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
15201     return DRE;
15202   }
15203 
15204   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
15205     // FIXME: avoid copy.
15206     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15207     if (MemExpr->hasExplicitTemplateArgs()) {
15208       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
15209       TemplateArgs = &TemplateArgsBuffer;
15210     }
15211 
15212     Expr *Base;
15213 
15214     // If we're filling in a static method where we used to have an
15215     // implicit member access, rewrite to a simple decl ref.
15216     if (MemExpr->isImplicitAccess()) {
15217       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
15218         DeclRefExpr *DRE = BuildDeclRefExpr(
15219             Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
15220             MemExpr->getQualifierLoc(), Found.getDecl(),
15221             MemExpr->getTemplateKeywordLoc(), TemplateArgs);
15222         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
15223         return DRE;
15224       } else {
15225         SourceLocation Loc = MemExpr->getMemberLoc();
15226         if (MemExpr->getQualifier())
15227           Loc = MemExpr->getQualifierLoc().getBeginLoc();
15228         Base =
15229             BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
15230       }
15231     } else
15232       Base = MemExpr->getBase();
15233 
15234     ExprValueKind valueKind;
15235     QualType type;
15236     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
15237       valueKind = VK_LValue;
15238       type = Fn->getType();
15239     } else {
15240       valueKind = VK_PRValue;
15241       type = Context.BoundMemberTy;
15242     }
15243 
15244     return BuildMemberExpr(
15245         Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
15246         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
15247         /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
15248         type, valueKind, OK_Ordinary, TemplateArgs);
15249   }
15250 
15251   llvm_unreachable("Invalid reference to overloaded function");
15252 }
15253 
15254 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
15255                                                 DeclAccessPair Found,
15256                                                 FunctionDecl *Fn) {
15257   return FixOverloadedFunctionReference(E.get(), Found, Fn);
15258 }
15259 
15260 bool clang::shouldEnforceArgLimit(bool PartialOverloading,
15261                                   FunctionDecl *Function) {
15262   if (!PartialOverloading || !Function)
15263     return true;
15264   if (Function->isVariadic())
15265     return false;
15266   if (const auto *Proto =
15267           dyn_cast<FunctionProtoType>(Function->getFunctionType()))
15268     if (Proto->isTemplateVariadic())
15269       return false;
15270   if (auto *Pattern = Function->getTemplateInstantiationPattern())
15271     if (const auto *Proto =
15272             dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
15273       if (Proto->isTemplateVariadic())
15274         return false;
15275   return true;
15276 }
15277