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     } else {
1751       return false;
1752     }
1753   }
1754   // Lvalue-to-rvalue conversion (C++11 4.1):
1755   //   A glvalue (3.10) of a non-function, non-array type T can
1756   //   be converted to a prvalue.
1757   bool argIsLValue = From->isGLValue();
1758   if (argIsLValue &&
1759       !FromType->isFunctionType() && !FromType->isArrayType() &&
1760       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1761     SCS.First = ICK_Lvalue_To_Rvalue;
1762 
1763     // C11 6.3.2.1p2:
1764     //   ... if the lvalue has atomic type, the value has the non-atomic version
1765     //   of the type of the lvalue ...
1766     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1767       FromType = Atomic->getValueType();
1768 
1769     // If T is a non-class type, the type of the rvalue is the
1770     // cv-unqualified version of T. Otherwise, the type of the rvalue
1771     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1772     // just strip the qualifiers because they don't matter.
1773     FromType = FromType.getUnqualifiedType();
1774   } else if (FromType->isArrayType()) {
1775     // Array-to-pointer conversion (C++ 4.2)
1776     SCS.First = ICK_Array_To_Pointer;
1777 
1778     // An lvalue or rvalue of type "array of N T" or "array of unknown
1779     // bound of T" can be converted to an rvalue of type "pointer to
1780     // T" (C++ 4.2p1).
1781     FromType = S.Context.getArrayDecayedType(FromType);
1782 
1783     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1784       // This conversion is deprecated in C++03 (D.4)
1785       SCS.DeprecatedStringLiteralToCharPtr = true;
1786 
1787       // For the purpose of ranking in overload resolution
1788       // (13.3.3.1.1), this conversion is considered an
1789       // array-to-pointer conversion followed by a qualification
1790       // conversion (4.4). (C++ 4.2p2)
1791       SCS.Second = ICK_Identity;
1792       SCS.Third = ICK_Qualification;
1793       SCS.QualificationIncludesObjCLifetime = false;
1794       SCS.setAllToTypes(FromType);
1795       return true;
1796     }
1797   } else if (FromType->isFunctionType() && argIsLValue) {
1798     // Function-to-pointer conversion (C++ 4.3).
1799     SCS.First = ICK_Function_To_Pointer;
1800 
1801     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1802       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1803         if (!S.checkAddressOfFunctionIsAvailable(FD))
1804           return false;
1805 
1806     // An lvalue of function type T can be converted to an rvalue of
1807     // type "pointer to T." The result is a pointer to the
1808     // function. (C++ 4.3p1).
1809     FromType = S.Context.getPointerType(FromType);
1810   } else {
1811     // We don't require any conversions for the first step.
1812     SCS.First = ICK_Identity;
1813   }
1814   SCS.setToType(0, FromType);
1815 
1816   // The second conversion can be an integral promotion, floating
1817   // point promotion, integral conversion, floating point conversion,
1818   // floating-integral conversion, pointer conversion,
1819   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1820   // For overloading in C, this can also be a "compatible-type"
1821   // conversion.
1822   bool IncompatibleObjC = false;
1823   ImplicitConversionKind SecondICK = ICK_Identity;
1824   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1825     // The unqualified versions of the types are the same: there's no
1826     // conversion to do.
1827     SCS.Second = ICK_Identity;
1828   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1829     // Integral promotion (C++ 4.5).
1830     SCS.Second = ICK_Integral_Promotion;
1831     FromType = ToType.getUnqualifiedType();
1832   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1833     // Floating point promotion (C++ 4.6).
1834     SCS.Second = ICK_Floating_Promotion;
1835     FromType = ToType.getUnqualifiedType();
1836   } else if (S.IsComplexPromotion(FromType, ToType)) {
1837     // Complex promotion (Clang extension)
1838     SCS.Second = ICK_Complex_Promotion;
1839     FromType = ToType.getUnqualifiedType();
1840   } else if (ToType->isBooleanType() &&
1841              (FromType->isArithmeticType() ||
1842               FromType->isAnyPointerType() ||
1843               FromType->isBlockPointerType() ||
1844               FromType->isMemberPointerType())) {
1845     // Boolean conversions (C++ 4.12).
1846     SCS.Second = ICK_Boolean_Conversion;
1847     FromType = S.Context.BoolTy;
1848   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1849              ToType->isIntegralType(S.Context)) {
1850     // Integral conversions (C++ 4.7).
1851     SCS.Second = ICK_Integral_Conversion;
1852     FromType = ToType.getUnqualifiedType();
1853   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1854     // Complex conversions (C99 6.3.1.6)
1855     SCS.Second = ICK_Complex_Conversion;
1856     FromType = ToType.getUnqualifiedType();
1857   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1858              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1859     // Complex-real conversions (C99 6.3.1.7)
1860     SCS.Second = ICK_Complex_Real;
1861     FromType = ToType.getUnqualifiedType();
1862   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1863     // FIXME: disable conversions between long double, __ibm128 and __float128
1864     // if their representation is different until there is back end support
1865     // We of course allow this conversion if long double is really double.
1866 
1867     // Conversions between bfloat and other floats are not permitted.
1868     if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty)
1869       return false;
1870 
1871     // Conversions between IEEE-quad and IBM-extended semantics are not
1872     // permitted.
1873     const llvm::fltSemantics &FromSem =
1874         S.Context.getFloatTypeSemantics(FromType);
1875     const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
1876     if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
1877          &ToSem == &llvm::APFloat::IEEEquad()) ||
1878         (&FromSem == &llvm::APFloat::IEEEquad() &&
1879          &ToSem == &llvm::APFloat::PPCDoubleDouble()))
1880       return false;
1881 
1882     // Floating point conversions (C++ 4.8).
1883     SCS.Second = ICK_Floating_Conversion;
1884     FromType = ToType.getUnqualifiedType();
1885   } else if ((FromType->isRealFloatingType() &&
1886               ToType->isIntegralType(S.Context)) ||
1887              (FromType->isIntegralOrUnscopedEnumerationType() &&
1888               ToType->isRealFloatingType())) {
1889     // Conversions between bfloat and int are not permitted.
1890     if (FromType->isBFloat16Type() || ToType->isBFloat16Type())
1891       return false;
1892 
1893     // Floating-integral conversions (C++ 4.9).
1894     SCS.Second = ICK_Floating_Integral;
1895     FromType = ToType.getUnqualifiedType();
1896   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1897     SCS.Second = ICK_Block_Pointer_Conversion;
1898   } else if (AllowObjCWritebackConversion &&
1899              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1900     SCS.Second = ICK_Writeback_Conversion;
1901   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1902                                    FromType, IncompatibleObjC)) {
1903     // Pointer conversions (C++ 4.10).
1904     SCS.Second = ICK_Pointer_Conversion;
1905     SCS.IncompatibleObjC = IncompatibleObjC;
1906     FromType = FromType.getUnqualifiedType();
1907   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1908                                          InOverloadResolution, FromType)) {
1909     // Pointer to member conversions (4.11).
1910     SCS.Second = ICK_Pointer_Member;
1911   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1912     SCS.Second = SecondICK;
1913     FromType = ToType.getUnqualifiedType();
1914   } else if (!S.getLangOpts().CPlusPlus &&
1915              S.Context.typesAreCompatible(ToType, FromType)) {
1916     // Compatible conversions (Clang extension for C function overloading)
1917     SCS.Second = ICK_Compatible_Conversion;
1918     FromType = ToType.getUnqualifiedType();
1919   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1920                                              InOverloadResolution,
1921                                              SCS, CStyle)) {
1922     SCS.Second = ICK_TransparentUnionConversion;
1923     FromType = ToType;
1924   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1925                                  CStyle)) {
1926     // tryAtomicConversion has updated the standard conversion sequence
1927     // appropriately.
1928     return true;
1929   } else if (ToType->isEventT() &&
1930              From->isIntegerConstantExpr(S.getASTContext()) &&
1931              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1932     SCS.Second = ICK_Zero_Event_Conversion;
1933     FromType = ToType;
1934   } else if (ToType->isQueueT() &&
1935              From->isIntegerConstantExpr(S.getASTContext()) &&
1936              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1937     SCS.Second = ICK_Zero_Queue_Conversion;
1938     FromType = ToType;
1939   } else if (ToType->isSamplerT() &&
1940              From->isIntegerConstantExpr(S.getASTContext())) {
1941     SCS.Second = ICK_Compatible_Conversion;
1942     FromType = ToType;
1943   } else {
1944     // No second conversion required.
1945     SCS.Second = ICK_Identity;
1946   }
1947   SCS.setToType(1, FromType);
1948 
1949   // The third conversion can be a function pointer conversion or a
1950   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1951   bool ObjCLifetimeConversion;
1952   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1953     // Function pointer conversions (removing 'noexcept') including removal of
1954     // 'noreturn' (Clang extension).
1955     SCS.Third = ICK_Function_Conversion;
1956   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1957                                          ObjCLifetimeConversion)) {
1958     SCS.Third = ICK_Qualification;
1959     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1960     FromType = ToType;
1961   } else {
1962     // No conversion required
1963     SCS.Third = ICK_Identity;
1964   }
1965 
1966   // C++ [over.best.ics]p6:
1967   //   [...] Any difference in top-level cv-qualification is
1968   //   subsumed by the initialization itself and does not constitute
1969   //   a conversion. [...]
1970   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1971   QualType CanonTo = S.Context.getCanonicalType(ToType);
1972   if (CanonFrom.getLocalUnqualifiedType()
1973                                      == CanonTo.getLocalUnqualifiedType() &&
1974       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1975     FromType = ToType;
1976     CanonFrom = CanonTo;
1977   }
1978 
1979   SCS.setToType(2, FromType);
1980 
1981   if (CanonFrom == CanonTo)
1982     return true;
1983 
1984   // If we have not converted the argument type to the parameter type,
1985   // this is a bad conversion sequence, unless we're resolving an overload in C.
1986   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1987     return false;
1988 
1989   ExprResult ER = ExprResult{From};
1990   Sema::AssignConvertType Conv =
1991       S.CheckSingleAssignmentConstraints(ToType, ER,
1992                                          /*Diagnose=*/false,
1993                                          /*DiagnoseCFAudited=*/false,
1994                                          /*ConvertRHS=*/false);
1995   ImplicitConversionKind SecondConv;
1996   switch (Conv) {
1997   case Sema::Compatible:
1998     SecondConv = ICK_C_Only_Conversion;
1999     break;
2000   // For our purposes, discarding qualifiers is just as bad as using an
2001   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2002   // qualifiers, as well.
2003   case Sema::CompatiblePointerDiscardsQualifiers:
2004   case Sema::IncompatiblePointer:
2005   case Sema::IncompatiblePointerSign:
2006     SecondConv = ICK_Incompatible_Pointer_Conversion;
2007     break;
2008   default:
2009     return false;
2010   }
2011 
2012   // First can only be an lvalue conversion, so we pretend that this was the
2013   // second conversion. First should already be valid from earlier in the
2014   // function.
2015   SCS.Second = SecondConv;
2016   SCS.setToType(1, ToType);
2017 
2018   // Third is Identity, because Second should rank us worse than any other
2019   // conversion. This could also be ICK_Qualification, but it's simpler to just
2020   // lump everything in with the second conversion, and we don't gain anything
2021   // from making this ICK_Qualification.
2022   SCS.Third = ICK_Identity;
2023   SCS.setToType(2, ToType);
2024   return true;
2025 }
2026 
2027 static bool
2028 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2029                                      QualType &ToType,
2030                                      bool InOverloadResolution,
2031                                      StandardConversionSequence &SCS,
2032                                      bool CStyle) {
2033 
2034   const RecordType *UT = ToType->getAsUnionType();
2035   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2036     return false;
2037   // The field to initialize within the transparent union.
2038   RecordDecl *UD = UT->getDecl();
2039   // It's compatible if the expression matches any of the fields.
2040   for (const auto *it : UD->fields()) {
2041     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2042                              CStyle, /*AllowObjCWritebackConversion=*/false)) {
2043       ToType = it->getType();
2044       return true;
2045     }
2046   }
2047   return false;
2048 }
2049 
2050 /// IsIntegralPromotion - Determines whether the conversion from the
2051 /// expression From (whose potentially-adjusted type is FromType) to
2052 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
2053 /// sets PromotedType to the promoted type.
2054 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2055   const BuiltinType *To = ToType->getAs<BuiltinType>();
2056   // All integers are built-in.
2057   if (!To) {
2058     return false;
2059   }
2060 
2061   // An rvalue of type char, signed char, unsigned char, short int, or
2062   // unsigned short int can be converted to an rvalue of type int if
2063   // int can represent all the values of the source type; otherwise,
2064   // the source rvalue can be converted to an rvalue of type unsigned
2065   // int (C++ 4.5p1).
2066   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
2067       !FromType->isEnumeralType()) {
2068     if (// We can promote any signed, promotable integer type to an int
2069         (FromType->isSignedIntegerType() ||
2070          // We can promote any unsigned integer type whose size is
2071          // less than int to an int.
2072          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2073       return To->getKind() == BuiltinType::Int;
2074     }
2075 
2076     return To->getKind() == BuiltinType::UInt;
2077   }
2078 
2079   // C++11 [conv.prom]p3:
2080   //   A prvalue of an unscoped enumeration type whose underlying type is not
2081   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2082   //   following types that can represent all the values of the enumeration
2083   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
2084   //   unsigned int, long int, unsigned long int, long long int, or unsigned
2085   //   long long int. If none of the types in that list can represent all the
2086   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2087   //   type can be converted to an rvalue a prvalue of the extended integer type
2088   //   with lowest integer conversion rank (4.13) greater than the rank of long
2089   //   long in which all the values of the enumeration can be represented. If
2090   //   there are two such extended types, the signed one is chosen.
2091   // C++11 [conv.prom]p4:
2092   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
2093   //   can be converted to a prvalue of its underlying type. Moreover, if
2094   //   integral promotion can be applied to its underlying type, a prvalue of an
2095   //   unscoped enumeration type whose underlying type is fixed can also be
2096   //   converted to a prvalue of the promoted underlying type.
2097   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2098     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2099     // provided for a scoped enumeration.
2100     if (FromEnumType->getDecl()->isScoped())
2101       return false;
2102 
2103     // We can perform an integral promotion to the underlying type of the enum,
2104     // even if that's not the promoted type. Note that the check for promoting
2105     // the underlying type is based on the type alone, and does not consider
2106     // the bitfield-ness of the actual source expression.
2107     if (FromEnumType->getDecl()->isFixed()) {
2108       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2109       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2110              IsIntegralPromotion(nullptr, Underlying, ToType);
2111     }
2112 
2113     // We have already pre-calculated the promotion type, so this is trivial.
2114     if (ToType->isIntegerType() &&
2115         isCompleteType(From->getBeginLoc(), FromType))
2116       return Context.hasSameUnqualifiedType(
2117           ToType, FromEnumType->getDecl()->getPromotionType());
2118 
2119     // C++ [conv.prom]p5:
2120     //   If the bit-field has an enumerated type, it is treated as any other
2121     //   value of that type for promotion purposes.
2122     //
2123     // ... so do not fall through into the bit-field checks below in C++.
2124     if (getLangOpts().CPlusPlus)
2125       return false;
2126   }
2127 
2128   // C++0x [conv.prom]p2:
2129   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2130   //   to an rvalue a prvalue of the first of the following types that can
2131   //   represent all the values of its underlying type: int, unsigned int,
2132   //   long int, unsigned long int, long long int, or unsigned long long int.
2133   //   If none of the types in that list can represent all the values of its
2134   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2135   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2136   //   type.
2137   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2138       ToType->isIntegerType()) {
2139     // Determine whether the type we're converting from is signed or
2140     // unsigned.
2141     bool FromIsSigned = FromType->isSignedIntegerType();
2142     uint64_t FromSize = Context.getTypeSize(FromType);
2143 
2144     // The types we'll try to promote to, in the appropriate
2145     // order. Try each of these types.
2146     QualType PromoteTypes[6] = {
2147       Context.IntTy, Context.UnsignedIntTy,
2148       Context.LongTy, Context.UnsignedLongTy ,
2149       Context.LongLongTy, Context.UnsignedLongLongTy
2150     };
2151     for (int Idx = 0; Idx < 6; ++Idx) {
2152       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2153       if (FromSize < ToSize ||
2154           (FromSize == ToSize &&
2155            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2156         // We found the type that we can promote to. If this is the
2157         // type we wanted, we have a promotion. Otherwise, no
2158         // promotion.
2159         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2160       }
2161     }
2162   }
2163 
2164   // An rvalue for an integral bit-field (9.6) can be converted to an
2165   // rvalue of type int if int can represent all the values of the
2166   // bit-field; otherwise, it can be converted to unsigned int if
2167   // unsigned int can represent all the values of the bit-field. If
2168   // the bit-field is larger yet, no integral promotion applies to
2169   // it. If the bit-field has an enumerated type, it is treated as any
2170   // other value of that type for promotion purposes (C++ 4.5p3).
2171   // FIXME: We should delay checking of bit-fields until we actually perform the
2172   // conversion.
2173   //
2174   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2175   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2176   // bit-fields and those whose underlying type is larger than int) for GCC
2177   // compatibility.
2178   if (From) {
2179     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2180       Optional<llvm::APSInt> BitWidth;
2181       if (FromType->isIntegralType(Context) &&
2182           (BitWidth =
2183                MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2184         llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2185         ToSize = Context.getTypeSize(ToType);
2186 
2187         // Are we promoting to an int from a bitfield that fits in an int?
2188         if (*BitWidth < ToSize ||
2189             (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2190           return To->getKind() == BuiltinType::Int;
2191         }
2192 
2193         // Are we promoting to an unsigned int from an unsigned bitfield
2194         // that fits into an unsigned int?
2195         if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2196           return To->getKind() == BuiltinType::UInt;
2197         }
2198 
2199         return false;
2200       }
2201     }
2202   }
2203 
2204   // An rvalue of type bool can be converted to an rvalue of type int,
2205   // with false becoming zero and true becoming one (C++ 4.5p4).
2206   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2207     return true;
2208   }
2209 
2210   return false;
2211 }
2212 
2213 /// IsFloatingPointPromotion - Determines whether the conversion from
2214 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2215 /// returns true and sets PromotedType to the promoted type.
2216 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2217   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2218     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2219       /// An rvalue of type float can be converted to an rvalue of type
2220       /// double. (C++ 4.6p1).
2221       if (FromBuiltin->getKind() == BuiltinType::Float &&
2222           ToBuiltin->getKind() == BuiltinType::Double)
2223         return true;
2224 
2225       // C99 6.3.1.5p1:
2226       //   When a float is promoted to double or long double, or a
2227       //   double is promoted to long double [...].
2228       if (!getLangOpts().CPlusPlus &&
2229           (FromBuiltin->getKind() == BuiltinType::Float ||
2230            FromBuiltin->getKind() == BuiltinType::Double) &&
2231           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2232            ToBuiltin->getKind() == BuiltinType::Float128 ||
2233            ToBuiltin->getKind() == BuiltinType::Ibm128))
2234         return true;
2235 
2236       // Half can be promoted to float.
2237       if (!getLangOpts().NativeHalfType &&
2238            FromBuiltin->getKind() == BuiltinType::Half &&
2239           ToBuiltin->getKind() == BuiltinType::Float)
2240         return true;
2241     }
2242 
2243   return false;
2244 }
2245 
2246 /// Determine if a conversion is a complex promotion.
2247 ///
2248 /// A complex promotion is defined as a complex -> complex conversion
2249 /// where the conversion between the underlying real types is a
2250 /// floating-point or integral promotion.
2251 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2252   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2253   if (!FromComplex)
2254     return false;
2255 
2256   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2257   if (!ToComplex)
2258     return false;
2259 
2260   return IsFloatingPointPromotion(FromComplex->getElementType(),
2261                                   ToComplex->getElementType()) ||
2262     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2263                         ToComplex->getElementType());
2264 }
2265 
2266 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2267 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2268 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2269 /// if non-empty, will be a pointer to ToType that may or may not have
2270 /// the right set of qualifiers on its pointee.
2271 ///
2272 static QualType
2273 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2274                                    QualType ToPointee, QualType ToType,
2275                                    ASTContext &Context,
2276                                    bool StripObjCLifetime = false) {
2277   assert((FromPtr->getTypeClass() == Type::Pointer ||
2278           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2279          "Invalid similarly-qualified pointer type");
2280 
2281   /// Conversions to 'id' subsume cv-qualifier conversions.
2282   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2283     return ToType.getUnqualifiedType();
2284 
2285   QualType CanonFromPointee
2286     = Context.getCanonicalType(FromPtr->getPointeeType());
2287   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2288   Qualifiers Quals = CanonFromPointee.getQualifiers();
2289 
2290   if (StripObjCLifetime)
2291     Quals.removeObjCLifetime();
2292 
2293   // Exact qualifier match -> return the pointer type we're converting to.
2294   if (CanonToPointee.getLocalQualifiers() == Quals) {
2295     // ToType is exactly what we need. Return it.
2296     if (!ToType.isNull())
2297       return ToType.getUnqualifiedType();
2298 
2299     // Build a pointer to ToPointee. It has the right qualifiers
2300     // already.
2301     if (isa<ObjCObjectPointerType>(ToType))
2302       return Context.getObjCObjectPointerType(ToPointee);
2303     return Context.getPointerType(ToPointee);
2304   }
2305 
2306   // Just build a canonical type that has the right qualifiers.
2307   QualType QualifiedCanonToPointee
2308     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2309 
2310   if (isa<ObjCObjectPointerType>(ToType))
2311     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2312   return Context.getPointerType(QualifiedCanonToPointee);
2313 }
2314 
2315 static bool isNullPointerConstantForConversion(Expr *Expr,
2316                                                bool InOverloadResolution,
2317                                                ASTContext &Context) {
2318   // Handle value-dependent integral null pointer constants correctly.
2319   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2320   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2321       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2322     return !InOverloadResolution;
2323 
2324   return Expr->isNullPointerConstant(Context,
2325                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2326                                         : Expr::NPC_ValueDependentIsNull);
2327 }
2328 
2329 /// IsPointerConversion - Determines whether the conversion of the
2330 /// expression From, which has the (possibly adjusted) type FromType,
2331 /// can be converted to the type ToType via a pointer conversion (C++
2332 /// 4.10). If so, returns true and places the converted type (that
2333 /// might differ from ToType in its cv-qualifiers at some level) into
2334 /// ConvertedType.
2335 ///
2336 /// This routine also supports conversions to and from block pointers
2337 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2338 /// pointers to interfaces. FIXME: Once we've determined the
2339 /// appropriate overloading rules for Objective-C, we may want to
2340 /// split the Objective-C checks into a different routine; however,
2341 /// GCC seems to consider all of these conversions to be pointer
2342 /// conversions, so for now they live here. IncompatibleObjC will be
2343 /// set if the conversion is an allowed Objective-C conversion that
2344 /// should result in a warning.
2345 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2346                                bool InOverloadResolution,
2347                                QualType& ConvertedType,
2348                                bool &IncompatibleObjC) {
2349   IncompatibleObjC = false;
2350   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2351                               IncompatibleObjC))
2352     return true;
2353 
2354   // Conversion from a null pointer constant to any Objective-C pointer type.
2355   if (ToType->isObjCObjectPointerType() &&
2356       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2357     ConvertedType = ToType;
2358     return true;
2359   }
2360 
2361   // Blocks: Block pointers can be converted to void*.
2362   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2363       ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2364     ConvertedType = ToType;
2365     return true;
2366   }
2367   // Blocks: A null pointer constant can be converted to a block
2368   // pointer type.
2369   if (ToType->isBlockPointerType() &&
2370       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2371     ConvertedType = ToType;
2372     return true;
2373   }
2374 
2375   // If the left-hand-side is nullptr_t, the right side can be a null
2376   // pointer constant.
2377   if (ToType->isNullPtrType() &&
2378       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2379     ConvertedType = ToType;
2380     return true;
2381   }
2382 
2383   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2384   if (!ToTypePtr)
2385     return false;
2386 
2387   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2388   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2389     ConvertedType = ToType;
2390     return true;
2391   }
2392 
2393   // Beyond this point, both types need to be pointers
2394   // , including objective-c pointers.
2395   QualType ToPointeeType = ToTypePtr->getPointeeType();
2396   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2397       !getLangOpts().ObjCAutoRefCount) {
2398     ConvertedType = BuildSimilarlyQualifiedPointerType(
2399         FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2400         Context);
2401     return true;
2402   }
2403   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2404   if (!FromTypePtr)
2405     return false;
2406 
2407   QualType FromPointeeType = FromTypePtr->getPointeeType();
2408 
2409   // If the unqualified pointee types are the same, this can't be a
2410   // pointer conversion, so don't do all of the work below.
2411   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2412     return false;
2413 
2414   // An rvalue of type "pointer to cv T," where T is an object type,
2415   // can be converted to an rvalue of type "pointer to cv void" (C++
2416   // 4.10p2).
2417   if (FromPointeeType->isIncompleteOrObjectType() &&
2418       ToPointeeType->isVoidType()) {
2419     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2420                                                        ToPointeeType,
2421                                                        ToType, Context,
2422                                                    /*StripObjCLifetime=*/true);
2423     return true;
2424   }
2425 
2426   // MSVC allows implicit function to void* type conversion.
2427   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2428       ToPointeeType->isVoidType()) {
2429     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2430                                                        ToPointeeType,
2431                                                        ToType, Context);
2432     return true;
2433   }
2434 
2435   // When we're overloading in C, we allow a special kind of pointer
2436   // conversion for compatible-but-not-identical pointee types.
2437   if (!getLangOpts().CPlusPlus &&
2438       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2439     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2440                                                        ToPointeeType,
2441                                                        ToType, Context);
2442     return true;
2443   }
2444 
2445   // C++ [conv.ptr]p3:
2446   //
2447   //   An rvalue of type "pointer to cv D," where D is a class type,
2448   //   can be converted to an rvalue of type "pointer to cv B," where
2449   //   B is a base class (clause 10) of D. If B is an inaccessible
2450   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2451   //   necessitates this conversion is ill-formed. The result of the
2452   //   conversion is a pointer to the base class sub-object of the
2453   //   derived class object. The null pointer value is converted to
2454   //   the null pointer value of the destination type.
2455   //
2456   // Note that we do not check for ambiguity or inaccessibility
2457   // here. That is handled by CheckPointerConversion.
2458   if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2459       ToPointeeType->isRecordType() &&
2460       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2461       IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2462     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2463                                                        ToPointeeType,
2464                                                        ToType, Context);
2465     return true;
2466   }
2467 
2468   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2469       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2470     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2471                                                        ToPointeeType,
2472                                                        ToType, Context);
2473     return true;
2474   }
2475 
2476   return false;
2477 }
2478 
2479 /// Adopt the given qualifiers for the given type.
2480 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2481   Qualifiers TQs = T.getQualifiers();
2482 
2483   // Check whether qualifiers already match.
2484   if (TQs == Qs)
2485     return T;
2486 
2487   if (Qs.compatiblyIncludes(TQs))
2488     return Context.getQualifiedType(T, Qs);
2489 
2490   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2491 }
2492 
2493 /// isObjCPointerConversion - Determines whether this is an
2494 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2495 /// with the same arguments and return values.
2496 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2497                                    QualType& ConvertedType,
2498                                    bool &IncompatibleObjC) {
2499   if (!getLangOpts().ObjC)
2500     return false;
2501 
2502   // The set of qualifiers on the type we're converting from.
2503   Qualifiers FromQualifiers = FromType.getQualifiers();
2504 
2505   // First, we handle all conversions on ObjC object pointer types.
2506   const ObjCObjectPointerType* ToObjCPtr =
2507     ToType->getAs<ObjCObjectPointerType>();
2508   const ObjCObjectPointerType *FromObjCPtr =
2509     FromType->getAs<ObjCObjectPointerType>();
2510 
2511   if (ToObjCPtr && FromObjCPtr) {
2512     // If the pointee types are the same (ignoring qualifications),
2513     // then this is not a pointer conversion.
2514     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2515                                        FromObjCPtr->getPointeeType()))
2516       return false;
2517 
2518     // Conversion between Objective-C pointers.
2519     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2520       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2521       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2522       if (getLangOpts().CPlusPlus && LHS && RHS &&
2523           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2524                                                 FromObjCPtr->getPointeeType()))
2525         return false;
2526       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2527                                                    ToObjCPtr->getPointeeType(),
2528                                                          ToType, Context);
2529       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2530       return true;
2531     }
2532 
2533     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2534       // Okay: this is some kind of implicit downcast of Objective-C
2535       // interfaces, which is permitted. However, we're going to
2536       // complain about it.
2537       IncompatibleObjC = true;
2538       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2539                                                    ToObjCPtr->getPointeeType(),
2540                                                          ToType, Context);
2541       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2542       return true;
2543     }
2544   }
2545   // Beyond this point, both types need to be C pointers or block pointers.
2546   QualType ToPointeeType;
2547   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2548     ToPointeeType = ToCPtr->getPointeeType();
2549   else if (const BlockPointerType *ToBlockPtr =
2550             ToType->getAs<BlockPointerType>()) {
2551     // Objective C++: We're able to convert from a pointer to any object
2552     // to a block pointer type.
2553     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2554       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2555       return true;
2556     }
2557     ToPointeeType = ToBlockPtr->getPointeeType();
2558   }
2559   else if (FromType->getAs<BlockPointerType>() &&
2560            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2561     // Objective C++: We're able to convert from a block pointer type to a
2562     // pointer to any object.
2563     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2564     return true;
2565   }
2566   else
2567     return false;
2568 
2569   QualType FromPointeeType;
2570   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2571     FromPointeeType = FromCPtr->getPointeeType();
2572   else if (const BlockPointerType *FromBlockPtr =
2573            FromType->getAs<BlockPointerType>())
2574     FromPointeeType = FromBlockPtr->getPointeeType();
2575   else
2576     return false;
2577 
2578   // If we have pointers to pointers, recursively check whether this
2579   // is an Objective-C conversion.
2580   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2581       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2582                               IncompatibleObjC)) {
2583     // We always complain about this conversion.
2584     IncompatibleObjC = true;
2585     ConvertedType = Context.getPointerType(ConvertedType);
2586     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2587     return true;
2588   }
2589   // Allow conversion of pointee being objective-c pointer to another one;
2590   // as in I* to id.
2591   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2592       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2593       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2594                               IncompatibleObjC)) {
2595 
2596     ConvertedType = Context.getPointerType(ConvertedType);
2597     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2598     return true;
2599   }
2600 
2601   // If we have pointers to functions or blocks, check whether the only
2602   // differences in the argument and result types are in Objective-C
2603   // pointer conversions. If so, we permit the conversion (but
2604   // complain about it).
2605   const FunctionProtoType *FromFunctionType
2606     = FromPointeeType->getAs<FunctionProtoType>();
2607   const FunctionProtoType *ToFunctionType
2608     = ToPointeeType->getAs<FunctionProtoType>();
2609   if (FromFunctionType && ToFunctionType) {
2610     // If the function types are exactly the same, this isn't an
2611     // Objective-C pointer conversion.
2612     if (Context.getCanonicalType(FromPointeeType)
2613           == Context.getCanonicalType(ToPointeeType))
2614       return false;
2615 
2616     // Perform the quick checks that will tell us whether these
2617     // function types are obviously different.
2618     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2619         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2620         FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2621       return false;
2622 
2623     bool HasObjCConversion = false;
2624     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2625         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2626       // Okay, the types match exactly. Nothing to do.
2627     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2628                                        ToFunctionType->getReturnType(),
2629                                        ConvertedType, IncompatibleObjC)) {
2630       // Okay, we have an Objective-C pointer conversion.
2631       HasObjCConversion = true;
2632     } else {
2633       // Function types are too different. Abort.
2634       return false;
2635     }
2636 
2637     // Check argument types.
2638     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2639          ArgIdx != NumArgs; ++ArgIdx) {
2640       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2641       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2642       if (Context.getCanonicalType(FromArgType)
2643             == Context.getCanonicalType(ToArgType)) {
2644         // Okay, the types match exactly. Nothing to do.
2645       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2646                                          ConvertedType, IncompatibleObjC)) {
2647         // Okay, we have an Objective-C pointer conversion.
2648         HasObjCConversion = true;
2649       } else {
2650         // Argument types are too different. Abort.
2651         return false;
2652       }
2653     }
2654 
2655     if (HasObjCConversion) {
2656       // We had an Objective-C conversion. Allow this pointer
2657       // conversion, but complain about it.
2658       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2659       IncompatibleObjC = true;
2660       return true;
2661     }
2662   }
2663 
2664   return false;
2665 }
2666 
2667 /// Determine whether this is an Objective-C writeback conversion,
2668 /// used for parameter passing when performing automatic reference counting.
2669 ///
2670 /// \param FromType The type we're converting form.
2671 ///
2672 /// \param ToType The type we're converting to.
2673 ///
2674 /// \param ConvertedType The type that will be produced after applying
2675 /// this conversion.
2676 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2677                                      QualType &ConvertedType) {
2678   if (!getLangOpts().ObjCAutoRefCount ||
2679       Context.hasSameUnqualifiedType(FromType, ToType))
2680     return false;
2681 
2682   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2683   QualType ToPointee;
2684   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2685     ToPointee = ToPointer->getPointeeType();
2686   else
2687     return false;
2688 
2689   Qualifiers ToQuals = ToPointee.getQualifiers();
2690   if (!ToPointee->isObjCLifetimeType() ||
2691       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2692       !ToQuals.withoutObjCLifetime().empty())
2693     return false;
2694 
2695   // Argument must be a pointer to __strong to __weak.
2696   QualType FromPointee;
2697   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2698     FromPointee = FromPointer->getPointeeType();
2699   else
2700     return false;
2701 
2702   Qualifiers FromQuals = FromPointee.getQualifiers();
2703   if (!FromPointee->isObjCLifetimeType() ||
2704       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2705        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2706     return false;
2707 
2708   // Make sure that we have compatible qualifiers.
2709   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2710   if (!ToQuals.compatiblyIncludes(FromQuals))
2711     return false;
2712 
2713   // Remove qualifiers from the pointee type we're converting from; they
2714   // aren't used in the compatibility check belong, and we'll be adding back
2715   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2716   FromPointee = FromPointee.getUnqualifiedType();
2717 
2718   // The unqualified form of the pointee types must be compatible.
2719   ToPointee = ToPointee.getUnqualifiedType();
2720   bool IncompatibleObjC;
2721   if (Context.typesAreCompatible(FromPointee, ToPointee))
2722     FromPointee = ToPointee;
2723   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2724                                     IncompatibleObjC))
2725     return false;
2726 
2727   /// Construct the type we're converting to, which is a pointer to
2728   /// __autoreleasing pointee.
2729   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2730   ConvertedType = Context.getPointerType(FromPointee);
2731   return true;
2732 }
2733 
2734 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2735                                     QualType& ConvertedType) {
2736   QualType ToPointeeType;
2737   if (const BlockPointerType *ToBlockPtr =
2738         ToType->getAs<BlockPointerType>())
2739     ToPointeeType = ToBlockPtr->getPointeeType();
2740   else
2741     return false;
2742 
2743   QualType FromPointeeType;
2744   if (const BlockPointerType *FromBlockPtr =
2745       FromType->getAs<BlockPointerType>())
2746     FromPointeeType = FromBlockPtr->getPointeeType();
2747   else
2748     return false;
2749   // We have pointer to blocks, check whether the only
2750   // differences in the argument and result types are in Objective-C
2751   // pointer conversions. If so, we permit the conversion.
2752 
2753   const FunctionProtoType *FromFunctionType
2754     = FromPointeeType->getAs<FunctionProtoType>();
2755   const FunctionProtoType *ToFunctionType
2756     = ToPointeeType->getAs<FunctionProtoType>();
2757 
2758   if (!FromFunctionType || !ToFunctionType)
2759     return false;
2760 
2761   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2762     return true;
2763 
2764   // Perform the quick checks that will tell us whether these
2765   // function types are obviously different.
2766   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2767       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2768     return false;
2769 
2770   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2771   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2772   if (FromEInfo != ToEInfo)
2773     return false;
2774 
2775   bool IncompatibleObjC = false;
2776   if (Context.hasSameType(FromFunctionType->getReturnType(),
2777                           ToFunctionType->getReturnType())) {
2778     // Okay, the types match exactly. Nothing to do.
2779   } else {
2780     QualType RHS = FromFunctionType->getReturnType();
2781     QualType LHS = ToFunctionType->getReturnType();
2782     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2783         !RHS.hasQualifiers() && LHS.hasQualifiers())
2784        LHS = LHS.getUnqualifiedType();
2785 
2786      if (Context.hasSameType(RHS,LHS)) {
2787        // OK exact match.
2788      } else if (isObjCPointerConversion(RHS, LHS,
2789                                         ConvertedType, IncompatibleObjC)) {
2790      if (IncompatibleObjC)
2791        return false;
2792      // Okay, we have an Objective-C pointer conversion.
2793      }
2794      else
2795        return false;
2796    }
2797 
2798    // Check argument types.
2799    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2800         ArgIdx != NumArgs; ++ArgIdx) {
2801      IncompatibleObjC = false;
2802      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2803      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2804      if (Context.hasSameType(FromArgType, ToArgType)) {
2805        // Okay, the types match exactly. Nothing to do.
2806      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2807                                         ConvertedType, IncompatibleObjC)) {
2808        if (IncompatibleObjC)
2809          return false;
2810        // Okay, we have an Objective-C pointer conversion.
2811      } else
2812        // Argument types are too different. Abort.
2813        return false;
2814    }
2815 
2816    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2817    bool CanUseToFPT, CanUseFromFPT;
2818    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2819                                       CanUseToFPT, CanUseFromFPT,
2820                                       NewParamInfos))
2821      return false;
2822 
2823    ConvertedType = ToType;
2824    return true;
2825 }
2826 
2827 enum {
2828   ft_default,
2829   ft_different_class,
2830   ft_parameter_arity,
2831   ft_parameter_mismatch,
2832   ft_return_type,
2833   ft_qualifer_mismatch,
2834   ft_noexcept
2835 };
2836 
2837 /// Attempts to get the FunctionProtoType from a Type. Handles
2838 /// MemberFunctionPointers properly.
2839 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2840   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2841     return FPT;
2842 
2843   if (auto *MPT = FromType->getAs<MemberPointerType>())
2844     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2845 
2846   return nullptr;
2847 }
2848 
2849 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2850 /// function types.  Catches different number of parameter, mismatch in
2851 /// parameter types, and different return types.
2852 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2853                                       QualType FromType, QualType ToType) {
2854   // If either type is not valid, include no extra info.
2855   if (FromType.isNull() || ToType.isNull()) {
2856     PDiag << ft_default;
2857     return;
2858   }
2859 
2860   // Get the function type from the pointers.
2861   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2862     const auto *FromMember = FromType->castAs<MemberPointerType>(),
2863                *ToMember = ToType->castAs<MemberPointerType>();
2864     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2865       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2866             << QualType(FromMember->getClass(), 0);
2867       return;
2868     }
2869     FromType = FromMember->getPointeeType();
2870     ToType = ToMember->getPointeeType();
2871   }
2872 
2873   if (FromType->isPointerType())
2874     FromType = FromType->getPointeeType();
2875   if (ToType->isPointerType())
2876     ToType = ToType->getPointeeType();
2877 
2878   // Remove references.
2879   FromType = FromType.getNonReferenceType();
2880   ToType = ToType.getNonReferenceType();
2881 
2882   // Don't print extra info for non-specialized template functions.
2883   if (FromType->isInstantiationDependentType() &&
2884       !FromType->getAs<TemplateSpecializationType>()) {
2885     PDiag << ft_default;
2886     return;
2887   }
2888 
2889   // No extra info for same types.
2890   if (Context.hasSameType(FromType, ToType)) {
2891     PDiag << ft_default;
2892     return;
2893   }
2894 
2895   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2896                           *ToFunction = tryGetFunctionProtoType(ToType);
2897 
2898   // Both types need to be function types.
2899   if (!FromFunction || !ToFunction) {
2900     PDiag << ft_default;
2901     return;
2902   }
2903 
2904   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2905     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2906           << FromFunction->getNumParams();
2907     return;
2908   }
2909 
2910   // Handle different parameter types.
2911   unsigned ArgPos;
2912   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2913     PDiag << ft_parameter_mismatch << ArgPos + 1
2914           << ToFunction->getParamType(ArgPos)
2915           << FromFunction->getParamType(ArgPos);
2916     return;
2917   }
2918 
2919   // Handle different return type.
2920   if (!Context.hasSameType(FromFunction->getReturnType(),
2921                            ToFunction->getReturnType())) {
2922     PDiag << ft_return_type << ToFunction->getReturnType()
2923           << FromFunction->getReturnType();
2924     return;
2925   }
2926 
2927   if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2928     PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2929           << FromFunction->getMethodQuals();
2930     return;
2931   }
2932 
2933   // Handle exception specification differences on canonical type (in C++17
2934   // onwards).
2935   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2936           ->isNothrow() !=
2937       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2938           ->isNothrow()) {
2939     PDiag << ft_noexcept;
2940     return;
2941   }
2942 
2943   // Unable to find a difference, so add no extra info.
2944   PDiag << ft_default;
2945 }
2946 
2947 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2948 /// for equality of their parameter types. Caller has already checked that
2949 /// they have same number of parameters.  If the parameters are different,
2950 /// ArgPos will have the parameter index of the first different parameter.
2951 /// If `Reversed` is true, the parameters of `NewType` will be compared in
2952 /// reverse order. That's useful if one of the functions is being used as a C++20
2953 /// synthesized operator overload with a reversed parameter order.
2954 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2955                                       const FunctionProtoType *NewType,
2956                                       unsigned *ArgPos, bool Reversed) {
2957   assert(OldType->getNumParams() == NewType->getNumParams() &&
2958          "Can't compare parameters of functions with different number of "
2959          "parameters!");
2960   for (size_t I = 0; I < OldType->getNumParams(); I++) {
2961     // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
2962     size_t J = Reversed ? (OldType->getNumParams() - I - 1) : I;
2963 
2964     // Ignore address spaces in pointee type. This is to disallow overloading
2965     // on __ptr32/__ptr64 address spaces.
2966     QualType Old = Context.removePtrSizeAddrSpace(OldType->getParamType(I).getUnqualifiedType());
2967     QualType New = Context.removePtrSizeAddrSpace(NewType->getParamType(J).getUnqualifiedType());
2968 
2969     if (!Context.hasSameType(Old, New)) {
2970       if (ArgPos)
2971         *ArgPos = I;
2972       return false;
2973     }
2974   }
2975   return true;
2976 }
2977 
2978 /// CheckPointerConversion - Check the pointer conversion from the
2979 /// expression From to the type ToType. This routine checks for
2980 /// ambiguous or inaccessible derived-to-base pointer
2981 /// conversions for which IsPointerConversion has already returned
2982 /// true. It returns true and produces a diagnostic if there was an
2983 /// error, or returns false otherwise.
2984 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2985                                   CastKind &Kind,
2986                                   CXXCastPath& BasePath,
2987                                   bool IgnoreBaseAccess,
2988                                   bool Diagnose) {
2989   QualType FromType = From->getType();
2990   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2991 
2992   Kind = CK_BitCast;
2993 
2994   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2995       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2996           Expr::NPCK_ZeroExpression) {
2997     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2998       DiagRuntimeBehavior(From->getExprLoc(), From,
2999                           PDiag(diag::warn_impcast_bool_to_null_pointer)
3000                             << ToType << From->getSourceRange());
3001     else if (!isUnevaluatedContext())
3002       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3003         << ToType << From->getSourceRange();
3004   }
3005   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3006     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3007       QualType FromPointeeType = FromPtrType->getPointeeType(),
3008                ToPointeeType   = ToPtrType->getPointeeType();
3009 
3010       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3011           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3012         // We must have a derived-to-base conversion. Check an
3013         // ambiguous or inaccessible conversion.
3014         unsigned InaccessibleID = 0;
3015         unsigned AmbiguousID = 0;
3016         if (Diagnose) {
3017           InaccessibleID = diag::err_upcast_to_inaccessible_base;
3018           AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3019         }
3020         if (CheckDerivedToBaseConversion(
3021                 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3022                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3023                 &BasePath, IgnoreBaseAccess))
3024           return true;
3025 
3026         // The conversion was successful.
3027         Kind = CK_DerivedToBase;
3028       }
3029 
3030       if (Diagnose && !IsCStyleOrFunctionalCast &&
3031           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3032         assert(getLangOpts().MSVCCompat &&
3033                "this should only be possible with MSVCCompat!");
3034         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3035             << From->getSourceRange();
3036       }
3037     }
3038   } else if (const ObjCObjectPointerType *ToPtrType =
3039                ToType->getAs<ObjCObjectPointerType>()) {
3040     if (const ObjCObjectPointerType *FromPtrType =
3041           FromType->getAs<ObjCObjectPointerType>()) {
3042       // Objective-C++ conversions are always okay.
3043       // FIXME: We should have a different class of conversions for the
3044       // Objective-C++ implicit conversions.
3045       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3046         return false;
3047     } else if (FromType->isBlockPointerType()) {
3048       Kind = CK_BlockPointerToObjCPointerCast;
3049     } else {
3050       Kind = CK_CPointerToObjCPointerCast;
3051     }
3052   } else if (ToType->isBlockPointerType()) {
3053     if (!FromType->isBlockPointerType())
3054       Kind = CK_AnyPointerToBlockPointerCast;
3055   }
3056 
3057   // We shouldn't fall into this case unless it's valid for other
3058   // reasons.
3059   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3060     Kind = CK_NullToPointer;
3061 
3062   return false;
3063 }
3064 
3065 /// IsMemberPointerConversion - Determines whether the conversion of the
3066 /// expression From, which has the (possibly adjusted) type FromType, can be
3067 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
3068 /// If so, returns true and places the converted type (that might differ from
3069 /// ToType in its cv-qualifiers at some level) into ConvertedType.
3070 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3071                                      QualType ToType,
3072                                      bool InOverloadResolution,
3073                                      QualType &ConvertedType) {
3074   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3075   if (!ToTypePtr)
3076     return false;
3077 
3078   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3079   if (From->isNullPointerConstant(Context,
3080                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3081                                         : Expr::NPC_ValueDependentIsNull)) {
3082     ConvertedType = ToType;
3083     return true;
3084   }
3085 
3086   // Otherwise, both types have to be member pointers.
3087   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3088   if (!FromTypePtr)
3089     return false;
3090 
3091   // A pointer to member of B can be converted to a pointer to member of D,
3092   // where D is derived from B (C++ 4.11p2).
3093   QualType FromClass(FromTypePtr->getClass(), 0);
3094   QualType ToClass(ToTypePtr->getClass(), 0);
3095 
3096   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3097       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3098     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3099                                                  ToClass.getTypePtr());
3100     return true;
3101   }
3102 
3103   return false;
3104 }
3105 
3106 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3107 /// expression From to the type ToType. This routine checks for ambiguous or
3108 /// virtual or inaccessible base-to-derived member pointer conversions
3109 /// for which IsMemberPointerConversion has already returned true. It returns
3110 /// true and produces a diagnostic if there was an error, or returns false
3111 /// otherwise.
3112 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3113                                         CastKind &Kind,
3114                                         CXXCastPath &BasePath,
3115                                         bool IgnoreBaseAccess) {
3116   QualType FromType = From->getType();
3117   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3118   if (!FromPtrType) {
3119     // This must be a null pointer to member pointer conversion
3120     assert(From->isNullPointerConstant(Context,
3121                                        Expr::NPC_ValueDependentIsNull) &&
3122            "Expr must be null pointer constant!");
3123     Kind = CK_NullToMemberPointer;
3124     return false;
3125   }
3126 
3127   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3128   assert(ToPtrType && "No member pointer cast has a target type "
3129                       "that is not a member pointer.");
3130 
3131   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3132   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3133 
3134   // FIXME: What about dependent types?
3135   assert(FromClass->isRecordType() && "Pointer into non-class.");
3136   assert(ToClass->isRecordType() && "Pointer into non-class.");
3137 
3138   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3139                      /*DetectVirtual=*/true);
3140   bool DerivationOkay =
3141       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3142   assert(DerivationOkay &&
3143          "Should not have been called if derivation isn't OK.");
3144   (void)DerivationOkay;
3145 
3146   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3147                                   getUnqualifiedType())) {
3148     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3149     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3150       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3151     return true;
3152   }
3153 
3154   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3155     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3156       << FromClass << ToClass << QualType(VBase, 0)
3157       << From->getSourceRange();
3158     return true;
3159   }
3160 
3161   if (!IgnoreBaseAccess)
3162     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3163                          Paths.front(),
3164                          diag::err_downcast_from_inaccessible_base);
3165 
3166   // Must be a base to derived member conversion.
3167   BuildBasePathArray(Paths, BasePath);
3168   Kind = CK_BaseToDerivedMemberPointer;
3169   return false;
3170 }
3171 
3172 /// Determine whether the lifetime conversion between the two given
3173 /// qualifiers sets is nontrivial.
3174 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3175                                                Qualifiers ToQuals) {
3176   // Converting anything to const __unsafe_unretained is trivial.
3177   if (ToQuals.hasConst() &&
3178       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3179     return false;
3180 
3181   return true;
3182 }
3183 
3184 /// Perform a single iteration of the loop for checking if a qualification
3185 /// conversion is valid.
3186 ///
3187 /// Specifically, check whether any change between the qualifiers of \p
3188 /// FromType and \p ToType is permissible, given knowledge about whether every
3189 /// outer layer is const-qualified.
3190 static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3191                                           bool CStyle, bool IsTopLevel,
3192                                           bool &PreviousToQualsIncludeConst,
3193                                           bool &ObjCLifetimeConversion) {
3194   Qualifiers FromQuals = FromType.getQualifiers();
3195   Qualifiers ToQuals = ToType.getQualifiers();
3196 
3197   // Ignore __unaligned qualifier.
3198   FromQuals.removeUnaligned();
3199 
3200   // Objective-C ARC:
3201   //   Check Objective-C lifetime conversions.
3202   if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3203     if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3204       if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3205         ObjCLifetimeConversion = true;
3206       FromQuals.removeObjCLifetime();
3207       ToQuals.removeObjCLifetime();
3208     } else {
3209       // Qualification conversions cannot cast between different
3210       // Objective-C lifetime qualifiers.
3211       return false;
3212     }
3213   }
3214 
3215   // Allow addition/removal of GC attributes but not changing GC attributes.
3216   if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3217       (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3218     FromQuals.removeObjCGCAttr();
3219     ToQuals.removeObjCGCAttr();
3220   }
3221 
3222   //   -- for every j > 0, if const is in cv 1,j then const is in cv
3223   //      2,j, and similarly for volatile.
3224   if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3225     return false;
3226 
3227   // If address spaces mismatch:
3228   //  - in top level it is only valid to convert to addr space that is a
3229   //    superset in all cases apart from C-style casts where we allow
3230   //    conversions between overlapping address spaces.
3231   //  - in non-top levels it is not a valid conversion.
3232   if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3233       (!IsTopLevel ||
3234        !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3235          (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3236     return false;
3237 
3238   //   -- if the cv 1,j and cv 2,j are different, then const is in
3239   //      every cv for 0 < k < j.
3240   if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3241       !PreviousToQualsIncludeConst)
3242     return false;
3243 
3244   // The following wording is from C++20, where the result of the conversion
3245   // is T3, not T2.
3246   //   -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3247   //      "array of unknown bound of"
3248   if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3249     return false;
3250 
3251   //   -- if the resulting P3,i is different from P1,i [...], then const is
3252   //      added to every cv 3_k for 0 < k < i.
3253   if (!CStyle && FromType->isConstantArrayType() &&
3254       ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3255     return false;
3256 
3257   // Keep track of whether all prior cv-qualifiers in the "to" type
3258   // include const.
3259   PreviousToQualsIncludeConst =
3260       PreviousToQualsIncludeConst && ToQuals.hasConst();
3261   return true;
3262 }
3263 
3264 /// IsQualificationConversion - Determines whether the conversion from
3265 /// an rvalue of type FromType to ToType is a qualification conversion
3266 /// (C++ 4.4).
3267 ///
3268 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3269 /// when the qualification conversion involves a change in the Objective-C
3270 /// object lifetime.
3271 bool
3272 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3273                                 bool CStyle, bool &ObjCLifetimeConversion) {
3274   FromType = Context.getCanonicalType(FromType);
3275   ToType = Context.getCanonicalType(ToType);
3276   ObjCLifetimeConversion = false;
3277 
3278   // If FromType and ToType are the same type, this is not a
3279   // qualification conversion.
3280   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3281     return false;
3282 
3283   // (C++ 4.4p4):
3284   //   A conversion can add cv-qualifiers at levels other than the first
3285   //   in multi-level pointers, subject to the following rules: [...]
3286   bool PreviousToQualsIncludeConst = true;
3287   bool UnwrappedAnyPointer = false;
3288   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3289     if (!isQualificationConversionStep(
3290             FromType, ToType, CStyle, !UnwrappedAnyPointer,
3291             PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3292       return false;
3293     UnwrappedAnyPointer = true;
3294   }
3295 
3296   // We are left with FromType and ToType being the pointee types
3297   // after unwrapping the original FromType and ToType the same number
3298   // of times. If we unwrapped any pointers, and if FromType and
3299   // ToType have the same unqualified type (since we checked
3300   // qualifiers above), then this is a qualification conversion.
3301   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3302 }
3303 
3304 /// - Determine whether this is a conversion from a scalar type to an
3305 /// atomic type.
3306 ///
3307 /// If successful, updates \c SCS's second and third steps in the conversion
3308 /// sequence to finish the conversion.
3309 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3310                                 bool InOverloadResolution,
3311                                 StandardConversionSequence &SCS,
3312                                 bool CStyle) {
3313   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3314   if (!ToAtomic)
3315     return false;
3316 
3317   StandardConversionSequence InnerSCS;
3318   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3319                             InOverloadResolution, InnerSCS,
3320                             CStyle, /*AllowObjCWritebackConversion=*/false))
3321     return false;
3322 
3323   SCS.Second = InnerSCS.Second;
3324   SCS.setToType(1, InnerSCS.getToType(1));
3325   SCS.Third = InnerSCS.Third;
3326   SCS.QualificationIncludesObjCLifetime
3327     = InnerSCS.QualificationIncludesObjCLifetime;
3328   SCS.setToType(2, InnerSCS.getToType(2));
3329   return true;
3330 }
3331 
3332 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3333                                               CXXConstructorDecl *Constructor,
3334                                               QualType Type) {
3335   const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3336   if (CtorType->getNumParams() > 0) {
3337     QualType FirstArg = CtorType->getParamType(0);
3338     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3339       return true;
3340   }
3341   return false;
3342 }
3343 
3344 static OverloadingResult
3345 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3346                                        CXXRecordDecl *To,
3347                                        UserDefinedConversionSequence &User,
3348                                        OverloadCandidateSet &CandidateSet,
3349                                        bool AllowExplicit) {
3350   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3351   for (auto *D : S.LookupConstructors(To)) {
3352     auto Info = getConstructorInfo(D);
3353     if (!Info)
3354       continue;
3355 
3356     bool Usable = !Info.Constructor->isInvalidDecl() &&
3357                   S.isInitListConstructor(Info.Constructor);
3358     if (Usable) {
3359       bool SuppressUserConversions = false;
3360       if (Info.ConstructorTmpl)
3361         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3362                                        /*ExplicitArgs*/ nullptr, From,
3363                                        CandidateSet, SuppressUserConversions,
3364                                        /*PartialOverloading*/ false,
3365                                        AllowExplicit);
3366       else
3367         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3368                                CandidateSet, SuppressUserConversions,
3369                                /*PartialOverloading*/ false, AllowExplicit);
3370     }
3371   }
3372 
3373   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3374 
3375   OverloadCandidateSet::iterator Best;
3376   switch (auto Result =
3377               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3378   case OR_Deleted:
3379   case OR_Success: {
3380     // Record the standard conversion we used and the conversion function.
3381     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3382     QualType ThisType = Constructor->getThisType();
3383     // Initializer lists don't have conversions as such.
3384     User.Before.setAsIdentityConversion();
3385     User.HadMultipleCandidates = HadMultipleCandidates;
3386     User.ConversionFunction = Constructor;
3387     User.FoundConversionFunction = Best->FoundDecl;
3388     User.After.setAsIdentityConversion();
3389     User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3390     User.After.setAllToTypes(ToType);
3391     return Result;
3392   }
3393 
3394   case OR_No_Viable_Function:
3395     return OR_No_Viable_Function;
3396   case OR_Ambiguous:
3397     return OR_Ambiguous;
3398   }
3399 
3400   llvm_unreachable("Invalid OverloadResult!");
3401 }
3402 
3403 /// Determines whether there is a user-defined conversion sequence
3404 /// (C++ [over.ics.user]) that converts expression From to the type
3405 /// ToType. If such a conversion exists, User will contain the
3406 /// user-defined conversion sequence that performs such a conversion
3407 /// and this routine will return true. Otherwise, this routine returns
3408 /// false and User is unspecified.
3409 ///
3410 /// \param AllowExplicit  true if the conversion should consider C++0x
3411 /// "explicit" conversion functions as well as non-explicit conversion
3412 /// functions (C++0x [class.conv.fct]p2).
3413 ///
3414 /// \param AllowObjCConversionOnExplicit true if the conversion should
3415 /// allow an extra Objective-C pointer conversion on uses of explicit
3416 /// constructors. Requires \c AllowExplicit to also be set.
3417 static OverloadingResult
3418 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3419                         UserDefinedConversionSequence &User,
3420                         OverloadCandidateSet &CandidateSet,
3421                         AllowedExplicit AllowExplicit,
3422                         bool AllowObjCConversionOnExplicit) {
3423   assert(AllowExplicit != AllowedExplicit::None ||
3424          !AllowObjCConversionOnExplicit);
3425   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3426 
3427   // Whether we will only visit constructors.
3428   bool ConstructorsOnly = false;
3429 
3430   // If the type we are conversion to is a class type, enumerate its
3431   // constructors.
3432   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3433     // C++ [over.match.ctor]p1:
3434     //   When objects of class type are direct-initialized (8.5), or
3435     //   copy-initialized from an expression of the same or a
3436     //   derived class type (8.5), overload resolution selects the
3437     //   constructor. [...] For copy-initialization, the candidate
3438     //   functions are all the converting constructors (12.3.1) of
3439     //   that class. The argument list is the expression-list within
3440     //   the parentheses of the initializer.
3441     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3442         (From->getType()->getAs<RecordType>() &&
3443          S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3444       ConstructorsOnly = true;
3445 
3446     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3447       // We're not going to find any constructors.
3448     } else if (CXXRecordDecl *ToRecordDecl
3449                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3450 
3451       Expr **Args = &From;
3452       unsigned NumArgs = 1;
3453       bool ListInitializing = false;
3454       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3455         // But first, see if there is an init-list-constructor that will work.
3456         OverloadingResult Result = IsInitializerListConstructorConversion(
3457             S, From, ToType, ToRecordDecl, User, CandidateSet,
3458             AllowExplicit == AllowedExplicit::All);
3459         if (Result != OR_No_Viable_Function)
3460           return Result;
3461         // Never mind.
3462         CandidateSet.clear(
3463             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3464 
3465         // If we're list-initializing, we pass the individual elements as
3466         // arguments, not the entire list.
3467         Args = InitList->getInits();
3468         NumArgs = InitList->getNumInits();
3469         ListInitializing = true;
3470       }
3471 
3472       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3473         auto Info = getConstructorInfo(D);
3474         if (!Info)
3475           continue;
3476 
3477         bool Usable = !Info.Constructor->isInvalidDecl();
3478         if (!ListInitializing)
3479           Usable = Usable && Info.Constructor->isConvertingConstructor(
3480                                  /*AllowExplicit*/ true);
3481         if (Usable) {
3482           bool SuppressUserConversions = !ConstructorsOnly;
3483           // C++20 [over.best.ics.general]/4.5:
3484           //   if the target is the first parameter of a constructor [of class
3485           //   X] and the constructor [...] is a candidate by [...] the second
3486           //   phase of [over.match.list] when the initializer list has exactly
3487           //   one element that is itself an initializer list, [...] and the
3488           //   conversion is to X or reference to cv X, user-defined conversion
3489           //   sequences are not cnosidered.
3490           if (SuppressUserConversions && ListInitializing) {
3491             SuppressUserConversions =
3492                 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
3493                 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3494                                                   ToType);
3495           }
3496           if (Info.ConstructorTmpl)
3497             S.AddTemplateOverloadCandidate(
3498                 Info.ConstructorTmpl, Info.FoundDecl,
3499                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3500                 CandidateSet, SuppressUserConversions,
3501                 /*PartialOverloading*/ false,
3502                 AllowExplicit == AllowedExplicit::All);
3503           else
3504             // Allow one user-defined conversion when user specifies a
3505             // From->ToType conversion via an static cast (c-style, etc).
3506             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3507                                    llvm::makeArrayRef(Args, NumArgs),
3508                                    CandidateSet, SuppressUserConversions,
3509                                    /*PartialOverloading*/ false,
3510                                    AllowExplicit == AllowedExplicit::All);
3511         }
3512       }
3513     }
3514   }
3515 
3516   // Enumerate conversion functions, if we're allowed to.
3517   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3518   } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3519     // No conversion functions from incomplete types.
3520   } else if (const RecordType *FromRecordType =
3521                  From->getType()->getAs<RecordType>()) {
3522     if (CXXRecordDecl *FromRecordDecl
3523          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3524       // Add all of the conversion functions as candidates.
3525       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3526       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3527         DeclAccessPair FoundDecl = I.getPair();
3528         NamedDecl *D = FoundDecl.getDecl();
3529         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3530         if (isa<UsingShadowDecl>(D))
3531           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3532 
3533         CXXConversionDecl *Conv;
3534         FunctionTemplateDecl *ConvTemplate;
3535         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3536           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3537         else
3538           Conv = cast<CXXConversionDecl>(D);
3539 
3540         if (ConvTemplate)
3541           S.AddTemplateConversionCandidate(
3542               ConvTemplate, FoundDecl, ActingContext, From, ToType,
3543               CandidateSet, AllowObjCConversionOnExplicit,
3544               AllowExplicit != AllowedExplicit::None);
3545         else
3546           S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3547                                    CandidateSet, AllowObjCConversionOnExplicit,
3548                                    AllowExplicit != AllowedExplicit::None);
3549       }
3550     }
3551   }
3552 
3553   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3554 
3555   OverloadCandidateSet::iterator Best;
3556   switch (auto Result =
3557               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3558   case OR_Success:
3559   case OR_Deleted:
3560     // Record the standard conversion we used and the conversion function.
3561     if (CXXConstructorDecl *Constructor
3562           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3563       // C++ [over.ics.user]p1:
3564       //   If the user-defined conversion is specified by a
3565       //   constructor (12.3.1), the initial standard conversion
3566       //   sequence converts the source type to the type required by
3567       //   the argument of the constructor.
3568       //
3569       QualType ThisType = Constructor->getThisType();
3570       if (isa<InitListExpr>(From)) {
3571         // Initializer lists don't have conversions as such.
3572         User.Before.setAsIdentityConversion();
3573       } else {
3574         if (Best->Conversions[0].isEllipsis())
3575           User.EllipsisConversion = true;
3576         else {
3577           User.Before = Best->Conversions[0].Standard;
3578           User.EllipsisConversion = false;
3579         }
3580       }
3581       User.HadMultipleCandidates = HadMultipleCandidates;
3582       User.ConversionFunction = Constructor;
3583       User.FoundConversionFunction = Best->FoundDecl;
3584       User.After.setAsIdentityConversion();
3585       User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3586       User.After.setAllToTypes(ToType);
3587       return Result;
3588     }
3589     if (CXXConversionDecl *Conversion
3590                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3591       // C++ [over.ics.user]p1:
3592       //
3593       //   [...] If the user-defined conversion is specified by a
3594       //   conversion function (12.3.2), the initial standard
3595       //   conversion sequence converts the source type to the
3596       //   implicit object parameter of the conversion function.
3597       User.Before = Best->Conversions[0].Standard;
3598       User.HadMultipleCandidates = HadMultipleCandidates;
3599       User.ConversionFunction = Conversion;
3600       User.FoundConversionFunction = Best->FoundDecl;
3601       User.EllipsisConversion = false;
3602 
3603       // C++ [over.ics.user]p2:
3604       //   The second standard conversion sequence converts the
3605       //   result of the user-defined conversion to the target type
3606       //   for the sequence. Since an implicit conversion sequence
3607       //   is an initialization, the special rules for
3608       //   initialization by user-defined conversion apply when
3609       //   selecting the best user-defined conversion for a
3610       //   user-defined conversion sequence (see 13.3.3 and
3611       //   13.3.3.1).
3612       User.After = Best->FinalConversion;
3613       return Result;
3614     }
3615     llvm_unreachable("Not a constructor or conversion function?");
3616 
3617   case OR_No_Viable_Function:
3618     return OR_No_Viable_Function;
3619 
3620   case OR_Ambiguous:
3621     return OR_Ambiguous;
3622   }
3623 
3624   llvm_unreachable("Invalid OverloadResult!");
3625 }
3626 
3627 bool
3628 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3629   ImplicitConversionSequence ICS;
3630   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3631                                     OverloadCandidateSet::CSK_Normal);
3632   OverloadingResult OvResult =
3633     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3634                             CandidateSet, AllowedExplicit::None, false);
3635 
3636   if (!(OvResult == OR_Ambiguous ||
3637         (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3638     return false;
3639 
3640   auto Cands = CandidateSet.CompleteCandidates(
3641       *this,
3642       OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3643       From);
3644   if (OvResult == OR_Ambiguous)
3645     Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3646         << From->getType() << ToType << From->getSourceRange();
3647   else { // OR_No_Viable_Function && !CandidateSet.empty()
3648     if (!RequireCompleteType(From->getBeginLoc(), ToType,
3649                              diag::err_typecheck_nonviable_condition_incomplete,
3650                              From->getType(), From->getSourceRange()))
3651       Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3652           << false << From->getType() << From->getSourceRange() << ToType;
3653   }
3654 
3655   CandidateSet.NoteCandidates(
3656                               *this, From, Cands);
3657   return true;
3658 }
3659 
3660 // Helper for compareConversionFunctions that gets the FunctionType that the
3661 // conversion-operator return  value 'points' to, or nullptr.
3662 static const FunctionType *
3663 getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
3664   const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
3665   const PointerType *RetPtrTy =
3666       ConvFuncTy->getReturnType()->getAs<PointerType>();
3667 
3668   if (!RetPtrTy)
3669     return nullptr;
3670 
3671   return RetPtrTy->getPointeeType()->getAs<FunctionType>();
3672 }
3673 
3674 /// Compare the user-defined conversion functions or constructors
3675 /// of two user-defined conversion sequences to determine whether any ordering
3676 /// is possible.
3677 static ImplicitConversionSequence::CompareKind
3678 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3679                            FunctionDecl *Function2) {
3680   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3681   CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
3682   if (!Conv1 || !Conv2)
3683     return ImplicitConversionSequence::Indistinguishable;
3684 
3685   if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
3686     return ImplicitConversionSequence::Indistinguishable;
3687 
3688   // Objective-C++:
3689   //   If both conversion functions are implicitly-declared conversions from
3690   //   a lambda closure type to a function pointer and a block pointer,
3691   //   respectively, always prefer the conversion to a function pointer,
3692   //   because the function pointer is more lightweight and is more likely
3693   //   to keep code working.
3694   if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
3695     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3696     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3697     if (Block1 != Block2)
3698       return Block1 ? ImplicitConversionSequence::Worse
3699                     : ImplicitConversionSequence::Better;
3700   }
3701 
3702   // In order to support multiple calling conventions for the lambda conversion
3703   // operator (such as when the free and member function calling convention is
3704   // different), prefer the 'free' mechanism, followed by the calling-convention
3705   // of operator(). The latter is in place to support the MSVC-like solution of
3706   // defining ALL of the possible conversions in regards to calling-convention.
3707   const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
3708   const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
3709 
3710   if (Conv1FuncRet && Conv2FuncRet &&
3711       Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
3712     CallingConv Conv1CC = Conv1FuncRet->getCallConv();
3713     CallingConv Conv2CC = Conv2FuncRet->getCallConv();
3714 
3715     CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
3716     const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
3717 
3718     CallingConv CallOpCC =
3719         CallOp->getType()->castAs<FunctionType>()->getCallConv();
3720     CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
3721         CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
3722     CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
3723         CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
3724 
3725     CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
3726     for (CallingConv CC : PrefOrder) {
3727       if (Conv1CC == CC)
3728         return ImplicitConversionSequence::Better;
3729       if (Conv2CC == CC)
3730         return ImplicitConversionSequence::Worse;
3731     }
3732   }
3733 
3734   return ImplicitConversionSequence::Indistinguishable;
3735 }
3736 
3737 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3738     const ImplicitConversionSequence &ICS) {
3739   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3740          (ICS.isUserDefined() &&
3741           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3742 }
3743 
3744 /// CompareImplicitConversionSequences - Compare two implicit
3745 /// conversion sequences to determine whether one is better than the
3746 /// other or if they are indistinguishable (C++ 13.3.3.2).
3747 static ImplicitConversionSequence::CompareKind
3748 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3749                                    const ImplicitConversionSequence& ICS1,
3750                                    const ImplicitConversionSequence& ICS2)
3751 {
3752   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3753   // conversion sequences (as defined in 13.3.3.1)
3754   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3755   //      conversion sequence than a user-defined conversion sequence or
3756   //      an ellipsis conversion sequence, and
3757   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3758   //      conversion sequence than an ellipsis conversion sequence
3759   //      (13.3.3.1.3).
3760   //
3761   // C++0x [over.best.ics]p10:
3762   //   For the purpose of ranking implicit conversion sequences as
3763   //   described in 13.3.3.2, the ambiguous conversion sequence is
3764   //   treated as a user-defined sequence that is indistinguishable
3765   //   from any other user-defined conversion sequence.
3766 
3767   // String literal to 'char *' conversion has been deprecated in C++03. It has
3768   // been removed from C++11. We still accept this conversion, if it happens at
3769   // the best viable function. Otherwise, this conversion is considered worse
3770   // than ellipsis conversion. Consider this as an extension; this is not in the
3771   // standard. For example:
3772   //
3773   // int &f(...);    // #1
3774   // void f(char*);  // #2
3775   // void g() { int &r = f("foo"); }
3776   //
3777   // In C++03, we pick #2 as the best viable function.
3778   // In C++11, we pick #1 as the best viable function, because ellipsis
3779   // conversion is better than string-literal to char* conversion (since there
3780   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3781   // convert arguments, #2 would be the best viable function in C++11.
3782   // If the best viable function has this conversion, a warning will be issued
3783   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3784 
3785   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3786       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3787           hasDeprecatedStringLiteralToCharPtrConversion(ICS2) &&
3788       // Ill-formedness must not differ
3789       ICS1.isBad() == ICS2.isBad())
3790     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3791                ? ImplicitConversionSequence::Worse
3792                : ImplicitConversionSequence::Better;
3793 
3794   if (ICS1.getKindRank() < ICS2.getKindRank())
3795     return ImplicitConversionSequence::Better;
3796   if (ICS2.getKindRank() < ICS1.getKindRank())
3797     return ImplicitConversionSequence::Worse;
3798 
3799   // The following checks require both conversion sequences to be of
3800   // the same kind.
3801   if (ICS1.getKind() != ICS2.getKind())
3802     return ImplicitConversionSequence::Indistinguishable;
3803 
3804   ImplicitConversionSequence::CompareKind Result =
3805       ImplicitConversionSequence::Indistinguishable;
3806 
3807   // Two implicit conversion sequences of the same form are
3808   // indistinguishable conversion sequences unless one of the
3809   // following rules apply: (C++ 13.3.3.2p3):
3810 
3811   // List-initialization sequence L1 is a better conversion sequence than
3812   // list-initialization sequence L2 if:
3813   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3814   //   if not that,
3815   // — L1 and L2 convert to arrays of the same element type, and either the
3816   //   number of elements n_1 initialized by L1 is less than the number of
3817   //   elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
3818   //   an array of unknown bound and L1 does not,
3819   // even if one of the other rules in this paragraph would otherwise apply.
3820   if (!ICS1.isBad()) {
3821     bool StdInit1 = false, StdInit2 = false;
3822     if (ICS1.hasInitializerListContainerType())
3823       StdInit1 = S.isStdInitializerList(ICS1.getInitializerListContainerType(),
3824                                         nullptr);
3825     if (ICS2.hasInitializerListContainerType())
3826       StdInit2 = S.isStdInitializerList(ICS2.getInitializerListContainerType(),
3827                                         nullptr);
3828     if (StdInit1 != StdInit2)
3829       return StdInit1 ? ImplicitConversionSequence::Better
3830                       : ImplicitConversionSequence::Worse;
3831 
3832     if (ICS1.hasInitializerListContainerType() &&
3833         ICS2.hasInitializerListContainerType())
3834       if (auto *CAT1 = S.Context.getAsConstantArrayType(
3835               ICS1.getInitializerListContainerType()))
3836         if (auto *CAT2 = S.Context.getAsConstantArrayType(
3837                 ICS2.getInitializerListContainerType())) {
3838           if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
3839                                                CAT2->getElementType())) {
3840             // Both to arrays of the same element type
3841             if (CAT1->getSize() != CAT2->getSize())
3842               // Different sized, the smaller wins
3843               return CAT1->getSize().ult(CAT2->getSize())
3844                          ? ImplicitConversionSequence::Better
3845                          : ImplicitConversionSequence::Worse;
3846             if (ICS1.isInitializerListOfIncompleteArray() !=
3847                 ICS2.isInitializerListOfIncompleteArray())
3848               // One is incomplete, it loses
3849               return ICS2.isInitializerListOfIncompleteArray()
3850                          ? ImplicitConversionSequence::Better
3851                          : ImplicitConversionSequence::Worse;
3852           }
3853         }
3854   }
3855 
3856   if (ICS1.isStandard())
3857     // Standard conversion sequence S1 is a better conversion sequence than
3858     // standard conversion sequence S2 if [...]
3859     Result = CompareStandardConversionSequences(S, Loc,
3860                                                 ICS1.Standard, ICS2.Standard);
3861   else if (ICS1.isUserDefined()) {
3862     // User-defined conversion sequence U1 is a better conversion
3863     // sequence than another user-defined conversion sequence U2 if
3864     // they contain the same user-defined conversion function or
3865     // constructor and if the second standard conversion sequence of
3866     // U1 is better than the second standard conversion sequence of
3867     // U2 (C++ 13.3.3.2p3).
3868     if (ICS1.UserDefined.ConversionFunction ==
3869           ICS2.UserDefined.ConversionFunction)
3870       Result = CompareStandardConversionSequences(S, Loc,
3871                                                   ICS1.UserDefined.After,
3872                                                   ICS2.UserDefined.After);
3873     else
3874       Result = compareConversionFunctions(S,
3875                                           ICS1.UserDefined.ConversionFunction,
3876                                           ICS2.UserDefined.ConversionFunction);
3877   }
3878 
3879   return Result;
3880 }
3881 
3882 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3883 // determine if one is a proper subset of the other.
3884 static ImplicitConversionSequence::CompareKind
3885 compareStandardConversionSubsets(ASTContext &Context,
3886                                  const StandardConversionSequence& SCS1,
3887                                  const StandardConversionSequence& SCS2) {
3888   ImplicitConversionSequence::CompareKind Result
3889     = ImplicitConversionSequence::Indistinguishable;
3890 
3891   // the identity conversion sequence is considered to be a subsequence of
3892   // any non-identity conversion sequence
3893   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3894     return ImplicitConversionSequence::Better;
3895   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3896     return ImplicitConversionSequence::Worse;
3897 
3898   if (SCS1.Second != SCS2.Second) {
3899     if (SCS1.Second == ICK_Identity)
3900       Result = ImplicitConversionSequence::Better;
3901     else if (SCS2.Second == ICK_Identity)
3902       Result = ImplicitConversionSequence::Worse;
3903     else
3904       return ImplicitConversionSequence::Indistinguishable;
3905   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3906     return ImplicitConversionSequence::Indistinguishable;
3907 
3908   if (SCS1.Third == SCS2.Third) {
3909     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3910                              : ImplicitConversionSequence::Indistinguishable;
3911   }
3912 
3913   if (SCS1.Third == ICK_Identity)
3914     return Result == ImplicitConversionSequence::Worse
3915              ? ImplicitConversionSequence::Indistinguishable
3916              : ImplicitConversionSequence::Better;
3917 
3918   if (SCS2.Third == ICK_Identity)
3919     return Result == ImplicitConversionSequence::Better
3920              ? ImplicitConversionSequence::Indistinguishable
3921              : ImplicitConversionSequence::Worse;
3922 
3923   return ImplicitConversionSequence::Indistinguishable;
3924 }
3925 
3926 /// Determine whether one of the given reference bindings is better
3927 /// than the other based on what kind of bindings they are.
3928 static bool
3929 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3930                              const StandardConversionSequence &SCS2) {
3931   // C++0x [over.ics.rank]p3b4:
3932   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3933   //      implicit object parameter of a non-static member function declared
3934   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3935   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3936   //      lvalue reference to a function lvalue and S2 binds an rvalue
3937   //      reference*.
3938   //
3939   // FIXME: Rvalue references. We're going rogue with the above edits,
3940   // because the semantics in the current C++0x working paper (N3225 at the
3941   // time of this writing) break the standard definition of std::forward
3942   // and std::reference_wrapper when dealing with references to functions.
3943   // Proposed wording changes submitted to CWG for consideration.
3944   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3945       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3946     return false;
3947 
3948   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3949           SCS2.IsLvalueReference) ||
3950          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3951           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3952 }
3953 
3954 enum class FixedEnumPromotion {
3955   None,
3956   ToUnderlyingType,
3957   ToPromotedUnderlyingType
3958 };
3959 
3960 /// Returns kind of fixed enum promotion the \a SCS uses.
3961 static FixedEnumPromotion
3962 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
3963 
3964   if (SCS.Second != ICK_Integral_Promotion)
3965     return FixedEnumPromotion::None;
3966 
3967   QualType FromType = SCS.getFromType();
3968   if (!FromType->isEnumeralType())
3969     return FixedEnumPromotion::None;
3970 
3971   EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
3972   if (!Enum->isFixed())
3973     return FixedEnumPromotion::None;
3974 
3975   QualType UnderlyingType = Enum->getIntegerType();
3976   if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
3977     return FixedEnumPromotion::ToUnderlyingType;
3978 
3979   return FixedEnumPromotion::ToPromotedUnderlyingType;
3980 }
3981 
3982 /// CompareStandardConversionSequences - Compare two standard
3983 /// conversion sequences to determine whether one is better than the
3984 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3985 static ImplicitConversionSequence::CompareKind
3986 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3987                                    const StandardConversionSequence& SCS1,
3988                                    const StandardConversionSequence& SCS2)
3989 {
3990   // Standard conversion sequence S1 is a better conversion sequence
3991   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3992 
3993   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3994   //     sequences in the canonical form defined by 13.3.3.1.1,
3995   //     excluding any Lvalue Transformation; the identity conversion
3996   //     sequence is considered to be a subsequence of any
3997   //     non-identity conversion sequence) or, if not that,
3998   if (ImplicitConversionSequence::CompareKind CK
3999         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
4000     return CK;
4001 
4002   //  -- the rank of S1 is better than the rank of S2 (by the rules
4003   //     defined below), or, if not that,
4004   ImplicitConversionRank Rank1 = SCS1.getRank();
4005   ImplicitConversionRank Rank2 = SCS2.getRank();
4006   if (Rank1 < Rank2)
4007     return ImplicitConversionSequence::Better;
4008   else if (Rank2 < Rank1)
4009     return ImplicitConversionSequence::Worse;
4010 
4011   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4012   // are indistinguishable unless one of the following rules
4013   // applies:
4014 
4015   //   A conversion that is not a conversion of a pointer, or
4016   //   pointer to member, to bool is better than another conversion
4017   //   that is such a conversion.
4018   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4019     return SCS2.isPointerConversionToBool()
4020              ? ImplicitConversionSequence::Better
4021              : ImplicitConversionSequence::Worse;
4022 
4023   // C++14 [over.ics.rank]p4b2:
4024   // This is retroactively applied to C++11 by CWG 1601.
4025   //
4026   //   A conversion that promotes an enumeration whose underlying type is fixed
4027   //   to its underlying type is better than one that promotes to the promoted
4028   //   underlying type, if the two are different.
4029   FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
4030   FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
4031   if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4032       FEP1 != FEP2)
4033     return FEP1 == FixedEnumPromotion::ToUnderlyingType
4034                ? ImplicitConversionSequence::Better
4035                : ImplicitConversionSequence::Worse;
4036 
4037   // C++ [over.ics.rank]p4b2:
4038   //
4039   //   If class B is derived directly or indirectly from class A,
4040   //   conversion of B* to A* is better than conversion of B* to
4041   //   void*, and conversion of A* to void* is better than conversion
4042   //   of B* to void*.
4043   bool SCS1ConvertsToVoid
4044     = SCS1.isPointerConversionToVoidPointer(S.Context);
4045   bool SCS2ConvertsToVoid
4046     = SCS2.isPointerConversionToVoidPointer(S.Context);
4047   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4048     // Exactly one of the conversion sequences is a conversion to
4049     // a void pointer; it's the worse conversion.
4050     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4051                               : ImplicitConversionSequence::Worse;
4052   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4053     // Neither conversion sequence converts to a void pointer; compare
4054     // their derived-to-base conversions.
4055     if (ImplicitConversionSequence::CompareKind DerivedCK
4056           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4057       return DerivedCK;
4058   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4059              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4060     // Both conversion sequences are conversions to void
4061     // pointers. Compare the source types to determine if there's an
4062     // inheritance relationship in their sources.
4063     QualType FromType1 = SCS1.getFromType();
4064     QualType FromType2 = SCS2.getFromType();
4065 
4066     // Adjust the types we're converting from via the array-to-pointer
4067     // conversion, if we need to.
4068     if (SCS1.First == ICK_Array_To_Pointer)
4069       FromType1 = S.Context.getArrayDecayedType(FromType1);
4070     if (SCS2.First == ICK_Array_To_Pointer)
4071       FromType2 = S.Context.getArrayDecayedType(FromType2);
4072 
4073     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4074     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4075 
4076     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4077       return ImplicitConversionSequence::Better;
4078     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4079       return ImplicitConversionSequence::Worse;
4080 
4081     // Objective-C++: If one interface is more specific than the
4082     // other, it is the better one.
4083     const ObjCObjectPointerType* FromObjCPtr1
4084       = FromType1->getAs<ObjCObjectPointerType>();
4085     const ObjCObjectPointerType* FromObjCPtr2
4086       = FromType2->getAs<ObjCObjectPointerType>();
4087     if (FromObjCPtr1 && FromObjCPtr2) {
4088       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4089                                                           FromObjCPtr2);
4090       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4091                                                            FromObjCPtr1);
4092       if (AssignLeft != AssignRight) {
4093         return AssignLeft? ImplicitConversionSequence::Better
4094                          : ImplicitConversionSequence::Worse;
4095       }
4096     }
4097   }
4098 
4099   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4100     // Check for a better reference binding based on the kind of bindings.
4101     if (isBetterReferenceBindingKind(SCS1, SCS2))
4102       return ImplicitConversionSequence::Better;
4103     else if (isBetterReferenceBindingKind(SCS2, SCS1))
4104       return ImplicitConversionSequence::Worse;
4105   }
4106 
4107   // Compare based on qualification conversions (C++ 13.3.3.2p3,
4108   // bullet 3).
4109   if (ImplicitConversionSequence::CompareKind QualCK
4110         = CompareQualificationConversions(S, SCS1, SCS2))
4111     return QualCK;
4112 
4113   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4114     // C++ [over.ics.rank]p3b4:
4115     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
4116     //      which the references refer are the same type except for
4117     //      top-level cv-qualifiers, and the type to which the reference
4118     //      initialized by S2 refers is more cv-qualified than the type
4119     //      to which the reference initialized by S1 refers.
4120     QualType T1 = SCS1.getToType(2);
4121     QualType T2 = SCS2.getToType(2);
4122     T1 = S.Context.getCanonicalType(T1);
4123     T2 = S.Context.getCanonicalType(T2);
4124     Qualifiers T1Quals, T2Quals;
4125     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4126     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4127     if (UnqualT1 == UnqualT2) {
4128       // Objective-C++ ARC: If the references refer to objects with different
4129       // lifetimes, prefer bindings that don't change lifetime.
4130       if (SCS1.ObjCLifetimeConversionBinding !=
4131                                           SCS2.ObjCLifetimeConversionBinding) {
4132         return SCS1.ObjCLifetimeConversionBinding
4133                                            ? ImplicitConversionSequence::Worse
4134                                            : ImplicitConversionSequence::Better;
4135       }
4136 
4137       // If the type is an array type, promote the element qualifiers to the
4138       // type for comparison.
4139       if (isa<ArrayType>(T1) && T1Quals)
4140         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4141       if (isa<ArrayType>(T2) && T2Quals)
4142         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4143       if (T2.isMoreQualifiedThan(T1))
4144         return ImplicitConversionSequence::Better;
4145       if (T1.isMoreQualifiedThan(T2))
4146         return ImplicitConversionSequence::Worse;
4147     }
4148   }
4149 
4150   // In Microsoft mode (below 19.28), prefer an integral conversion to a
4151   // floating-to-integral conversion if the integral conversion
4152   // is between types of the same size.
4153   // For example:
4154   // void f(float);
4155   // void f(int);
4156   // int main {
4157   //    long a;
4158   //    f(a);
4159   // }
4160   // Here, MSVC will call f(int) instead of generating a compile error
4161   // as clang will do in standard mode.
4162   if (S.getLangOpts().MSVCCompat &&
4163       !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) &&
4164       SCS1.Second == ICK_Integral_Conversion &&
4165       SCS2.Second == ICK_Floating_Integral &&
4166       S.Context.getTypeSize(SCS1.getFromType()) ==
4167           S.Context.getTypeSize(SCS1.getToType(2)))
4168     return ImplicitConversionSequence::Better;
4169 
4170   // Prefer a compatible vector conversion over a lax vector conversion
4171   // For example:
4172   //
4173   // typedef float __v4sf __attribute__((__vector_size__(16)));
4174   // void f(vector float);
4175   // void f(vector signed int);
4176   // int main() {
4177   //   __v4sf a;
4178   //   f(a);
4179   // }
4180   // Here, we'd like to choose f(vector float) and not
4181   // report an ambiguous call error
4182   if (SCS1.Second == ICK_Vector_Conversion &&
4183       SCS2.Second == ICK_Vector_Conversion) {
4184     bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4185         SCS1.getFromType(), SCS1.getToType(2));
4186     bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4187         SCS2.getFromType(), SCS2.getToType(2));
4188 
4189     if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4190       return SCS1IsCompatibleVectorConversion
4191                  ? ImplicitConversionSequence::Better
4192                  : ImplicitConversionSequence::Worse;
4193   }
4194 
4195   if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4196       SCS2.Second == ICK_SVE_Vector_Conversion) {
4197     bool SCS1IsCompatibleSVEVectorConversion =
4198         S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4199     bool SCS2IsCompatibleSVEVectorConversion =
4200         S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4201 
4202     if (SCS1IsCompatibleSVEVectorConversion !=
4203         SCS2IsCompatibleSVEVectorConversion)
4204       return SCS1IsCompatibleSVEVectorConversion
4205                  ? ImplicitConversionSequence::Better
4206                  : ImplicitConversionSequence::Worse;
4207   }
4208 
4209   return ImplicitConversionSequence::Indistinguishable;
4210 }
4211 
4212 /// CompareQualificationConversions - Compares two standard conversion
4213 /// sequences to determine whether they can be ranked based on their
4214 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4215 static ImplicitConversionSequence::CompareKind
4216 CompareQualificationConversions(Sema &S,
4217                                 const StandardConversionSequence& SCS1,
4218                                 const StandardConversionSequence& SCS2) {
4219   // C++ [over.ics.rank]p3:
4220   //  -- S1 and S2 differ only in their qualification conversion and
4221   //     yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4222   // [C++98]
4223   //     [...] and the cv-qualification signature of type T1 is a proper subset
4224   //     of the cv-qualification signature of type T2, and S1 is not the
4225   //     deprecated string literal array-to-pointer conversion (4.2).
4226   // [C++2a]
4227   //     [...] where T1 can be converted to T2 by a qualification conversion.
4228   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4229       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4230     return ImplicitConversionSequence::Indistinguishable;
4231 
4232   // FIXME: the example in the standard doesn't use a qualification
4233   // conversion (!)
4234   QualType T1 = SCS1.getToType(2);
4235   QualType T2 = SCS2.getToType(2);
4236   T1 = S.Context.getCanonicalType(T1);
4237   T2 = S.Context.getCanonicalType(T2);
4238   assert(!T1->isReferenceType() && !T2->isReferenceType());
4239   Qualifiers T1Quals, T2Quals;
4240   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4241   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4242 
4243   // If the types are the same, we won't learn anything by unwrapping
4244   // them.
4245   if (UnqualT1 == UnqualT2)
4246     return ImplicitConversionSequence::Indistinguishable;
4247 
4248   // Don't ever prefer a standard conversion sequence that uses the deprecated
4249   // string literal array to pointer conversion.
4250   bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4251   bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4252 
4253   // Objective-C++ ARC:
4254   //   Prefer qualification conversions not involving a change in lifetime
4255   //   to qualification conversions that do change lifetime.
4256   if (SCS1.QualificationIncludesObjCLifetime &&
4257       !SCS2.QualificationIncludesObjCLifetime)
4258     CanPick1 = false;
4259   if (SCS2.QualificationIncludesObjCLifetime &&
4260       !SCS1.QualificationIncludesObjCLifetime)
4261     CanPick2 = false;
4262 
4263   bool ObjCLifetimeConversion;
4264   if (CanPick1 &&
4265       !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4266     CanPick1 = false;
4267   // FIXME: In Objective-C ARC, we can have qualification conversions in both
4268   // directions, so we can't short-cut this second check in general.
4269   if (CanPick2 &&
4270       !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4271     CanPick2 = false;
4272 
4273   if (CanPick1 != CanPick2)
4274     return CanPick1 ? ImplicitConversionSequence::Better
4275                     : ImplicitConversionSequence::Worse;
4276   return ImplicitConversionSequence::Indistinguishable;
4277 }
4278 
4279 /// CompareDerivedToBaseConversions - Compares two standard conversion
4280 /// sequences to determine whether they can be ranked based on their
4281 /// various kinds of derived-to-base conversions (C++
4282 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4283 /// conversions between Objective-C interface types.
4284 static ImplicitConversionSequence::CompareKind
4285 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4286                                 const StandardConversionSequence& SCS1,
4287                                 const StandardConversionSequence& SCS2) {
4288   QualType FromType1 = SCS1.getFromType();
4289   QualType ToType1 = SCS1.getToType(1);
4290   QualType FromType2 = SCS2.getFromType();
4291   QualType ToType2 = SCS2.getToType(1);
4292 
4293   // Adjust the types we're converting from via the array-to-pointer
4294   // conversion, if we need to.
4295   if (SCS1.First == ICK_Array_To_Pointer)
4296     FromType1 = S.Context.getArrayDecayedType(FromType1);
4297   if (SCS2.First == ICK_Array_To_Pointer)
4298     FromType2 = S.Context.getArrayDecayedType(FromType2);
4299 
4300   // Canonicalize all of the types.
4301   FromType1 = S.Context.getCanonicalType(FromType1);
4302   ToType1 = S.Context.getCanonicalType(ToType1);
4303   FromType2 = S.Context.getCanonicalType(FromType2);
4304   ToType2 = S.Context.getCanonicalType(ToType2);
4305 
4306   // C++ [over.ics.rank]p4b3:
4307   //
4308   //   If class B is derived directly or indirectly from class A and
4309   //   class C is derived directly or indirectly from B,
4310   //
4311   // Compare based on pointer conversions.
4312   if (SCS1.Second == ICK_Pointer_Conversion &&
4313       SCS2.Second == ICK_Pointer_Conversion &&
4314       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4315       FromType1->isPointerType() && FromType2->isPointerType() &&
4316       ToType1->isPointerType() && ToType2->isPointerType()) {
4317     QualType FromPointee1 =
4318         FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4319     QualType ToPointee1 =
4320         ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4321     QualType FromPointee2 =
4322         FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4323     QualType ToPointee2 =
4324         ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4325 
4326     //   -- conversion of C* to B* is better than conversion of C* to A*,
4327     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4328       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4329         return ImplicitConversionSequence::Better;
4330       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4331         return ImplicitConversionSequence::Worse;
4332     }
4333 
4334     //   -- conversion of B* to A* is better than conversion of C* to A*,
4335     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4336       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4337         return ImplicitConversionSequence::Better;
4338       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4339         return ImplicitConversionSequence::Worse;
4340     }
4341   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4342              SCS2.Second == ICK_Pointer_Conversion) {
4343     const ObjCObjectPointerType *FromPtr1
4344       = FromType1->getAs<ObjCObjectPointerType>();
4345     const ObjCObjectPointerType *FromPtr2
4346       = FromType2->getAs<ObjCObjectPointerType>();
4347     const ObjCObjectPointerType *ToPtr1
4348       = ToType1->getAs<ObjCObjectPointerType>();
4349     const ObjCObjectPointerType *ToPtr2
4350       = ToType2->getAs<ObjCObjectPointerType>();
4351 
4352     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4353       // Apply the same conversion ranking rules for Objective-C pointer types
4354       // that we do for C++ pointers to class types. However, we employ the
4355       // Objective-C pseudo-subtyping relationship used for assignment of
4356       // Objective-C pointer types.
4357       bool FromAssignLeft
4358         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4359       bool FromAssignRight
4360         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4361       bool ToAssignLeft
4362         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4363       bool ToAssignRight
4364         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4365 
4366       // A conversion to an a non-id object pointer type or qualified 'id'
4367       // type is better than a conversion to 'id'.
4368       if (ToPtr1->isObjCIdType() &&
4369           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4370         return ImplicitConversionSequence::Worse;
4371       if (ToPtr2->isObjCIdType() &&
4372           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4373         return ImplicitConversionSequence::Better;
4374 
4375       // A conversion to a non-id object pointer type is better than a
4376       // conversion to a qualified 'id' type
4377       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4378         return ImplicitConversionSequence::Worse;
4379       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4380         return ImplicitConversionSequence::Better;
4381 
4382       // A conversion to an a non-Class object pointer type or qualified 'Class'
4383       // type is better than a conversion to 'Class'.
4384       if (ToPtr1->isObjCClassType() &&
4385           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4386         return ImplicitConversionSequence::Worse;
4387       if (ToPtr2->isObjCClassType() &&
4388           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4389         return ImplicitConversionSequence::Better;
4390 
4391       // A conversion to a non-Class object pointer type is better than a
4392       // conversion to a qualified 'Class' type.
4393       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4394         return ImplicitConversionSequence::Worse;
4395       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4396         return ImplicitConversionSequence::Better;
4397 
4398       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4399       if (S.Context.hasSameType(FromType1, FromType2) &&
4400           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4401           (ToAssignLeft != ToAssignRight)) {
4402         if (FromPtr1->isSpecialized()) {
4403           // "conversion of B<A> * to B * is better than conversion of B * to
4404           // C *.
4405           bool IsFirstSame =
4406               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4407           bool IsSecondSame =
4408               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4409           if (IsFirstSame) {
4410             if (!IsSecondSame)
4411               return ImplicitConversionSequence::Better;
4412           } else if (IsSecondSame)
4413             return ImplicitConversionSequence::Worse;
4414         }
4415         return ToAssignLeft? ImplicitConversionSequence::Worse
4416                            : ImplicitConversionSequence::Better;
4417       }
4418 
4419       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4420       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4421           (FromAssignLeft != FromAssignRight))
4422         return FromAssignLeft? ImplicitConversionSequence::Better
4423         : ImplicitConversionSequence::Worse;
4424     }
4425   }
4426 
4427   // Ranking of member-pointer types.
4428   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4429       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4430       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4431     const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4432     const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4433     const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4434     const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4435     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4436     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4437     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4438     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4439     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4440     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4441     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4442     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4443     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4444     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4445       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4446         return ImplicitConversionSequence::Worse;
4447       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4448         return ImplicitConversionSequence::Better;
4449     }
4450     // conversion of B::* to C::* is better than conversion of A::* to C::*
4451     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4452       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4453         return ImplicitConversionSequence::Better;
4454       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4455         return ImplicitConversionSequence::Worse;
4456     }
4457   }
4458 
4459   if (SCS1.Second == ICK_Derived_To_Base) {
4460     //   -- conversion of C to B is better than conversion of C to A,
4461     //   -- binding of an expression of type C to a reference of type
4462     //      B& is better than binding an expression of type C to a
4463     //      reference of type A&,
4464     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4465         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4466       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4467         return ImplicitConversionSequence::Better;
4468       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4469         return ImplicitConversionSequence::Worse;
4470     }
4471 
4472     //   -- conversion of B to A is better than conversion of C to A.
4473     //   -- binding of an expression of type B to a reference of type
4474     //      A& is better than binding an expression of type C to a
4475     //      reference of type A&,
4476     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4477         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4478       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4479         return ImplicitConversionSequence::Better;
4480       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4481         return ImplicitConversionSequence::Worse;
4482     }
4483   }
4484 
4485   return ImplicitConversionSequence::Indistinguishable;
4486 }
4487 
4488 /// Determine whether the given type is valid, e.g., it is not an invalid
4489 /// C++ class.
4490 static bool isTypeValid(QualType T) {
4491   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4492     return !Record->isInvalidDecl();
4493 
4494   return true;
4495 }
4496 
4497 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4498   if (!T.getQualifiers().hasUnaligned())
4499     return T;
4500 
4501   Qualifiers Q;
4502   T = Ctx.getUnqualifiedArrayType(T, Q);
4503   Q.removeUnaligned();
4504   return Ctx.getQualifiedType(T, Q);
4505 }
4506 
4507 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4508 /// determine whether they are reference-compatible,
4509 /// reference-related, or incompatible, for use in C++ initialization by
4510 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4511 /// type, and the first type (T1) is the pointee type of the reference
4512 /// type being initialized.
4513 Sema::ReferenceCompareResult
4514 Sema::CompareReferenceRelationship(SourceLocation Loc,
4515                                    QualType OrigT1, QualType OrigT2,
4516                                    ReferenceConversions *ConvOut) {
4517   assert(!OrigT1->isReferenceType() &&
4518     "T1 must be the pointee type of the reference type");
4519   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4520 
4521   QualType T1 = Context.getCanonicalType(OrigT1);
4522   QualType T2 = Context.getCanonicalType(OrigT2);
4523   Qualifiers T1Quals, T2Quals;
4524   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4525   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4526 
4527   ReferenceConversions ConvTmp;
4528   ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4529   Conv = ReferenceConversions();
4530 
4531   // C++2a [dcl.init.ref]p4:
4532   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4533   //   reference-related to "cv2 T2" if T1 is similar to T2, or
4534   //   T1 is a base class of T2.
4535   //   "cv1 T1" is reference-compatible with "cv2 T2" if
4536   //   a prvalue of type "pointer to cv2 T2" can be converted to the type
4537   //   "pointer to cv1 T1" via a standard conversion sequence.
4538 
4539   // Check for standard conversions we can apply to pointers: derived-to-base
4540   // conversions, ObjC pointer conversions, and function pointer conversions.
4541   // (Qualification conversions are checked last.)
4542   QualType ConvertedT2;
4543   if (UnqualT1 == UnqualT2) {
4544     // Nothing to do.
4545   } else if (isCompleteType(Loc, OrigT2) &&
4546              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4547              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4548     Conv |= ReferenceConversions::DerivedToBase;
4549   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4550            UnqualT2->isObjCObjectOrInterfaceType() &&
4551            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4552     Conv |= ReferenceConversions::ObjC;
4553   else if (UnqualT2->isFunctionType() &&
4554            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4555     Conv |= ReferenceConversions::Function;
4556     // No need to check qualifiers; function types don't have them.
4557     return Ref_Compatible;
4558   }
4559   bool ConvertedReferent = Conv != 0;
4560 
4561   // We can have a qualification conversion. Compute whether the types are
4562   // similar at the same time.
4563   bool PreviousToQualsIncludeConst = true;
4564   bool TopLevel = true;
4565   do {
4566     if (T1 == T2)
4567       break;
4568 
4569     // We will need a qualification conversion.
4570     Conv |= ReferenceConversions::Qualification;
4571 
4572     // Track whether we performed a qualification conversion anywhere other
4573     // than the top level. This matters for ranking reference bindings in
4574     // overload resolution.
4575     if (!TopLevel)
4576       Conv |= ReferenceConversions::NestedQualification;
4577 
4578     // MS compiler ignores __unaligned qualifier for references; do the same.
4579     T1 = withoutUnaligned(Context, T1);
4580     T2 = withoutUnaligned(Context, T2);
4581 
4582     // If we find a qualifier mismatch, the types are not reference-compatible,
4583     // but are still be reference-related if they're similar.
4584     bool ObjCLifetimeConversion = false;
4585     if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4586                                        PreviousToQualsIncludeConst,
4587                                        ObjCLifetimeConversion))
4588       return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4589                  ? Ref_Related
4590                  : Ref_Incompatible;
4591 
4592     // FIXME: Should we track this for any level other than the first?
4593     if (ObjCLifetimeConversion)
4594       Conv |= ReferenceConversions::ObjCLifetime;
4595 
4596     TopLevel = false;
4597   } while (Context.UnwrapSimilarTypes(T1, T2));
4598 
4599   // At this point, if the types are reference-related, we must either have the
4600   // same inner type (ignoring qualifiers), or must have already worked out how
4601   // to convert the referent.
4602   return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4603              ? Ref_Compatible
4604              : Ref_Incompatible;
4605 }
4606 
4607 /// Look for a user-defined conversion to a value reference-compatible
4608 ///        with DeclType. Return true if something definite is found.
4609 static bool
4610 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4611                          QualType DeclType, SourceLocation DeclLoc,
4612                          Expr *Init, QualType T2, bool AllowRvalues,
4613                          bool AllowExplicit) {
4614   assert(T2->isRecordType() && "Can only find conversions of record types.");
4615   auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4616 
4617   OverloadCandidateSet CandidateSet(
4618       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4619   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4620   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4621     NamedDecl *D = *I;
4622     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4623     if (isa<UsingShadowDecl>(D))
4624       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4625 
4626     FunctionTemplateDecl *ConvTemplate
4627       = dyn_cast<FunctionTemplateDecl>(D);
4628     CXXConversionDecl *Conv;
4629     if (ConvTemplate)
4630       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4631     else
4632       Conv = cast<CXXConversionDecl>(D);
4633 
4634     if (AllowRvalues) {
4635       // If we are initializing an rvalue reference, don't permit conversion
4636       // functions that return lvalues.
4637       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4638         const ReferenceType *RefType
4639           = Conv->getConversionType()->getAs<LValueReferenceType>();
4640         if (RefType && !RefType->getPointeeType()->isFunctionType())
4641           continue;
4642       }
4643 
4644       if (!ConvTemplate &&
4645           S.CompareReferenceRelationship(
4646               DeclLoc,
4647               Conv->getConversionType()
4648                   .getNonReferenceType()
4649                   .getUnqualifiedType(),
4650               DeclType.getNonReferenceType().getUnqualifiedType()) ==
4651               Sema::Ref_Incompatible)
4652         continue;
4653     } else {
4654       // If the conversion function doesn't return a reference type,
4655       // it can't be considered for this conversion. An rvalue reference
4656       // is only acceptable if its referencee is a function type.
4657 
4658       const ReferenceType *RefType =
4659         Conv->getConversionType()->getAs<ReferenceType>();
4660       if (!RefType ||
4661           (!RefType->isLValueReferenceType() &&
4662            !RefType->getPointeeType()->isFunctionType()))
4663         continue;
4664     }
4665 
4666     if (ConvTemplate)
4667       S.AddTemplateConversionCandidate(
4668           ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4669           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4670     else
4671       S.AddConversionCandidate(
4672           Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4673           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4674   }
4675 
4676   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4677 
4678   OverloadCandidateSet::iterator Best;
4679   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4680   case OR_Success:
4681     // C++ [over.ics.ref]p1:
4682     //
4683     //   [...] If the parameter binds directly to the result of
4684     //   applying a conversion function to the argument
4685     //   expression, the implicit conversion sequence is a
4686     //   user-defined conversion sequence (13.3.3.1.2), with the
4687     //   second standard conversion sequence either an identity
4688     //   conversion or, if the conversion function returns an
4689     //   entity of a type that is a derived class of the parameter
4690     //   type, a derived-to-base Conversion.
4691     if (!Best->FinalConversion.DirectBinding)
4692       return false;
4693 
4694     ICS.setUserDefined();
4695     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4696     ICS.UserDefined.After = Best->FinalConversion;
4697     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4698     ICS.UserDefined.ConversionFunction = Best->Function;
4699     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4700     ICS.UserDefined.EllipsisConversion = false;
4701     assert(ICS.UserDefined.After.ReferenceBinding &&
4702            ICS.UserDefined.After.DirectBinding &&
4703            "Expected a direct reference binding!");
4704     return true;
4705 
4706   case OR_Ambiguous:
4707     ICS.setAmbiguous();
4708     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4709          Cand != CandidateSet.end(); ++Cand)
4710       if (Cand->Best)
4711         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4712     return true;
4713 
4714   case OR_No_Viable_Function:
4715   case OR_Deleted:
4716     // There was no suitable conversion, or we found a deleted
4717     // conversion; continue with other checks.
4718     return false;
4719   }
4720 
4721   llvm_unreachable("Invalid OverloadResult!");
4722 }
4723 
4724 /// Compute an implicit conversion sequence for reference
4725 /// initialization.
4726 static ImplicitConversionSequence
4727 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4728                  SourceLocation DeclLoc,
4729                  bool SuppressUserConversions,
4730                  bool AllowExplicit) {
4731   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4732 
4733   // Most paths end in a failed conversion.
4734   ImplicitConversionSequence ICS;
4735   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4736 
4737   QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4738   QualType T2 = Init->getType();
4739 
4740   // If the initializer is the address of an overloaded function, try
4741   // to resolve the overloaded function. If all goes well, T2 is the
4742   // type of the resulting function.
4743   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4744     DeclAccessPair Found;
4745     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4746                                                                 false, Found))
4747       T2 = Fn->getType();
4748   }
4749 
4750   // Compute some basic properties of the types and the initializer.
4751   bool isRValRef = DeclType->isRValueReferenceType();
4752   Expr::Classification InitCategory = Init->Classify(S.Context);
4753 
4754   Sema::ReferenceConversions RefConv;
4755   Sema::ReferenceCompareResult RefRelationship =
4756       S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4757 
4758   auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4759     ICS.setStandard();
4760     ICS.Standard.First = ICK_Identity;
4761     // FIXME: A reference binding can be a function conversion too. We should
4762     // consider that when ordering reference-to-function bindings.
4763     ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4764                               ? ICK_Derived_To_Base
4765                               : (RefConv & Sema::ReferenceConversions::ObjC)
4766                                     ? ICK_Compatible_Conversion
4767                                     : ICK_Identity;
4768     // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4769     // a reference binding that performs a non-top-level qualification
4770     // conversion as a qualification conversion, not as an identity conversion.
4771     ICS.Standard.Third = (RefConv &
4772                               Sema::ReferenceConversions::NestedQualification)
4773                              ? ICK_Qualification
4774                              : ICK_Identity;
4775     ICS.Standard.setFromType(T2);
4776     ICS.Standard.setToType(0, T2);
4777     ICS.Standard.setToType(1, T1);
4778     ICS.Standard.setToType(2, T1);
4779     ICS.Standard.ReferenceBinding = true;
4780     ICS.Standard.DirectBinding = BindsDirectly;
4781     ICS.Standard.IsLvalueReference = !isRValRef;
4782     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4783     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4784     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4785     ICS.Standard.ObjCLifetimeConversionBinding =
4786         (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4787     ICS.Standard.CopyConstructor = nullptr;
4788     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4789   };
4790 
4791   // C++0x [dcl.init.ref]p5:
4792   //   A reference to type "cv1 T1" is initialized by an expression
4793   //   of type "cv2 T2" as follows:
4794 
4795   //     -- If reference is an lvalue reference and the initializer expression
4796   if (!isRValRef) {
4797     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4798     //        reference-compatible with "cv2 T2," or
4799     //
4800     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4801     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4802       // C++ [over.ics.ref]p1:
4803       //   When a parameter of reference type binds directly (8.5.3)
4804       //   to an argument expression, the implicit conversion sequence
4805       //   is the identity conversion, unless the argument expression
4806       //   has a type that is a derived class of the parameter type,
4807       //   in which case the implicit conversion sequence is a
4808       //   derived-to-base Conversion (13.3.3.1).
4809       SetAsReferenceBinding(/*BindsDirectly=*/true);
4810 
4811       // Nothing more to do: the inaccessibility/ambiguity check for
4812       // derived-to-base conversions is suppressed when we're
4813       // computing the implicit conversion sequence (C++
4814       // [over.best.ics]p2).
4815       return ICS;
4816     }
4817 
4818     //       -- has a class type (i.e., T2 is a class type), where T1 is
4819     //          not reference-related to T2, and can be implicitly
4820     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4821     //          is reference-compatible with "cv3 T3" 92) (this
4822     //          conversion is selected by enumerating the applicable
4823     //          conversion functions (13.3.1.6) and choosing the best
4824     //          one through overload resolution (13.3)),
4825     if (!SuppressUserConversions && T2->isRecordType() &&
4826         S.isCompleteType(DeclLoc, T2) &&
4827         RefRelationship == Sema::Ref_Incompatible) {
4828       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4829                                    Init, T2, /*AllowRvalues=*/false,
4830                                    AllowExplicit))
4831         return ICS;
4832     }
4833   }
4834 
4835   //     -- Otherwise, the reference shall be an lvalue reference to a
4836   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4837   //        shall be an rvalue reference.
4838   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
4839     if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
4840       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4841     return ICS;
4842   }
4843 
4844   //       -- If the initializer expression
4845   //
4846   //            -- is an xvalue, class prvalue, array prvalue or function
4847   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4848   if (RefRelationship == Sema::Ref_Compatible &&
4849       (InitCategory.isXValue() ||
4850        (InitCategory.isPRValue() &&
4851           (T2->isRecordType() || T2->isArrayType())) ||
4852        (InitCategory.isLValue() && T2->isFunctionType()))) {
4853     // In C++11, this is always a direct binding. In C++98/03, it's a direct
4854     // binding unless we're binding to a class prvalue.
4855     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4856     // allow the use of rvalue references in C++98/03 for the benefit of
4857     // standard library implementors; therefore, we need the xvalue check here.
4858     SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4859                           !(InitCategory.isPRValue() || T2->isRecordType()));
4860     return ICS;
4861   }
4862 
4863   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4864   //               reference-related to T2, and can be implicitly converted to
4865   //               an xvalue, class prvalue, or function lvalue of type
4866   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4867   //               "cv3 T3",
4868   //
4869   //          then the reference is bound to the value of the initializer
4870   //          expression in the first case and to the result of the conversion
4871   //          in the second case (or, in either case, to an appropriate base
4872   //          class subobject).
4873   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4874       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4875       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4876                                Init, T2, /*AllowRvalues=*/true,
4877                                AllowExplicit)) {
4878     // In the second case, if the reference is an rvalue reference
4879     // and the second standard conversion sequence of the
4880     // user-defined conversion sequence includes an lvalue-to-rvalue
4881     // conversion, the program is ill-formed.
4882     if (ICS.isUserDefined() && isRValRef &&
4883         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4884       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4885 
4886     return ICS;
4887   }
4888 
4889   // A temporary of function type cannot be created; don't even try.
4890   if (T1->isFunctionType())
4891     return ICS;
4892 
4893   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4894   //          initialized from the initializer expression using the
4895   //          rules for a non-reference copy initialization (8.5). The
4896   //          reference is then bound to the temporary. If T1 is
4897   //          reference-related to T2, cv1 must be the same
4898   //          cv-qualification as, or greater cv-qualification than,
4899   //          cv2; otherwise, the program is ill-formed.
4900   if (RefRelationship == Sema::Ref_Related) {
4901     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4902     // we would be reference-compatible or reference-compatible with
4903     // added qualification. But that wasn't the case, so the reference
4904     // initialization fails.
4905     //
4906     // Note that we only want to check address spaces and cvr-qualifiers here.
4907     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4908     Qualifiers T1Quals = T1.getQualifiers();
4909     Qualifiers T2Quals = T2.getQualifiers();
4910     T1Quals.removeObjCGCAttr();
4911     T1Quals.removeObjCLifetime();
4912     T2Quals.removeObjCGCAttr();
4913     T2Quals.removeObjCLifetime();
4914     // MS compiler ignores __unaligned qualifier for references; do the same.
4915     T1Quals.removeUnaligned();
4916     T2Quals.removeUnaligned();
4917     if (!T1Quals.compatiblyIncludes(T2Quals))
4918       return ICS;
4919   }
4920 
4921   // If at least one of the types is a class type, the types are not
4922   // related, and we aren't allowed any user conversions, the
4923   // reference binding fails. This case is important for breaking
4924   // recursion, since TryImplicitConversion below will attempt to
4925   // create a temporary through the use of a copy constructor.
4926   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4927       (T1->isRecordType() || T2->isRecordType()))
4928     return ICS;
4929 
4930   // If T1 is reference-related to T2 and the reference is an rvalue
4931   // reference, the initializer expression shall not be an lvalue.
4932   if (RefRelationship >= Sema::Ref_Related && isRValRef &&
4933       Init->Classify(S.Context).isLValue()) {
4934     ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType);
4935     return ICS;
4936   }
4937 
4938   // C++ [over.ics.ref]p2:
4939   //   When a parameter of reference type is not bound directly to
4940   //   an argument expression, the conversion sequence is the one
4941   //   required to convert the argument expression to the
4942   //   underlying type of the reference according to
4943   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4944   //   to copy-initializing a temporary of the underlying type with
4945   //   the argument expression. Any difference in top-level
4946   //   cv-qualification is subsumed by the initialization itself
4947   //   and does not constitute a conversion.
4948   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4949                               AllowedExplicit::None,
4950                               /*InOverloadResolution=*/false,
4951                               /*CStyle=*/false,
4952                               /*AllowObjCWritebackConversion=*/false,
4953                               /*AllowObjCConversionOnExplicit=*/false);
4954 
4955   // Of course, that's still a reference binding.
4956   if (ICS.isStandard()) {
4957     ICS.Standard.ReferenceBinding = true;
4958     ICS.Standard.IsLvalueReference = !isRValRef;
4959     ICS.Standard.BindsToFunctionLvalue = false;
4960     ICS.Standard.BindsToRvalue = true;
4961     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4962     ICS.Standard.ObjCLifetimeConversionBinding = false;
4963   } else if (ICS.isUserDefined()) {
4964     const ReferenceType *LValRefType =
4965         ICS.UserDefined.ConversionFunction->getReturnType()
4966             ->getAs<LValueReferenceType>();
4967 
4968     // C++ [over.ics.ref]p3:
4969     //   Except for an implicit object parameter, for which see 13.3.1, a
4970     //   standard conversion sequence cannot be formed if it requires [...]
4971     //   binding an rvalue reference to an lvalue other than a function
4972     //   lvalue.
4973     // Note that the function case is not possible here.
4974     if (isRValRef && LValRefType) {
4975       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4976       return ICS;
4977     }
4978 
4979     ICS.UserDefined.After.ReferenceBinding = true;
4980     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4981     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4982     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4983     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4984     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4985   }
4986 
4987   return ICS;
4988 }
4989 
4990 static ImplicitConversionSequence
4991 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4992                       bool SuppressUserConversions,
4993                       bool InOverloadResolution,
4994                       bool AllowObjCWritebackConversion,
4995                       bool AllowExplicit = false);
4996 
4997 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4998 /// initializer list From.
4999 static ImplicitConversionSequence
5000 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5001                   bool SuppressUserConversions,
5002                   bool InOverloadResolution,
5003                   bool AllowObjCWritebackConversion) {
5004   // C++11 [over.ics.list]p1:
5005   //   When an argument is an initializer list, it is not an expression and
5006   //   special rules apply for converting it to a parameter type.
5007 
5008   ImplicitConversionSequence Result;
5009   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5010 
5011   // We need a complete type for what follows.  With one C++20 exception,
5012   // incomplete types can never be initialized from init lists.
5013   QualType InitTy = ToType;
5014   const ArrayType *AT = S.Context.getAsArrayType(ToType);
5015   if (AT && S.getLangOpts().CPlusPlus20)
5016     if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5017       // C++20 allows list initialization of an incomplete array type.
5018       InitTy = IAT->getElementType();
5019   if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5020     return Result;
5021 
5022   // Per DR1467:
5023   //   If the parameter type is a class X and the initializer list has a single
5024   //   element of type cv U, where U is X or a class derived from X, the
5025   //   implicit conversion sequence is the one required to convert the element
5026   //   to the parameter type.
5027   //
5028   //   Otherwise, if the parameter type is a character array [... ]
5029   //   and the initializer list has a single element that is an
5030   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5031   //   implicit conversion sequence is the identity conversion.
5032   if (From->getNumInits() == 1) {
5033     if (ToType->isRecordType()) {
5034       QualType InitType = From->getInit(0)->getType();
5035       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5036           S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5037         return TryCopyInitialization(S, From->getInit(0), ToType,
5038                                      SuppressUserConversions,
5039                                      InOverloadResolution,
5040                                      AllowObjCWritebackConversion);
5041     }
5042 
5043     if (AT && S.IsStringInit(From->getInit(0), AT)) {
5044       InitializedEntity Entity =
5045           InitializedEntity::InitializeParameter(S.Context, ToType,
5046                                                  /*Consumed=*/false);
5047       if (S.CanPerformCopyInitialization(Entity, From)) {
5048         Result.setStandard();
5049         Result.Standard.setAsIdentityConversion();
5050         Result.Standard.setFromType(ToType);
5051         Result.Standard.setAllToTypes(ToType);
5052         return Result;
5053       }
5054     }
5055   }
5056 
5057   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5058   // C++11 [over.ics.list]p2:
5059   //   If the parameter type is std::initializer_list<X> or "array of X" and
5060   //   all the elements can be implicitly converted to X, the implicit
5061   //   conversion sequence is the worst conversion necessary to convert an
5062   //   element of the list to X.
5063   //
5064   // C++14 [over.ics.list]p3:
5065   //   Otherwise, if the parameter type is "array of N X", if the initializer
5066   //   list has exactly N elements or if it has fewer than N elements and X is
5067   //   default-constructible, and if all the elements of the initializer list
5068   //   can be implicitly converted to X, the implicit conversion sequence is
5069   //   the worst conversion necessary to convert an element of the list to X.
5070   if (AT || S.isStdInitializerList(ToType, &InitTy)) {
5071     unsigned e = From->getNumInits();
5072     ImplicitConversionSequence DfltElt;
5073     DfltElt.setBad(BadConversionSequence::no_conversion, QualType(),
5074                    QualType());
5075     QualType ContTy = ToType;
5076     bool IsUnbounded = false;
5077     if (AT) {
5078       InitTy = AT->getElementType();
5079       if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5080         if (CT->getSize().ult(e)) {
5081           // Too many inits, fatally bad
5082           Result.setBad(BadConversionSequence::too_many_initializers, From,
5083                         ToType);
5084           Result.setInitializerListContainerType(ContTy, IsUnbounded);
5085           return Result;
5086         }
5087         if (CT->getSize().ugt(e)) {
5088           // Need an init from empty {}, is there one?
5089           InitListExpr EmptyList(S.Context, From->getEndLoc(), None,
5090                                  From->getEndLoc());
5091           EmptyList.setType(S.Context.VoidTy);
5092           DfltElt = TryListConversion(
5093               S, &EmptyList, InitTy, SuppressUserConversions,
5094               InOverloadResolution, AllowObjCWritebackConversion);
5095           if (DfltElt.isBad()) {
5096             // No {} init, fatally bad
5097             Result.setBad(BadConversionSequence::too_few_initializers, From,
5098                           ToType);
5099             Result.setInitializerListContainerType(ContTy, IsUnbounded);
5100             return Result;
5101           }
5102         }
5103       } else {
5104         assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5105         IsUnbounded = true;
5106         if (!e) {
5107           // Cannot convert to zero-sized.
5108           Result.setBad(BadConversionSequence::too_few_initializers, From,
5109                         ToType);
5110           Result.setInitializerListContainerType(ContTy, IsUnbounded);
5111           return Result;
5112         }
5113         llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5114         ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5115                                                 ArrayType::Normal, 0);
5116       }
5117     }
5118 
5119     Result.setStandard();
5120     Result.Standard.setAsIdentityConversion();
5121     Result.Standard.setFromType(InitTy);
5122     Result.Standard.setAllToTypes(InitTy);
5123     for (unsigned i = 0; i < e; ++i) {
5124       Expr *Init = From->getInit(i);
5125       ImplicitConversionSequence ICS = TryCopyInitialization(
5126           S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5127           AllowObjCWritebackConversion);
5128 
5129       // Keep the worse conversion seen so far.
5130       // FIXME: Sequences are not totally ordered, so 'worse' can be
5131       // ambiguous. CWG has been informed.
5132       if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS,
5133                                              Result) ==
5134           ImplicitConversionSequence::Worse) {
5135         Result = ICS;
5136         // Bail as soon as we find something unconvertible.
5137         if (Result.isBad()) {
5138           Result.setInitializerListContainerType(ContTy, IsUnbounded);
5139           return Result;
5140         }
5141       }
5142     }
5143 
5144     // If we needed any implicit {} initialization, compare that now.
5145     // over.ics.list/6 indicates we should compare that conversion.  Again CWG
5146     // has been informed that this might not be the best thing.
5147     if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5148                                 S, From->getEndLoc(), DfltElt, Result) ==
5149                                 ImplicitConversionSequence::Worse)
5150       Result = DfltElt;
5151     // Record the type being initialized so that we may compare sequences
5152     Result.setInitializerListContainerType(ContTy, IsUnbounded);
5153     return Result;
5154   }
5155 
5156   // C++14 [over.ics.list]p4:
5157   // C++11 [over.ics.list]p3:
5158   //   Otherwise, if the parameter is a non-aggregate class X and overload
5159   //   resolution chooses a single best constructor [...] the implicit
5160   //   conversion sequence is a user-defined conversion sequence. If multiple
5161   //   constructors are viable but none is better than the others, the
5162   //   implicit conversion sequence is a user-defined conversion sequence.
5163   if (ToType->isRecordType() && !ToType->isAggregateType()) {
5164     // This function can deal with initializer lists.
5165     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5166                                     AllowedExplicit::None,
5167                                     InOverloadResolution, /*CStyle=*/false,
5168                                     AllowObjCWritebackConversion,
5169                                     /*AllowObjCConversionOnExplicit=*/false);
5170   }
5171 
5172   // C++14 [over.ics.list]p5:
5173   // C++11 [over.ics.list]p4:
5174   //   Otherwise, if the parameter has an aggregate type which can be
5175   //   initialized from the initializer list [...] the implicit conversion
5176   //   sequence is a user-defined conversion sequence.
5177   if (ToType->isAggregateType()) {
5178     // Type is an aggregate, argument is an init list. At this point it comes
5179     // down to checking whether the initialization works.
5180     // FIXME: Find out whether this parameter is consumed or not.
5181     InitializedEntity Entity =
5182         InitializedEntity::InitializeParameter(S.Context, ToType,
5183                                                /*Consumed=*/false);
5184     if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5185                                                                  From)) {
5186       Result.setUserDefined();
5187       Result.UserDefined.Before.setAsIdentityConversion();
5188       // Initializer lists don't have a type.
5189       Result.UserDefined.Before.setFromType(QualType());
5190       Result.UserDefined.Before.setAllToTypes(QualType());
5191 
5192       Result.UserDefined.After.setAsIdentityConversion();
5193       Result.UserDefined.After.setFromType(ToType);
5194       Result.UserDefined.After.setAllToTypes(ToType);
5195       Result.UserDefined.ConversionFunction = nullptr;
5196     }
5197     return Result;
5198   }
5199 
5200   // C++14 [over.ics.list]p6:
5201   // C++11 [over.ics.list]p5:
5202   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5203   if (ToType->isReferenceType()) {
5204     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5205     // mention initializer lists in any way. So we go by what list-
5206     // initialization would do and try to extrapolate from that.
5207 
5208     QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5209 
5210     // If the initializer list has a single element that is reference-related
5211     // to the parameter type, we initialize the reference from that.
5212     if (From->getNumInits() == 1) {
5213       Expr *Init = From->getInit(0);
5214 
5215       QualType T2 = Init->getType();
5216 
5217       // If the initializer is the address of an overloaded function, try
5218       // to resolve the overloaded function. If all goes well, T2 is the
5219       // type of the resulting function.
5220       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5221         DeclAccessPair Found;
5222         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5223                                    Init, ToType, false, Found))
5224           T2 = Fn->getType();
5225       }
5226 
5227       // Compute some basic properties of the types and the initializer.
5228       Sema::ReferenceCompareResult RefRelationship =
5229           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5230 
5231       if (RefRelationship >= Sema::Ref_Related) {
5232         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5233                                 SuppressUserConversions,
5234                                 /*AllowExplicit=*/false);
5235       }
5236     }
5237 
5238     // Otherwise, we bind the reference to a temporary created from the
5239     // initializer list.
5240     Result = TryListConversion(S, From, T1, SuppressUserConversions,
5241                                InOverloadResolution,
5242                                AllowObjCWritebackConversion);
5243     if (Result.isFailure())
5244       return Result;
5245     assert(!Result.isEllipsis() &&
5246            "Sub-initialization cannot result in ellipsis conversion.");
5247 
5248     // Can we even bind to a temporary?
5249     if (ToType->isRValueReferenceType() ||
5250         (T1.isConstQualified() && !T1.isVolatileQualified())) {
5251       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5252                                             Result.UserDefined.After;
5253       SCS.ReferenceBinding = true;
5254       SCS.IsLvalueReference = ToType->isLValueReferenceType();
5255       SCS.BindsToRvalue = true;
5256       SCS.BindsToFunctionLvalue = false;
5257       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5258       SCS.ObjCLifetimeConversionBinding = false;
5259     } else
5260       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5261                     From, ToType);
5262     return Result;
5263   }
5264 
5265   // C++14 [over.ics.list]p7:
5266   // C++11 [over.ics.list]p6:
5267   //   Otherwise, if the parameter type is not a class:
5268   if (!ToType->isRecordType()) {
5269     //    - if the initializer list has one element that is not itself an
5270     //      initializer list, the implicit conversion sequence is the one
5271     //      required to convert the element to the parameter type.
5272     unsigned NumInits = From->getNumInits();
5273     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5274       Result = TryCopyInitialization(S, From->getInit(0), ToType,
5275                                      SuppressUserConversions,
5276                                      InOverloadResolution,
5277                                      AllowObjCWritebackConversion);
5278     //    - if the initializer list has no elements, the implicit conversion
5279     //      sequence is the identity conversion.
5280     else if (NumInits == 0) {
5281       Result.setStandard();
5282       Result.Standard.setAsIdentityConversion();
5283       Result.Standard.setFromType(ToType);
5284       Result.Standard.setAllToTypes(ToType);
5285     }
5286     return Result;
5287   }
5288 
5289   // C++14 [over.ics.list]p8:
5290   // C++11 [over.ics.list]p7:
5291   //   In all cases other than those enumerated above, no conversion is possible
5292   return Result;
5293 }
5294 
5295 /// TryCopyInitialization - Try to copy-initialize a value of type
5296 /// ToType from the expression From. Return the implicit conversion
5297 /// sequence required to pass this argument, which may be a bad
5298 /// conversion sequence (meaning that the argument cannot be passed to
5299 /// a parameter of this type). If @p SuppressUserConversions, then we
5300 /// do not permit any user-defined conversion sequences.
5301 static ImplicitConversionSequence
5302 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5303                       bool SuppressUserConversions,
5304                       bool InOverloadResolution,
5305                       bool AllowObjCWritebackConversion,
5306                       bool AllowExplicit) {
5307   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5308     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5309                              InOverloadResolution,AllowObjCWritebackConversion);
5310 
5311   if (ToType->isReferenceType())
5312     return TryReferenceInit(S, From, ToType,
5313                             /*FIXME:*/ From->getBeginLoc(),
5314                             SuppressUserConversions, AllowExplicit);
5315 
5316   return TryImplicitConversion(S, From, ToType,
5317                                SuppressUserConversions,
5318                                AllowedExplicit::None,
5319                                InOverloadResolution,
5320                                /*CStyle=*/false,
5321                                AllowObjCWritebackConversion,
5322                                /*AllowObjCConversionOnExplicit=*/false);
5323 }
5324 
5325 static bool TryCopyInitialization(const CanQualType FromQTy,
5326                                   const CanQualType ToQTy,
5327                                   Sema &S,
5328                                   SourceLocation Loc,
5329                                   ExprValueKind FromVK) {
5330   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5331   ImplicitConversionSequence ICS =
5332     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5333 
5334   return !ICS.isBad();
5335 }
5336 
5337 /// TryObjectArgumentInitialization - Try to initialize the object
5338 /// parameter of the given member function (@c Method) from the
5339 /// expression @p From.
5340 static ImplicitConversionSequence
5341 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5342                                 Expr::Classification FromClassification,
5343                                 CXXMethodDecl *Method,
5344                                 CXXRecordDecl *ActingContext) {
5345   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5346   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5347   //                 const volatile object.
5348   Qualifiers Quals = Method->getMethodQualifiers();
5349   if (isa<CXXDestructorDecl>(Method)) {
5350     Quals.addConst();
5351     Quals.addVolatile();
5352   }
5353 
5354   QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5355 
5356   // Set up the conversion sequence as a "bad" conversion, to allow us
5357   // to exit early.
5358   ImplicitConversionSequence ICS;
5359 
5360   // We need to have an object of class type.
5361   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5362     FromType = PT->getPointeeType();
5363 
5364     // When we had a pointer, it's implicitly dereferenced, so we
5365     // better have an lvalue.
5366     assert(FromClassification.isLValue());
5367   }
5368 
5369   assert(FromType->isRecordType());
5370 
5371   // C++0x [over.match.funcs]p4:
5372   //   For non-static member functions, the type of the implicit object
5373   //   parameter is
5374   //
5375   //     - "lvalue reference to cv X" for functions declared without a
5376   //        ref-qualifier or with the & ref-qualifier
5377   //     - "rvalue reference to cv X" for functions declared with the &&
5378   //        ref-qualifier
5379   //
5380   // where X is the class of which the function is a member and cv is the
5381   // cv-qualification on the member function declaration.
5382   //
5383   // However, when finding an implicit conversion sequence for the argument, we
5384   // are not allowed to perform user-defined conversions
5385   // (C++ [over.match.funcs]p5). We perform a simplified version of
5386   // reference binding here, that allows class rvalues to bind to
5387   // non-constant references.
5388 
5389   // First check the qualifiers.
5390   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5391   if (ImplicitParamType.getCVRQualifiers()
5392                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5393       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5394     ICS.setBad(BadConversionSequence::bad_qualifiers,
5395                FromType, ImplicitParamType);
5396     return ICS;
5397   }
5398 
5399   if (FromTypeCanon.hasAddressSpace()) {
5400     Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5401     Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5402     if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5403       ICS.setBad(BadConversionSequence::bad_qualifiers,
5404                  FromType, ImplicitParamType);
5405       return ICS;
5406     }
5407   }
5408 
5409   // Check that we have either the same type or a derived type. It
5410   // affects the conversion rank.
5411   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5412   ImplicitConversionKind SecondKind;
5413   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5414     SecondKind = ICK_Identity;
5415   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5416     SecondKind = ICK_Derived_To_Base;
5417   else {
5418     ICS.setBad(BadConversionSequence::unrelated_class,
5419                FromType, ImplicitParamType);
5420     return ICS;
5421   }
5422 
5423   // Check the ref-qualifier.
5424   switch (Method->getRefQualifier()) {
5425   case RQ_None:
5426     // Do nothing; we don't care about lvalueness or rvalueness.
5427     break;
5428 
5429   case RQ_LValue:
5430     if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5431       // non-const lvalue reference cannot bind to an rvalue
5432       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5433                  ImplicitParamType);
5434       return ICS;
5435     }
5436     break;
5437 
5438   case RQ_RValue:
5439     if (!FromClassification.isRValue()) {
5440       // rvalue reference cannot bind to an lvalue
5441       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5442                  ImplicitParamType);
5443       return ICS;
5444     }
5445     break;
5446   }
5447 
5448   // Success. Mark this as a reference binding.
5449   ICS.setStandard();
5450   ICS.Standard.setAsIdentityConversion();
5451   ICS.Standard.Second = SecondKind;
5452   ICS.Standard.setFromType(FromType);
5453   ICS.Standard.setAllToTypes(ImplicitParamType);
5454   ICS.Standard.ReferenceBinding = true;
5455   ICS.Standard.DirectBinding = true;
5456   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5457   ICS.Standard.BindsToFunctionLvalue = false;
5458   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5459   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5460     = (Method->getRefQualifier() == RQ_None);
5461   return ICS;
5462 }
5463 
5464 /// PerformObjectArgumentInitialization - Perform initialization of
5465 /// the implicit object parameter for the given Method with the given
5466 /// expression.
5467 ExprResult
5468 Sema::PerformObjectArgumentInitialization(Expr *From,
5469                                           NestedNameSpecifier *Qualifier,
5470                                           NamedDecl *FoundDecl,
5471                                           CXXMethodDecl *Method) {
5472   QualType FromRecordType, DestType;
5473   QualType ImplicitParamRecordType  =
5474     Method->getThisType()->castAs<PointerType>()->getPointeeType();
5475 
5476   Expr::Classification FromClassification;
5477   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5478     FromRecordType = PT->getPointeeType();
5479     DestType = Method->getThisType();
5480     FromClassification = Expr::Classification::makeSimpleLValue();
5481   } else {
5482     FromRecordType = From->getType();
5483     DestType = ImplicitParamRecordType;
5484     FromClassification = From->Classify(Context);
5485 
5486     // When performing member access on a prvalue, materialize a temporary.
5487     if (From->isPRValue()) {
5488       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5489                                             Method->getRefQualifier() !=
5490                                                 RefQualifierKind::RQ_RValue);
5491     }
5492   }
5493 
5494   // Note that we always use the true parent context when performing
5495   // the actual argument initialization.
5496   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5497       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5498       Method->getParent());
5499   if (ICS.isBad()) {
5500     switch (ICS.Bad.Kind) {
5501     case BadConversionSequence::bad_qualifiers: {
5502       Qualifiers FromQs = FromRecordType.getQualifiers();
5503       Qualifiers ToQs = DestType.getQualifiers();
5504       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5505       if (CVR) {
5506         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5507             << Method->getDeclName() << FromRecordType << (CVR - 1)
5508             << From->getSourceRange();
5509         Diag(Method->getLocation(), diag::note_previous_decl)
5510           << Method->getDeclName();
5511         return ExprError();
5512       }
5513       break;
5514     }
5515 
5516     case BadConversionSequence::lvalue_ref_to_rvalue:
5517     case BadConversionSequence::rvalue_ref_to_lvalue: {
5518       bool IsRValueQualified =
5519         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5520       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5521           << Method->getDeclName() << FromClassification.isRValue()
5522           << IsRValueQualified;
5523       Diag(Method->getLocation(), diag::note_previous_decl)
5524         << Method->getDeclName();
5525       return ExprError();
5526     }
5527 
5528     case BadConversionSequence::no_conversion:
5529     case BadConversionSequence::unrelated_class:
5530       break;
5531 
5532     case BadConversionSequence::too_few_initializers:
5533     case BadConversionSequence::too_many_initializers:
5534       llvm_unreachable("Lists are not objects");
5535     }
5536 
5537     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5538            << ImplicitParamRecordType << FromRecordType
5539            << From->getSourceRange();
5540   }
5541 
5542   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5543     ExprResult FromRes =
5544       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5545     if (FromRes.isInvalid())
5546       return ExprError();
5547     From = FromRes.get();
5548   }
5549 
5550   if (!Context.hasSameType(From->getType(), DestType)) {
5551     CastKind CK;
5552     QualType PteeTy = DestType->getPointeeType();
5553     LangAS DestAS =
5554         PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5555     if (FromRecordType.getAddressSpace() != DestAS)
5556       CK = CK_AddressSpaceConversion;
5557     else
5558       CK = CK_NoOp;
5559     From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5560   }
5561   return From;
5562 }
5563 
5564 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5565 /// expression From to bool (C++0x [conv]p3).
5566 static ImplicitConversionSequence
5567 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5568   // C++ [dcl.init]/17.8:
5569   //   - Otherwise, if the initialization is direct-initialization, the source
5570   //     type is std::nullptr_t, and the destination type is bool, the initial
5571   //     value of the object being initialized is false.
5572   if (From->getType()->isNullPtrType())
5573     return ImplicitConversionSequence::getNullptrToBool(From->getType(),
5574                                                         S.Context.BoolTy,
5575                                                         From->isGLValue());
5576 
5577   // All other direct-initialization of bool is equivalent to an implicit
5578   // conversion to bool in which explicit conversions are permitted.
5579   return TryImplicitConversion(S, From, S.Context.BoolTy,
5580                                /*SuppressUserConversions=*/false,
5581                                AllowedExplicit::Conversions,
5582                                /*InOverloadResolution=*/false,
5583                                /*CStyle=*/false,
5584                                /*AllowObjCWritebackConversion=*/false,
5585                                /*AllowObjCConversionOnExplicit=*/false);
5586 }
5587 
5588 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5589 /// of the expression From to bool (C++0x [conv]p3).
5590 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5591   if (checkPlaceholderForOverload(*this, From))
5592     return ExprError();
5593 
5594   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5595   if (!ICS.isBad())
5596     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5597 
5598   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5599     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5600            << From->getType() << From->getSourceRange();
5601   return ExprError();
5602 }
5603 
5604 /// Check that the specified conversion is permitted in a converted constant
5605 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5606 /// is acceptable.
5607 static bool CheckConvertedConstantConversions(Sema &S,
5608                                               StandardConversionSequence &SCS) {
5609   // Since we know that the target type is an integral or unscoped enumeration
5610   // type, most conversion kinds are impossible. All possible First and Third
5611   // conversions are fine.
5612   switch (SCS.Second) {
5613   case ICK_Identity:
5614   case ICK_Integral_Promotion:
5615   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5616   case ICK_Zero_Queue_Conversion:
5617     return true;
5618 
5619   case ICK_Boolean_Conversion:
5620     // Conversion from an integral or unscoped enumeration type to bool is
5621     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5622     // conversion, so we allow it in a converted constant expression.
5623     //
5624     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5625     // a lot of popular code. We should at least add a warning for this
5626     // (non-conforming) extension.
5627     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5628            SCS.getToType(2)->isBooleanType();
5629 
5630   case ICK_Pointer_Conversion:
5631   case ICK_Pointer_Member:
5632     // C++1z: null pointer conversions and null member pointer conversions are
5633     // only permitted if the source type is std::nullptr_t.
5634     return SCS.getFromType()->isNullPtrType();
5635 
5636   case ICK_Floating_Promotion:
5637   case ICK_Complex_Promotion:
5638   case ICK_Floating_Conversion:
5639   case ICK_Complex_Conversion:
5640   case ICK_Floating_Integral:
5641   case ICK_Compatible_Conversion:
5642   case ICK_Derived_To_Base:
5643   case ICK_Vector_Conversion:
5644   case ICK_SVE_Vector_Conversion:
5645   case ICK_Vector_Splat:
5646   case ICK_Complex_Real:
5647   case ICK_Block_Pointer_Conversion:
5648   case ICK_TransparentUnionConversion:
5649   case ICK_Writeback_Conversion:
5650   case ICK_Zero_Event_Conversion:
5651   case ICK_C_Only_Conversion:
5652   case ICK_Incompatible_Pointer_Conversion:
5653     return false;
5654 
5655   case ICK_Lvalue_To_Rvalue:
5656   case ICK_Array_To_Pointer:
5657   case ICK_Function_To_Pointer:
5658     llvm_unreachable("found a first conversion kind in Second");
5659 
5660   case ICK_Function_Conversion:
5661   case ICK_Qualification:
5662     llvm_unreachable("found a third conversion kind in Second");
5663 
5664   case ICK_Num_Conversion_Kinds:
5665     break;
5666   }
5667 
5668   llvm_unreachable("unknown conversion kind");
5669 }
5670 
5671 /// CheckConvertedConstantExpression - Check that the expression From is a
5672 /// converted constant expression of type T, perform the conversion and produce
5673 /// the converted expression, per C++11 [expr.const]p3.
5674 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5675                                                    QualType T, APValue &Value,
5676                                                    Sema::CCEKind CCE,
5677                                                    bool RequireInt,
5678                                                    NamedDecl *Dest) {
5679   assert(S.getLangOpts().CPlusPlus11 &&
5680          "converted constant expression outside C++11");
5681 
5682   if (checkPlaceholderForOverload(S, From))
5683     return ExprError();
5684 
5685   // C++1z [expr.const]p3:
5686   //  A converted constant expression of type T is an expression,
5687   //  implicitly converted to type T, where the converted
5688   //  expression is a constant expression and the implicit conversion
5689   //  sequence contains only [... list of conversions ...].
5690   ImplicitConversionSequence ICS =
5691       (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept)
5692           ? TryContextuallyConvertToBool(S, From)
5693           : TryCopyInitialization(S, From, T,
5694                                   /*SuppressUserConversions=*/false,
5695                                   /*InOverloadResolution=*/false,
5696                                   /*AllowObjCWritebackConversion=*/false,
5697                                   /*AllowExplicit=*/false);
5698   StandardConversionSequence *SCS = nullptr;
5699   switch (ICS.getKind()) {
5700   case ImplicitConversionSequence::StandardConversion:
5701     SCS = &ICS.Standard;
5702     break;
5703   case ImplicitConversionSequence::UserDefinedConversion:
5704     if (T->isRecordType())
5705       SCS = &ICS.UserDefined.Before;
5706     else
5707       SCS = &ICS.UserDefined.After;
5708     break;
5709   case ImplicitConversionSequence::AmbiguousConversion:
5710   case ImplicitConversionSequence::BadConversion:
5711     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5712       return S.Diag(From->getBeginLoc(),
5713                     diag::err_typecheck_converted_constant_expression)
5714              << From->getType() << From->getSourceRange() << T;
5715     return ExprError();
5716 
5717   case ImplicitConversionSequence::EllipsisConversion:
5718     llvm_unreachable("ellipsis conversion in converted constant expression");
5719   }
5720 
5721   // Check that we would only use permitted conversions.
5722   if (!CheckConvertedConstantConversions(S, *SCS)) {
5723     return S.Diag(From->getBeginLoc(),
5724                   diag::err_typecheck_converted_constant_expression_disallowed)
5725            << From->getType() << From->getSourceRange() << T;
5726   }
5727   // [...] and where the reference binding (if any) binds directly.
5728   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5729     return S.Diag(From->getBeginLoc(),
5730                   diag::err_typecheck_converted_constant_expression_indirect)
5731            << From->getType() << From->getSourceRange() << T;
5732   }
5733 
5734   // Usually we can simply apply the ImplicitConversionSequence we formed
5735   // earlier, but that's not guaranteed to work when initializing an object of
5736   // class type.
5737   ExprResult Result;
5738   if (T->isRecordType()) {
5739     assert(CCE == Sema::CCEK_TemplateArg &&
5740            "unexpected class type converted constant expr");
5741     Result = S.PerformCopyInitialization(
5742         InitializedEntity::InitializeTemplateParameter(
5743             T, cast<NonTypeTemplateParmDecl>(Dest)),
5744         SourceLocation(), From);
5745   } else {
5746     Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5747   }
5748   if (Result.isInvalid())
5749     return Result;
5750 
5751   // C++2a [intro.execution]p5:
5752   //   A full-expression is [...] a constant-expression [...]
5753   Result =
5754       S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5755                             /*DiscardedValue=*/false, /*IsConstexpr=*/true);
5756   if (Result.isInvalid())
5757     return Result;
5758 
5759   // Check for a narrowing implicit conversion.
5760   bool ReturnPreNarrowingValue = false;
5761   APValue PreNarrowingValue;
5762   QualType PreNarrowingType;
5763   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5764                                 PreNarrowingType)) {
5765   case NK_Dependent_Narrowing:
5766     // Implicit conversion to a narrower type, but the expression is
5767     // value-dependent so we can't tell whether it's actually narrowing.
5768   case NK_Variable_Narrowing:
5769     // Implicit conversion to a narrower type, and the value is not a constant
5770     // expression. We'll diagnose this in a moment.
5771   case NK_Not_Narrowing:
5772     break;
5773 
5774   case NK_Constant_Narrowing:
5775     if (CCE == Sema::CCEK_ArrayBound &&
5776         PreNarrowingType->isIntegralOrEnumerationType() &&
5777         PreNarrowingValue.isInt()) {
5778       // Don't diagnose array bound narrowing here; we produce more precise
5779       // errors by allowing the un-narrowed value through.
5780       ReturnPreNarrowingValue = true;
5781       break;
5782     }
5783     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5784         << CCE << /*Constant*/ 1
5785         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5786     break;
5787 
5788   case NK_Type_Narrowing:
5789     // FIXME: It would be better to diagnose that the expression is not a
5790     // constant expression.
5791     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5792         << CCE << /*Constant*/ 0 << From->getType() << T;
5793     break;
5794   }
5795 
5796   if (Result.get()->isValueDependent()) {
5797     Value = APValue();
5798     return Result;
5799   }
5800 
5801   // Check the expression is a constant expression.
5802   SmallVector<PartialDiagnosticAt, 8> Notes;
5803   Expr::EvalResult Eval;
5804   Eval.Diag = &Notes;
5805 
5806   ConstantExprKind Kind;
5807   if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
5808     Kind = ConstantExprKind::ClassTemplateArgument;
5809   else if (CCE == Sema::CCEK_TemplateArg)
5810     Kind = ConstantExprKind::NonClassTemplateArgument;
5811   else
5812     Kind = ConstantExprKind::Normal;
5813 
5814   if (!Result.get()->EvaluateAsConstantExpr(Eval, S.Context, Kind) ||
5815       (RequireInt && !Eval.Val.isInt())) {
5816     // The expression can't be folded, so we can't keep it at this position in
5817     // the AST.
5818     Result = ExprError();
5819   } else {
5820     Value = Eval.Val;
5821 
5822     if (Notes.empty()) {
5823       // It's a constant expression.
5824       Expr *E = ConstantExpr::Create(S.Context, Result.get(), Value);
5825       if (ReturnPreNarrowingValue)
5826         Value = std::move(PreNarrowingValue);
5827       return E;
5828     }
5829   }
5830 
5831   // It's not a constant expression. Produce an appropriate diagnostic.
5832   if (Notes.size() == 1 &&
5833       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
5834     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5835   } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
5836                                    diag::note_constexpr_invalid_template_arg) {
5837     Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
5838     for (unsigned I = 0; I < Notes.size(); ++I)
5839       S.Diag(Notes[I].first, Notes[I].second);
5840   } else {
5841     S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5842         << CCE << From->getSourceRange();
5843     for (unsigned I = 0; I < Notes.size(); ++I)
5844       S.Diag(Notes[I].first, Notes[I].second);
5845   }
5846   return ExprError();
5847 }
5848 
5849 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5850                                                   APValue &Value, CCEKind CCE,
5851                                                   NamedDecl *Dest) {
5852   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
5853                                             Dest);
5854 }
5855 
5856 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5857                                                   llvm::APSInt &Value,
5858                                                   CCEKind CCE) {
5859   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5860 
5861   APValue V;
5862   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
5863                                               /*Dest=*/nullptr);
5864   if (!R.isInvalid() && !R.get()->isValueDependent())
5865     Value = V.getInt();
5866   return R;
5867 }
5868 
5869 
5870 /// dropPointerConversions - If the given standard conversion sequence
5871 /// involves any pointer conversions, remove them.  This may change
5872 /// the result type of the conversion sequence.
5873 static void dropPointerConversion(StandardConversionSequence &SCS) {
5874   if (SCS.Second == ICK_Pointer_Conversion) {
5875     SCS.Second = ICK_Identity;
5876     SCS.Third = ICK_Identity;
5877     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5878   }
5879 }
5880 
5881 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5882 /// convert the expression From to an Objective-C pointer type.
5883 static ImplicitConversionSequence
5884 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5885   // Do an implicit conversion to 'id'.
5886   QualType Ty = S.Context.getObjCIdType();
5887   ImplicitConversionSequence ICS
5888     = TryImplicitConversion(S, From, Ty,
5889                             // FIXME: Are these flags correct?
5890                             /*SuppressUserConversions=*/false,
5891                             AllowedExplicit::Conversions,
5892                             /*InOverloadResolution=*/false,
5893                             /*CStyle=*/false,
5894                             /*AllowObjCWritebackConversion=*/false,
5895                             /*AllowObjCConversionOnExplicit=*/true);
5896 
5897   // Strip off any final conversions to 'id'.
5898   switch (ICS.getKind()) {
5899   case ImplicitConversionSequence::BadConversion:
5900   case ImplicitConversionSequence::AmbiguousConversion:
5901   case ImplicitConversionSequence::EllipsisConversion:
5902     break;
5903 
5904   case ImplicitConversionSequence::UserDefinedConversion:
5905     dropPointerConversion(ICS.UserDefined.After);
5906     break;
5907 
5908   case ImplicitConversionSequence::StandardConversion:
5909     dropPointerConversion(ICS.Standard);
5910     break;
5911   }
5912 
5913   return ICS;
5914 }
5915 
5916 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5917 /// conversion of the expression From to an Objective-C pointer type.
5918 /// Returns a valid but null ExprResult if no conversion sequence exists.
5919 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5920   if (checkPlaceholderForOverload(*this, From))
5921     return ExprError();
5922 
5923   QualType Ty = Context.getObjCIdType();
5924   ImplicitConversionSequence ICS =
5925     TryContextuallyConvertToObjCPointer(*this, From);
5926   if (!ICS.isBad())
5927     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5928   return ExprResult();
5929 }
5930 
5931 /// Determine whether the provided type is an integral type, or an enumeration
5932 /// type of a permitted flavor.
5933 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5934   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5935                                  : T->isIntegralOrUnscopedEnumerationType();
5936 }
5937 
5938 static ExprResult
5939 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5940                             Sema::ContextualImplicitConverter &Converter,
5941                             QualType T, UnresolvedSetImpl &ViableConversions) {
5942 
5943   if (Converter.Suppress)
5944     return ExprError();
5945 
5946   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5947   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5948     CXXConversionDecl *Conv =
5949         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5950     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5951     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5952   }
5953   return From;
5954 }
5955 
5956 static bool
5957 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5958                            Sema::ContextualImplicitConverter &Converter,
5959                            QualType T, bool HadMultipleCandidates,
5960                            UnresolvedSetImpl &ExplicitConversions) {
5961   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5962     DeclAccessPair Found = ExplicitConversions[0];
5963     CXXConversionDecl *Conversion =
5964         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5965 
5966     // The user probably meant to invoke the given explicit
5967     // conversion; use it.
5968     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5969     std::string TypeStr;
5970     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5971 
5972     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5973         << FixItHint::CreateInsertion(From->getBeginLoc(),
5974                                       "static_cast<" + TypeStr + ">(")
5975         << FixItHint::CreateInsertion(
5976                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5977     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5978 
5979     // If we aren't in a SFINAE context, build a call to the
5980     // explicit conversion function.
5981     if (SemaRef.isSFINAEContext())
5982       return true;
5983 
5984     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5985     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5986                                                        HadMultipleCandidates);
5987     if (Result.isInvalid())
5988       return true;
5989     // Record usage of conversion in an implicit cast.
5990     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5991                                     CK_UserDefinedConversion, Result.get(),
5992                                     nullptr, Result.get()->getValueKind(),
5993                                     SemaRef.CurFPFeatureOverrides());
5994   }
5995   return false;
5996 }
5997 
5998 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5999                              Sema::ContextualImplicitConverter &Converter,
6000                              QualType T, bool HadMultipleCandidates,
6001                              DeclAccessPair &Found) {
6002   CXXConversionDecl *Conversion =
6003       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6004   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6005 
6006   QualType ToType = Conversion->getConversionType().getNonReferenceType();
6007   if (!Converter.SuppressConversion) {
6008     if (SemaRef.isSFINAEContext())
6009       return true;
6010 
6011     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6012         << From->getSourceRange();
6013   }
6014 
6015   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6016                                                      HadMultipleCandidates);
6017   if (Result.isInvalid())
6018     return true;
6019   // Record usage of conversion in an implicit cast.
6020   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6021                                   CK_UserDefinedConversion, Result.get(),
6022                                   nullptr, Result.get()->getValueKind(),
6023                                   SemaRef.CurFPFeatureOverrides());
6024   return false;
6025 }
6026 
6027 static ExprResult finishContextualImplicitConversion(
6028     Sema &SemaRef, SourceLocation Loc, Expr *From,
6029     Sema::ContextualImplicitConverter &Converter) {
6030   if (!Converter.match(From->getType()) && !Converter.Suppress)
6031     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6032         << From->getSourceRange();
6033 
6034   return SemaRef.DefaultLvalueConversion(From);
6035 }
6036 
6037 static void
6038 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
6039                                   UnresolvedSetImpl &ViableConversions,
6040                                   OverloadCandidateSet &CandidateSet) {
6041   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6042     DeclAccessPair FoundDecl = ViableConversions[I];
6043     NamedDecl *D = FoundDecl.getDecl();
6044     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6045     if (isa<UsingShadowDecl>(D))
6046       D = cast<UsingShadowDecl>(D)->getTargetDecl();
6047 
6048     CXXConversionDecl *Conv;
6049     FunctionTemplateDecl *ConvTemplate;
6050     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
6051       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6052     else
6053       Conv = cast<CXXConversionDecl>(D);
6054 
6055     if (ConvTemplate)
6056       SemaRef.AddTemplateConversionCandidate(
6057           ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6058           /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
6059     else
6060       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
6061                                      ToType, CandidateSet,
6062                                      /*AllowObjCConversionOnExplicit=*/false,
6063                                      /*AllowExplicit*/ true);
6064   }
6065 }
6066 
6067 /// Attempt to convert the given expression to a type which is accepted
6068 /// by the given converter.
6069 ///
6070 /// This routine will attempt to convert an expression of class type to a
6071 /// type accepted by the specified converter. In C++11 and before, the class
6072 /// must have a single non-explicit conversion function converting to a matching
6073 /// type. In C++1y, there can be multiple such conversion functions, but only
6074 /// one target type.
6075 ///
6076 /// \param Loc The source location of the construct that requires the
6077 /// conversion.
6078 ///
6079 /// \param From The expression we're converting from.
6080 ///
6081 /// \param Converter Used to control and diagnose the conversion process.
6082 ///
6083 /// \returns The expression, converted to an integral or enumeration type if
6084 /// successful.
6085 ExprResult Sema::PerformContextualImplicitConversion(
6086     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6087   // We can't perform any more checking for type-dependent expressions.
6088   if (From->isTypeDependent())
6089     return From;
6090 
6091   // Process placeholders immediately.
6092   if (From->hasPlaceholderType()) {
6093     ExprResult result = CheckPlaceholderExpr(From);
6094     if (result.isInvalid())
6095       return result;
6096     From = result.get();
6097   }
6098 
6099   // If the expression already has a matching type, we're golden.
6100   QualType T = From->getType();
6101   if (Converter.match(T))
6102     return DefaultLvalueConversion(From);
6103 
6104   // FIXME: Check for missing '()' if T is a function type?
6105 
6106   // We can only perform contextual implicit conversions on objects of class
6107   // type.
6108   const RecordType *RecordTy = T->getAs<RecordType>();
6109   if (!RecordTy || !getLangOpts().CPlusPlus) {
6110     if (!Converter.Suppress)
6111       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6112     return From;
6113   }
6114 
6115   // We must have a complete class type.
6116   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6117     ContextualImplicitConverter &Converter;
6118     Expr *From;
6119 
6120     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6121         : Converter(Converter), From(From) {}
6122 
6123     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6124       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6125     }
6126   } IncompleteDiagnoser(Converter, From);
6127 
6128   if (Converter.Suppress ? !isCompleteType(Loc, T)
6129                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6130     return From;
6131 
6132   // Look for a conversion to an integral or enumeration type.
6133   UnresolvedSet<4>
6134       ViableConversions; // These are *potentially* viable in C++1y.
6135   UnresolvedSet<4> ExplicitConversions;
6136   const auto &Conversions =
6137       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
6138 
6139   bool HadMultipleCandidates =
6140       (std::distance(Conversions.begin(), Conversions.end()) > 1);
6141 
6142   // To check that there is only one target type, in C++1y:
6143   QualType ToType;
6144   bool HasUniqueTargetType = true;
6145 
6146   // Collect explicit or viable (potentially in C++1y) conversions.
6147   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6148     NamedDecl *D = (*I)->getUnderlyingDecl();
6149     CXXConversionDecl *Conversion;
6150     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6151     if (ConvTemplate) {
6152       if (getLangOpts().CPlusPlus14)
6153         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6154       else
6155         continue; // C++11 does not consider conversion operator templates(?).
6156     } else
6157       Conversion = cast<CXXConversionDecl>(D);
6158 
6159     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6160            "Conversion operator templates are considered potentially "
6161            "viable in C++1y");
6162 
6163     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6164     if (Converter.match(CurToType) || ConvTemplate) {
6165 
6166       if (Conversion->isExplicit()) {
6167         // FIXME: For C++1y, do we need this restriction?
6168         // cf. diagnoseNoViableConversion()
6169         if (!ConvTemplate)
6170           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6171       } else {
6172         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6173           if (ToType.isNull())
6174             ToType = CurToType.getUnqualifiedType();
6175           else if (HasUniqueTargetType &&
6176                    (CurToType.getUnqualifiedType() != ToType))
6177             HasUniqueTargetType = false;
6178         }
6179         ViableConversions.addDecl(I.getDecl(), I.getAccess());
6180       }
6181     }
6182   }
6183 
6184   if (getLangOpts().CPlusPlus14) {
6185     // C++1y [conv]p6:
6186     // ... An expression e of class type E appearing in such a context
6187     // is said to be contextually implicitly converted to a specified
6188     // type T and is well-formed if and only if e can be implicitly
6189     // converted to a type T that is determined as follows: E is searched
6190     // for conversion functions whose return type is cv T or reference to
6191     // cv T such that T is allowed by the context. There shall be
6192     // exactly one such T.
6193 
6194     // If no unique T is found:
6195     if (ToType.isNull()) {
6196       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6197                                      HadMultipleCandidates,
6198                                      ExplicitConversions))
6199         return ExprError();
6200       return finishContextualImplicitConversion(*this, Loc, From, Converter);
6201     }
6202 
6203     // If more than one unique Ts are found:
6204     if (!HasUniqueTargetType)
6205       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6206                                          ViableConversions);
6207 
6208     // If one unique T is found:
6209     // First, build a candidate set from the previously recorded
6210     // potentially viable conversions.
6211     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6212     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6213                                       CandidateSet);
6214 
6215     // Then, perform overload resolution over the candidate set.
6216     OverloadCandidateSet::iterator Best;
6217     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6218     case OR_Success: {
6219       // Apply this conversion.
6220       DeclAccessPair Found =
6221           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6222       if (recordConversion(*this, Loc, From, Converter, T,
6223                            HadMultipleCandidates, Found))
6224         return ExprError();
6225       break;
6226     }
6227     case OR_Ambiguous:
6228       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6229                                          ViableConversions);
6230     case OR_No_Viable_Function:
6231       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6232                                      HadMultipleCandidates,
6233                                      ExplicitConversions))
6234         return ExprError();
6235       LLVM_FALLTHROUGH;
6236     case OR_Deleted:
6237       // We'll complain below about a non-integral condition type.
6238       break;
6239     }
6240   } else {
6241     switch (ViableConversions.size()) {
6242     case 0: {
6243       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6244                                      HadMultipleCandidates,
6245                                      ExplicitConversions))
6246         return ExprError();
6247 
6248       // We'll complain below about a non-integral condition type.
6249       break;
6250     }
6251     case 1: {
6252       // Apply this conversion.
6253       DeclAccessPair Found = ViableConversions[0];
6254       if (recordConversion(*this, Loc, From, Converter, T,
6255                            HadMultipleCandidates, Found))
6256         return ExprError();
6257       break;
6258     }
6259     default:
6260       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6261                                          ViableConversions);
6262     }
6263   }
6264 
6265   return finishContextualImplicitConversion(*this, Loc, From, Converter);
6266 }
6267 
6268 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6269 /// an acceptable non-member overloaded operator for a call whose
6270 /// arguments have types T1 (and, if non-empty, T2). This routine
6271 /// implements the check in C++ [over.match.oper]p3b2 concerning
6272 /// enumeration types.
6273 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6274                                                    FunctionDecl *Fn,
6275                                                    ArrayRef<Expr *> Args) {
6276   QualType T1 = Args[0]->getType();
6277   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6278 
6279   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6280     return true;
6281 
6282   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6283     return true;
6284 
6285   const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6286   if (Proto->getNumParams() < 1)
6287     return false;
6288 
6289   if (T1->isEnumeralType()) {
6290     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6291     if (Context.hasSameUnqualifiedType(T1, ArgType))
6292       return true;
6293   }
6294 
6295   if (Proto->getNumParams() < 2)
6296     return false;
6297 
6298   if (!T2.isNull() && T2->isEnumeralType()) {
6299     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6300     if (Context.hasSameUnqualifiedType(T2, ArgType))
6301       return true;
6302   }
6303 
6304   return false;
6305 }
6306 
6307 /// AddOverloadCandidate - Adds the given function to the set of
6308 /// candidate functions, using the given function call arguments.  If
6309 /// @p SuppressUserConversions, then don't allow user-defined
6310 /// conversions via constructors or conversion operators.
6311 ///
6312 /// \param PartialOverloading true if we are performing "partial" overloading
6313 /// based on an incomplete set of function arguments. This feature is used by
6314 /// code completion.
6315 void Sema::AddOverloadCandidate(
6316     FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6317     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6318     bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6319     ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6320     OverloadCandidateParamOrder PO) {
6321   const FunctionProtoType *Proto
6322     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6323   assert(Proto && "Functions without a prototype cannot be overloaded");
6324   assert(!Function->getDescribedFunctionTemplate() &&
6325          "Use AddTemplateOverloadCandidate for function templates");
6326 
6327   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6328     if (!isa<CXXConstructorDecl>(Method)) {
6329       // If we get here, it's because we're calling a member function
6330       // that is named without a member access expression (e.g.,
6331       // "this->f") that was either written explicitly or created
6332       // implicitly. This can happen with a qualified call to a member
6333       // function, e.g., X::f(). We use an empty type for the implied
6334       // object argument (C++ [over.call.func]p3), and the acting context
6335       // is irrelevant.
6336       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6337                          Expr::Classification::makeSimpleLValue(), Args,
6338                          CandidateSet, SuppressUserConversions,
6339                          PartialOverloading, EarlyConversions, PO);
6340       return;
6341     }
6342     // We treat a constructor like a non-member function, since its object
6343     // argument doesn't participate in overload resolution.
6344   }
6345 
6346   if (!CandidateSet.isNewCandidate(Function, PO))
6347     return;
6348 
6349   // C++11 [class.copy]p11: [DR1402]
6350   //   A defaulted move constructor that is defined as deleted is ignored by
6351   //   overload resolution.
6352   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6353   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6354       Constructor->isMoveConstructor())
6355     return;
6356 
6357   // Overload resolution is always an unevaluated context.
6358   EnterExpressionEvaluationContext Unevaluated(
6359       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6360 
6361   // C++ [over.match.oper]p3:
6362   //   if no operand has a class type, only those non-member functions in the
6363   //   lookup set that have a first parameter of type T1 or "reference to
6364   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6365   //   is a right operand) a second parameter of type T2 or "reference to
6366   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
6367   //   candidate functions.
6368   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6369       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6370     return;
6371 
6372   // Add this candidate
6373   OverloadCandidate &Candidate =
6374       CandidateSet.addCandidate(Args.size(), EarlyConversions);
6375   Candidate.FoundDecl = FoundDecl;
6376   Candidate.Function = Function;
6377   Candidate.Viable = true;
6378   Candidate.RewriteKind =
6379       CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6380   Candidate.IsSurrogate = false;
6381   Candidate.IsADLCandidate = IsADLCandidate;
6382   Candidate.IgnoreObjectArgument = false;
6383   Candidate.ExplicitCallArguments = Args.size();
6384 
6385   // Explicit functions are not actually candidates at all if we're not
6386   // allowing them in this context, but keep them around so we can point
6387   // to them in diagnostics.
6388   if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6389     Candidate.Viable = false;
6390     Candidate.FailureKind = ovl_fail_explicit;
6391     return;
6392   }
6393 
6394   if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6395       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6396     Candidate.Viable = false;
6397     Candidate.FailureKind = ovl_non_default_multiversion_function;
6398     return;
6399   }
6400 
6401   if (Constructor) {
6402     // C++ [class.copy]p3:
6403     //   A member function template is never instantiated to perform the copy
6404     //   of a class object to an object of its class type.
6405     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6406     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6407         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6408          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6409                        ClassType))) {
6410       Candidate.Viable = false;
6411       Candidate.FailureKind = ovl_fail_illegal_constructor;
6412       return;
6413     }
6414 
6415     // C++ [over.match.funcs]p8: (proposed DR resolution)
6416     //   A constructor inherited from class type C that has a first parameter
6417     //   of type "reference to P" (including such a constructor instantiated
6418     //   from a template) is excluded from the set of candidate functions when
6419     //   constructing an object of type cv D if the argument list has exactly
6420     //   one argument and D is reference-related to P and P is reference-related
6421     //   to C.
6422     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6423     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6424         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6425       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6426       QualType C = Context.getRecordType(Constructor->getParent());
6427       QualType D = Context.getRecordType(Shadow->getParent());
6428       SourceLocation Loc = Args.front()->getExprLoc();
6429       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6430           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6431         Candidate.Viable = false;
6432         Candidate.FailureKind = ovl_fail_inhctor_slice;
6433         return;
6434       }
6435     }
6436 
6437     // Check that the constructor is capable of constructing an object in the
6438     // destination address space.
6439     if (!Qualifiers::isAddressSpaceSupersetOf(
6440             Constructor->getMethodQualifiers().getAddressSpace(),
6441             CandidateSet.getDestAS())) {
6442       Candidate.Viable = false;
6443       Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6444     }
6445   }
6446 
6447   unsigned NumParams = Proto->getNumParams();
6448 
6449   // (C++ 13.3.2p2): A candidate function having fewer than m
6450   // parameters is viable only if it has an ellipsis in its parameter
6451   // list (8.3.5).
6452   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6453       !Proto->isVariadic() &&
6454       shouldEnforceArgLimit(PartialOverloading, Function)) {
6455     Candidate.Viable = false;
6456     Candidate.FailureKind = ovl_fail_too_many_arguments;
6457     return;
6458   }
6459 
6460   // (C++ 13.3.2p2): A candidate function having more than m parameters
6461   // is viable only if the (m+1)st parameter has a default argument
6462   // (8.3.6). For the purposes of overload resolution, the
6463   // parameter list is truncated on the right, so that there are
6464   // exactly m parameters.
6465   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6466   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6467     // Not enough arguments.
6468     Candidate.Viable = false;
6469     Candidate.FailureKind = ovl_fail_too_few_arguments;
6470     return;
6471   }
6472 
6473   // (CUDA B.1): Check for invalid calls between targets.
6474   if (getLangOpts().CUDA)
6475     if (const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true))
6476       // Skip the check for callers that are implicit members, because in this
6477       // case we may not yet know what the member's target is; the target is
6478       // inferred for the member automatically, based on the bases and fields of
6479       // the class.
6480       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6481         Candidate.Viable = false;
6482         Candidate.FailureKind = ovl_fail_bad_target;
6483         return;
6484       }
6485 
6486   if (Function->getTrailingRequiresClause()) {
6487     ConstraintSatisfaction Satisfaction;
6488     if (CheckFunctionConstraints(Function, Satisfaction) ||
6489         !Satisfaction.IsSatisfied) {
6490       Candidate.Viable = false;
6491       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6492       return;
6493     }
6494   }
6495 
6496   // Determine the implicit conversion sequences for each of the
6497   // arguments.
6498   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6499     unsigned ConvIdx =
6500         PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6501     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6502       // We already formed a conversion sequence for this parameter during
6503       // template argument deduction.
6504     } else if (ArgIdx < NumParams) {
6505       // (C++ 13.3.2p3): for F to be a viable function, there shall
6506       // exist for each argument an implicit conversion sequence
6507       // (13.3.3.1) that converts that argument to the corresponding
6508       // parameter of F.
6509       QualType ParamType = Proto->getParamType(ArgIdx);
6510       Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6511           *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6512           /*InOverloadResolution=*/true,
6513           /*AllowObjCWritebackConversion=*/
6514           getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6515       if (Candidate.Conversions[ConvIdx].isBad()) {
6516         Candidate.Viable = false;
6517         Candidate.FailureKind = ovl_fail_bad_conversion;
6518         return;
6519       }
6520     } else {
6521       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6522       // argument for which there is no corresponding parameter is
6523       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6524       Candidate.Conversions[ConvIdx].setEllipsis();
6525     }
6526   }
6527 
6528   if (EnableIfAttr *FailedAttr =
6529           CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
6530     Candidate.Viable = false;
6531     Candidate.FailureKind = ovl_fail_enable_if;
6532     Candidate.DeductionFailure.Data = FailedAttr;
6533     return;
6534   }
6535 }
6536 
6537 ObjCMethodDecl *
6538 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6539                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6540   if (Methods.size() <= 1)
6541     return nullptr;
6542 
6543   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6544     bool Match = true;
6545     ObjCMethodDecl *Method = Methods[b];
6546     unsigned NumNamedArgs = Sel.getNumArgs();
6547     // Method might have more arguments than selector indicates. This is due
6548     // to addition of c-style arguments in method.
6549     if (Method->param_size() > NumNamedArgs)
6550       NumNamedArgs = Method->param_size();
6551     if (Args.size() < NumNamedArgs)
6552       continue;
6553 
6554     for (unsigned i = 0; i < NumNamedArgs; i++) {
6555       // We can't do any type-checking on a type-dependent argument.
6556       if (Args[i]->isTypeDependent()) {
6557         Match = false;
6558         break;
6559       }
6560 
6561       ParmVarDecl *param = Method->parameters()[i];
6562       Expr *argExpr = Args[i];
6563       assert(argExpr && "SelectBestMethod(): missing expression");
6564 
6565       // Strip the unbridged-cast placeholder expression off unless it's
6566       // a consumed argument.
6567       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6568           !param->hasAttr<CFConsumedAttr>())
6569         argExpr = stripARCUnbridgedCast(argExpr);
6570 
6571       // If the parameter is __unknown_anytype, move on to the next method.
6572       if (param->getType() == Context.UnknownAnyTy) {
6573         Match = false;
6574         break;
6575       }
6576 
6577       ImplicitConversionSequence ConversionState
6578         = TryCopyInitialization(*this, argExpr, param->getType(),
6579                                 /*SuppressUserConversions*/false,
6580                                 /*InOverloadResolution=*/true,
6581                                 /*AllowObjCWritebackConversion=*/
6582                                 getLangOpts().ObjCAutoRefCount,
6583                                 /*AllowExplicit*/false);
6584       // This function looks for a reasonably-exact match, so we consider
6585       // incompatible pointer conversions to be a failure here.
6586       if (ConversionState.isBad() ||
6587           (ConversionState.isStandard() &&
6588            ConversionState.Standard.Second ==
6589                ICK_Incompatible_Pointer_Conversion)) {
6590         Match = false;
6591         break;
6592       }
6593     }
6594     // Promote additional arguments to variadic methods.
6595     if (Match && Method->isVariadic()) {
6596       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6597         if (Args[i]->isTypeDependent()) {
6598           Match = false;
6599           break;
6600         }
6601         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6602                                                           nullptr);
6603         if (Arg.isInvalid()) {
6604           Match = false;
6605           break;
6606         }
6607       }
6608     } else {
6609       // Check for extra arguments to non-variadic methods.
6610       if (Args.size() != NumNamedArgs)
6611         Match = false;
6612       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6613         // Special case when selectors have no argument. In this case, select
6614         // one with the most general result type of 'id'.
6615         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6616           QualType ReturnT = Methods[b]->getReturnType();
6617           if (ReturnT->isObjCIdType())
6618             return Methods[b];
6619         }
6620       }
6621     }
6622 
6623     if (Match)
6624       return Method;
6625   }
6626   return nullptr;
6627 }
6628 
6629 static bool convertArgsForAvailabilityChecks(
6630     Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
6631     ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
6632     Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
6633   if (ThisArg) {
6634     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6635     assert(!isa<CXXConstructorDecl>(Method) &&
6636            "Shouldn't have `this` for ctors!");
6637     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6638     ExprResult R = S.PerformObjectArgumentInitialization(
6639         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6640     if (R.isInvalid())
6641       return false;
6642     ConvertedThis = R.get();
6643   } else {
6644     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6645       (void)MD;
6646       assert((MissingImplicitThis || MD->isStatic() ||
6647               isa<CXXConstructorDecl>(MD)) &&
6648              "Expected `this` for non-ctor instance methods");
6649     }
6650     ConvertedThis = nullptr;
6651   }
6652 
6653   // Ignore any variadic arguments. Converting them is pointless, since the
6654   // user can't refer to them in the function condition.
6655   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6656 
6657   // Convert the arguments.
6658   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6659     ExprResult R;
6660     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6661                                         S.Context, Function->getParamDecl(I)),
6662                                     SourceLocation(), Args[I]);
6663 
6664     if (R.isInvalid())
6665       return false;
6666 
6667     ConvertedArgs.push_back(R.get());
6668   }
6669 
6670   if (Trap.hasErrorOccurred())
6671     return false;
6672 
6673   // Push default arguments if needed.
6674   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6675     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6676       ParmVarDecl *P = Function->getParamDecl(i);
6677       if (!P->hasDefaultArg())
6678         return false;
6679       ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
6680       if (R.isInvalid())
6681         return false;
6682       ConvertedArgs.push_back(R.get());
6683     }
6684 
6685     if (Trap.hasErrorOccurred())
6686       return false;
6687   }
6688   return true;
6689 }
6690 
6691 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
6692                                   SourceLocation CallLoc,
6693                                   ArrayRef<Expr *> Args,
6694                                   bool MissingImplicitThis) {
6695   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6696   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6697     return nullptr;
6698 
6699   SFINAETrap Trap(*this);
6700   SmallVector<Expr *, 16> ConvertedArgs;
6701   // FIXME: We should look into making enable_if late-parsed.
6702   Expr *DiscardedThis;
6703   if (!convertArgsForAvailabilityChecks(
6704           *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
6705           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6706     return *EnableIfAttrs.begin();
6707 
6708   for (auto *EIA : EnableIfAttrs) {
6709     APValue Result;
6710     // FIXME: This doesn't consider value-dependent cases, because doing so is
6711     // very difficult. Ideally, we should handle them more gracefully.
6712     if (EIA->getCond()->isValueDependent() ||
6713         !EIA->getCond()->EvaluateWithSubstitution(
6714             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6715       return EIA;
6716 
6717     if (!Result.isInt() || !Result.getInt().getBoolValue())
6718       return EIA;
6719   }
6720   return nullptr;
6721 }
6722 
6723 template <typename CheckFn>
6724 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6725                                         bool ArgDependent, SourceLocation Loc,
6726                                         CheckFn &&IsSuccessful) {
6727   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6728   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6729     if (ArgDependent == DIA->getArgDependent())
6730       Attrs.push_back(DIA);
6731   }
6732 
6733   // Common case: No diagnose_if attributes, so we can quit early.
6734   if (Attrs.empty())
6735     return false;
6736 
6737   auto WarningBegin = std::stable_partition(
6738       Attrs.begin(), Attrs.end(),
6739       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6740 
6741   // Note that diagnose_if attributes are late-parsed, so they appear in the
6742   // correct order (unlike enable_if attributes).
6743   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6744                                IsSuccessful);
6745   if (ErrAttr != WarningBegin) {
6746     const DiagnoseIfAttr *DIA = *ErrAttr;
6747     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6748     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6749         << DIA->getParent() << DIA->getCond()->getSourceRange();
6750     return true;
6751   }
6752 
6753   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6754     if (IsSuccessful(DIA)) {
6755       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6756       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6757           << DIA->getParent() << DIA->getCond()->getSourceRange();
6758     }
6759 
6760   return false;
6761 }
6762 
6763 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6764                                                const Expr *ThisArg,
6765                                                ArrayRef<const Expr *> Args,
6766                                                SourceLocation Loc) {
6767   return diagnoseDiagnoseIfAttrsWith(
6768       *this, Function, /*ArgDependent=*/true, Loc,
6769       [&](const DiagnoseIfAttr *DIA) {
6770         APValue Result;
6771         // It's sane to use the same Args for any redecl of this function, since
6772         // EvaluateWithSubstitution only cares about the position of each
6773         // argument in the arg list, not the ParmVarDecl* it maps to.
6774         if (!DIA->getCond()->EvaluateWithSubstitution(
6775                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6776           return false;
6777         return Result.isInt() && Result.getInt().getBoolValue();
6778       });
6779 }
6780 
6781 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6782                                                  SourceLocation Loc) {
6783   return diagnoseDiagnoseIfAttrsWith(
6784       *this, ND, /*ArgDependent=*/false, Loc,
6785       [&](const DiagnoseIfAttr *DIA) {
6786         bool Result;
6787         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6788                Result;
6789       });
6790 }
6791 
6792 /// Add all of the function declarations in the given function set to
6793 /// the overload candidate set.
6794 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6795                                  ArrayRef<Expr *> Args,
6796                                  OverloadCandidateSet &CandidateSet,
6797                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6798                                  bool SuppressUserConversions,
6799                                  bool PartialOverloading,
6800                                  bool FirstArgumentIsBase) {
6801   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6802     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6803     ArrayRef<Expr *> FunctionArgs = Args;
6804 
6805     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6806     FunctionDecl *FD =
6807         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6808 
6809     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6810       QualType ObjectType;
6811       Expr::Classification ObjectClassification;
6812       if (Args.size() > 0) {
6813         if (Expr *E = Args[0]) {
6814           // Use the explicit base to restrict the lookup:
6815           ObjectType = E->getType();
6816           // Pointers in the object arguments are implicitly dereferenced, so we
6817           // always classify them as l-values.
6818           if (!ObjectType.isNull() && ObjectType->isPointerType())
6819             ObjectClassification = Expr::Classification::makeSimpleLValue();
6820           else
6821             ObjectClassification = E->Classify(Context);
6822         } // .. else there is an implicit base.
6823         FunctionArgs = Args.slice(1);
6824       }
6825       if (FunTmpl) {
6826         AddMethodTemplateCandidate(
6827             FunTmpl, F.getPair(),
6828             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6829             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6830             FunctionArgs, CandidateSet, SuppressUserConversions,
6831             PartialOverloading);
6832       } else {
6833         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6834                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6835                            ObjectClassification, FunctionArgs, CandidateSet,
6836                            SuppressUserConversions, PartialOverloading);
6837       }
6838     } else {
6839       // This branch handles both standalone functions and static methods.
6840 
6841       // Slice the first argument (which is the base) when we access
6842       // static method as non-static.
6843       if (Args.size() > 0 &&
6844           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6845                         !isa<CXXConstructorDecl>(FD)))) {
6846         assert(cast<CXXMethodDecl>(FD)->isStatic());
6847         FunctionArgs = Args.slice(1);
6848       }
6849       if (FunTmpl) {
6850         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6851                                      ExplicitTemplateArgs, FunctionArgs,
6852                                      CandidateSet, SuppressUserConversions,
6853                                      PartialOverloading);
6854       } else {
6855         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6856                              SuppressUserConversions, PartialOverloading);
6857       }
6858     }
6859   }
6860 }
6861 
6862 /// AddMethodCandidate - Adds a named decl (which is some kind of
6863 /// method) as a method candidate to the given overload set.
6864 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
6865                               Expr::Classification ObjectClassification,
6866                               ArrayRef<Expr *> Args,
6867                               OverloadCandidateSet &CandidateSet,
6868                               bool SuppressUserConversions,
6869                               OverloadCandidateParamOrder PO) {
6870   NamedDecl *Decl = FoundDecl.getDecl();
6871   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6872 
6873   if (isa<UsingShadowDecl>(Decl))
6874     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6875 
6876   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6877     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6878            "Expected a member function template");
6879     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6880                                /*ExplicitArgs*/ nullptr, ObjectType,
6881                                ObjectClassification, Args, CandidateSet,
6882                                SuppressUserConversions, false, PO);
6883   } else {
6884     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6885                        ObjectType, ObjectClassification, Args, CandidateSet,
6886                        SuppressUserConversions, false, None, PO);
6887   }
6888 }
6889 
6890 /// AddMethodCandidate - Adds the given C++ member function to the set
6891 /// of candidate functions, using the given function call arguments
6892 /// and the object argument (@c Object). For example, in a call
6893 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6894 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6895 /// allow user-defined conversions via constructors or conversion
6896 /// operators.
6897 void
6898 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6899                          CXXRecordDecl *ActingContext, QualType ObjectType,
6900                          Expr::Classification ObjectClassification,
6901                          ArrayRef<Expr *> Args,
6902                          OverloadCandidateSet &CandidateSet,
6903                          bool SuppressUserConversions,
6904                          bool PartialOverloading,
6905                          ConversionSequenceList EarlyConversions,
6906                          OverloadCandidateParamOrder PO) {
6907   const FunctionProtoType *Proto
6908     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6909   assert(Proto && "Methods without a prototype cannot be overloaded");
6910   assert(!isa<CXXConstructorDecl>(Method) &&
6911          "Use AddOverloadCandidate for constructors");
6912 
6913   if (!CandidateSet.isNewCandidate(Method, PO))
6914     return;
6915 
6916   // C++11 [class.copy]p23: [DR1402]
6917   //   A defaulted move assignment operator that is defined as deleted is
6918   //   ignored by overload resolution.
6919   if (Method->isDefaulted() && Method->isDeleted() &&
6920       Method->isMoveAssignmentOperator())
6921     return;
6922 
6923   // Overload resolution is always an unevaluated context.
6924   EnterExpressionEvaluationContext Unevaluated(
6925       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6926 
6927   // Add this candidate
6928   OverloadCandidate &Candidate =
6929       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6930   Candidate.FoundDecl = FoundDecl;
6931   Candidate.Function = Method;
6932   Candidate.RewriteKind =
6933       CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
6934   Candidate.IsSurrogate = false;
6935   Candidate.IgnoreObjectArgument = false;
6936   Candidate.ExplicitCallArguments = Args.size();
6937 
6938   unsigned NumParams = Proto->getNumParams();
6939 
6940   // (C++ 13.3.2p2): A candidate function having fewer than m
6941   // parameters is viable only if it has an ellipsis in its parameter
6942   // list (8.3.5).
6943   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6944       !Proto->isVariadic() &&
6945       shouldEnforceArgLimit(PartialOverloading, Method)) {
6946     Candidate.Viable = false;
6947     Candidate.FailureKind = ovl_fail_too_many_arguments;
6948     return;
6949   }
6950 
6951   // (C++ 13.3.2p2): A candidate function having more than m parameters
6952   // is viable only if the (m+1)st parameter has a default argument
6953   // (8.3.6). For the purposes of overload resolution, the
6954   // parameter list is truncated on the right, so that there are
6955   // exactly m parameters.
6956   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6957   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6958     // Not enough arguments.
6959     Candidate.Viable = false;
6960     Candidate.FailureKind = ovl_fail_too_few_arguments;
6961     return;
6962   }
6963 
6964   Candidate.Viable = true;
6965 
6966   if (Method->isStatic() || ObjectType.isNull())
6967     // The implicit object argument is ignored.
6968     Candidate.IgnoreObjectArgument = true;
6969   else {
6970     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
6971     // Determine the implicit conversion sequence for the object
6972     // parameter.
6973     Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization(
6974         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6975         Method, ActingContext);
6976     if (Candidate.Conversions[ConvIdx].isBad()) {
6977       Candidate.Viable = false;
6978       Candidate.FailureKind = ovl_fail_bad_conversion;
6979       return;
6980     }
6981   }
6982 
6983   // (CUDA B.1): Check for invalid calls between targets.
6984   if (getLangOpts().CUDA)
6985     if (const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true))
6986       if (!IsAllowedCUDACall(Caller, Method)) {
6987         Candidate.Viable = false;
6988         Candidate.FailureKind = ovl_fail_bad_target;
6989         return;
6990       }
6991 
6992   if (Method->getTrailingRequiresClause()) {
6993     ConstraintSatisfaction Satisfaction;
6994     if (CheckFunctionConstraints(Method, Satisfaction) ||
6995         !Satisfaction.IsSatisfied) {
6996       Candidate.Viable = false;
6997       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6998       return;
6999     }
7000   }
7001 
7002   // Determine the implicit conversion sequences for each of the
7003   // arguments.
7004   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7005     unsigned ConvIdx =
7006         PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
7007     if (Candidate.Conversions[ConvIdx].isInitialized()) {
7008       // We already formed a conversion sequence for this parameter during
7009       // template argument deduction.
7010     } else if (ArgIdx < NumParams) {
7011       // (C++ 13.3.2p3): for F to be a viable function, there shall
7012       // exist for each argument an implicit conversion sequence
7013       // (13.3.3.1) that converts that argument to the corresponding
7014       // parameter of F.
7015       QualType ParamType = Proto->getParamType(ArgIdx);
7016       Candidate.Conversions[ConvIdx]
7017         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7018                                 SuppressUserConversions,
7019                                 /*InOverloadResolution=*/true,
7020                                 /*AllowObjCWritebackConversion=*/
7021                                   getLangOpts().ObjCAutoRefCount);
7022       if (Candidate.Conversions[ConvIdx].isBad()) {
7023         Candidate.Viable = false;
7024         Candidate.FailureKind = ovl_fail_bad_conversion;
7025         return;
7026       }
7027     } else {
7028       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7029       // argument for which there is no corresponding parameter is
7030       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7031       Candidate.Conversions[ConvIdx].setEllipsis();
7032     }
7033   }
7034 
7035   if (EnableIfAttr *FailedAttr =
7036           CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7037     Candidate.Viable = false;
7038     Candidate.FailureKind = ovl_fail_enable_if;
7039     Candidate.DeductionFailure.Data = FailedAttr;
7040     return;
7041   }
7042 
7043   if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
7044       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
7045     Candidate.Viable = false;
7046     Candidate.FailureKind = ovl_non_default_multiversion_function;
7047   }
7048 }
7049 
7050 /// Add a C++ member function template as a candidate to the candidate
7051 /// set, using template argument deduction to produce an appropriate member
7052 /// function template specialization.
7053 void Sema::AddMethodTemplateCandidate(
7054     FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7055     CXXRecordDecl *ActingContext,
7056     TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7057     Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7058     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7059     bool PartialOverloading, OverloadCandidateParamOrder PO) {
7060   if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7061     return;
7062 
7063   // C++ [over.match.funcs]p7:
7064   //   In each case where a candidate is a function template, candidate
7065   //   function template specializations are generated using template argument
7066   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
7067   //   candidate functions in the usual way.113) A given name can refer to one
7068   //   or more function templates and also to a set of overloaded non-template
7069   //   functions. In such a case, the candidate functions generated from each
7070   //   function template are combined with the set of non-template candidate
7071   //   functions.
7072   TemplateDeductionInfo Info(CandidateSet.getLocation());
7073   FunctionDecl *Specialization = nullptr;
7074   ConversionSequenceList Conversions;
7075   if (TemplateDeductionResult Result = DeduceTemplateArguments(
7076           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7077           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7078             return CheckNonDependentConversions(
7079                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7080                 SuppressUserConversions, ActingContext, ObjectType,
7081                 ObjectClassification, PO);
7082           })) {
7083     OverloadCandidate &Candidate =
7084         CandidateSet.addCandidate(Conversions.size(), Conversions);
7085     Candidate.FoundDecl = FoundDecl;
7086     Candidate.Function = MethodTmpl->getTemplatedDecl();
7087     Candidate.Viable = false;
7088     Candidate.RewriteKind =
7089       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7090     Candidate.IsSurrogate = false;
7091     Candidate.IgnoreObjectArgument =
7092         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
7093         ObjectType.isNull();
7094     Candidate.ExplicitCallArguments = Args.size();
7095     if (Result == TDK_NonDependentConversionFailure)
7096       Candidate.FailureKind = ovl_fail_bad_conversion;
7097     else {
7098       Candidate.FailureKind = ovl_fail_bad_deduction;
7099       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7100                                                             Info);
7101     }
7102     return;
7103   }
7104 
7105   // Add the function template specialization produced by template argument
7106   // deduction as a candidate.
7107   assert(Specialization && "Missing member function template specialization?");
7108   assert(isa<CXXMethodDecl>(Specialization) &&
7109          "Specialization is not a member function?");
7110   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
7111                      ActingContext, ObjectType, ObjectClassification, Args,
7112                      CandidateSet, SuppressUserConversions, PartialOverloading,
7113                      Conversions, PO);
7114 }
7115 
7116 /// Determine whether a given function template has a simple explicit specifier
7117 /// or a non-value-dependent explicit-specification that evaluates to true.
7118 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
7119   return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
7120 }
7121 
7122 /// Add a C++ function template specialization as a candidate
7123 /// in the candidate set, using template argument deduction to produce
7124 /// an appropriate function template specialization.
7125 void Sema::AddTemplateOverloadCandidate(
7126     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7127     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7128     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7129     bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7130     OverloadCandidateParamOrder PO) {
7131   if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
7132     return;
7133 
7134   // If the function template has a non-dependent explicit specification,
7135   // exclude it now if appropriate; we are not permitted to perform deduction
7136   // and substitution in this case.
7137   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7138     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7139     Candidate.FoundDecl = FoundDecl;
7140     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7141     Candidate.Viable = false;
7142     Candidate.FailureKind = ovl_fail_explicit;
7143     return;
7144   }
7145 
7146   // C++ [over.match.funcs]p7:
7147   //   In each case where a candidate is a function template, candidate
7148   //   function template specializations are generated using template argument
7149   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
7150   //   candidate functions in the usual way.113) A given name can refer to one
7151   //   or more function templates and also to a set of overloaded non-template
7152   //   functions. In such a case, the candidate functions generated from each
7153   //   function template are combined with the set of non-template candidate
7154   //   functions.
7155   TemplateDeductionInfo Info(CandidateSet.getLocation());
7156   FunctionDecl *Specialization = nullptr;
7157   ConversionSequenceList Conversions;
7158   if (TemplateDeductionResult Result = DeduceTemplateArguments(
7159           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7160           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7161             return CheckNonDependentConversions(
7162                 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7163                 SuppressUserConversions, nullptr, QualType(), {}, PO);
7164           })) {
7165     OverloadCandidate &Candidate =
7166         CandidateSet.addCandidate(Conversions.size(), Conversions);
7167     Candidate.FoundDecl = FoundDecl;
7168     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7169     Candidate.Viable = false;
7170     Candidate.RewriteKind =
7171       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7172     Candidate.IsSurrogate = false;
7173     Candidate.IsADLCandidate = IsADLCandidate;
7174     // Ignore the object argument if there is one, since we don't have an object
7175     // type.
7176     Candidate.IgnoreObjectArgument =
7177         isa<CXXMethodDecl>(Candidate.Function) &&
7178         !isa<CXXConstructorDecl>(Candidate.Function);
7179     Candidate.ExplicitCallArguments = Args.size();
7180     if (Result == TDK_NonDependentConversionFailure)
7181       Candidate.FailureKind = ovl_fail_bad_conversion;
7182     else {
7183       Candidate.FailureKind = ovl_fail_bad_deduction;
7184       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7185                                                             Info);
7186     }
7187     return;
7188   }
7189 
7190   // Add the function template specialization produced by template argument
7191   // deduction as a candidate.
7192   assert(Specialization && "Missing function template specialization?");
7193   AddOverloadCandidate(
7194       Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7195       PartialOverloading, AllowExplicit,
7196       /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO);
7197 }
7198 
7199 /// Check that implicit conversion sequences can be formed for each argument
7200 /// whose corresponding parameter has a non-dependent type, per DR1391's
7201 /// [temp.deduct.call]p10.
7202 bool Sema::CheckNonDependentConversions(
7203     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7204     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7205     ConversionSequenceList &Conversions, bool SuppressUserConversions,
7206     CXXRecordDecl *ActingContext, QualType ObjectType,
7207     Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7208   // FIXME: The cases in which we allow explicit conversions for constructor
7209   // arguments never consider calling a constructor template. It's not clear
7210   // that is correct.
7211   const bool AllowExplicit = false;
7212 
7213   auto *FD = FunctionTemplate->getTemplatedDecl();
7214   auto *Method = dyn_cast<CXXMethodDecl>(FD);
7215   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7216   unsigned ThisConversions = HasThisConversion ? 1 : 0;
7217 
7218   Conversions =
7219       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7220 
7221   // Overload resolution is always an unevaluated context.
7222   EnterExpressionEvaluationContext Unevaluated(
7223       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7224 
7225   // For a method call, check the 'this' conversion here too. DR1391 doesn't
7226   // require that, but this check should never result in a hard error, and
7227   // overload resolution is permitted to sidestep instantiations.
7228   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7229       !ObjectType.isNull()) {
7230     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7231     Conversions[ConvIdx] = TryObjectArgumentInitialization(
7232         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7233         Method, ActingContext);
7234     if (Conversions[ConvIdx].isBad())
7235       return true;
7236   }
7237 
7238   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
7239        ++I) {
7240     QualType ParamType = ParamTypes[I];
7241     if (!ParamType->isDependentType()) {
7242       unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
7243                              ? 0
7244                              : (ThisConversions + I);
7245       Conversions[ConvIdx]
7246         = TryCopyInitialization(*this, Args[I], ParamType,
7247                                 SuppressUserConversions,
7248                                 /*InOverloadResolution=*/true,
7249                                 /*AllowObjCWritebackConversion=*/
7250                                   getLangOpts().ObjCAutoRefCount,
7251                                 AllowExplicit);
7252       if (Conversions[ConvIdx].isBad())
7253         return true;
7254     }
7255   }
7256 
7257   return false;
7258 }
7259 
7260 /// Determine whether this is an allowable conversion from the result
7261 /// of an explicit conversion operator to the expected type, per C++
7262 /// [over.match.conv]p1 and [over.match.ref]p1.
7263 ///
7264 /// \param ConvType The return type of the conversion function.
7265 ///
7266 /// \param ToType The type we are converting to.
7267 ///
7268 /// \param AllowObjCPointerConversion Allow a conversion from one
7269 /// Objective-C pointer to another.
7270 ///
7271 /// \returns true if the conversion is allowable, false otherwise.
7272 static bool isAllowableExplicitConversion(Sema &S,
7273                                           QualType ConvType, QualType ToType,
7274                                           bool AllowObjCPointerConversion) {
7275   QualType ToNonRefType = ToType.getNonReferenceType();
7276 
7277   // Easy case: the types are the same.
7278   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7279     return true;
7280 
7281   // Allow qualification conversions.
7282   bool ObjCLifetimeConversion;
7283   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7284                                   ObjCLifetimeConversion))
7285     return true;
7286 
7287   // If we're not allowed to consider Objective-C pointer conversions,
7288   // we're done.
7289   if (!AllowObjCPointerConversion)
7290     return false;
7291 
7292   // Is this an Objective-C pointer conversion?
7293   bool IncompatibleObjC = false;
7294   QualType ConvertedType;
7295   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7296                                    IncompatibleObjC);
7297 }
7298 
7299 /// AddConversionCandidate - Add a C++ conversion function as a
7300 /// candidate in the candidate set (C++ [over.match.conv],
7301 /// C++ [over.match.copy]). From is the expression we're converting from,
7302 /// and ToType is the type that we're eventually trying to convert to
7303 /// (which may or may not be the same type as the type that the
7304 /// conversion function produces).
7305 void Sema::AddConversionCandidate(
7306     CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7307     CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7308     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7309     bool AllowExplicit, bool AllowResultConversion) {
7310   assert(!Conversion->getDescribedFunctionTemplate() &&
7311          "Conversion function templates use AddTemplateConversionCandidate");
7312   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7313   if (!CandidateSet.isNewCandidate(Conversion))
7314     return;
7315 
7316   // If the conversion function has an undeduced return type, trigger its
7317   // deduction now.
7318   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7319     if (DeduceReturnType(Conversion, From->getExprLoc()))
7320       return;
7321     ConvType = Conversion->getConversionType().getNonReferenceType();
7322   }
7323 
7324   // If we don't allow any conversion of the result type, ignore conversion
7325   // functions that don't convert to exactly (possibly cv-qualified) T.
7326   if (!AllowResultConversion &&
7327       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7328     return;
7329 
7330   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7331   // operator is only a candidate if its return type is the target type or
7332   // can be converted to the target type with a qualification conversion.
7333   //
7334   // FIXME: Include such functions in the candidate list and explain why we
7335   // can't select them.
7336   if (Conversion->isExplicit() &&
7337       !isAllowableExplicitConversion(*this, ConvType, ToType,
7338                                      AllowObjCConversionOnExplicit))
7339     return;
7340 
7341   // Overload resolution is always an unevaluated context.
7342   EnterExpressionEvaluationContext Unevaluated(
7343       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7344 
7345   // Add this candidate
7346   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7347   Candidate.FoundDecl = FoundDecl;
7348   Candidate.Function = Conversion;
7349   Candidate.IsSurrogate = false;
7350   Candidate.IgnoreObjectArgument = false;
7351   Candidate.FinalConversion.setAsIdentityConversion();
7352   Candidate.FinalConversion.setFromType(ConvType);
7353   Candidate.FinalConversion.setAllToTypes(ToType);
7354   Candidate.Viable = true;
7355   Candidate.ExplicitCallArguments = 1;
7356 
7357   // Explicit functions are not actually candidates at all if we're not
7358   // allowing them in this context, but keep them around so we can point
7359   // to them in diagnostics.
7360   if (!AllowExplicit && Conversion->isExplicit()) {
7361     Candidate.Viable = false;
7362     Candidate.FailureKind = ovl_fail_explicit;
7363     return;
7364   }
7365 
7366   // C++ [over.match.funcs]p4:
7367   //   For conversion functions, the function is considered to be a member of
7368   //   the class of the implicit implied object argument for the purpose of
7369   //   defining the type of the implicit object parameter.
7370   //
7371   // Determine the implicit conversion sequence for the implicit
7372   // object parameter.
7373   QualType ImplicitParamType = From->getType();
7374   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7375     ImplicitParamType = FromPtrType->getPointeeType();
7376   CXXRecordDecl *ConversionContext
7377     = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
7378 
7379   Candidate.Conversions[0] = TryObjectArgumentInitialization(
7380       *this, CandidateSet.getLocation(), From->getType(),
7381       From->Classify(Context), Conversion, ConversionContext);
7382 
7383   if (Candidate.Conversions[0].isBad()) {
7384     Candidate.Viable = false;
7385     Candidate.FailureKind = ovl_fail_bad_conversion;
7386     return;
7387   }
7388 
7389   if (Conversion->getTrailingRequiresClause()) {
7390     ConstraintSatisfaction Satisfaction;
7391     if (CheckFunctionConstraints(Conversion, Satisfaction) ||
7392         !Satisfaction.IsSatisfied) {
7393       Candidate.Viable = false;
7394       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7395       return;
7396     }
7397   }
7398 
7399   // We won't go through a user-defined type conversion function to convert a
7400   // derived to base as such conversions are given Conversion Rank. They only
7401   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7402   QualType FromCanon
7403     = Context.getCanonicalType(From->getType().getUnqualifiedType());
7404   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7405   if (FromCanon == ToCanon ||
7406       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7407     Candidate.Viable = false;
7408     Candidate.FailureKind = ovl_fail_trivial_conversion;
7409     return;
7410   }
7411 
7412   // To determine what the conversion from the result of calling the
7413   // conversion function to the type we're eventually trying to
7414   // convert to (ToType), we need to synthesize a call to the
7415   // conversion function and attempt copy initialization from it. This
7416   // makes sure that we get the right semantics with respect to
7417   // lvalues/rvalues and the type. Fortunately, we can allocate this
7418   // call on the stack and we don't need its arguments to be
7419   // well-formed.
7420   DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7421                             VK_LValue, From->getBeginLoc());
7422   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7423                                 Context.getPointerType(Conversion->getType()),
7424                                 CK_FunctionToPointerDecay, &ConversionRef,
7425                                 VK_PRValue, FPOptionsOverride());
7426 
7427   QualType ConversionType = Conversion->getConversionType();
7428   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7429     Candidate.Viable = false;
7430     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7431     return;
7432   }
7433 
7434   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7435 
7436   // Note that it is safe to allocate CallExpr on the stack here because
7437   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7438   // allocator).
7439   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7440 
7441   alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7442   CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7443       Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7444 
7445   ImplicitConversionSequence ICS =
7446       TryCopyInitialization(*this, TheTemporaryCall, ToType,
7447                             /*SuppressUserConversions=*/true,
7448                             /*InOverloadResolution=*/false,
7449                             /*AllowObjCWritebackConversion=*/false);
7450 
7451   switch (ICS.getKind()) {
7452   case ImplicitConversionSequence::StandardConversion:
7453     Candidate.FinalConversion = ICS.Standard;
7454 
7455     // C++ [over.ics.user]p3:
7456     //   If the user-defined conversion is specified by a specialization of a
7457     //   conversion function template, the second standard conversion sequence
7458     //   shall have exact match rank.
7459     if (Conversion->getPrimaryTemplate() &&
7460         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7461       Candidate.Viable = false;
7462       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7463       return;
7464     }
7465 
7466     // C++0x [dcl.init.ref]p5:
7467     //    In the second case, if the reference is an rvalue reference and
7468     //    the second standard conversion sequence of the user-defined
7469     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7470     //    program is ill-formed.
7471     if (ToType->isRValueReferenceType() &&
7472         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7473       Candidate.Viable = false;
7474       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7475       return;
7476     }
7477     break;
7478 
7479   case ImplicitConversionSequence::BadConversion:
7480     Candidate.Viable = false;
7481     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7482     return;
7483 
7484   default:
7485     llvm_unreachable(
7486            "Can only end up with a standard conversion sequence or failure");
7487   }
7488 
7489   if (EnableIfAttr *FailedAttr =
7490           CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7491     Candidate.Viable = false;
7492     Candidate.FailureKind = ovl_fail_enable_if;
7493     Candidate.DeductionFailure.Data = FailedAttr;
7494     return;
7495   }
7496 
7497   if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7498       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7499     Candidate.Viable = false;
7500     Candidate.FailureKind = ovl_non_default_multiversion_function;
7501   }
7502 }
7503 
7504 /// Adds a conversion function template specialization
7505 /// candidate to the overload set, using template argument deduction
7506 /// to deduce the template arguments of the conversion function
7507 /// template from the type that we are converting to (C++
7508 /// [temp.deduct.conv]).
7509 void Sema::AddTemplateConversionCandidate(
7510     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7511     CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7512     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7513     bool AllowExplicit, bool AllowResultConversion) {
7514   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7515          "Only conversion function templates permitted here");
7516 
7517   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7518     return;
7519 
7520   // If the function template has a non-dependent explicit specification,
7521   // exclude it now if appropriate; we are not permitted to perform deduction
7522   // and substitution in this case.
7523   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7524     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7525     Candidate.FoundDecl = FoundDecl;
7526     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7527     Candidate.Viable = false;
7528     Candidate.FailureKind = ovl_fail_explicit;
7529     return;
7530   }
7531 
7532   TemplateDeductionInfo Info(CandidateSet.getLocation());
7533   CXXConversionDecl *Specialization = nullptr;
7534   if (TemplateDeductionResult Result
7535         = DeduceTemplateArguments(FunctionTemplate, ToType,
7536                                   Specialization, Info)) {
7537     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7538     Candidate.FoundDecl = FoundDecl;
7539     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7540     Candidate.Viable = false;
7541     Candidate.FailureKind = ovl_fail_bad_deduction;
7542     Candidate.IsSurrogate = false;
7543     Candidate.IgnoreObjectArgument = false;
7544     Candidate.ExplicitCallArguments = 1;
7545     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7546                                                           Info);
7547     return;
7548   }
7549 
7550   // Add the conversion function template specialization produced by
7551   // template argument deduction as a candidate.
7552   assert(Specialization && "Missing function template specialization?");
7553   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7554                          CandidateSet, AllowObjCConversionOnExplicit,
7555                          AllowExplicit, AllowResultConversion);
7556 }
7557 
7558 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7559 /// converts the given @c Object to a function pointer via the
7560 /// conversion function @c Conversion, and then attempts to call it
7561 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7562 /// the type of function that we'll eventually be calling.
7563 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7564                                  DeclAccessPair FoundDecl,
7565                                  CXXRecordDecl *ActingContext,
7566                                  const FunctionProtoType *Proto,
7567                                  Expr *Object,
7568                                  ArrayRef<Expr *> Args,
7569                                  OverloadCandidateSet& CandidateSet) {
7570   if (!CandidateSet.isNewCandidate(Conversion))
7571     return;
7572 
7573   // Overload resolution is always an unevaluated context.
7574   EnterExpressionEvaluationContext Unevaluated(
7575       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7576 
7577   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7578   Candidate.FoundDecl = FoundDecl;
7579   Candidate.Function = nullptr;
7580   Candidate.Surrogate = Conversion;
7581   Candidate.Viable = true;
7582   Candidate.IsSurrogate = true;
7583   Candidate.IgnoreObjectArgument = false;
7584   Candidate.ExplicitCallArguments = Args.size();
7585 
7586   // Determine the implicit conversion sequence for the implicit
7587   // object parameter.
7588   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7589       *this, CandidateSet.getLocation(), Object->getType(),
7590       Object->Classify(Context), Conversion, ActingContext);
7591   if (ObjectInit.isBad()) {
7592     Candidate.Viable = false;
7593     Candidate.FailureKind = ovl_fail_bad_conversion;
7594     Candidate.Conversions[0] = ObjectInit;
7595     return;
7596   }
7597 
7598   // The first conversion is actually a user-defined conversion whose
7599   // first conversion is ObjectInit's standard conversion (which is
7600   // effectively a reference binding). Record it as such.
7601   Candidate.Conversions[0].setUserDefined();
7602   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7603   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7604   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7605   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7606   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7607   Candidate.Conversions[0].UserDefined.After
7608     = Candidate.Conversions[0].UserDefined.Before;
7609   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7610 
7611   // Find the
7612   unsigned NumParams = Proto->getNumParams();
7613 
7614   // (C++ 13.3.2p2): A candidate function having fewer than m
7615   // parameters is viable only if it has an ellipsis in its parameter
7616   // list (8.3.5).
7617   if (Args.size() > NumParams && !Proto->isVariadic()) {
7618     Candidate.Viable = false;
7619     Candidate.FailureKind = ovl_fail_too_many_arguments;
7620     return;
7621   }
7622 
7623   // Function types don't have any default arguments, so just check if
7624   // we have enough arguments.
7625   if (Args.size() < NumParams) {
7626     // Not enough arguments.
7627     Candidate.Viable = false;
7628     Candidate.FailureKind = ovl_fail_too_few_arguments;
7629     return;
7630   }
7631 
7632   // Determine the implicit conversion sequences for each of the
7633   // arguments.
7634   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7635     if (ArgIdx < NumParams) {
7636       // (C++ 13.3.2p3): for F to be a viable function, there shall
7637       // exist for each argument an implicit conversion sequence
7638       // (13.3.3.1) that converts that argument to the corresponding
7639       // parameter of F.
7640       QualType ParamType = Proto->getParamType(ArgIdx);
7641       Candidate.Conversions[ArgIdx + 1]
7642         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7643                                 /*SuppressUserConversions=*/false,
7644                                 /*InOverloadResolution=*/false,
7645                                 /*AllowObjCWritebackConversion=*/
7646                                   getLangOpts().ObjCAutoRefCount);
7647       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7648         Candidate.Viable = false;
7649         Candidate.FailureKind = ovl_fail_bad_conversion;
7650         return;
7651       }
7652     } else {
7653       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7654       // argument for which there is no corresponding parameter is
7655       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7656       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7657     }
7658   }
7659 
7660   if (EnableIfAttr *FailedAttr =
7661           CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7662     Candidate.Viable = false;
7663     Candidate.FailureKind = ovl_fail_enable_if;
7664     Candidate.DeductionFailure.Data = FailedAttr;
7665     return;
7666   }
7667 }
7668 
7669 /// Add all of the non-member operator function declarations in the given
7670 /// function set to the overload candidate set.
7671 void Sema::AddNonMemberOperatorCandidates(
7672     const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
7673     OverloadCandidateSet &CandidateSet,
7674     TemplateArgumentListInfo *ExplicitTemplateArgs) {
7675   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7676     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7677     ArrayRef<Expr *> FunctionArgs = Args;
7678 
7679     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7680     FunctionDecl *FD =
7681         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7682 
7683     // Don't consider rewritten functions if we're not rewriting.
7684     if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
7685       continue;
7686 
7687     assert(!isa<CXXMethodDecl>(FD) &&
7688            "unqualified operator lookup found a member function");
7689 
7690     if (FunTmpl) {
7691       AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
7692                                    FunctionArgs, CandidateSet);
7693       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7694         AddTemplateOverloadCandidate(
7695             FunTmpl, F.getPair(), ExplicitTemplateArgs,
7696             {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
7697             true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
7698     } else {
7699       if (ExplicitTemplateArgs)
7700         continue;
7701       AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
7702       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7703         AddOverloadCandidate(FD, F.getPair(),
7704                              {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
7705                              false, false, true, false, ADLCallKind::NotADL,
7706                              None, OverloadCandidateParamOrder::Reversed);
7707     }
7708   }
7709 }
7710 
7711 /// Add overload candidates for overloaded operators that are
7712 /// member functions.
7713 ///
7714 /// Add the overloaded operator candidates that are member functions
7715 /// for the operator Op that was used in an operator expression such
7716 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7717 /// CandidateSet will store the added overload candidates. (C++
7718 /// [over.match.oper]).
7719 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7720                                        SourceLocation OpLoc,
7721                                        ArrayRef<Expr *> Args,
7722                                        OverloadCandidateSet &CandidateSet,
7723                                        OverloadCandidateParamOrder PO) {
7724   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7725 
7726   // C++ [over.match.oper]p3:
7727   //   For a unary operator @ with an operand of a type whose
7728   //   cv-unqualified version is T1, and for a binary operator @ with
7729   //   a left operand of a type whose cv-unqualified version is T1 and
7730   //   a right operand of a type whose cv-unqualified version is T2,
7731   //   three sets of candidate functions, designated member
7732   //   candidates, non-member candidates and built-in candidates, are
7733   //   constructed as follows:
7734   QualType T1 = Args[0]->getType();
7735 
7736   //     -- If T1 is a complete class type or a class currently being
7737   //        defined, the set of member candidates is the result of the
7738   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7739   //        the set of member candidates is empty.
7740   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7741     // Complete the type if it can be completed.
7742     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7743       return;
7744     // If the type is neither complete nor being defined, bail out now.
7745     if (!T1Rec->getDecl()->getDefinition())
7746       return;
7747 
7748     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7749     LookupQualifiedName(Operators, T1Rec->getDecl());
7750     Operators.suppressDiagnostics();
7751 
7752     for (LookupResult::iterator Oper = Operators.begin(),
7753                              OperEnd = Operators.end();
7754          Oper != OperEnd;
7755          ++Oper)
7756       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7757                          Args[0]->Classify(Context), Args.slice(1),
7758                          CandidateSet, /*SuppressUserConversion=*/false, PO);
7759   }
7760 }
7761 
7762 /// AddBuiltinCandidate - Add a candidate for a built-in
7763 /// operator. ResultTy and ParamTys are the result and parameter types
7764 /// of the built-in candidate, respectively. Args and NumArgs are the
7765 /// arguments being passed to the candidate. IsAssignmentOperator
7766 /// should be true when this built-in candidate is an assignment
7767 /// operator. NumContextualBoolArguments is the number of arguments
7768 /// (at the beginning of the argument list) that will be contextually
7769 /// converted to bool.
7770 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7771                                OverloadCandidateSet& CandidateSet,
7772                                bool IsAssignmentOperator,
7773                                unsigned NumContextualBoolArguments) {
7774   // Overload resolution is always an unevaluated context.
7775   EnterExpressionEvaluationContext Unevaluated(
7776       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7777 
7778   // Add this candidate
7779   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7780   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7781   Candidate.Function = nullptr;
7782   Candidate.IsSurrogate = false;
7783   Candidate.IgnoreObjectArgument = false;
7784   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7785 
7786   // Determine the implicit conversion sequences for each of the
7787   // arguments.
7788   Candidate.Viable = true;
7789   Candidate.ExplicitCallArguments = Args.size();
7790   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7791     // C++ [over.match.oper]p4:
7792     //   For the built-in assignment operators, conversions of the
7793     //   left operand are restricted as follows:
7794     //     -- no temporaries are introduced to hold the left operand, and
7795     //     -- no user-defined conversions are applied to the left
7796     //        operand to achieve a type match with the left-most
7797     //        parameter of a built-in candidate.
7798     //
7799     // We block these conversions by turning off user-defined
7800     // conversions, since that is the only way that initialization of
7801     // a reference to a non-class type can occur from something that
7802     // is not of the same type.
7803     if (ArgIdx < NumContextualBoolArguments) {
7804       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7805              "Contextual conversion to bool requires bool type");
7806       Candidate.Conversions[ArgIdx]
7807         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7808     } else {
7809       Candidate.Conversions[ArgIdx]
7810         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7811                                 ArgIdx == 0 && IsAssignmentOperator,
7812                                 /*InOverloadResolution=*/false,
7813                                 /*AllowObjCWritebackConversion=*/
7814                                   getLangOpts().ObjCAutoRefCount);
7815     }
7816     if (Candidate.Conversions[ArgIdx].isBad()) {
7817       Candidate.Viable = false;
7818       Candidate.FailureKind = ovl_fail_bad_conversion;
7819       break;
7820     }
7821   }
7822 }
7823 
7824 namespace {
7825 
7826 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7827 /// candidate operator functions for built-in operators (C++
7828 /// [over.built]). The types are separated into pointer types and
7829 /// enumeration types.
7830 class BuiltinCandidateTypeSet  {
7831   /// TypeSet - A set of types.
7832   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7833                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7834 
7835   /// PointerTypes - The set of pointer types that will be used in the
7836   /// built-in candidates.
7837   TypeSet PointerTypes;
7838 
7839   /// MemberPointerTypes - The set of member pointer types that will be
7840   /// used in the built-in candidates.
7841   TypeSet MemberPointerTypes;
7842 
7843   /// EnumerationTypes - The set of enumeration types that will be
7844   /// used in the built-in candidates.
7845   TypeSet EnumerationTypes;
7846 
7847   /// The set of vector types that will be used in the built-in
7848   /// candidates.
7849   TypeSet VectorTypes;
7850 
7851   /// The set of matrix types that will be used in the built-in
7852   /// candidates.
7853   TypeSet MatrixTypes;
7854 
7855   /// A flag indicating non-record types are viable candidates
7856   bool HasNonRecordTypes;
7857 
7858   /// A flag indicating whether either arithmetic or enumeration types
7859   /// were present in the candidate set.
7860   bool HasArithmeticOrEnumeralTypes;
7861 
7862   /// A flag indicating whether the nullptr type was present in the
7863   /// candidate set.
7864   bool HasNullPtrType;
7865 
7866   /// Sema - The semantic analysis instance where we are building the
7867   /// candidate type set.
7868   Sema &SemaRef;
7869 
7870   /// Context - The AST context in which we will build the type sets.
7871   ASTContext &Context;
7872 
7873   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7874                                                const Qualifiers &VisibleQuals);
7875   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7876 
7877 public:
7878   /// iterator - Iterates through the types that are part of the set.
7879   typedef TypeSet::iterator iterator;
7880 
7881   BuiltinCandidateTypeSet(Sema &SemaRef)
7882     : HasNonRecordTypes(false),
7883       HasArithmeticOrEnumeralTypes(false),
7884       HasNullPtrType(false),
7885       SemaRef(SemaRef),
7886       Context(SemaRef.Context) { }
7887 
7888   void AddTypesConvertedFrom(QualType Ty,
7889                              SourceLocation Loc,
7890                              bool AllowUserConversions,
7891                              bool AllowExplicitConversions,
7892                              const Qualifiers &VisibleTypeConversionsQuals);
7893 
7894   llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
7895   llvm::iterator_range<iterator> member_pointer_types() {
7896     return MemberPointerTypes;
7897   }
7898   llvm::iterator_range<iterator> enumeration_types() {
7899     return EnumerationTypes;
7900   }
7901   llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
7902   llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
7903 
7904   bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
7905   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7906   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7907   bool hasNullPtrType() const { return HasNullPtrType; }
7908 };
7909 
7910 } // end anonymous namespace
7911 
7912 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7913 /// the set of pointer types along with any more-qualified variants of
7914 /// that type. For example, if @p Ty is "int const *", this routine
7915 /// will add "int const *", "int const volatile *", "int const
7916 /// restrict *", and "int const volatile restrict *" to the set of
7917 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7918 /// false otherwise.
7919 ///
7920 /// FIXME: what to do about extended qualifiers?
7921 bool
7922 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7923                                              const Qualifiers &VisibleQuals) {
7924 
7925   // Insert this type.
7926   if (!PointerTypes.insert(Ty))
7927     return false;
7928 
7929   QualType PointeeTy;
7930   const PointerType *PointerTy = Ty->getAs<PointerType>();
7931   bool buildObjCPtr = false;
7932   if (!PointerTy) {
7933     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7934     PointeeTy = PTy->getPointeeType();
7935     buildObjCPtr = true;
7936   } else {
7937     PointeeTy = PointerTy->getPointeeType();
7938   }
7939 
7940   // Don't add qualified variants of arrays. For one, they're not allowed
7941   // (the qualifier would sink to the element type), and for another, the
7942   // only overload situation where it matters is subscript or pointer +- int,
7943   // and those shouldn't have qualifier variants anyway.
7944   if (PointeeTy->isArrayType())
7945     return true;
7946 
7947   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7948   bool hasVolatile = VisibleQuals.hasVolatile();
7949   bool hasRestrict = VisibleQuals.hasRestrict();
7950 
7951   // Iterate through all strict supersets of BaseCVR.
7952   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7953     if ((CVR | BaseCVR) != CVR) continue;
7954     // Skip over volatile if no volatile found anywhere in the types.
7955     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7956 
7957     // Skip over restrict if no restrict found anywhere in the types, or if
7958     // the type cannot be restrict-qualified.
7959     if ((CVR & Qualifiers::Restrict) &&
7960         (!hasRestrict ||
7961          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7962       continue;
7963 
7964     // Build qualified pointee type.
7965     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7966 
7967     // Build qualified pointer type.
7968     QualType QPointerTy;
7969     if (!buildObjCPtr)
7970       QPointerTy = Context.getPointerType(QPointeeTy);
7971     else
7972       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7973 
7974     // Insert qualified pointer type.
7975     PointerTypes.insert(QPointerTy);
7976   }
7977 
7978   return true;
7979 }
7980 
7981 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7982 /// to the set of pointer types along with any more-qualified variants of
7983 /// that type. For example, if @p Ty is "int const *", this routine
7984 /// will add "int const *", "int const volatile *", "int const
7985 /// restrict *", and "int const volatile restrict *" to the set of
7986 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7987 /// false otherwise.
7988 ///
7989 /// FIXME: what to do about extended qualifiers?
7990 bool
7991 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7992     QualType Ty) {
7993   // Insert this type.
7994   if (!MemberPointerTypes.insert(Ty))
7995     return false;
7996 
7997   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7998   assert(PointerTy && "type was not a member pointer type!");
7999 
8000   QualType PointeeTy = PointerTy->getPointeeType();
8001   // Don't add qualified variants of arrays. For one, they're not allowed
8002   // (the qualifier would sink to the element type), and for another, the
8003   // only overload situation where it matters is subscript or pointer +- int,
8004   // and those shouldn't have qualifier variants anyway.
8005   if (PointeeTy->isArrayType())
8006     return true;
8007   const Type *ClassTy = PointerTy->getClass();
8008 
8009   // Iterate through all strict supersets of the pointee type's CVR
8010   // qualifiers.
8011   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8012   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8013     if ((CVR | BaseCVR) != CVR) continue;
8014 
8015     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8016     MemberPointerTypes.insert(
8017       Context.getMemberPointerType(QPointeeTy, ClassTy));
8018   }
8019 
8020   return true;
8021 }
8022 
8023 /// AddTypesConvertedFrom - Add each of the types to which the type @p
8024 /// Ty can be implicit converted to the given set of @p Types. We're
8025 /// primarily interested in pointer types and enumeration types. We also
8026 /// take member pointer types, for the conditional operator.
8027 /// AllowUserConversions is true if we should look at the conversion
8028 /// functions of a class type, and AllowExplicitConversions if we
8029 /// should also include the explicit conversion functions of a class
8030 /// type.
8031 void
8032 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
8033                                                SourceLocation Loc,
8034                                                bool AllowUserConversions,
8035                                                bool AllowExplicitConversions,
8036                                                const Qualifiers &VisibleQuals) {
8037   // Only deal with canonical types.
8038   Ty = Context.getCanonicalType(Ty);
8039 
8040   // Look through reference types; they aren't part of the type of an
8041   // expression for the purposes of conversions.
8042   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
8043     Ty = RefTy->getPointeeType();
8044 
8045   // If we're dealing with an array type, decay to the pointer.
8046   if (Ty->isArrayType())
8047     Ty = SemaRef.Context.getArrayDecayedType(Ty);
8048 
8049   // Otherwise, we don't care about qualifiers on the type.
8050   Ty = Ty.getLocalUnqualifiedType();
8051 
8052   // Flag if we ever add a non-record type.
8053   const RecordType *TyRec = Ty->getAs<RecordType>();
8054   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
8055 
8056   // Flag if we encounter an arithmetic type.
8057   HasArithmeticOrEnumeralTypes =
8058     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
8059 
8060   if (Ty->isObjCIdType() || Ty->isObjCClassType())
8061     PointerTypes.insert(Ty);
8062   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
8063     // Insert our type, and its more-qualified variants, into the set
8064     // of types.
8065     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
8066       return;
8067   } else if (Ty->isMemberPointerType()) {
8068     // Member pointers are far easier, since the pointee can't be converted.
8069     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
8070       return;
8071   } else if (Ty->isEnumeralType()) {
8072     HasArithmeticOrEnumeralTypes = true;
8073     EnumerationTypes.insert(Ty);
8074   } else if (Ty->isVectorType()) {
8075     // We treat vector types as arithmetic types in many contexts as an
8076     // extension.
8077     HasArithmeticOrEnumeralTypes = true;
8078     VectorTypes.insert(Ty);
8079   } else if (Ty->isMatrixType()) {
8080     // Similar to vector types, we treat vector types as arithmetic types in
8081     // many contexts as an extension.
8082     HasArithmeticOrEnumeralTypes = true;
8083     MatrixTypes.insert(Ty);
8084   } else if (Ty->isNullPtrType()) {
8085     HasNullPtrType = true;
8086   } else if (AllowUserConversions && TyRec) {
8087     // No conversion functions in incomplete types.
8088     if (!SemaRef.isCompleteType(Loc, Ty))
8089       return;
8090 
8091     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8092     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8093       if (isa<UsingShadowDecl>(D))
8094         D = cast<UsingShadowDecl>(D)->getTargetDecl();
8095 
8096       // Skip conversion function templates; they don't tell us anything
8097       // about which builtin types we can convert to.
8098       if (isa<FunctionTemplateDecl>(D))
8099         continue;
8100 
8101       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
8102       if (AllowExplicitConversions || !Conv->isExplicit()) {
8103         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
8104                               VisibleQuals);
8105       }
8106     }
8107   }
8108 }
8109 /// Helper function for adjusting address spaces for the pointer or reference
8110 /// operands of builtin operators depending on the argument.
8111 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
8112                                                         Expr *Arg) {
8113   return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
8114 }
8115 
8116 /// Helper function for AddBuiltinOperatorCandidates() that adds
8117 /// the volatile- and non-volatile-qualified assignment operators for the
8118 /// given type to the candidate set.
8119 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
8120                                                    QualType T,
8121                                                    ArrayRef<Expr *> Args,
8122                                     OverloadCandidateSet &CandidateSet) {
8123   QualType ParamTypes[2];
8124 
8125   // T& operator=(T&, T)
8126   ParamTypes[0] = S.Context.getLValueReferenceType(
8127       AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
8128   ParamTypes[1] = T;
8129   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8130                         /*IsAssignmentOperator=*/true);
8131 
8132   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
8133     // volatile T& operator=(volatile T&, T)
8134     ParamTypes[0] = S.Context.getLValueReferenceType(
8135         AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
8136                                                 Args[0]));
8137     ParamTypes[1] = T;
8138     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8139                           /*IsAssignmentOperator=*/true);
8140   }
8141 }
8142 
8143 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8144 /// if any, found in visible type conversion functions found in ArgExpr's type.
8145 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8146     Qualifiers VRQuals;
8147     const RecordType *TyRec;
8148     if (const MemberPointerType *RHSMPType =
8149         ArgExpr->getType()->getAs<MemberPointerType>())
8150       TyRec = RHSMPType->getClass()->getAs<RecordType>();
8151     else
8152       TyRec = ArgExpr->getType()->getAs<RecordType>();
8153     if (!TyRec) {
8154       // Just to be safe, assume the worst case.
8155       VRQuals.addVolatile();
8156       VRQuals.addRestrict();
8157       return VRQuals;
8158     }
8159 
8160     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8161     if (!ClassDecl->hasDefinition())
8162       return VRQuals;
8163 
8164     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8165       if (isa<UsingShadowDecl>(D))
8166         D = cast<UsingShadowDecl>(D)->getTargetDecl();
8167       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8168         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8169         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8170           CanTy = ResTypeRef->getPointeeType();
8171         // Need to go down the pointer/mempointer chain and add qualifiers
8172         // as see them.
8173         bool done = false;
8174         while (!done) {
8175           if (CanTy.isRestrictQualified())
8176             VRQuals.addRestrict();
8177           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8178             CanTy = ResTypePtr->getPointeeType();
8179           else if (const MemberPointerType *ResTypeMPtr =
8180                 CanTy->getAs<MemberPointerType>())
8181             CanTy = ResTypeMPtr->getPointeeType();
8182           else
8183             done = true;
8184           if (CanTy.isVolatileQualified())
8185             VRQuals.addVolatile();
8186           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8187             return VRQuals;
8188         }
8189       }
8190     }
8191     return VRQuals;
8192 }
8193 
8194 namespace {
8195 
8196 /// Helper class to manage the addition of builtin operator overload
8197 /// candidates. It provides shared state and utility methods used throughout
8198 /// the process, as well as a helper method to add each group of builtin
8199 /// operator overloads from the standard to a candidate set.
8200 class BuiltinOperatorOverloadBuilder {
8201   // Common instance state available to all overload candidate addition methods.
8202   Sema &S;
8203   ArrayRef<Expr *> Args;
8204   Qualifiers VisibleTypeConversionsQuals;
8205   bool HasArithmeticOrEnumeralCandidateType;
8206   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8207   OverloadCandidateSet &CandidateSet;
8208 
8209   static constexpr int ArithmeticTypesCap = 24;
8210   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8211 
8212   // Define some indices used to iterate over the arithmetic types in
8213   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
8214   // types are that preserved by promotion (C++ [over.built]p2).
8215   unsigned FirstIntegralType,
8216            LastIntegralType;
8217   unsigned FirstPromotedIntegralType,
8218            LastPromotedIntegralType;
8219   unsigned FirstPromotedArithmeticType,
8220            LastPromotedArithmeticType;
8221   unsigned NumArithmeticTypes;
8222 
8223   void InitArithmeticTypes() {
8224     // Start of promoted types.
8225     FirstPromotedArithmeticType = 0;
8226     ArithmeticTypes.push_back(S.Context.FloatTy);
8227     ArithmeticTypes.push_back(S.Context.DoubleTy);
8228     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8229     if (S.Context.getTargetInfo().hasFloat128Type())
8230       ArithmeticTypes.push_back(S.Context.Float128Ty);
8231     if (S.Context.getTargetInfo().hasIbm128Type())
8232       ArithmeticTypes.push_back(S.Context.Ibm128Ty);
8233 
8234     // Start of integral types.
8235     FirstIntegralType = ArithmeticTypes.size();
8236     FirstPromotedIntegralType = ArithmeticTypes.size();
8237     ArithmeticTypes.push_back(S.Context.IntTy);
8238     ArithmeticTypes.push_back(S.Context.LongTy);
8239     ArithmeticTypes.push_back(S.Context.LongLongTy);
8240     if (S.Context.getTargetInfo().hasInt128Type() ||
8241         (S.Context.getAuxTargetInfo() &&
8242          S.Context.getAuxTargetInfo()->hasInt128Type()))
8243       ArithmeticTypes.push_back(S.Context.Int128Ty);
8244     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8245     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8246     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8247     if (S.Context.getTargetInfo().hasInt128Type() ||
8248         (S.Context.getAuxTargetInfo() &&
8249          S.Context.getAuxTargetInfo()->hasInt128Type()))
8250       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8251     LastPromotedIntegralType = ArithmeticTypes.size();
8252     LastPromotedArithmeticType = ArithmeticTypes.size();
8253     // End of promoted types.
8254 
8255     ArithmeticTypes.push_back(S.Context.BoolTy);
8256     ArithmeticTypes.push_back(S.Context.CharTy);
8257     ArithmeticTypes.push_back(S.Context.WCharTy);
8258     if (S.Context.getLangOpts().Char8)
8259       ArithmeticTypes.push_back(S.Context.Char8Ty);
8260     ArithmeticTypes.push_back(S.Context.Char16Ty);
8261     ArithmeticTypes.push_back(S.Context.Char32Ty);
8262     ArithmeticTypes.push_back(S.Context.SignedCharTy);
8263     ArithmeticTypes.push_back(S.Context.ShortTy);
8264     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8265     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8266     LastIntegralType = ArithmeticTypes.size();
8267     NumArithmeticTypes = ArithmeticTypes.size();
8268     // End of integral types.
8269     // FIXME: What about complex? What about half?
8270 
8271     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
8272            "Enough inline storage for all arithmetic types.");
8273   }
8274 
8275   /// Helper method to factor out the common pattern of adding overloads
8276   /// for '++' and '--' builtin operators.
8277   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8278                                            bool HasVolatile,
8279                                            bool HasRestrict) {
8280     QualType ParamTypes[2] = {
8281       S.Context.getLValueReferenceType(CandidateTy),
8282       S.Context.IntTy
8283     };
8284 
8285     // Non-volatile version.
8286     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8287 
8288     // Use a heuristic to reduce number of builtin candidates in the set:
8289     // add volatile version only if there are conversions to a volatile type.
8290     if (HasVolatile) {
8291       ParamTypes[0] =
8292         S.Context.getLValueReferenceType(
8293           S.Context.getVolatileType(CandidateTy));
8294       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8295     }
8296 
8297     // Add restrict version only if there are conversions to a restrict type
8298     // and our candidate type is a non-restrict-qualified pointer.
8299     if (HasRestrict && CandidateTy->isAnyPointerType() &&
8300         !CandidateTy.isRestrictQualified()) {
8301       ParamTypes[0]
8302         = S.Context.getLValueReferenceType(
8303             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8304       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8305 
8306       if (HasVolatile) {
8307         ParamTypes[0]
8308           = S.Context.getLValueReferenceType(
8309               S.Context.getCVRQualifiedType(CandidateTy,
8310                                             (Qualifiers::Volatile |
8311                                              Qualifiers::Restrict)));
8312         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8313       }
8314     }
8315 
8316   }
8317 
8318   /// Helper to add an overload candidate for a binary builtin with types \p L
8319   /// and \p R.
8320   void AddCandidate(QualType L, QualType R) {
8321     QualType LandR[2] = {L, R};
8322     S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8323   }
8324 
8325 public:
8326   BuiltinOperatorOverloadBuilder(
8327     Sema &S, ArrayRef<Expr *> Args,
8328     Qualifiers VisibleTypeConversionsQuals,
8329     bool HasArithmeticOrEnumeralCandidateType,
8330     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8331     OverloadCandidateSet &CandidateSet)
8332     : S(S), Args(Args),
8333       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8334       HasArithmeticOrEnumeralCandidateType(
8335         HasArithmeticOrEnumeralCandidateType),
8336       CandidateTypes(CandidateTypes),
8337       CandidateSet(CandidateSet) {
8338 
8339     InitArithmeticTypes();
8340   }
8341 
8342   // Increment is deprecated for bool since C++17.
8343   //
8344   // C++ [over.built]p3:
8345   //
8346   //   For every pair (T, VQ), where T is an arithmetic type other
8347   //   than bool, and VQ is either volatile or empty, there exist
8348   //   candidate operator functions of the form
8349   //
8350   //       VQ T&      operator++(VQ T&);
8351   //       T          operator++(VQ T&, int);
8352   //
8353   // C++ [over.built]p4:
8354   //
8355   //   For every pair (T, VQ), where T is an arithmetic type other
8356   //   than bool, and VQ is either volatile or empty, there exist
8357   //   candidate operator functions of the form
8358   //
8359   //       VQ T&      operator--(VQ T&);
8360   //       T          operator--(VQ T&, int);
8361   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8362     if (!HasArithmeticOrEnumeralCandidateType)
8363       return;
8364 
8365     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8366       const auto TypeOfT = ArithmeticTypes[Arith];
8367       if (TypeOfT == S.Context.BoolTy) {
8368         if (Op == OO_MinusMinus)
8369           continue;
8370         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8371           continue;
8372       }
8373       addPlusPlusMinusMinusStyleOverloads(
8374         TypeOfT,
8375         VisibleTypeConversionsQuals.hasVolatile(),
8376         VisibleTypeConversionsQuals.hasRestrict());
8377     }
8378   }
8379 
8380   // C++ [over.built]p5:
8381   //
8382   //   For every pair (T, VQ), where T is a cv-qualified or
8383   //   cv-unqualified object type, and VQ is either volatile or
8384   //   empty, there exist candidate operator functions of the form
8385   //
8386   //       T*VQ&      operator++(T*VQ&);
8387   //       T*VQ&      operator--(T*VQ&);
8388   //       T*         operator++(T*VQ&, int);
8389   //       T*         operator--(T*VQ&, int);
8390   void addPlusPlusMinusMinusPointerOverloads() {
8391     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
8392       // Skip pointer types that aren't pointers to object types.
8393       if (!PtrTy->getPointeeType()->isObjectType())
8394         continue;
8395 
8396       addPlusPlusMinusMinusStyleOverloads(
8397           PtrTy,
8398           (!PtrTy.isVolatileQualified() &&
8399            VisibleTypeConversionsQuals.hasVolatile()),
8400           (!PtrTy.isRestrictQualified() &&
8401            VisibleTypeConversionsQuals.hasRestrict()));
8402     }
8403   }
8404 
8405   // C++ [over.built]p6:
8406   //   For every cv-qualified or cv-unqualified object type T, there
8407   //   exist candidate operator functions of the form
8408   //
8409   //       T&         operator*(T*);
8410   //
8411   // C++ [over.built]p7:
8412   //   For every function type T that does not have cv-qualifiers or a
8413   //   ref-qualifier, there exist candidate operator functions of the form
8414   //       T&         operator*(T*);
8415   void addUnaryStarPointerOverloads() {
8416     for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
8417       QualType PointeeTy = ParamTy->getPointeeType();
8418       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8419         continue;
8420 
8421       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8422         if (Proto->getMethodQuals() || Proto->getRefQualifier())
8423           continue;
8424 
8425       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8426     }
8427   }
8428 
8429   // C++ [over.built]p9:
8430   //  For every promoted arithmetic type T, there exist candidate
8431   //  operator functions of the form
8432   //
8433   //       T         operator+(T);
8434   //       T         operator-(T);
8435   void addUnaryPlusOrMinusArithmeticOverloads() {
8436     if (!HasArithmeticOrEnumeralCandidateType)
8437       return;
8438 
8439     for (unsigned Arith = FirstPromotedArithmeticType;
8440          Arith < LastPromotedArithmeticType; ++Arith) {
8441       QualType ArithTy = ArithmeticTypes[Arith];
8442       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8443     }
8444 
8445     // Extension: We also add these operators for vector types.
8446     for (QualType VecTy : CandidateTypes[0].vector_types())
8447       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8448   }
8449 
8450   // C++ [over.built]p8:
8451   //   For every type T, there exist candidate operator functions of
8452   //   the form
8453   //
8454   //       T*         operator+(T*);
8455   void addUnaryPlusPointerOverloads() {
8456     for (QualType ParamTy : CandidateTypes[0].pointer_types())
8457       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8458   }
8459 
8460   // C++ [over.built]p10:
8461   //   For every promoted integral type T, there exist candidate
8462   //   operator functions of the form
8463   //
8464   //        T         operator~(T);
8465   void addUnaryTildePromotedIntegralOverloads() {
8466     if (!HasArithmeticOrEnumeralCandidateType)
8467       return;
8468 
8469     for (unsigned Int = FirstPromotedIntegralType;
8470          Int < LastPromotedIntegralType; ++Int) {
8471       QualType IntTy = ArithmeticTypes[Int];
8472       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8473     }
8474 
8475     // Extension: We also add this operator for vector types.
8476     for (QualType VecTy : CandidateTypes[0].vector_types())
8477       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8478   }
8479 
8480   // C++ [over.match.oper]p16:
8481   //   For every pointer to member type T or type std::nullptr_t, there
8482   //   exist candidate operator functions of the form
8483   //
8484   //        bool operator==(T,T);
8485   //        bool operator!=(T,T);
8486   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8487     /// Set of (canonical) types that we've already handled.
8488     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8489 
8490     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8491       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
8492         // Don't add the same builtin candidate twice.
8493         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
8494           continue;
8495 
8496         QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
8497         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8498       }
8499 
8500       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8501         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8502         if (AddedTypes.insert(NullPtrTy).second) {
8503           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8504           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8505         }
8506       }
8507     }
8508   }
8509 
8510   // C++ [over.built]p15:
8511   //
8512   //   For every T, where T is an enumeration type or a pointer type,
8513   //   there exist candidate operator functions of the form
8514   //
8515   //        bool       operator<(T, T);
8516   //        bool       operator>(T, T);
8517   //        bool       operator<=(T, T);
8518   //        bool       operator>=(T, T);
8519   //        bool       operator==(T, T);
8520   //        bool       operator!=(T, T);
8521   //           R       operator<=>(T, T)
8522   void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
8523     // C++ [over.match.oper]p3:
8524     //   [...]the built-in candidates include all of the candidate operator
8525     //   functions defined in 13.6 that, compared to the given operator, [...]
8526     //   do not have the same parameter-type-list as any non-template non-member
8527     //   candidate.
8528     //
8529     // Note that in practice, this only affects enumeration types because there
8530     // aren't any built-in candidates of record type, and a user-defined operator
8531     // must have an operand of record or enumeration type. Also, the only other
8532     // overloaded operator with enumeration arguments, operator=,
8533     // cannot be overloaded for enumeration types, so this is the only place
8534     // where we must suppress candidates like this.
8535     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8536       UserDefinedBinaryOperators;
8537 
8538     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8539       if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
8540         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8541                                          CEnd = CandidateSet.end();
8542              C != CEnd; ++C) {
8543           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8544             continue;
8545 
8546           if (C->Function->isFunctionTemplateSpecialization())
8547             continue;
8548 
8549           // We interpret "same parameter-type-list" as applying to the
8550           // "synthesized candidate, with the order of the two parameters
8551           // reversed", not to the original function.
8552           bool Reversed = C->isReversed();
8553           QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
8554                                         ->getType()
8555                                         .getUnqualifiedType();
8556           QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
8557                                          ->getType()
8558                                          .getUnqualifiedType();
8559 
8560           // Skip if either parameter isn't of enumeral type.
8561           if (!FirstParamType->isEnumeralType() ||
8562               !SecondParamType->isEnumeralType())
8563             continue;
8564 
8565           // Add this operator to the set of known user-defined operators.
8566           UserDefinedBinaryOperators.insert(
8567             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8568                            S.Context.getCanonicalType(SecondParamType)));
8569         }
8570       }
8571     }
8572 
8573     /// Set of (canonical) types that we've already handled.
8574     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8575 
8576     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8577       for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
8578         // Don't add the same builtin candidate twice.
8579         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8580           continue;
8581         if (IsSpaceship && PtrTy->isFunctionPointerType())
8582           continue;
8583 
8584         QualType ParamTypes[2] = {PtrTy, PtrTy};
8585         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8586       }
8587       for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
8588         CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
8589 
8590         // Don't add the same builtin candidate twice, or if a user defined
8591         // candidate exists.
8592         if (!AddedTypes.insert(CanonType).second ||
8593             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8594                                                             CanonType)))
8595           continue;
8596         QualType ParamTypes[2] = {EnumTy, EnumTy};
8597         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8598       }
8599     }
8600   }
8601 
8602   // C++ [over.built]p13:
8603   //
8604   //   For every cv-qualified or cv-unqualified object type T
8605   //   there exist candidate operator functions of the form
8606   //
8607   //      T*         operator+(T*, ptrdiff_t);
8608   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8609   //      T*         operator-(T*, ptrdiff_t);
8610   //      T*         operator+(ptrdiff_t, T*);
8611   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8612   //
8613   // C++ [over.built]p14:
8614   //
8615   //   For every T, where T is a pointer to object type, there
8616   //   exist candidate operator functions of the form
8617   //
8618   //      ptrdiff_t  operator-(T, T);
8619   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8620     /// Set of (canonical) types that we've already handled.
8621     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8622 
8623     for (int Arg = 0; Arg < 2; ++Arg) {
8624       QualType AsymmetricParamTypes[2] = {
8625         S.Context.getPointerDiffType(),
8626         S.Context.getPointerDiffType(),
8627       };
8628       for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
8629         QualType PointeeTy = PtrTy->getPointeeType();
8630         if (!PointeeTy->isObjectType())
8631           continue;
8632 
8633         AsymmetricParamTypes[Arg] = PtrTy;
8634         if (Arg == 0 || Op == OO_Plus) {
8635           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8636           // T* operator+(ptrdiff_t, T*);
8637           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8638         }
8639         if (Op == OO_Minus) {
8640           // ptrdiff_t operator-(T, T);
8641           if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8642             continue;
8643 
8644           QualType ParamTypes[2] = {PtrTy, PtrTy};
8645           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8646         }
8647       }
8648     }
8649   }
8650 
8651   // C++ [over.built]p12:
8652   //
8653   //   For every pair of promoted arithmetic types L and R, there
8654   //   exist candidate operator functions of the form
8655   //
8656   //        LR         operator*(L, R);
8657   //        LR         operator/(L, R);
8658   //        LR         operator+(L, R);
8659   //        LR         operator-(L, R);
8660   //        bool       operator<(L, R);
8661   //        bool       operator>(L, R);
8662   //        bool       operator<=(L, R);
8663   //        bool       operator>=(L, R);
8664   //        bool       operator==(L, R);
8665   //        bool       operator!=(L, R);
8666   //
8667   //   where LR is the result of the usual arithmetic conversions
8668   //   between types L and R.
8669   //
8670   // C++ [over.built]p24:
8671   //
8672   //   For every pair of promoted arithmetic types L and R, there exist
8673   //   candidate operator functions of the form
8674   //
8675   //        LR       operator?(bool, L, R);
8676   //
8677   //   where LR is the result of the usual arithmetic conversions
8678   //   between types L and R.
8679   // Our candidates ignore the first parameter.
8680   void addGenericBinaryArithmeticOverloads() {
8681     if (!HasArithmeticOrEnumeralCandidateType)
8682       return;
8683 
8684     for (unsigned Left = FirstPromotedArithmeticType;
8685          Left < LastPromotedArithmeticType; ++Left) {
8686       for (unsigned Right = FirstPromotedArithmeticType;
8687            Right < LastPromotedArithmeticType; ++Right) {
8688         QualType LandR[2] = { ArithmeticTypes[Left],
8689                               ArithmeticTypes[Right] };
8690         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8691       }
8692     }
8693 
8694     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8695     // conditional operator for vector types.
8696     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8697       for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
8698         QualType LandR[2] = {Vec1Ty, Vec2Ty};
8699         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8700       }
8701   }
8702 
8703   /// Add binary operator overloads for each candidate matrix type M1, M2:
8704   ///  * (M1, M1) -> M1
8705   ///  * (M1, M1.getElementType()) -> M1
8706   ///  * (M2.getElementType(), M2) -> M2
8707   ///  * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
8708   void addMatrixBinaryArithmeticOverloads() {
8709     if (!HasArithmeticOrEnumeralCandidateType)
8710       return;
8711 
8712     for (QualType M1 : CandidateTypes[0].matrix_types()) {
8713       AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
8714       AddCandidate(M1, M1);
8715     }
8716 
8717     for (QualType M2 : CandidateTypes[1].matrix_types()) {
8718       AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
8719       if (!CandidateTypes[0].containsMatrixType(M2))
8720         AddCandidate(M2, M2);
8721     }
8722   }
8723 
8724   // C++2a [over.built]p14:
8725   //
8726   //   For every integral type T there exists a candidate operator function
8727   //   of the form
8728   //
8729   //        std::strong_ordering operator<=>(T, T)
8730   //
8731   // C++2a [over.built]p15:
8732   //
8733   //   For every pair of floating-point types L and R, there exists a candidate
8734   //   operator function of the form
8735   //
8736   //       std::partial_ordering operator<=>(L, R);
8737   //
8738   // FIXME: The current specification for integral types doesn't play nice with
8739   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8740   // comparisons. Under the current spec this can lead to ambiguity during
8741   // overload resolution. For example:
8742   //
8743   //   enum A : int {a};
8744   //   auto x = (a <=> (long)42);
8745   //
8746   //   error: call is ambiguous for arguments 'A' and 'long'.
8747   //   note: candidate operator<=>(int, int)
8748   //   note: candidate operator<=>(long, long)
8749   //
8750   // To avoid this error, this function deviates from the specification and adds
8751   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8752   // arithmetic types (the same as the generic relational overloads).
8753   //
8754   // For now this function acts as a placeholder.
8755   void addThreeWayArithmeticOverloads() {
8756     addGenericBinaryArithmeticOverloads();
8757   }
8758 
8759   // C++ [over.built]p17:
8760   //
8761   //   For every pair of promoted integral types L and R, there
8762   //   exist candidate operator functions of the form
8763   //
8764   //      LR         operator%(L, R);
8765   //      LR         operator&(L, R);
8766   //      LR         operator^(L, R);
8767   //      LR         operator|(L, R);
8768   //      L          operator<<(L, R);
8769   //      L          operator>>(L, R);
8770   //
8771   //   where LR is the result of the usual arithmetic conversions
8772   //   between types L and R.
8773   void addBinaryBitwiseArithmeticOverloads() {
8774     if (!HasArithmeticOrEnumeralCandidateType)
8775       return;
8776 
8777     for (unsigned Left = FirstPromotedIntegralType;
8778          Left < LastPromotedIntegralType; ++Left) {
8779       for (unsigned Right = FirstPromotedIntegralType;
8780            Right < LastPromotedIntegralType; ++Right) {
8781         QualType LandR[2] = { ArithmeticTypes[Left],
8782                               ArithmeticTypes[Right] };
8783         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8784       }
8785     }
8786   }
8787 
8788   // C++ [over.built]p20:
8789   //
8790   //   For every pair (T, VQ), where T is an enumeration or
8791   //   pointer to member type and VQ is either volatile or
8792   //   empty, there exist candidate operator functions of the form
8793   //
8794   //        VQ T&      operator=(VQ T&, T);
8795   void addAssignmentMemberPointerOrEnumeralOverloads() {
8796     /// Set of (canonical) types that we've already handled.
8797     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8798 
8799     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8800       for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
8801         if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
8802           continue;
8803 
8804         AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
8805       }
8806 
8807       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
8808         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
8809           continue;
8810 
8811         AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
8812       }
8813     }
8814   }
8815 
8816   // C++ [over.built]p19:
8817   //
8818   //   For every pair (T, VQ), where T is any type and VQ is either
8819   //   volatile or empty, there exist candidate operator functions
8820   //   of the form
8821   //
8822   //        T*VQ&      operator=(T*VQ&, T*);
8823   //
8824   // C++ [over.built]p21:
8825   //
8826   //   For every pair (T, VQ), where T is a cv-qualified or
8827   //   cv-unqualified object type and VQ is either volatile or
8828   //   empty, there exist candidate operator functions of the form
8829   //
8830   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8831   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8832   void addAssignmentPointerOverloads(bool isEqualOp) {
8833     /// Set of (canonical) types that we've already handled.
8834     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8835 
8836     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
8837       // If this is operator=, keep track of the builtin candidates we added.
8838       if (isEqualOp)
8839         AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
8840       else if (!PtrTy->getPointeeType()->isObjectType())
8841         continue;
8842 
8843       // non-volatile version
8844       QualType ParamTypes[2] = {
8845           S.Context.getLValueReferenceType(PtrTy),
8846           isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
8847       };
8848       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8849                             /*IsAssignmentOperator=*/ isEqualOp);
8850 
8851       bool NeedVolatile = !PtrTy.isVolatileQualified() &&
8852                           VisibleTypeConversionsQuals.hasVolatile();
8853       if (NeedVolatile) {
8854         // volatile version
8855         ParamTypes[0] =
8856             S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy));
8857         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8858                               /*IsAssignmentOperator=*/isEqualOp);
8859       }
8860 
8861       if (!PtrTy.isRestrictQualified() &&
8862           VisibleTypeConversionsQuals.hasRestrict()) {
8863         // restrict version
8864         ParamTypes[0] =
8865             S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy));
8866         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8867                               /*IsAssignmentOperator=*/isEqualOp);
8868 
8869         if (NeedVolatile) {
8870           // volatile restrict version
8871           ParamTypes[0] =
8872               S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
8873                   PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
8874           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8875                                 /*IsAssignmentOperator=*/isEqualOp);
8876         }
8877       }
8878     }
8879 
8880     if (isEqualOp) {
8881       for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
8882         // Make sure we don't add the same candidate twice.
8883         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8884           continue;
8885 
8886         QualType ParamTypes[2] = {
8887             S.Context.getLValueReferenceType(PtrTy),
8888             PtrTy,
8889         };
8890 
8891         // non-volatile version
8892         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8893                               /*IsAssignmentOperator=*/true);
8894 
8895         bool NeedVolatile = !PtrTy.isVolatileQualified() &&
8896                             VisibleTypeConversionsQuals.hasVolatile();
8897         if (NeedVolatile) {
8898           // volatile version
8899           ParamTypes[0] = S.Context.getLValueReferenceType(
8900               S.Context.getVolatileType(PtrTy));
8901           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8902                                 /*IsAssignmentOperator=*/true);
8903         }
8904 
8905         if (!PtrTy.isRestrictQualified() &&
8906             VisibleTypeConversionsQuals.hasRestrict()) {
8907           // restrict version
8908           ParamTypes[0] = S.Context.getLValueReferenceType(
8909               S.Context.getRestrictType(PtrTy));
8910           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8911                                 /*IsAssignmentOperator=*/true);
8912 
8913           if (NeedVolatile) {
8914             // volatile restrict version
8915             ParamTypes[0] =
8916                 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
8917                     PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
8918             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8919                                   /*IsAssignmentOperator=*/true);
8920           }
8921         }
8922       }
8923     }
8924   }
8925 
8926   // C++ [over.built]p18:
8927   //
8928   //   For every triple (L, VQ, R), where L is an arithmetic type,
8929   //   VQ is either volatile or empty, and R is a promoted
8930   //   arithmetic type, there exist candidate operator functions of
8931   //   the form
8932   //
8933   //        VQ L&      operator=(VQ L&, R);
8934   //        VQ L&      operator*=(VQ L&, R);
8935   //        VQ L&      operator/=(VQ L&, R);
8936   //        VQ L&      operator+=(VQ L&, R);
8937   //        VQ L&      operator-=(VQ L&, R);
8938   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8939     if (!HasArithmeticOrEnumeralCandidateType)
8940       return;
8941 
8942     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8943       for (unsigned Right = FirstPromotedArithmeticType;
8944            Right < LastPromotedArithmeticType; ++Right) {
8945         QualType ParamTypes[2];
8946         ParamTypes[1] = ArithmeticTypes[Right];
8947         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8948             S, ArithmeticTypes[Left], Args[0]);
8949         // Add this built-in operator as a candidate (VQ is empty).
8950         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8951         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8952                               /*IsAssignmentOperator=*/isEqualOp);
8953 
8954         // Add this built-in operator as a candidate (VQ is 'volatile').
8955         if (VisibleTypeConversionsQuals.hasVolatile()) {
8956           ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy);
8957           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8958           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8959                                 /*IsAssignmentOperator=*/isEqualOp);
8960         }
8961       }
8962     }
8963 
8964     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8965     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8966       for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
8967         QualType ParamTypes[2];
8968         ParamTypes[1] = Vec2Ty;
8969         // Add this built-in operator as a candidate (VQ is empty).
8970         ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
8971         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8972                               /*IsAssignmentOperator=*/isEqualOp);
8973 
8974         // Add this built-in operator as a candidate (VQ is 'volatile').
8975         if (VisibleTypeConversionsQuals.hasVolatile()) {
8976           ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
8977           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8978           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8979                                 /*IsAssignmentOperator=*/isEqualOp);
8980         }
8981       }
8982   }
8983 
8984   // C++ [over.built]p22:
8985   //
8986   //   For every triple (L, VQ, R), where L is an integral type, VQ
8987   //   is either volatile or empty, and R is a promoted integral
8988   //   type, there exist candidate operator functions of the form
8989   //
8990   //        VQ L&       operator%=(VQ L&, R);
8991   //        VQ L&       operator<<=(VQ L&, R);
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   void addAssignmentIntegralOverloads() {
8997     if (!HasArithmeticOrEnumeralCandidateType)
8998       return;
8999 
9000     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
9001       for (unsigned Right = FirstPromotedIntegralType;
9002            Right < LastPromotedIntegralType; ++Right) {
9003         QualType ParamTypes[2];
9004         ParamTypes[1] = ArithmeticTypes[Right];
9005         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
9006             S, ArithmeticTypes[Left], Args[0]);
9007         // Add this built-in operator as a candidate (VQ is empty).
9008         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
9009         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9010         if (VisibleTypeConversionsQuals.hasVolatile()) {
9011           // Add this built-in operator as a candidate (VQ is 'volatile').
9012           ParamTypes[0] = LeftBaseTy;
9013           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
9014           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
9015           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9016         }
9017       }
9018     }
9019   }
9020 
9021   // C++ [over.operator]p23:
9022   //
9023   //   There also exist candidate operator functions of the form
9024   //
9025   //        bool        operator!(bool);
9026   //        bool        operator&&(bool, bool);
9027   //        bool        operator||(bool, bool);
9028   void addExclaimOverload() {
9029     QualType ParamTy = S.Context.BoolTy;
9030     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
9031                           /*IsAssignmentOperator=*/false,
9032                           /*NumContextualBoolArguments=*/1);
9033   }
9034   void addAmpAmpOrPipePipeOverload() {
9035     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
9036     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9037                           /*IsAssignmentOperator=*/false,
9038                           /*NumContextualBoolArguments=*/2);
9039   }
9040 
9041   // C++ [over.built]p13:
9042   //
9043   //   For every cv-qualified or cv-unqualified object type T there
9044   //   exist candidate operator functions of the form
9045   //
9046   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
9047   //        T&         operator[](T*, ptrdiff_t);
9048   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
9049   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
9050   //        T&         operator[](ptrdiff_t, T*);
9051   void addSubscriptOverloads() {
9052     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9053       QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
9054       QualType PointeeType = PtrTy->getPointeeType();
9055       if (!PointeeType->isObjectType())
9056         continue;
9057 
9058       // T& operator[](T*, ptrdiff_t)
9059       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9060     }
9061 
9062     for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9063       QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
9064       QualType PointeeType = PtrTy->getPointeeType();
9065       if (!PointeeType->isObjectType())
9066         continue;
9067 
9068       // T& operator[](ptrdiff_t, T*)
9069       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9070     }
9071   }
9072 
9073   // C++ [over.built]p11:
9074   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9075   //    C1 is the same type as C2 or is a derived class of C2, T is an object
9076   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9077   //    there exist candidate operator functions of the form
9078   //
9079   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9080   //
9081   //    where CV12 is the union of CV1 and CV2.
9082   void addArrowStarOverloads() {
9083     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9084       QualType C1Ty = PtrTy;
9085       QualType C1;
9086       QualifierCollector Q1;
9087       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
9088       if (!isa<RecordType>(C1))
9089         continue;
9090       // heuristic to reduce number of builtin candidates in the set.
9091       // Add volatile/restrict version only if there are conversions to a
9092       // volatile/restrict type.
9093       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9094         continue;
9095       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9096         continue;
9097       for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
9098         const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
9099         QualType C2 = QualType(mptr->getClass(), 0);
9100         C2 = C2.getUnqualifiedType();
9101         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9102           break;
9103         QualType ParamTypes[2] = {PtrTy, MemPtrTy};
9104         // build CV12 T&
9105         QualType T = mptr->getPointeeType();
9106         if (!VisibleTypeConversionsQuals.hasVolatile() &&
9107             T.isVolatileQualified())
9108           continue;
9109         if (!VisibleTypeConversionsQuals.hasRestrict() &&
9110             T.isRestrictQualified())
9111           continue;
9112         T = Q1.apply(S.Context, T);
9113         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9114       }
9115     }
9116   }
9117 
9118   // Note that we don't consider the first argument, since it has been
9119   // contextually converted to bool long ago. The candidates below are
9120   // therefore added as binary.
9121   //
9122   // C++ [over.built]p25:
9123   //   For every type T, where T is a pointer, pointer-to-member, or scoped
9124   //   enumeration type, there exist candidate operator functions of the form
9125   //
9126   //        T        operator?(bool, T, T);
9127   //
9128   void addConditionalOperatorOverloads() {
9129     /// Set of (canonical) types that we've already handled.
9130     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9131 
9132     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9133       for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9134         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9135           continue;
9136 
9137         QualType ParamTypes[2] = {PtrTy, PtrTy};
9138         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9139       }
9140 
9141       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9142         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9143           continue;
9144 
9145         QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9146         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9147       }
9148 
9149       if (S.getLangOpts().CPlusPlus11) {
9150         for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9151           if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
9152             continue;
9153 
9154           if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9155             continue;
9156 
9157           QualType ParamTypes[2] = {EnumTy, EnumTy};
9158           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9159         }
9160       }
9161     }
9162   }
9163 };
9164 
9165 } // end anonymous namespace
9166 
9167 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
9168 /// operator overloads to the candidate set (C++ [over.built]), based
9169 /// on the operator @p Op and the arguments given. For example, if the
9170 /// operator is a binary '+', this routine might add "int
9171 /// operator+(int, int)" to cover integer addition.
9172 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9173                                         SourceLocation OpLoc,
9174                                         ArrayRef<Expr *> Args,
9175                                         OverloadCandidateSet &CandidateSet) {
9176   // Find all of the types that the arguments can convert to, but only
9177   // if the operator we're looking at has built-in operator candidates
9178   // that make use of these types. Also record whether we encounter non-record
9179   // candidate types or either arithmetic or enumeral candidate types.
9180   Qualifiers VisibleTypeConversionsQuals;
9181   VisibleTypeConversionsQuals.addConst();
9182   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
9183     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9184 
9185   bool HasNonRecordCandidateType = false;
9186   bool HasArithmeticOrEnumeralCandidateType = false;
9187   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9188   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9189     CandidateTypes.emplace_back(*this);
9190     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9191                                                  OpLoc,
9192                                                  true,
9193                                                  (Op == OO_Exclaim ||
9194                                                   Op == OO_AmpAmp ||
9195                                                   Op == OO_PipePipe),
9196                                                  VisibleTypeConversionsQuals);
9197     HasNonRecordCandidateType = HasNonRecordCandidateType ||
9198         CandidateTypes[ArgIdx].hasNonRecordTypes();
9199     HasArithmeticOrEnumeralCandidateType =
9200         HasArithmeticOrEnumeralCandidateType ||
9201         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9202   }
9203 
9204   // Exit early when no non-record types have been added to the candidate set
9205   // for any of the arguments to the operator.
9206   //
9207   // We can't exit early for !, ||, or &&, since there we have always have
9208   // 'bool' overloads.
9209   if (!HasNonRecordCandidateType &&
9210       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9211     return;
9212 
9213   // Setup an object to manage the common state for building overloads.
9214   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9215                                            VisibleTypeConversionsQuals,
9216                                            HasArithmeticOrEnumeralCandidateType,
9217                                            CandidateTypes, CandidateSet);
9218 
9219   // Dispatch over the operation to add in only those overloads which apply.
9220   switch (Op) {
9221   case OO_None:
9222   case NUM_OVERLOADED_OPERATORS:
9223     llvm_unreachable("Expected an overloaded operator");
9224 
9225   case OO_New:
9226   case OO_Delete:
9227   case OO_Array_New:
9228   case OO_Array_Delete:
9229   case OO_Call:
9230     llvm_unreachable(
9231                     "Special operators don't use AddBuiltinOperatorCandidates");
9232 
9233   case OO_Comma:
9234   case OO_Arrow:
9235   case OO_Coawait:
9236     // C++ [over.match.oper]p3:
9237     //   -- For the operator ',', the unary operator '&', the
9238     //      operator '->', or the operator 'co_await', the
9239     //      built-in candidates set is empty.
9240     break;
9241 
9242   case OO_Plus: // '+' is either unary or binary
9243     if (Args.size() == 1)
9244       OpBuilder.addUnaryPlusPointerOverloads();
9245     LLVM_FALLTHROUGH;
9246 
9247   case OO_Minus: // '-' is either unary or binary
9248     if (Args.size() == 1) {
9249       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9250     } else {
9251       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9252       OpBuilder.addGenericBinaryArithmeticOverloads();
9253       OpBuilder.addMatrixBinaryArithmeticOverloads();
9254     }
9255     break;
9256 
9257   case OO_Star: // '*' is either unary or binary
9258     if (Args.size() == 1)
9259       OpBuilder.addUnaryStarPointerOverloads();
9260     else {
9261       OpBuilder.addGenericBinaryArithmeticOverloads();
9262       OpBuilder.addMatrixBinaryArithmeticOverloads();
9263     }
9264     break;
9265 
9266   case OO_Slash:
9267     OpBuilder.addGenericBinaryArithmeticOverloads();
9268     break;
9269 
9270   case OO_PlusPlus:
9271   case OO_MinusMinus:
9272     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9273     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9274     break;
9275 
9276   case OO_EqualEqual:
9277   case OO_ExclaimEqual:
9278     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9279     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9280     OpBuilder.addGenericBinaryArithmeticOverloads();
9281     break;
9282 
9283   case OO_Less:
9284   case OO_Greater:
9285   case OO_LessEqual:
9286   case OO_GreaterEqual:
9287     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9288     OpBuilder.addGenericBinaryArithmeticOverloads();
9289     break;
9290 
9291   case OO_Spaceship:
9292     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
9293     OpBuilder.addThreeWayArithmeticOverloads();
9294     break;
9295 
9296   case OO_Percent:
9297   case OO_Caret:
9298   case OO_Pipe:
9299   case OO_LessLess:
9300   case OO_GreaterGreater:
9301     OpBuilder.addBinaryBitwiseArithmeticOverloads();
9302     break;
9303 
9304   case OO_Amp: // '&' is either unary or binary
9305     if (Args.size() == 1)
9306       // C++ [over.match.oper]p3:
9307       //   -- For the operator ',', the unary operator '&', or the
9308       //      operator '->', the built-in candidates set is empty.
9309       break;
9310 
9311     OpBuilder.addBinaryBitwiseArithmeticOverloads();
9312     break;
9313 
9314   case OO_Tilde:
9315     OpBuilder.addUnaryTildePromotedIntegralOverloads();
9316     break;
9317 
9318   case OO_Equal:
9319     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9320     LLVM_FALLTHROUGH;
9321 
9322   case OO_PlusEqual:
9323   case OO_MinusEqual:
9324     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9325     LLVM_FALLTHROUGH;
9326 
9327   case OO_StarEqual:
9328   case OO_SlashEqual:
9329     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9330     break;
9331 
9332   case OO_PercentEqual:
9333   case OO_LessLessEqual:
9334   case OO_GreaterGreaterEqual:
9335   case OO_AmpEqual:
9336   case OO_CaretEqual:
9337   case OO_PipeEqual:
9338     OpBuilder.addAssignmentIntegralOverloads();
9339     break;
9340 
9341   case OO_Exclaim:
9342     OpBuilder.addExclaimOverload();
9343     break;
9344 
9345   case OO_AmpAmp:
9346   case OO_PipePipe:
9347     OpBuilder.addAmpAmpOrPipePipeOverload();
9348     break;
9349 
9350   case OO_Subscript:
9351     if (Args.size() == 2)
9352       OpBuilder.addSubscriptOverloads();
9353     break;
9354 
9355   case OO_ArrowStar:
9356     OpBuilder.addArrowStarOverloads();
9357     break;
9358 
9359   case OO_Conditional:
9360     OpBuilder.addConditionalOperatorOverloads();
9361     OpBuilder.addGenericBinaryArithmeticOverloads();
9362     break;
9363   }
9364 }
9365 
9366 /// Add function candidates found via argument-dependent lookup
9367 /// to the set of overloading candidates.
9368 ///
9369 /// This routine performs argument-dependent name lookup based on the
9370 /// given function name (which may also be an operator name) and adds
9371 /// all of the overload candidates found by ADL to the overload
9372 /// candidate set (C++ [basic.lookup.argdep]).
9373 void
9374 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9375                                            SourceLocation Loc,
9376                                            ArrayRef<Expr *> Args,
9377                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
9378                                            OverloadCandidateSet& CandidateSet,
9379                                            bool PartialOverloading) {
9380   ADLResult Fns;
9381 
9382   // FIXME: This approach for uniquing ADL results (and removing
9383   // redundant candidates from the set) relies on pointer-equality,
9384   // which means we need to key off the canonical decl.  However,
9385   // always going back to the canonical decl might not get us the
9386   // right set of default arguments.  What default arguments are
9387   // we supposed to consider on ADL candidates, anyway?
9388 
9389   // FIXME: Pass in the explicit template arguments?
9390   ArgumentDependentLookup(Name, Loc, Args, Fns);
9391 
9392   // Erase all of the candidates we already knew about.
9393   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9394                                    CandEnd = CandidateSet.end();
9395        Cand != CandEnd; ++Cand)
9396     if (Cand->Function) {
9397       Fns.erase(Cand->Function);
9398       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9399         Fns.erase(FunTmpl);
9400     }
9401 
9402   // For each of the ADL candidates we found, add it to the overload
9403   // set.
9404   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9405     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9406 
9407     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9408       if (ExplicitTemplateArgs)
9409         continue;
9410 
9411       AddOverloadCandidate(
9412           FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
9413           PartialOverloading, /*AllowExplicit=*/true,
9414           /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
9415       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) {
9416         AddOverloadCandidate(
9417             FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
9418             /*SuppressUserConversions=*/false, PartialOverloading,
9419             /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
9420             ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed);
9421       }
9422     } else {
9423       auto *FTD = cast<FunctionTemplateDecl>(*I);
9424       AddTemplateOverloadCandidate(
9425           FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
9426           /*SuppressUserConversions=*/false, PartialOverloading,
9427           /*AllowExplicit=*/true, ADLCallKind::UsesADL);
9428       if (CandidateSet.getRewriteInfo().shouldAddReversed(
9429               Context, FTD->getTemplatedDecl())) {
9430         AddTemplateOverloadCandidate(
9431             FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
9432             CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
9433             /*AllowExplicit=*/true, ADLCallKind::UsesADL,
9434             OverloadCandidateParamOrder::Reversed);
9435       }
9436     }
9437   }
9438 }
9439 
9440 namespace {
9441 enum class Comparison { Equal, Better, Worse };
9442 }
9443 
9444 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9445 /// overload resolution.
9446 ///
9447 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9448 /// Cand1's first N enable_if attributes have precisely the same conditions as
9449 /// Cand2's first N enable_if attributes (where N = the number of enable_if
9450 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9451 ///
9452 /// Note that you can have a pair of candidates such that Cand1's enable_if
9453 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9454 /// worse than Cand1's.
9455 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9456                                        const FunctionDecl *Cand2) {
9457   // Common case: One (or both) decls don't have enable_if attrs.
9458   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9459   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9460   if (!Cand1Attr || !Cand2Attr) {
9461     if (Cand1Attr == Cand2Attr)
9462       return Comparison::Equal;
9463     return Cand1Attr ? Comparison::Better : Comparison::Worse;
9464   }
9465 
9466   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9467   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9468 
9469   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9470   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9471     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9472     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9473 
9474     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9475     // has fewer enable_if attributes than Cand2, and vice versa.
9476     if (!Cand1A)
9477       return Comparison::Worse;
9478     if (!Cand2A)
9479       return Comparison::Better;
9480 
9481     Cand1ID.clear();
9482     Cand2ID.clear();
9483 
9484     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9485     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9486     if (Cand1ID != Cand2ID)
9487       return Comparison::Worse;
9488   }
9489 
9490   return Comparison::Equal;
9491 }
9492 
9493 static Comparison
9494 isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9495                               const OverloadCandidate &Cand2) {
9496   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9497       !Cand2.Function->isMultiVersion())
9498     return Comparison::Equal;
9499 
9500   // If both are invalid, they are equal. If one of them is invalid, the other
9501   // is better.
9502   if (Cand1.Function->isInvalidDecl()) {
9503     if (Cand2.Function->isInvalidDecl())
9504       return Comparison::Equal;
9505     return Comparison::Worse;
9506   }
9507   if (Cand2.Function->isInvalidDecl())
9508     return Comparison::Better;
9509 
9510   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9511   // cpu_dispatch, else arbitrarily based on the identifiers.
9512   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9513   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9514   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9515   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9516 
9517   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9518     return Comparison::Equal;
9519 
9520   if (Cand1CPUDisp && !Cand2CPUDisp)
9521     return Comparison::Better;
9522   if (Cand2CPUDisp && !Cand1CPUDisp)
9523     return Comparison::Worse;
9524 
9525   if (Cand1CPUSpec && Cand2CPUSpec) {
9526     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9527       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
9528                  ? Comparison::Better
9529                  : Comparison::Worse;
9530 
9531     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9532         FirstDiff = std::mismatch(
9533             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9534             Cand2CPUSpec->cpus_begin(),
9535             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9536               return LHS->getName() == RHS->getName();
9537             });
9538 
9539     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9540            "Two different cpu-specific versions should not have the same "
9541            "identifier list, otherwise they'd be the same decl!");
9542     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
9543                ? Comparison::Better
9544                : Comparison::Worse;
9545   }
9546   llvm_unreachable("No way to get here unless both had cpu_dispatch");
9547 }
9548 
9549 /// Compute the type of the implicit object parameter for the given function,
9550 /// if any. Returns None if there is no implicit object parameter, and a null
9551 /// QualType if there is a 'matches anything' implicit object parameter.
9552 static Optional<QualType> getImplicitObjectParamType(ASTContext &Context,
9553                                                      const FunctionDecl *F) {
9554   if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
9555     return llvm::None;
9556 
9557   auto *M = cast<CXXMethodDecl>(F);
9558   // Static member functions' object parameters match all types.
9559   if (M->isStatic())
9560     return QualType();
9561 
9562   QualType T = M->getThisObjectType();
9563   if (M->getRefQualifier() == RQ_RValue)
9564     return Context.getRValueReferenceType(T);
9565   return Context.getLValueReferenceType(T);
9566 }
9567 
9568 static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1,
9569                                    const FunctionDecl *F2, unsigned NumParams) {
9570   if (declaresSameEntity(F1, F2))
9571     return true;
9572 
9573   auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
9574     if (First) {
9575       if (Optional<QualType> T = getImplicitObjectParamType(Context, F))
9576         return *T;
9577     }
9578     assert(I < F->getNumParams());
9579     return F->getParamDecl(I++)->getType();
9580   };
9581 
9582   unsigned I1 = 0, I2 = 0;
9583   for (unsigned I = 0; I != NumParams; ++I) {
9584     QualType T1 = NextParam(F1, I1, I == 0);
9585     QualType T2 = NextParam(F2, I2, I == 0);
9586     assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
9587     if (!Context.hasSameUnqualifiedType(T1, T2))
9588       return false;
9589   }
9590   return true;
9591 }
9592 
9593 /// We're allowed to use constraints partial ordering only if the candidates
9594 /// have the same parameter types:
9595 /// [temp.func.order]p6.2.2 [...] or if the function parameters that
9596 /// positionally correspond between the two templates are not of the same type,
9597 /// neither template is more specialized than the other.
9598 /// [over.match.best]p2.6
9599 /// F1 and F2 are non-template functions with the same parameter-type-lists,
9600 /// and F1 is more constrained than F2 [...]
9601 static bool canCompareFunctionConstraints(Sema &S,
9602                                           const OverloadCandidate &Cand1,
9603                                           const OverloadCandidate &Cand2) {
9604   // FIXME: Per P2113R0 we also need to compare the template parameter lists
9605   // when comparing template functions.
9606   if (Cand1.Function && Cand2.Function && Cand1.Function->hasPrototype() &&
9607       Cand2.Function->hasPrototype()) {
9608     auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType());
9609     auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType());
9610     if (PT1->getNumParams() == PT2->getNumParams() &&
9611         PT1->isVariadic() == PT2->isVariadic() &&
9612         S.FunctionParamTypesAreEqual(PT1, PT2, nullptr,
9613                                      Cand1.isReversed() ^ Cand2.isReversed()))
9614       return true;
9615   }
9616   return false;
9617 }
9618 
9619 /// isBetterOverloadCandidate - Determines whether the first overload
9620 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9621 bool clang::isBetterOverloadCandidate(
9622     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9623     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9624   // Define viable functions to be better candidates than non-viable
9625   // functions.
9626   if (!Cand2.Viable)
9627     return Cand1.Viable;
9628   else if (!Cand1.Viable)
9629     return false;
9630 
9631   // [CUDA] A function with 'never' preference is marked not viable, therefore
9632   // is never shown up here. The worst preference shown up here is 'wrong side',
9633   // e.g. an H function called by a HD function in device compilation. This is
9634   // valid AST as long as the HD function is not emitted, e.g. it is an inline
9635   // function which is called only by an H function. A deferred diagnostic will
9636   // be triggered if it is emitted. However a wrong-sided function is still
9637   // a viable candidate here.
9638   //
9639   // If Cand1 can be emitted and Cand2 cannot be emitted in the current
9640   // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
9641   // can be emitted, Cand1 is not better than Cand2. This rule should have
9642   // precedence over other rules.
9643   //
9644   // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
9645   // other rules should be used to determine which is better. This is because
9646   // host/device based overloading resolution is mostly for determining
9647   // viability of a function. If two functions are both viable, other factors
9648   // should take precedence in preference, e.g. the standard-defined preferences
9649   // like argument conversion ranks or enable_if partial-ordering. The
9650   // preference for pass-object-size parameters is probably most similar to a
9651   // type-based-overloading decision and so should take priority.
9652   //
9653   // If other rules cannot determine which is better, CUDA preference will be
9654   // used again to determine which is better.
9655   //
9656   // TODO: Currently IdentifyCUDAPreference does not return correct values
9657   // for functions called in global variable initializers due to missing
9658   // correct context about device/host. Therefore we can only enforce this
9659   // rule when there is a caller. We should enforce this rule for functions
9660   // in global variable initializers once proper context is added.
9661   //
9662   // TODO: We can only enable the hostness based overloading resolution when
9663   // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
9664   // overloading resolution diagnostics.
9665   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
9666       S.getLangOpts().GPUExcludeWrongSideOverloads) {
9667     if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
9668       bool IsCallerImplicitHD = Sema::isCUDAImplicitHostDeviceFunction(Caller);
9669       bool IsCand1ImplicitHD =
9670           Sema::isCUDAImplicitHostDeviceFunction(Cand1.Function);
9671       bool IsCand2ImplicitHD =
9672           Sema::isCUDAImplicitHostDeviceFunction(Cand2.Function);
9673       auto P1 = S.IdentifyCUDAPreference(Caller, Cand1.Function);
9674       auto P2 = S.IdentifyCUDAPreference(Caller, Cand2.Function);
9675       assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never);
9676       // The implicit HD function may be a function in a system header which
9677       // is forced by pragma. In device compilation, if we prefer HD candidates
9678       // over wrong-sided candidates, overloading resolution may change, which
9679       // may result in non-deferrable diagnostics. As a workaround, we let
9680       // implicit HD candidates take equal preference as wrong-sided candidates.
9681       // This will preserve the overloading resolution.
9682       // TODO: We still need special handling of implicit HD functions since
9683       // they may incur other diagnostics to be deferred. We should make all
9684       // host/device related diagnostics deferrable and remove special handling
9685       // of implicit HD functions.
9686       auto EmitThreshold =
9687           (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
9688            (IsCand1ImplicitHD || IsCand2ImplicitHD))
9689               ? Sema::CFP_Never
9690               : Sema::CFP_WrongSide;
9691       auto Cand1Emittable = P1 > EmitThreshold;
9692       auto Cand2Emittable = P2 > EmitThreshold;
9693       if (Cand1Emittable && !Cand2Emittable)
9694         return true;
9695       if (!Cand1Emittable && Cand2Emittable)
9696         return false;
9697     }
9698   }
9699 
9700   // C++ [over.match.best]p1:
9701   //
9702   //   -- if F is a static member function, ICS1(F) is defined such
9703   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9704   //      any function G, and, symmetrically, ICS1(G) is neither
9705   //      better nor worse than ICS1(F).
9706   unsigned StartArg = 0;
9707   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9708     StartArg = 1;
9709 
9710   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9711     // We don't allow incompatible pointer conversions in C++.
9712     if (!S.getLangOpts().CPlusPlus)
9713       return ICS.isStandard() &&
9714              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9715 
9716     // The only ill-formed conversion we allow in C++ is the string literal to
9717     // char* conversion, which is only considered ill-formed after C++11.
9718     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9719            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9720   };
9721 
9722   // Define functions that don't require ill-formed conversions for a given
9723   // argument to be better candidates than functions that do.
9724   unsigned NumArgs = Cand1.Conversions.size();
9725   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9726   bool HasBetterConversion = false;
9727   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9728     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9729     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9730     if (Cand1Bad != Cand2Bad) {
9731       if (Cand1Bad)
9732         return false;
9733       HasBetterConversion = true;
9734     }
9735   }
9736 
9737   if (HasBetterConversion)
9738     return true;
9739 
9740   // C++ [over.match.best]p1:
9741   //   A viable function F1 is defined to be a better function than another
9742   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9743   //   conversion sequence than ICSi(F2), and then...
9744   bool HasWorseConversion = false;
9745   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9746     switch (CompareImplicitConversionSequences(S, Loc,
9747                                                Cand1.Conversions[ArgIdx],
9748                                                Cand2.Conversions[ArgIdx])) {
9749     case ImplicitConversionSequence::Better:
9750       // Cand1 has a better conversion sequence.
9751       HasBetterConversion = true;
9752       break;
9753 
9754     case ImplicitConversionSequence::Worse:
9755       if (Cand1.Function && Cand2.Function &&
9756           Cand1.isReversed() != Cand2.isReversed() &&
9757           haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function,
9758                                  NumArgs)) {
9759         // Work around large-scale breakage caused by considering reversed
9760         // forms of operator== in C++20:
9761         //
9762         // When comparing a function against a reversed function with the same
9763         // parameter types, if we have a better conversion for one argument and
9764         // a worse conversion for the other, the implicit conversion sequences
9765         // are treated as being equally good.
9766         //
9767         // This prevents a comparison function from being considered ambiguous
9768         // with a reversed form that is written in the same way.
9769         //
9770         // We diagnose this as an extension from CreateOverloadedBinOp.
9771         HasWorseConversion = true;
9772         break;
9773       }
9774 
9775       // Cand1 can't be better than Cand2.
9776       return false;
9777 
9778     case ImplicitConversionSequence::Indistinguishable:
9779       // Do nothing.
9780       break;
9781     }
9782   }
9783 
9784   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9785   //       ICSj(F2), or, if not that,
9786   if (HasBetterConversion && !HasWorseConversion)
9787     return true;
9788 
9789   //   -- the context is an initialization by user-defined conversion
9790   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9791   //      from the return type of F1 to the destination type (i.e.,
9792   //      the type of the entity being initialized) is a better
9793   //      conversion sequence than the standard conversion sequence
9794   //      from the return type of F2 to the destination type.
9795   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9796       Cand1.Function && Cand2.Function &&
9797       isa<CXXConversionDecl>(Cand1.Function) &&
9798       isa<CXXConversionDecl>(Cand2.Function)) {
9799     // First check whether we prefer one of the conversion functions over the
9800     // other. This only distinguishes the results in non-standard, extension
9801     // cases such as the conversion from a lambda closure type to a function
9802     // pointer or block.
9803     ImplicitConversionSequence::CompareKind Result =
9804         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9805     if (Result == ImplicitConversionSequence::Indistinguishable)
9806       Result = CompareStandardConversionSequences(S, Loc,
9807                                                   Cand1.FinalConversion,
9808                                                   Cand2.FinalConversion);
9809 
9810     if (Result != ImplicitConversionSequence::Indistinguishable)
9811       return Result == ImplicitConversionSequence::Better;
9812 
9813     // FIXME: Compare kind of reference binding if conversion functions
9814     // convert to a reference type used in direct reference binding, per
9815     // C++14 [over.match.best]p1 section 2 bullet 3.
9816   }
9817 
9818   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9819   // as combined with the resolution to CWG issue 243.
9820   //
9821   // When the context is initialization by constructor ([over.match.ctor] or
9822   // either phase of [over.match.list]), a constructor is preferred over
9823   // a conversion function.
9824   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9825       Cand1.Function && Cand2.Function &&
9826       isa<CXXConstructorDecl>(Cand1.Function) !=
9827           isa<CXXConstructorDecl>(Cand2.Function))
9828     return isa<CXXConstructorDecl>(Cand1.Function);
9829 
9830   //    -- F1 is a non-template function and F2 is a function template
9831   //       specialization, or, if not that,
9832   bool Cand1IsSpecialization = Cand1.Function &&
9833                                Cand1.Function->getPrimaryTemplate();
9834   bool Cand2IsSpecialization = Cand2.Function &&
9835                                Cand2.Function->getPrimaryTemplate();
9836   if (Cand1IsSpecialization != Cand2IsSpecialization)
9837     return Cand2IsSpecialization;
9838 
9839   //   -- F1 and F2 are function template specializations, and the function
9840   //      template for F1 is more specialized than the template for F2
9841   //      according to the partial ordering rules described in 14.5.5.2, or,
9842   //      if not that,
9843   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9844     if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
9845             Cand1.Function->getPrimaryTemplate(),
9846             Cand2.Function->getPrimaryTemplate(), Loc,
9847             isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
9848                                                    : TPOC_Call,
9849             Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments,
9850             Cand1.isReversed() ^ Cand2.isReversed(),
9851             canCompareFunctionConstraints(S, Cand1, Cand2)))
9852       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9853   }
9854 
9855   //   -— F1 and F2 are non-template functions with the same
9856   //      parameter-type-lists, and F1 is more constrained than F2 [...],
9857   if (!Cand1IsSpecialization && !Cand2IsSpecialization &&
9858       canCompareFunctionConstraints(S, Cand1, Cand2)) {
9859     Expr *RC1 = Cand1.Function->getTrailingRequiresClause();
9860     Expr *RC2 = Cand2.Function->getTrailingRequiresClause();
9861     if (RC1 && RC2) {
9862       bool AtLeastAsConstrained1, AtLeastAsConstrained2;
9863       if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function, {RC2},
9864                                    AtLeastAsConstrained1) ||
9865           S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function, {RC1},
9866                                    AtLeastAsConstrained2))
9867         return false;
9868       if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
9869         return AtLeastAsConstrained1;
9870     } else if (RC1 || RC2) {
9871       return RC1 != nullptr;
9872     }
9873   }
9874 
9875   //   -- F1 is a constructor for a class D, F2 is a constructor for a base
9876   //      class B of D, and for all arguments the corresponding parameters of
9877   //      F1 and F2 have the same type.
9878   // FIXME: Implement the "all parameters have the same type" check.
9879   bool Cand1IsInherited =
9880       isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9881   bool Cand2IsInherited =
9882       isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9883   if (Cand1IsInherited != Cand2IsInherited)
9884     return Cand2IsInherited;
9885   else if (Cand1IsInherited) {
9886     assert(Cand2IsInherited);
9887     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9888     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9889     if (Cand1Class->isDerivedFrom(Cand2Class))
9890       return true;
9891     if (Cand2Class->isDerivedFrom(Cand1Class))
9892       return false;
9893     // Inherited from sibling base classes: still ambiguous.
9894   }
9895 
9896   //   -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
9897   //   -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
9898   //      with reversed order of parameters and F1 is not
9899   //
9900   // We rank reversed + different operator as worse than just reversed, but
9901   // that comparison can never happen, because we only consider reversing for
9902   // the maximally-rewritten operator (== or <=>).
9903   if (Cand1.RewriteKind != Cand2.RewriteKind)
9904     return Cand1.RewriteKind < Cand2.RewriteKind;
9905 
9906   // Check C++17 tie-breakers for deduction guides.
9907   {
9908     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9909     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9910     if (Guide1 && Guide2) {
9911       //  -- F1 is generated from a deduction-guide and F2 is not
9912       if (Guide1->isImplicit() != Guide2->isImplicit())
9913         return Guide2->isImplicit();
9914 
9915       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9916       if (Guide1->isCopyDeductionCandidate())
9917         return true;
9918     }
9919   }
9920 
9921   // Check for enable_if value-based overload resolution.
9922   if (Cand1.Function && Cand2.Function) {
9923     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9924     if (Cmp != Comparison::Equal)
9925       return Cmp == Comparison::Better;
9926   }
9927 
9928   bool HasPS1 = Cand1.Function != nullptr &&
9929                 functionHasPassObjectSizeParams(Cand1.Function);
9930   bool HasPS2 = Cand2.Function != nullptr &&
9931                 functionHasPassObjectSizeParams(Cand2.Function);
9932   if (HasPS1 != HasPS2 && HasPS1)
9933     return true;
9934 
9935   auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
9936   if (MV == Comparison::Better)
9937     return true;
9938   if (MV == Comparison::Worse)
9939     return false;
9940 
9941   // If other rules cannot determine which is better, CUDA preference is used
9942   // to determine which is better.
9943   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9944     FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
9945     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9946            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9947   }
9948 
9949   // General member function overloading is handled above, so this only handles
9950   // constructors with address spaces.
9951   // This only handles address spaces since C++ has no other
9952   // qualifier that can be used with constructors.
9953   const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
9954   const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
9955   if (CD1 && CD2) {
9956     LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
9957     LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
9958     if (AS1 != AS2) {
9959       if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
9960         return true;
9961       if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
9962         return false;
9963     }
9964   }
9965 
9966   return false;
9967 }
9968 
9969 /// Determine whether two declarations are "equivalent" for the purposes of
9970 /// name lookup and overload resolution. This applies when the same internal/no
9971 /// linkage entity is defined by two modules (probably by textually including
9972 /// the same header). In such a case, we don't consider the declarations to
9973 /// declare the same entity, but we also don't want lookups with both
9974 /// declarations visible to be ambiguous in some cases (this happens when using
9975 /// a modularized libstdc++).
9976 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9977                                                   const NamedDecl *B) {
9978   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9979   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9980   if (!VA || !VB)
9981     return false;
9982 
9983   // The declarations must be declaring the same name as an internal linkage
9984   // entity in different modules.
9985   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9986           VB->getDeclContext()->getRedeclContext()) ||
9987       getOwningModule(VA) == getOwningModule(VB) ||
9988       VA->isExternallyVisible() || VB->isExternallyVisible())
9989     return false;
9990 
9991   // Check that the declarations appear to be equivalent.
9992   //
9993   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9994   // For constants and functions, we should check the initializer or body is
9995   // the same. For non-constant variables, we shouldn't allow it at all.
9996   if (Context.hasSameType(VA->getType(), VB->getType()))
9997     return true;
9998 
9999   // Enum constants within unnamed enumerations will have different types, but
10000   // may still be similar enough to be interchangeable for our purposes.
10001   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
10002     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
10003       // Only handle anonymous enums. If the enumerations were named and
10004       // equivalent, they would have been merged to the same type.
10005       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
10006       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
10007       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
10008           !Context.hasSameType(EnumA->getIntegerType(),
10009                                EnumB->getIntegerType()))
10010         return false;
10011       // Allow this only if the value is the same for both enumerators.
10012       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
10013     }
10014   }
10015 
10016   // Nothing else is sufficiently similar.
10017   return false;
10018 }
10019 
10020 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
10021     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
10022   assert(D && "Unknown declaration");
10023   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
10024 
10025   Module *M = getOwningModule(D);
10026   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
10027       << !M << (M ? M->getFullModuleName() : "");
10028 
10029   for (auto *E : Equiv) {
10030     Module *M = getOwningModule(E);
10031     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
10032         << !M << (M ? M->getFullModuleName() : "");
10033   }
10034 }
10035 
10036 /// Computes the best viable function (C++ 13.3.3)
10037 /// within an overload candidate set.
10038 ///
10039 /// \param Loc The location of the function name (or operator symbol) for
10040 /// which overload resolution occurs.
10041 ///
10042 /// \param Best If overload resolution was successful or found a deleted
10043 /// function, \p Best points to the candidate function found.
10044 ///
10045 /// \returns The result of overload resolution.
10046 OverloadingResult
10047 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
10048                                          iterator &Best) {
10049   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
10050   std::transform(begin(), end(), std::back_inserter(Candidates),
10051                  [](OverloadCandidate &Cand) { return &Cand; });
10052 
10053   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
10054   // are accepted by both clang and NVCC. However, during a particular
10055   // compilation mode only one call variant is viable. We need to
10056   // exclude non-viable overload candidates from consideration based
10057   // only on their host/device attributes. Specifically, if one
10058   // candidate call is WrongSide and the other is SameSide, we ignore
10059   // the WrongSide candidate.
10060   // We only need to remove wrong-sided candidates here if
10061   // -fgpu-exclude-wrong-side-overloads is off. When
10062   // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
10063   // uniformly in isBetterOverloadCandidate.
10064   if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) {
10065     const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10066     bool ContainsSameSideCandidate =
10067         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
10068           // Check viable function only.
10069           return Cand->Viable && Cand->Function &&
10070                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
10071                      Sema::CFP_SameSide;
10072         });
10073     if (ContainsSameSideCandidate) {
10074       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
10075         // Check viable function only to avoid unnecessary data copying/moving.
10076         return Cand->Viable && Cand->Function &&
10077                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
10078                    Sema::CFP_WrongSide;
10079       };
10080       llvm::erase_if(Candidates, IsWrongSideCandidate);
10081     }
10082   }
10083 
10084   // Find the best viable function.
10085   Best = end();
10086   for (auto *Cand : Candidates) {
10087     Cand->Best = false;
10088     if (Cand->Viable)
10089       if (Best == end() ||
10090           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
10091         Best = Cand;
10092   }
10093 
10094   // If we didn't find any viable functions, abort.
10095   if (Best == end())
10096     return OR_No_Viable_Function;
10097 
10098   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
10099 
10100   llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
10101   PendingBest.push_back(&*Best);
10102   Best->Best = true;
10103 
10104   // Make sure that this function is better than every other viable
10105   // function. If not, we have an ambiguity.
10106   while (!PendingBest.empty()) {
10107     auto *Curr = PendingBest.pop_back_val();
10108     for (auto *Cand : Candidates) {
10109       if (Cand->Viable && !Cand->Best &&
10110           !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
10111         PendingBest.push_back(Cand);
10112         Cand->Best = true;
10113 
10114         if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
10115                                                      Curr->Function))
10116           EquivalentCands.push_back(Cand->Function);
10117         else
10118           Best = end();
10119       }
10120     }
10121   }
10122 
10123   // If we found more than one best candidate, this is ambiguous.
10124   if (Best == end())
10125     return OR_Ambiguous;
10126 
10127   // Best is the best viable function.
10128   if (Best->Function && Best->Function->isDeleted())
10129     return OR_Deleted;
10130 
10131   if (!EquivalentCands.empty())
10132     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
10133                                                     EquivalentCands);
10134 
10135   return OR_Success;
10136 }
10137 
10138 namespace {
10139 
10140 enum OverloadCandidateKind {
10141   oc_function,
10142   oc_method,
10143   oc_reversed_binary_operator,
10144   oc_constructor,
10145   oc_implicit_default_constructor,
10146   oc_implicit_copy_constructor,
10147   oc_implicit_move_constructor,
10148   oc_implicit_copy_assignment,
10149   oc_implicit_move_assignment,
10150   oc_implicit_equality_comparison,
10151   oc_inherited_constructor
10152 };
10153 
10154 enum OverloadCandidateSelect {
10155   ocs_non_template,
10156   ocs_template,
10157   ocs_described_template,
10158 };
10159 
10160 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
10161 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
10162                           OverloadCandidateRewriteKind CRK,
10163                           std::string &Description) {
10164 
10165   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
10166   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
10167     isTemplate = true;
10168     Description = S.getTemplateArgumentBindingsText(
10169         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
10170   }
10171 
10172   OverloadCandidateSelect Select = [&]() {
10173     if (!Description.empty())
10174       return ocs_described_template;
10175     return isTemplate ? ocs_template : ocs_non_template;
10176   }();
10177 
10178   OverloadCandidateKind Kind = [&]() {
10179     if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
10180       return oc_implicit_equality_comparison;
10181 
10182     if (CRK & CRK_Reversed)
10183       return oc_reversed_binary_operator;
10184 
10185     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
10186       if (!Ctor->isImplicit()) {
10187         if (isa<ConstructorUsingShadowDecl>(Found))
10188           return oc_inherited_constructor;
10189         else
10190           return oc_constructor;
10191       }
10192 
10193       if (Ctor->isDefaultConstructor())
10194         return oc_implicit_default_constructor;
10195 
10196       if (Ctor->isMoveConstructor())
10197         return oc_implicit_move_constructor;
10198 
10199       assert(Ctor->isCopyConstructor() &&
10200              "unexpected sort of implicit constructor");
10201       return oc_implicit_copy_constructor;
10202     }
10203 
10204     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
10205       // This actually gets spelled 'candidate function' for now, but
10206       // it doesn't hurt to split it out.
10207       if (!Meth->isImplicit())
10208         return oc_method;
10209 
10210       if (Meth->isMoveAssignmentOperator())
10211         return oc_implicit_move_assignment;
10212 
10213       if (Meth->isCopyAssignmentOperator())
10214         return oc_implicit_copy_assignment;
10215 
10216       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
10217       return oc_method;
10218     }
10219 
10220     return oc_function;
10221   }();
10222 
10223   return std::make_pair(Kind, Select);
10224 }
10225 
10226 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
10227   // FIXME: It'd be nice to only emit a note once per using-decl per overload
10228   // set.
10229   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
10230     S.Diag(FoundDecl->getLocation(),
10231            diag::note_ovl_candidate_inherited_constructor)
10232       << Shadow->getNominatedBaseClass();
10233 }
10234 
10235 } // end anonymous namespace
10236 
10237 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
10238                                     const FunctionDecl *FD) {
10239   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
10240     bool AlwaysTrue;
10241     if (EnableIf->getCond()->isValueDependent() ||
10242         !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
10243       return false;
10244     if (!AlwaysTrue)
10245       return false;
10246   }
10247   return true;
10248 }
10249 
10250 /// Returns true if we can take the address of the function.
10251 ///
10252 /// \param Complain - If true, we'll emit a diagnostic
10253 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
10254 ///   we in overload resolution?
10255 /// \param Loc - The location of the statement we're complaining about. Ignored
10256 ///   if we're not complaining, or if we're in overload resolution.
10257 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
10258                                               bool Complain,
10259                                               bool InOverloadResolution,
10260                                               SourceLocation Loc) {
10261   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
10262     if (Complain) {
10263       if (InOverloadResolution)
10264         S.Diag(FD->getBeginLoc(),
10265                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
10266       else
10267         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
10268     }
10269     return false;
10270   }
10271 
10272   if (FD->getTrailingRequiresClause()) {
10273     ConstraintSatisfaction Satisfaction;
10274     if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
10275       return false;
10276     if (!Satisfaction.IsSatisfied) {
10277       if (Complain) {
10278         if (InOverloadResolution) {
10279           SmallString<128> TemplateArgString;
10280           if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
10281             TemplateArgString += " ";
10282             TemplateArgString += S.getTemplateArgumentBindingsText(
10283                 FunTmpl->getTemplateParameters(),
10284                 *FD->getTemplateSpecializationArgs());
10285           }
10286 
10287           S.Diag(FD->getBeginLoc(),
10288                  diag::note_ovl_candidate_unsatisfied_constraints)
10289               << TemplateArgString;
10290         } else
10291           S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
10292               << FD;
10293         S.DiagnoseUnsatisfiedConstraint(Satisfaction);
10294       }
10295       return false;
10296     }
10297   }
10298 
10299   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
10300     return P->hasAttr<PassObjectSizeAttr>();
10301   });
10302   if (I == FD->param_end())
10303     return true;
10304 
10305   if (Complain) {
10306     // Add one to ParamNo because it's user-facing
10307     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
10308     if (InOverloadResolution)
10309       S.Diag(FD->getLocation(),
10310              diag::note_ovl_candidate_has_pass_object_size_params)
10311           << ParamNo;
10312     else
10313       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
10314           << FD << ParamNo;
10315   }
10316   return false;
10317 }
10318 
10319 static bool checkAddressOfCandidateIsAvailable(Sema &S,
10320                                                const FunctionDecl *FD) {
10321   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
10322                                            /*InOverloadResolution=*/true,
10323                                            /*Loc=*/SourceLocation());
10324 }
10325 
10326 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10327                                              bool Complain,
10328                                              SourceLocation Loc) {
10329   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
10330                                              /*InOverloadResolution=*/false,
10331                                              Loc);
10332 }
10333 
10334 // Don't print candidates other than the one that matches the calling
10335 // convention of the call operator, since that is guaranteed to exist.
10336 static bool shouldSkipNotingLambdaConversionDecl(FunctionDecl *Fn) {
10337   const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
10338 
10339   if (!ConvD)
10340     return false;
10341   const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
10342   if (!RD->isLambda())
10343     return false;
10344 
10345   CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
10346   CallingConv CallOpCC =
10347       CallOp->getType()->castAs<FunctionType>()->getCallConv();
10348   QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
10349   CallingConv ConvToCC =
10350       ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
10351 
10352   return ConvToCC != CallOpCC;
10353 }
10354 
10355 // Notes the location of an overload candidate.
10356 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
10357                                  OverloadCandidateRewriteKind RewriteKind,
10358                                  QualType DestType, bool TakingAddress) {
10359   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
10360     return;
10361   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
10362       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
10363     return;
10364   if (shouldSkipNotingLambdaConversionDecl(Fn))
10365     return;
10366 
10367   std::string FnDesc;
10368   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
10369       ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
10370   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
10371                          << (unsigned)KSPair.first << (unsigned)KSPair.second
10372                          << Fn << FnDesc;
10373 
10374   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
10375   Diag(Fn->getLocation(), PD);
10376   MaybeEmitInheritedConstructorNote(*this, Found);
10377 }
10378 
10379 static void
10380 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
10381   // Perhaps the ambiguity was caused by two atomic constraints that are
10382   // 'identical' but not equivalent:
10383   //
10384   // void foo() requires (sizeof(T) > 4) { } // #1
10385   // void foo() requires (sizeof(T) > 4) && T::value { } // #2
10386   //
10387   // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
10388   // #2 to subsume #1, but these constraint are not considered equivalent
10389   // according to the subsumption rules because they are not the same
10390   // source-level construct. This behavior is quite confusing and we should try
10391   // to help the user figure out what happened.
10392 
10393   SmallVector<const Expr *, 3> FirstAC, SecondAC;
10394   FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
10395   for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10396     if (!I->Function)
10397       continue;
10398     SmallVector<const Expr *, 3> AC;
10399     if (auto *Template = I->Function->getPrimaryTemplate())
10400       Template->getAssociatedConstraints(AC);
10401     else
10402       I->Function->getAssociatedConstraints(AC);
10403     if (AC.empty())
10404       continue;
10405     if (FirstCand == nullptr) {
10406       FirstCand = I->Function;
10407       FirstAC = AC;
10408     } else if (SecondCand == nullptr) {
10409       SecondCand = I->Function;
10410       SecondAC = AC;
10411     } else {
10412       // We have more than one pair of constrained functions - this check is
10413       // expensive and we'd rather not try to diagnose it.
10414       return;
10415     }
10416   }
10417   if (!SecondCand)
10418     return;
10419   // The diagnostic can only happen if there are associated constraints on
10420   // both sides (there needs to be some identical atomic constraint).
10421   if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
10422                                                       SecondCand, SecondAC))
10423     // Just show the user one diagnostic, they'll probably figure it out
10424     // from here.
10425     return;
10426 }
10427 
10428 // Notes the location of all overload candidates designated through
10429 // OverloadedExpr
10430 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
10431                                      bool TakingAddress) {
10432   assert(OverloadedExpr->getType() == Context.OverloadTy);
10433 
10434   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
10435   OverloadExpr *OvlExpr = Ovl.Expression;
10436 
10437   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10438                             IEnd = OvlExpr->decls_end();
10439        I != IEnd; ++I) {
10440     if (FunctionTemplateDecl *FunTmpl =
10441                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
10442       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
10443                             TakingAddress);
10444     } else if (FunctionDecl *Fun
10445                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
10446       NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
10447     }
10448   }
10449 }
10450 
10451 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
10452 /// "lead" diagnostic; it will be given two arguments, the source and
10453 /// target types of the conversion.
10454 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
10455                                  Sema &S,
10456                                  SourceLocation CaretLoc,
10457                                  const PartialDiagnostic &PDiag) const {
10458   S.Diag(CaretLoc, PDiag)
10459     << Ambiguous.getFromType() << Ambiguous.getToType();
10460   unsigned CandsShown = 0;
10461   AmbiguousConversionSequence::const_iterator I, E;
10462   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
10463     if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
10464       break;
10465     ++CandsShown;
10466     S.NoteOverloadCandidate(I->first, I->second);
10467   }
10468   S.Diags.overloadCandidatesShown(CandsShown);
10469   if (I != E)
10470     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
10471 }
10472 
10473 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
10474                                   unsigned I, bool TakingCandidateAddress) {
10475   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
10476   assert(Conv.isBad());
10477   assert(Cand->Function && "for now, candidate must be a function");
10478   FunctionDecl *Fn = Cand->Function;
10479 
10480   // There's a conversion slot for the object argument if this is a
10481   // non-constructor method.  Note that 'I' corresponds the
10482   // conversion-slot index.
10483   bool isObjectArgument = false;
10484   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
10485     if (I == 0)
10486       isObjectArgument = true;
10487     else
10488       I--;
10489   }
10490 
10491   std::string FnDesc;
10492   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10493       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
10494                                 FnDesc);
10495 
10496   Expr *FromExpr = Conv.Bad.FromExpr;
10497   QualType FromTy = Conv.Bad.getFromType();
10498   QualType ToTy = Conv.Bad.getToType();
10499 
10500   if (FromTy == S.Context.OverloadTy) {
10501     assert(FromExpr && "overload set argument came from implicit argument?");
10502     Expr *E = FromExpr->IgnoreParens();
10503     if (isa<UnaryOperator>(E))
10504       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
10505     DeclarationName Name = cast<OverloadExpr>(E)->getName();
10506 
10507     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
10508         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10509         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
10510         << Name << I + 1;
10511     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10512     return;
10513   }
10514 
10515   // Do some hand-waving analysis to see if the non-viability is due
10516   // to a qualifier mismatch.
10517   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
10518   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
10519   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
10520     CToTy = RT->getPointeeType();
10521   else {
10522     // TODO: detect and diagnose the full richness of const mismatches.
10523     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
10524       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
10525         CFromTy = FromPT->getPointeeType();
10526         CToTy = ToPT->getPointeeType();
10527       }
10528   }
10529 
10530   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
10531       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
10532     Qualifiers FromQs = CFromTy.getQualifiers();
10533     Qualifiers ToQs = CToTy.getQualifiers();
10534 
10535     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
10536       if (isObjectArgument)
10537         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
10538             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10539             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10540             << FromQs.getAddressSpace() << ToQs.getAddressSpace();
10541       else
10542         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
10543             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10544             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10545             << FromQs.getAddressSpace() << ToQs.getAddressSpace()
10546             << ToTy->isReferenceType() << I + 1;
10547       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10548       return;
10549     }
10550 
10551     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10552       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
10553           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10554           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10555           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
10556           << (unsigned)isObjectArgument << I + 1;
10557       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10558       return;
10559     }
10560 
10561     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
10562       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
10563           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10564           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10565           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
10566           << (unsigned)isObjectArgument << I + 1;
10567       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10568       return;
10569     }
10570 
10571     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
10572       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
10573           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10574           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10575           << FromQs.hasUnaligned() << I + 1;
10576       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10577       return;
10578     }
10579 
10580     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
10581     assert(CVR && "expected qualifiers mismatch");
10582 
10583     if (isObjectArgument) {
10584       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
10585           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10586           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10587           << (CVR - 1);
10588     } else {
10589       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
10590           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10591           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10592           << (CVR - 1) << I + 1;
10593     }
10594     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10595     return;
10596   }
10597 
10598   if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
10599       Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
10600     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
10601         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10602         << (unsigned)isObjectArgument << I + 1
10603         << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
10604         << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
10605     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10606     return;
10607   }
10608 
10609   // Special diagnostic for failure to convert an initializer list, since
10610   // telling the user that it has type void is not useful.
10611   if (FromExpr && isa<InitListExpr>(FromExpr)) {
10612     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
10613         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10614         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10615         << ToTy << (unsigned)isObjectArgument << I + 1
10616         << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1
10617             : Conv.Bad.Kind == BadConversionSequence::too_many_initializers
10618                 ? 2
10619                 : 0);
10620     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10621     return;
10622   }
10623 
10624   // Diagnose references or pointers to incomplete types differently,
10625   // since it's far from impossible that the incompleteness triggered
10626   // the failure.
10627   QualType TempFromTy = FromTy.getNonReferenceType();
10628   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
10629     TempFromTy = PTy->getPointeeType();
10630   if (TempFromTy->isIncompleteType()) {
10631     // Emit the generic diagnostic and, optionally, add the hints to it.
10632     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
10633         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10634         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10635         << ToTy << (unsigned)isObjectArgument << I + 1
10636         << (unsigned)(Cand->Fix.Kind);
10637 
10638     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10639     return;
10640   }
10641 
10642   // Diagnose base -> derived pointer conversions.
10643   unsigned BaseToDerivedConversion = 0;
10644   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
10645     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
10646       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10647                                                FromPtrTy->getPointeeType()) &&
10648           !FromPtrTy->getPointeeType()->isIncompleteType() &&
10649           !ToPtrTy->getPointeeType()->isIncompleteType() &&
10650           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
10651                           FromPtrTy->getPointeeType()))
10652         BaseToDerivedConversion = 1;
10653     }
10654   } else if (const ObjCObjectPointerType *FromPtrTy
10655                                     = FromTy->getAs<ObjCObjectPointerType>()) {
10656     if (const ObjCObjectPointerType *ToPtrTy
10657                                         = ToTy->getAs<ObjCObjectPointerType>())
10658       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
10659         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
10660           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10661                                                 FromPtrTy->getPointeeType()) &&
10662               FromIface->isSuperClassOf(ToIface))
10663             BaseToDerivedConversion = 2;
10664   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
10665     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
10666         !FromTy->isIncompleteType() &&
10667         !ToRefTy->getPointeeType()->isIncompleteType() &&
10668         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
10669       BaseToDerivedConversion = 3;
10670     }
10671   }
10672 
10673   if (BaseToDerivedConversion) {
10674     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
10675         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10676         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10677         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
10678     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10679     return;
10680   }
10681 
10682   if (isa<ObjCObjectPointerType>(CFromTy) &&
10683       isa<PointerType>(CToTy)) {
10684       Qualifiers FromQs = CFromTy.getQualifiers();
10685       Qualifiers ToQs = CToTy.getQualifiers();
10686       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10687         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
10688             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10689             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10690             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
10691         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10692         return;
10693       }
10694   }
10695 
10696   if (TakingCandidateAddress &&
10697       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
10698     return;
10699 
10700   // Emit the generic diagnostic and, optionally, add the hints to it.
10701   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
10702   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10703         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10704         << ToTy << (unsigned)isObjectArgument << I + 1
10705         << (unsigned)(Cand->Fix.Kind);
10706 
10707   // If we can fix the conversion, suggest the FixIts.
10708   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
10709        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
10710     FDiag << *HI;
10711   S.Diag(Fn->getLocation(), FDiag);
10712 
10713   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10714 }
10715 
10716 /// Additional arity mismatch diagnosis specific to a function overload
10717 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
10718 /// over a candidate in any candidate set.
10719 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
10720                                unsigned NumArgs) {
10721   FunctionDecl *Fn = Cand->Function;
10722   unsigned MinParams = Fn->getMinRequiredArguments();
10723 
10724   // With invalid overloaded operators, it's possible that we think we
10725   // have an arity mismatch when in fact it looks like we have the
10726   // right number of arguments, because only overloaded operators have
10727   // the weird behavior of overloading member and non-member functions.
10728   // Just don't report anything.
10729   if (Fn->isInvalidDecl() &&
10730       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
10731     return true;
10732 
10733   if (NumArgs < MinParams) {
10734     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
10735            (Cand->FailureKind == ovl_fail_bad_deduction &&
10736             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
10737   } else {
10738     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
10739            (Cand->FailureKind == ovl_fail_bad_deduction &&
10740             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
10741   }
10742 
10743   return false;
10744 }
10745 
10746 /// General arity mismatch diagnosis over a candidate in a candidate set.
10747 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
10748                                   unsigned NumFormalArgs) {
10749   assert(isa<FunctionDecl>(D) &&
10750       "The templated declaration should at least be a function"
10751       " when diagnosing bad template argument deduction due to too many"
10752       " or too few arguments");
10753 
10754   FunctionDecl *Fn = cast<FunctionDecl>(D);
10755 
10756   // TODO: treat calls to a missing default constructor as a special case
10757   const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
10758   unsigned MinParams = Fn->getMinRequiredArguments();
10759 
10760   // at least / at most / exactly
10761   unsigned mode, modeCount;
10762   if (NumFormalArgs < MinParams) {
10763     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
10764         FnTy->isTemplateVariadic())
10765       mode = 0; // "at least"
10766     else
10767       mode = 2; // "exactly"
10768     modeCount = MinParams;
10769   } else {
10770     if (MinParams != FnTy->getNumParams())
10771       mode = 1; // "at most"
10772     else
10773       mode = 2; // "exactly"
10774     modeCount = FnTy->getNumParams();
10775   }
10776 
10777   std::string Description;
10778   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10779       ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
10780 
10781   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10782     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10783         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10784         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
10785   else
10786     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
10787         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10788         << Description << mode << modeCount << NumFormalArgs;
10789 
10790   MaybeEmitInheritedConstructorNote(S, Found);
10791 }
10792 
10793 /// Arity mismatch diagnosis specific to a function overload candidate.
10794 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
10795                                   unsigned NumFormalArgs) {
10796   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
10797     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10798 }
10799 
10800 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10801   if (TemplateDecl *TD = Templated->getDescribedTemplate())
10802     return TD;
10803   llvm_unreachable("Unsupported: Getting the described template declaration"
10804                    " for bad deduction diagnosis");
10805 }
10806 
10807 /// Diagnose a failed template-argument deduction.
10808 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10809                                  DeductionFailureInfo &DeductionFailure,
10810                                  unsigned NumArgs,
10811                                  bool TakingCandidateAddress) {
10812   TemplateParameter Param = DeductionFailure.getTemplateParameter();
10813   NamedDecl *ParamD;
10814   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10815   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10816   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10817   switch (DeductionFailure.Result) {
10818   case Sema::TDK_Success:
10819     llvm_unreachable("TDK_success while diagnosing bad deduction");
10820 
10821   case Sema::TDK_Incomplete: {
10822     assert(ParamD && "no parameter found for incomplete deduction result");
10823     S.Diag(Templated->getLocation(),
10824            diag::note_ovl_candidate_incomplete_deduction)
10825         << ParamD->getDeclName();
10826     MaybeEmitInheritedConstructorNote(S, Found);
10827     return;
10828   }
10829 
10830   case Sema::TDK_IncompletePack: {
10831     assert(ParamD && "no parameter found for incomplete deduction result");
10832     S.Diag(Templated->getLocation(),
10833            diag::note_ovl_candidate_incomplete_deduction_pack)
10834         << ParamD->getDeclName()
10835         << (DeductionFailure.getFirstArg()->pack_size() + 1)
10836         << *DeductionFailure.getFirstArg();
10837     MaybeEmitInheritedConstructorNote(S, Found);
10838     return;
10839   }
10840 
10841   case Sema::TDK_Underqualified: {
10842     assert(ParamD && "no parameter found for bad qualifiers deduction result");
10843     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10844 
10845     QualType Param = DeductionFailure.getFirstArg()->getAsType();
10846 
10847     // Param will have been canonicalized, but it should just be a
10848     // qualified version of ParamD, so move the qualifiers to that.
10849     QualifierCollector Qs;
10850     Qs.strip(Param);
10851     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10852     assert(S.Context.hasSameType(Param, NonCanonParam));
10853 
10854     // Arg has also been canonicalized, but there's nothing we can do
10855     // about that.  It also doesn't matter as much, because it won't
10856     // have any template parameters in it (because deduction isn't
10857     // done on dependent types).
10858     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10859 
10860     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10861         << ParamD->getDeclName() << Arg << NonCanonParam;
10862     MaybeEmitInheritedConstructorNote(S, Found);
10863     return;
10864   }
10865 
10866   case Sema::TDK_Inconsistent: {
10867     assert(ParamD && "no parameter found for inconsistent deduction result");
10868     int which = 0;
10869     if (isa<TemplateTypeParmDecl>(ParamD))
10870       which = 0;
10871     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10872       // Deduction might have failed because we deduced arguments of two
10873       // different types for a non-type template parameter.
10874       // FIXME: Use a different TDK value for this.
10875       QualType T1 =
10876           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10877       QualType T2 =
10878           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10879       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10880         S.Diag(Templated->getLocation(),
10881                diag::note_ovl_candidate_inconsistent_deduction_types)
10882           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10883           << *DeductionFailure.getSecondArg() << T2;
10884         MaybeEmitInheritedConstructorNote(S, Found);
10885         return;
10886       }
10887 
10888       which = 1;
10889     } else {
10890       which = 2;
10891     }
10892 
10893     // Tweak the diagnostic if the problem is that we deduced packs of
10894     // different arities. We'll print the actual packs anyway in case that
10895     // includes additional useful information.
10896     if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
10897         DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
10898         DeductionFailure.getFirstArg()->pack_size() !=
10899             DeductionFailure.getSecondArg()->pack_size()) {
10900       which = 3;
10901     }
10902 
10903     S.Diag(Templated->getLocation(),
10904            diag::note_ovl_candidate_inconsistent_deduction)
10905         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10906         << *DeductionFailure.getSecondArg();
10907     MaybeEmitInheritedConstructorNote(S, Found);
10908     return;
10909   }
10910 
10911   case Sema::TDK_InvalidExplicitArguments:
10912     assert(ParamD && "no parameter found for invalid explicit arguments");
10913     if (ParamD->getDeclName())
10914       S.Diag(Templated->getLocation(),
10915              diag::note_ovl_candidate_explicit_arg_mismatch_named)
10916           << ParamD->getDeclName();
10917     else {
10918       int index = 0;
10919       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10920         index = TTP->getIndex();
10921       else if (NonTypeTemplateParmDecl *NTTP
10922                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10923         index = NTTP->getIndex();
10924       else
10925         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10926       S.Diag(Templated->getLocation(),
10927              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10928           << (index + 1);
10929     }
10930     MaybeEmitInheritedConstructorNote(S, Found);
10931     return;
10932 
10933   case Sema::TDK_ConstraintsNotSatisfied: {
10934     // Format the template argument list into the argument string.
10935     SmallString<128> TemplateArgString;
10936     TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
10937     TemplateArgString = " ";
10938     TemplateArgString += S.getTemplateArgumentBindingsText(
10939         getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10940     if (TemplateArgString.size() == 1)
10941       TemplateArgString.clear();
10942     S.Diag(Templated->getLocation(),
10943            diag::note_ovl_candidate_unsatisfied_constraints)
10944         << TemplateArgString;
10945 
10946     S.DiagnoseUnsatisfiedConstraint(
10947         static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
10948     return;
10949   }
10950   case Sema::TDK_TooManyArguments:
10951   case Sema::TDK_TooFewArguments:
10952     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10953     return;
10954 
10955   case Sema::TDK_InstantiationDepth:
10956     S.Diag(Templated->getLocation(),
10957            diag::note_ovl_candidate_instantiation_depth);
10958     MaybeEmitInheritedConstructorNote(S, Found);
10959     return;
10960 
10961   case Sema::TDK_SubstitutionFailure: {
10962     // Format the template argument list into the argument string.
10963     SmallString<128> TemplateArgString;
10964     if (TemplateArgumentList *Args =
10965             DeductionFailure.getTemplateArgumentList()) {
10966       TemplateArgString = " ";
10967       TemplateArgString += S.getTemplateArgumentBindingsText(
10968           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10969       if (TemplateArgString.size() == 1)
10970         TemplateArgString.clear();
10971     }
10972 
10973     // If this candidate was disabled by enable_if, say so.
10974     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10975     if (PDiag && PDiag->second.getDiagID() ==
10976           diag::err_typename_nested_not_found_enable_if) {
10977       // FIXME: Use the source range of the condition, and the fully-qualified
10978       //        name of the enable_if template. These are both present in PDiag.
10979       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10980         << "'enable_if'" << TemplateArgString;
10981       return;
10982     }
10983 
10984     // We found a specific requirement that disabled the enable_if.
10985     if (PDiag && PDiag->second.getDiagID() ==
10986         diag::err_typename_nested_not_found_requirement) {
10987       S.Diag(Templated->getLocation(),
10988              diag::note_ovl_candidate_disabled_by_requirement)
10989         << PDiag->second.getStringArg(0) << TemplateArgString;
10990       return;
10991     }
10992 
10993     // Format the SFINAE diagnostic into the argument string.
10994     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10995     //        formatted message in another diagnostic.
10996     SmallString<128> SFINAEArgString;
10997     SourceRange R;
10998     if (PDiag) {
10999       SFINAEArgString = ": ";
11000       R = SourceRange(PDiag->first, PDiag->first);
11001       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
11002     }
11003 
11004     S.Diag(Templated->getLocation(),
11005            diag::note_ovl_candidate_substitution_failure)
11006         << TemplateArgString << SFINAEArgString << R;
11007     MaybeEmitInheritedConstructorNote(S, Found);
11008     return;
11009   }
11010 
11011   case Sema::TDK_DeducedMismatch:
11012   case Sema::TDK_DeducedMismatchNested: {
11013     // Format the template argument list into the argument string.
11014     SmallString<128> TemplateArgString;
11015     if (TemplateArgumentList *Args =
11016             DeductionFailure.getTemplateArgumentList()) {
11017       TemplateArgString = " ";
11018       TemplateArgString += S.getTemplateArgumentBindingsText(
11019           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11020       if (TemplateArgString.size() == 1)
11021         TemplateArgString.clear();
11022     }
11023 
11024     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
11025         << (*DeductionFailure.getCallArgIndex() + 1)
11026         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
11027         << TemplateArgString
11028         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
11029     break;
11030   }
11031 
11032   case Sema::TDK_NonDeducedMismatch: {
11033     // FIXME: Provide a source location to indicate what we couldn't match.
11034     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
11035     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
11036     if (FirstTA.getKind() == TemplateArgument::Template &&
11037         SecondTA.getKind() == TemplateArgument::Template) {
11038       TemplateName FirstTN = FirstTA.getAsTemplate();
11039       TemplateName SecondTN = SecondTA.getAsTemplate();
11040       if (FirstTN.getKind() == TemplateName::Template &&
11041           SecondTN.getKind() == TemplateName::Template) {
11042         if (FirstTN.getAsTemplateDecl()->getName() ==
11043             SecondTN.getAsTemplateDecl()->getName()) {
11044           // FIXME: This fixes a bad diagnostic where both templates are named
11045           // the same.  This particular case is a bit difficult since:
11046           // 1) It is passed as a string to the diagnostic printer.
11047           // 2) The diagnostic printer only attempts to find a better
11048           //    name for types, not decls.
11049           // Ideally, this should folded into the diagnostic printer.
11050           S.Diag(Templated->getLocation(),
11051                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
11052               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
11053           return;
11054         }
11055       }
11056     }
11057 
11058     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
11059         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
11060       return;
11061 
11062     // FIXME: For generic lambda parameters, check if the function is a lambda
11063     // call operator, and if so, emit a prettier and more informative
11064     // diagnostic that mentions 'auto' and lambda in addition to
11065     // (or instead of?) the canonical template type parameters.
11066     S.Diag(Templated->getLocation(),
11067            diag::note_ovl_candidate_non_deduced_mismatch)
11068         << FirstTA << SecondTA;
11069     return;
11070   }
11071   // TODO: diagnose these individually, then kill off
11072   // note_ovl_candidate_bad_deduction, which is uselessly vague.
11073   case Sema::TDK_MiscellaneousDeductionFailure:
11074     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
11075     MaybeEmitInheritedConstructorNote(S, Found);
11076     return;
11077   case Sema::TDK_CUDATargetMismatch:
11078     S.Diag(Templated->getLocation(),
11079            diag::note_cuda_ovl_candidate_target_mismatch);
11080     return;
11081   }
11082 }
11083 
11084 /// Diagnose a failed template-argument deduction, for function calls.
11085 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
11086                                  unsigned NumArgs,
11087                                  bool TakingCandidateAddress) {
11088   unsigned TDK = Cand->DeductionFailure.Result;
11089   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
11090     if (CheckArityMismatch(S, Cand, NumArgs))
11091       return;
11092   }
11093   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
11094                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
11095 }
11096 
11097 /// CUDA: diagnose an invalid call across targets.
11098 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
11099   FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11100   FunctionDecl *Callee = Cand->Function;
11101 
11102   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
11103                            CalleeTarget = S.IdentifyCUDATarget(Callee);
11104 
11105   std::string FnDesc;
11106   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11107       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
11108                                 Cand->getRewriteKind(), FnDesc);
11109 
11110   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
11111       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11112       << FnDesc /* Ignored */
11113       << CalleeTarget << CallerTarget;
11114 
11115   // This could be an implicit constructor for which we could not infer the
11116   // target due to a collsion. Diagnose that case.
11117   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
11118   if (Meth != nullptr && Meth->isImplicit()) {
11119     CXXRecordDecl *ParentClass = Meth->getParent();
11120     Sema::CXXSpecialMember CSM;
11121 
11122     switch (FnKindPair.first) {
11123     default:
11124       return;
11125     case oc_implicit_default_constructor:
11126       CSM = Sema::CXXDefaultConstructor;
11127       break;
11128     case oc_implicit_copy_constructor:
11129       CSM = Sema::CXXCopyConstructor;
11130       break;
11131     case oc_implicit_move_constructor:
11132       CSM = Sema::CXXMoveConstructor;
11133       break;
11134     case oc_implicit_copy_assignment:
11135       CSM = Sema::CXXCopyAssignment;
11136       break;
11137     case oc_implicit_move_assignment:
11138       CSM = Sema::CXXMoveAssignment;
11139       break;
11140     };
11141 
11142     bool ConstRHS = false;
11143     if (Meth->getNumParams()) {
11144       if (const ReferenceType *RT =
11145               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
11146         ConstRHS = RT->getPointeeType().isConstQualified();
11147       }
11148     }
11149 
11150     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
11151                                               /* ConstRHS */ ConstRHS,
11152                                               /* Diagnose */ true);
11153   }
11154 }
11155 
11156 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
11157   FunctionDecl *Callee = Cand->Function;
11158   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
11159 
11160   S.Diag(Callee->getLocation(),
11161          diag::note_ovl_candidate_disabled_by_function_cond_attr)
11162       << Attr->getCond()->getSourceRange() << Attr->getMessage();
11163 }
11164 
11165 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
11166   ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function);
11167   assert(ES.isExplicit() && "not an explicit candidate");
11168 
11169   unsigned Kind;
11170   switch (Cand->Function->getDeclKind()) {
11171   case Decl::Kind::CXXConstructor:
11172     Kind = 0;
11173     break;
11174   case Decl::Kind::CXXConversion:
11175     Kind = 1;
11176     break;
11177   case Decl::Kind::CXXDeductionGuide:
11178     Kind = Cand->Function->isImplicit() ? 0 : 2;
11179     break;
11180   default:
11181     llvm_unreachable("invalid Decl");
11182   }
11183 
11184   // Note the location of the first (in-class) declaration; a redeclaration
11185   // (particularly an out-of-class definition) will typically lack the
11186   // 'explicit' specifier.
11187   // FIXME: This is probably a good thing to do for all 'candidate' notes.
11188   FunctionDecl *First = Cand->Function->getFirstDecl();
11189   if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
11190     First = Pattern->getFirstDecl();
11191 
11192   S.Diag(First->getLocation(),
11193          diag::note_ovl_candidate_explicit)
11194       << Kind << (ES.getExpr() ? 1 : 0)
11195       << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
11196 }
11197 
11198 /// Generates a 'note' diagnostic for an overload candidate.  We've
11199 /// already generated a primary error at the call site.
11200 ///
11201 /// It really does need to be a single diagnostic with its caret
11202 /// pointed at the candidate declaration.  Yes, this creates some
11203 /// major challenges of technical writing.  Yes, this makes pointing
11204 /// out problems with specific arguments quite awkward.  It's still
11205 /// better than generating twenty screens of text for every failed
11206 /// overload.
11207 ///
11208 /// It would be great to be able to express per-candidate problems
11209 /// more richly for those diagnostic clients that cared, but we'd
11210 /// still have to be just as careful with the default diagnostics.
11211 /// \param CtorDestAS Addr space of object being constructed (for ctor
11212 /// candidates only).
11213 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
11214                                   unsigned NumArgs,
11215                                   bool TakingCandidateAddress,
11216                                   LangAS CtorDestAS = LangAS::Default) {
11217   FunctionDecl *Fn = Cand->Function;
11218   if (shouldSkipNotingLambdaConversionDecl(Fn))
11219     return;
11220 
11221   // Note deleted candidates, but only if they're viable.
11222   if (Cand->Viable) {
11223     if (Fn->isDeleted()) {
11224       std::string FnDesc;
11225       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11226           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11227                                     Cand->getRewriteKind(), FnDesc);
11228 
11229       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
11230           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11231           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
11232       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11233       return;
11234     }
11235 
11236     // We don't really have anything else to say about viable candidates.
11237     S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11238     return;
11239   }
11240 
11241   switch (Cand->FailureKind) {
11242   case ovl_fail_too_many_arguments:
11243   case ovl_fail_too_few_arguments:
11244     return DiagnoseArityMismatch(S, Cand, NumArgs);
11245 
11246   case ovl_fail_bad_deduction:
11247     return DiagnoseBadDeduction(S, Cand, NumArgs,
11248                                 TakingCandidateAddress);
11249 
11250   case ovl_fail_illegal_constructor: {
11251     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
11252       << (Fn->getPrimaryTemplate() ? 1 : 0);
11253     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11254     return;
11255   }
11256 
11257   case ovl_fail_object_addrspace_mismatch: {
11258     Qualifiers QualsForPrinting;
11259     QualsForPrinting.setAddressSpace(CtorDestAS);
11260     S.Diag(Fn->getLocation(),
11261            diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
11262         << QualsForPrinting;
11263     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11264     return;
11265   }
11266 
11267   case ovl_fail_trivial_conversion:
11268   case ovl_fail_bad_final_conversion:
11269   case ovl_fail_final_conversion_not_exact:
11270     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11271 
11272   case ovl_fail_bad_conversion: {
11273     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
11274     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
11275       if (Cand->Conversions[I].isBad())
11276         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
11277 
11278     // FIXME: this currently happens when we're called from SemaInit
11279     // when user-conversion overload fails.  Figure out how to handle
11280     // those conditions and diagnose them well.
11281     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11282   }
11283 
11284   case ovl_fail_bad_target:
11285     return DiagnoseBadTarget(S, Cand);
11286 
11287   case ovl_fail_enable_if:
11288     return DiagnoseFailedEnableIfAttr(S, Cand);
11289 
11290   case ovl_fail_explicit:
11291     return DiagnoseFailedExplicitSpec(S, Cand);
11292 
11293   case ovl_fail_inhctor_slice:
11294     // It's generally not interesting to note copy/move constructors here.
11295     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
11296       return;
11297     S.Diag(Fn->getLocation(),
11298            diag::note_ovl_candidate_inherited_constructor_slice)
11299       << (Fn->getPrimaryTemplate() ? 1 : 0)
11300       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
11301     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11302     return;
11303 
11304   case ovl_fail_addr_not_available: {
11305     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
11306     (void)Available;
11307     assert(!Available);
11308     break;
11309   }
11310   case ovl_non_default_multiversion_function:
11311     // Do nothing, these should simply be ignored.
11312     break;
11313 
11314   case ovl_fail_constraints_not_satisfied: {
11315     std::string FnDesc;
11316     std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11317         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11318                                   Cand->getRewriteKind(), FnDesc);
11319 
11320     S.Diag(Fn->getLocation(),
11321            diag::note_ovl_candidate_constraints_not_satisfied)
11322         << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11323         << FnDesc /* Ignored */;
11324     ConstraintSatisfaction Satisfaction;
11325     if (S.CheckFunctionConstraints(Fn, Satisfaction))
11326       break;
11327     S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11328   }
11329   }
11330 }
11331 
11332 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
11333   if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate))
11334     return;
11335 
11336   // Desugar the type of the surrogate down to a function type,
11337   // retaining as many typedefs as possible while still showing
11338   // the function type (and, therefore, its parameter types).
11339   QualType FnType = Cand->Surrogate->getConversionType();
11340   bool isLValueReference = false;
11341   bool isRValueReference = false;
11342   bool isPointer = false;
11343   if (const LValueReferenceType *FnTypeRef =
11344         FnType->getAs<LValueReferenceType>()) {
11345     FnType = FnTypeRef->getPointeeType();
11346     isLValueReference = true;
11347   } else if (const RValueReferenceType *FnTypeRef =
11348                FnType->getAs<RValueReferenceType>()) {
11349     FnType = FnTypeRef->getPointeeType();
11350     isRValueReference = true;
11351   }
11352   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
11353     FnType = FnTypePtr->getPointeeType();
11354     isPointer = true;
11355   }
11356   // Desugar down to a function type.
11357   FnType = QualType(FnType->getAs<FunctionType>(), 0);
11358   // Reconstruct the pointer/reference as appropriate.
11359   if (isPointer) FnType = S.Context.getPointerType(FnType);
11360   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
11361   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
11362 
11363   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
11364     << FnType;
11365 }
11366 
11367 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
11368                                          SourceLocation OpLoc,
11369                                          OverloadCandidate *Cand) {
11370   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
11371   std::string TypeStr("operator");
11372   TypeStr += Opc;
11373   TypeStr += "(";
11374   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
11375   if (Cand->Conversions.size() == 1) {
11376     TypeStr += ")";
11377     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11378   } else {
11379     TypeStr += ", ";
11380     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
11381     TypeStr += ")";
11382     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11383   }
11384 }
11385 
11386 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
11387                                          OverloadCandidate *Cand) {
11388   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
11389     if (ICS.isBad()) break; // all meaningless after first invalid
11390     if (!ICS.isAmbiguous()) continue;
11391 
11392     ICS.DiagnoseAmbiguousConversion(
11393         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
11394   }
11395 }
11396 
11397 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
11398   if (Cand->Function)
11399     return Cand->Function->getLocation();
11400   if (Cand->IsSurrogate)
11401     return Cand->Surrogate->getLocation();
11402   return SourceLocation();
11403 }
11404 
11405 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
11406   switch ((Sema::TemplateDeductionResult)DFI.Result) {
11407   case Sema::TDK_Success:
11408   case Sema::TDK_NonDependentConversionFailure:
11409     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
11410 
11411   case Sema::TDK_Invalid:
11412   case Sema::TDK_Incomplete:
11413   case Sema::TDK_IncompletePack:
11414     return 1;
11415 
11416   case Sema::TDK_Underqualified:
11417   case Sema::TDK_Inconsistent:
11418     return 2;
11419 
11420   case Sema::TDK_SubstitutionFailure:
11421   case Sema::TDK_DeducedMismatch:
11422   case Sema::TDK_ConstraintsNotSatisfied:
11423   case Sema::TDK_DeducedMismatchNested:
11424   case Sema::TDK_NonDeducedMismatch:
11425   case Sema::TDK_MiscellaneousDeductionFailure:
11426   case Sema::TDK_CUDATargetMismatch:
11427     return 3;
11428 
11429   case Sema::TDK_InstantiationDepth:
11430     return 4;
11431 
11432   case Sema::TDK_InvalidExplicitArguments:
11433     return 5;
11434 
11435   case Sema::TDK_TooManyArguments:
11436   case Sema::TDK_TooFewArguments:
11437     return 6;
11438   }
11439   llvm_unreachable("Unhandled deduction result");
11440 }
11441 
11442 namespace {
11443 struct CompareOverloadCandidatesForDisplay {
11444   Sema &S;
11445   SourceLocation Loc;
11446   size_t NumArgs;
11447   OverloadCandidateSet::CandidateSetKind CSK;
11448 
11449   CompareOverloadCandidatesForDisplay(
11450       Sema &S, SourceLocation Loc, size_t NArgs,
11451       OverloadCandidateSet::CandidateSetKind CSK)
11452       : S(S), NumArgs(NArgs), CSK(CSK) {}
11453 
11454   OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
11455     // If there are too many or too few arguments, that's the high-order bit we
11456     // want to sort by, even if the immediate failure kind was something else.
11457     if (C->FailureKind == ovl_fail_too_many_arguments ||
11458         C->FailureKind == ovl_fail_too_few_arguments)
11459       return static_cast<OverloadFailureKind>(C->FailureKind);
11460 
11461     if (C->Function) {
11462       if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
11463         return ovl_fail_too_many_arguments;
11464       if (NumArgs < C->Function->getMinRequiredArguments())
11465         return ovl_fail_too_few_arguments;
11466     }
11467 
11468     return static_cast<OverloadFailureKind>(C->FailureKind);
11469   }
11470 
11471   bool operator()(const OverloadCandidate *L,
11472                   const OverloadCandidate *R) {
11473     // Fast-path this check.
11474     if (L == R) return false;
11475 
11476     // Order first by viability.
11477     if (L->Viable) {
11478       if (!R->Viable) return true;
11479 
11480       // TODO: introduce a tri-valued comparison for overload
11481       // candidates.  Would be more worthwhile if we had a sort
11482       // that could exploit it.
11483       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
11484         return true;
11485       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
11486         return false;
11487     } else if (R->Viable)
11488       return false;
11489 
11490     assert(L->Viable == R->Viable);
11491 
11492     // Criteria by which we can sort non-viable candidates:
11493     if (!L->Viable) {
11494       OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
11495       OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
11496 
11497       // 1. Arity mismatches come after other candidates.
11498       if (LFailureKind == ovl_fail_too_many_arguments ||
11499           LFailureKind == ovl_fail_too_few_arguments) {
11500         if (RFailureKind == ovl_fail_too_many_arguments ||
11501             RFailureKind == ovl_fail_too_few_arguments) {
11502           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
11503           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
11504           if (LDist == RDist) {
11505             if (LFailureKind == RFailureKind)
11506               // Sort non-surrogates before surrogates.
11507               return !L->IsSurrogate && R->IsSurrogate;
11508             // Sort candidates requiring fewer parameters than there were
11509             // arguments given after candidates requiring more parameters
11510             // than there were arguments given.
11511             return LFailureKind == ovl_fail_too_many_arguments;
11512           }
11513           return LDist < RDist;
11514         }
11515         return false;
11516       }
11517       if (RFailureKind == ovl_fail_too_many_arguments ||
11518           RFailureKind == ovl_fail_too_few_arguments)
11519         return true;
11520 
11521       // 2. Bad conversions come first and are ordered by the number
11522       // of bad conversions and quality of good conversions.
11523       if (LFailureKind == ovl_fail_bad_conversion) {
11524         if (RFailureKind != ovl_fail_bad_conversion)
11525           return true;
11526 
11527         // The conversion that can be fixed with a smaller number of changes,
11528         // comes first.
11529         unsigned numLFixes = L->Fix.NumConversionsFixed;
11530         unsigned numRFixes = R->Fix.NumConversionsFixed;
11531         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
11532         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
11533         if (numLFixes != numRFixes) {
11534           return numLFixes < numRFixes;
11535         }
11536 
11537         // If there's any ordering between the defined conversions...
11538         // FIXME: this might not be transitive.
11539         assert(L->Conversions.size() == R->Conversions.size());
11540 
11541         int leftBetter = 0;
11542         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
11543         for (unsigned E = L->Conversions.size(); I != E; ++I) {
11544           switch (CompareImplicitConversionSequences(S, Loc,
11545                                                      L->Conversions[I],
11546                                                      R->Conversions[I])) {
11547           case ImplicitConversionSequence::Better:
11548             leftBetter++;
11549             break;
11550 
11551           case ImplicitConversionSequence::Worse:
11552             leftBetter--;
11553             break;
11554 
11555           case ImplicitConversionSequence::Indistinguishable:
11556             break;
11557           }
11558         }
11559         if (leftBetter > 0) return true;
11560         if (leftBetter < 0) return false;
11561 
11562       } else if (RFailureKind == ovl_fail_bad_conversion)
11563         return false;
11564 
11565       if (LFailureKind == ovl_fail_bad_deduction) {
11566         if (RFailureKind != ovl_fail_bad_deduction)
11567           return true;
11568 
11569         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11570           return RankDeductionFailure(L->DeductionFailure)
11571                < RankDeductionFailure(R->DeductionFailure);
11572       } else if (RFailureKind == ovl_fail_bad_deduction)
11573         return false;
11574 
11575       // TODO: others?
11576     }
11577 
11578     // Sort everything else by location.
11579     SourceLocation LLoc = GetLocationForCandidate(L);
11580     SourceLocation RLoc = GetLocationForCandidate(R);
11581 
11582     // Put candidates without locations (e.g. builtins) at the end.
11583     if (LLoc.isInvalid()) return false;
11584     if (RLoc.isInvalid()) return true;
11585 
11586     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11587   }
11588 };
11589 }
11590 
11591 /// CompleteNonViableCandidate - Normally, overload resolution only
11592 /// computes up to the first bad conversion. Produces the FixIt set if
11593 /// possible.
11594 static void
11595 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
11596                            ArrayRef<Expr *> Args,
11597                            OverloadCandidateSet::CandidateSetKind CSK) {
11598   assert(!Cand->Viable);
11599 
11600   // Don't do anything on failures other than bad conversion.
11601   if (Cand->FailureKind != ovl_fail_bad_conversion)
11602     return;
11603 
11604   // We only want the FixIts if all the arguments can be corrected.
11605   bool Unfixable = false;
11606   // Use a implicit copy initialization to check conversion fixes.
11607   Cand->Fix.setConversionChecker(TryCopyInitialization);
11608 
11609   // Attempt to fix the bad conversion.
11610   unsigned ConvCount = Cand->Conversions.size();
11611   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
11612        ++ConvIdx) {
11613     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
11614     if (Cand->Conversions[ConvIdx].isInitialized() &&
11615         Cand->Conversions[ConvIdx].isBad()) {
11616       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11617       break;
11618     }
11619   }
11620 
11621   // FIXME: this should probably be preserved from the overload
11622   // operation somehow.
11623   bool SuppressUserConversions = false;
11624 
11625   unsigned ConvIdx = 0;
11626   unsigned ArgIdx = 0;
11627   ArrayRef<QualType> ParamTypes;
11628   bool Reversed = Cand->isReversed();
11629 
11630   if (Cand->IsSurrogate) {
11631     QualType ConvType
11632       = Cand->Surrogate->getConversionType().getNonReferenceType();
11633     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11634       ConvType = ConvPtrType->getPointeeType();
11635     ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
11636     // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11637     ConvIdx = 1;
11638   } else if (Cand->Function) {
11639     ParamTypes =
11640         Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
11641     if (isa<CXXMethodDecl>(Cand->Function) &&
11642         !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
11643       // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11644       ConvIdx = 1;
11645       if (CSK == OverloadCandidateSet::CSK_Operator &&
11646           Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
11647           Cand->Function->getDeclName().getCXXOverloadedOperator() !=
11648               OO_Subscript)
11649         // Argument 0 is 'this', which doesn't have a corresponding parameter.
11650         ArgIdx = 1;
11651     }
11652   } else {
11653     // Builtin operator.
11654     assert(ConvCount <= 3);
11655     ParamTypes = Cand->BuiltinParamTypes;
11656   }
11657 
11658   // Fill in the rest of the conversions.
11659   for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
11660        ConvIdx != ConvCount;
11661        ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
11662     assert(ArgIdx < Args.size() && "no argument for this arg conversion");
11663     if (Cand->Conversions[ConvIdx].isInitialized()) {
11664       // We've already checked this conversion.
11665     } else if (ParamIdx < ParamTypes.size()) {
11666       if (ParamTypes[ParamIdx]->isDependentType())
11667         Cand->Conversions[ConvIdx].setAsIdentityConversion(
11668             Args[ArgIdx]->getType());
11669       else {
11670         Cand->Conversions[ConvIdx] =
11671             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
11672                                   SuppressUserConversions,
11673                                   /*InOverloadResolution=*/true,
11674                                   /*AllowObjCWritebackConversion=*/
11675                                   S.getLangOpts().ObjCAutoRefCount);
11676         // Store the FixIt in the candidate if it exists.
11677         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
11678           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11679       }
11680     } else
11681       Cand->Conversions[ConvIdx].setEllipsis();
11682   }
11683 }
11684 
11685 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
11686     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11687     SourceLocation OpLoc,
11688     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11689   // Sort the candidates by viability and position.  Sorting directly would
11690   // be prohibitive, so we make a set of pointers and sort those.
11691   SmallVector<OverloadCandidate*, 32> Cands;
11692   if (OCD == OCD_AllCandidates) Cands.reserve(size());
11693   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11694     if (!Filter(*Cand))
11695       continue;
11696     switch (OCD) {
11697     case OCD_AllCandidates:
11698       if (!Cand->Viable) {
11699         if (!Cand->Function && !Cand->IsSurrogate) {
11700           // This a non-viable builtin candidate.  We do not, in general,
11701           // want to list every possible builtin candidate.
11702           continue;
11703         }
11704         CompleteNonViableCandidate(S, Cand, Args, Kind);
11705       }
11706       break;
11707 
11708     case OCD_ViableCandidates:
11709       if (!Cand->Viable)
11710         continue;
11711       break;
11712 
11713     case OCD_AmbiguousCandidates:
11714       if (!Cand->Best)
11715         continue;
11716       break;
11717     }
11718 
11719     Cands.push_back(Cand);
11720   }
11721 
11722   llvm::stable_sort(
11723       Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
11724 
11725   return Cands;
11726 }
11727 
11728 bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
11729                                             SourceLocation OpLoc) {
11730   bool DeferHint = false;
11731   if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
11732     // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
11733     // host device candidates.
11734     auto WrongSidedCands =
11735         CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
11736           return (Cand.Viable == false &&
11737                   Cand.FailureKind == ovl_fail_bad_target) ||
11738                  (Cand.Function &&
11739                   Cand.Function->template hasAttr<CUDAHostAttr>() &&
11740                   Cand.Function->template hasAttr<CUDADeviceAttr>());
11741         });
11742     DeferHint = !WrongSidedCands.empty();
11743   }
11744   return DeferHint;
11745 }
11746 
11747 /// When overload resolution fails, prints diagnostic messages containing the
11748 /// candidates in the candidate set.
11749 void OverloadCandidateSet::NoteCandidates(
11750     PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
11751     ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
11752     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11753 
11754   auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
11755 
11756   S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
11757 
11758   NoteCandidates(S, Args, Cands, Opc, OpLoc);
11759 
11760   if (OCD == OCD_AmbiguousCandidates)
11761     MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
11762 }
11763 
11764 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
11765                                           ArrayRef<OverloadCandidate *> Cands,
11766                                           StringRef Opc, SourceLocation OpLoc) {
11767   bool ReportedAmbiguousConversions = false;
11768 
11769   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11770   unsigned CandsShown = 0;
11771   auto I = Cands.begin(), E = Cands.end();
11772   for (; I != E; ++I) {
11773     OverloadCandidate *Cand = *I;
11774 
11775     if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
11776         ShowOverloads == Ovl_Best) {
11777       break;
11778     }
11779     ++CandsShown;
11780 
11781     if (Cand->Function)
11782       NoteFunctionCandidate(S, Cand, Args.size(),
11783                             /*TakingCandidateAddress=*/false, DestAS);
11784     else if (Cand->IsSurrogate)
11785       NoteSurrogateCandidate(S, Cand);
11786     else {
11787       assert(Cand->Viable &&
11788              "Non-viable built-in candidates are not added to Cands.");
11789       // Generally we only see ambiguities including viable builtin
11790       // operators if overload resolution got screwed up by an
11791       // ambiguous user-defined conversion.
11792       //
11793       // FIXME: It's quite possible for different conversions to see
11794       // different ambiguities, though.
11795       if (!ReportedAmbiguousConversions) {
11796         NoteAmbiguousUserConversions(S, OpLoc, Cand);
11797         ReportedAmbiguousConversions = true;
11798       }
11799 
11800       // If this is a viable builtin, print it.
11801       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
11802     }
11803   }
11804 
11805   // Inform S.Diags that we've shown an overload set with N elements.  This may
11806   // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
11807   S.Diags.overloadCandidatesShown(CandsShown);
11808 
11809   if (I != E)
11810     S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
11811            shouldDeferDiags(S, Args, OpLoc))
11812         << int(E - I);
11813 }
11814 
11815 static SourceLocation
11816 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
11817   return Cand->Specialization ? Cand->Specialization->getLocation()
11818                               : SourceLocation();
11819 }
11820 
11821 namespace {
11822 struct CompareTemplateSpecCandidatesForDisplay {
11823   Sema &S;
11824   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
11825 
11826   bool operator()(const TemplateSpecCandidate *L,
11827                   const TemplateSpecCandidate *R) {
11828     // Fast-path this check.
11829     if (L == R)
11830       return false;
11831 
11832     // Assuming that both candidates are not matches...
11833 
11834     // Sort by the ranking of deduction failures.
11835     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11836       return RankDeductionFailure(L->DeductionFailure) <
11837              RankDeductionFailure(R->DeductionFailure);
11838 
11839     // Sort everything else by location.
11840     SourceLocation LLoc = GetLocationForCandidate(L);
11841     SourceLocation RLoc = GetLocationForCandidate(R);
11842 
11843     // Put candidates without locations (e.g. builtins) at the end.
11844     if (LLoc.isInvalid())
11845       return false;
11846     if (RLoc.isInvalid())
11847       return true;
11848 
11849     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11850   }
11851 };
11852 }
11853 
11854 /// Diagnose a template argument deduction failure.
11855 /// We are treating these failures as overload failures due to bad
11856 /// deductions.
11857 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
11858                                                  bool ForTakingAddress) {
11859   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
11860                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
11861 }
11862 
11863 void TemplateSpecCandidateSet::destroyCandidates() {
11864   for (iterator i = begin(), e = end(); i != e; ++i) {
11865     i->DeductionFailure.Destroy();
11866   }
11867 }
11868 
11869 void TemplateSpecCandidateSet::clear() {
11870   destroyCandidates();
11871   Candidates.clear();
11872 }
11873 
11874 /// NoteCandidates - When no template specialization match is found, prints
11875 /// diagnostic messages containing the non-matching specializations that form
11876 /// the candidate set.
11877 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
11878 /// OCD == OCD_AllCandidates and Cand->Viable == false.
11879 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
11880   // Sort the candidates by position (assuming no candidate is a match).
11881   // Sorting directly would be prohibitive, so we make a set of pointers
11882   // and sort those.
11883   SmallVector<TemplateSpecCandidate *, 32> Cands;
11884   Cands.reserve(size());
11885   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11886     if (Cand->Specialization)
11887       Cands.push_back(Cand);
11888     // Otherwise, this is a non-matching builtin candidate.  We do not,
11889     // in general, want to list every possible builtin candidate.
11890   }
11891 
11892   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
11893 
11894   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
11895   // for generalization purposes (?).
11896   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11897 
11898   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
11899   unsigned CandsShown = 0;
11900   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11901     TemplateSpecCandidate *Cand = *I;
11902 
11903     // Set an arbitrary limit on the number of candidates we'll spam
11904     // the user with.  FIXME: This limit should depend on details of the
11905     // candidate list.
11906     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
11907       break;
11908     ++CandsShown;
11909 
11910     assert(Cand->Specialization &&
11911            "Non-matching built-in candidates are not added to Cands.");
11912     Cand->NoteDeductionFailure(S, ForTakingAddress);
11913   }
11914 
11915   if (I != E)
11916     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
11917 }
11918 
11919 // [PossiblyAFunctionType]  -->   [Return]
11920 // NonFunctionType --> NonFunctionType
11921 // R (A) --> R(A)
11922 // R (*)(A) --> R (A)
11923 // R (&)(A) --> R (A)
11924 // R (S::*)(A) --> R (A)
11925 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
11926   QualType Ret = PossiblyAFunctionType;
11927   if (const PointerType *ToTypePtr =
11928     PossiblyAFunctionType->getAs<PointerType>())
11929     Ret = ToTypePtr->getPointeeType();
11930   else if (const ReferenceType *ToTypeRef =
11931     PossiblyAFunctionType->getAs<ReferenceType>())
11932     Ret = ToTypeRef->getPointeeType();
11933   else if (const MemberPointerType *MemTypePtr =
11934     PossiblyAFunctionType->getAs<MemberPointerType>())
11935     Ret = MemTypePtr->getPointeeType();
11936   Ret =
11937     Context.getCanonicalType(Ret).getUnqualifiedType();
11938   return Ret;
11939 }
11940 
11941 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
11942                                  bool Complain = true) {
11943   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
11944       S.DeduceReturnType(FD, Loc, Complain))
11945     return true;
11946 
11947   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
11948   if (S.getLangOpts().CPlusPlus17 &&
11949       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
11950       !S.ResolveExceptionSpec(Loc, FPT))
11951     return true;
11952 
11953   return false;
11954 }
11955 
11956 namespace {
11957 // A helper class to help with address of function resolution
11958 // - allows us to avoid passing around all those ugly parameters
11959 class AddressOfFunctionResolver {
11960   Sema& S;
11961   Expr* SourceExpr;
11962   const QualType& TargetType;
11963   QualType TargetFunctionType; // Extracted function type from target type
11964 
11965   bool Complain;
11966   //DeclAccessPair& ResultFunctionAccessPair;
11967   ASTContext& Context;
11968 
11969   bool TargetTypeIsNonStaticMemberFunction;
11970   bool FoundNonTemplateFunction;
11971   bool StaticMemberFunctionFromBoundPointer;
11972   bool HasComplained;
11973 
11974   OverloadExpr::FindResult OvlExprInfo;
11975   OverloadExpr *OvlExpr;
11976   TemplateArgumentListInfo OvlExplicitTemplateArgs;
11977   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
11978   TemplateSpecCandidateSet FailedCandidates;
11979 
11980 public:
11981   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
11982                             const QualType &TargetType, bool Complain)
11983       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
11984         Complain(Complain), Context(S.getASTContext()),
11985         TargetTypeIsNonStaticMemberFunction(
11986             !!TargetType->getAs<MemberPointerType>()),
11987         FoundNonTemplateFunction(false),
11988         StaticMemberFunctionFromBoundPointer(false),
11989         HasComplained(false),
11990         OvlExprInfo(OverloadExpr::find(SourceExpr)),
11991         OvlExpr(OvlExprInfo.Expression),
11992         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
11993     ExtractUnqualifiedFunctionTypeFromTargetType();
11994 
11995     if (TargetFunctionType->isFunctionType()) {
11996       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
11997         if (!UME->isImplicitAccess() &&
11998             !S.ResolveSingleFunctionTemplateSpecialization(UME))
11999           StaticMemberFunctionFromBoundPointer = true;
12000     } else if (OvlExpr->hasExplicitTemplateArgs()) {
12001       DeclAccessPair dap;
12002       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
12003               OvlExpr, false, &dap)) {
12004         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
12005           if (!Method->isStatic()) {
12006             // If the target type is a non-function type and the function found
12007             // is a non-static member function, pretend as if that was the
12008             // target, it's the only possible type to end up with.
12009             TargetTypeIsNonStaticMemberFunction = true;
12010 
12011             // And skip adding the function if its not in the proper form.
12012             // We'll diagnose this due to an empty set of functions.
12013             if (!OvlExprInfo.HasFormOfMemberPointer)
12014               return;
12015           }
12016 
12017         Matches.push_back(std::make_pair(dap, Fn));
12018       }
12019       return;
12020     }
12021 
12022     if (OvlExpr->hasExplicitTemplateArgs())
12023       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
12024 
12025     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
12026       // C++ [over.over]p4:
12027       //   If more than one function is selected, [...]
12028       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
12029         if (FoundNonTemplateFunction)
12030           EliminateAllTemplateMatches();
12031         else
12032           EliminateAllExceptMostSpecializedTemplate();
12033       }
12034     }
12035 
12036     if (S.getLangOpts().CUDA && Matches.size() > 1)
12037       EliminateSuboptimalCudaMatches();
12038   }
12039 
12040   bool hasComplained() const { return HasComplained; }
12041 
12042 private:
12043   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
12044     QualType Discard;
12045     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
12046            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
12047   }
12048 
12049   /// \return true if A is considered a better overload candidate for the
12050   /// desired type than B.
12051   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
12052     // If A doesn't have exactly the correct type, we don't want to classify it
12053     // as "better" than anything else. This way, the user is required to
12054     // disambiguate for us if there are multiple candidates and no exact match.
12055     return candidateHasExactlyCorrectType(A) &&
12056            (!candidateHasExactlyCorrectType(B) ||
12057             compareEnableIfAttrs(S, A, B) == Comparison::Better);
12058   }
12059 
12060   /// \return true if we were able to eliminate all but one overload candidate,
12061   /// false otherwise.
12062   bool eliminiateSuboptimalOverloadCandidates() {
12063     // Same algorithm as overload resolution -- one pass to pick the "best",
12064     // another pass to be sure that nothing is better than the best.
12065     auto Best = Matches.begin();
12066     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
12067       if (isBetterCandidate(I->second, Best->second))
12068         Best = I;
12069 
12070     const FunctionDecl *BestFn = Best->second;
12071     auto IsBestOrInferiorToBest = [this, BestFn](
12072         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
12073       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
12074     };
12075 
12076     // Note: We explicitly leave Matches unmodified if there isn't a clear best
12077     // option, so we can potentially give the user a better error
12078     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
12079       return false;
12080     Matches[0] = *Best;
12081     Matches.resize(1);
12082     return true;
12083   }
12084 
12085   bool isTargetTypeAFunction() const {
12086     return TargetFunctionType->isFunctionType();
12087   }
12088 
12089   // [ToType]     [Return]
12090 
12091   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
12092   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
12093   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
12094   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
12095     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
12096   }
12097 
12098   // return true if any matching specializations were found
12099   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
12100                                    const DeclAccessPair& CurAccessFunPair) {
12101     if (CXXMethodDecl *Method
12102               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
12103       // Skip non-static function templates when converting to pointer, and
12104       // static when converting to member pointer.
12105       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
12106         return false;
12107     }
12108     else if (TargetTypeIsNonStaticMemberFunction)
12109       return false;
12110 
12111     // C++ [over.over]p2:
12112     //   If the name is a function template, template argument deduction is
12113     //   done (14.8.2.2), and if the argument deduction succeeds, the
12114     //   resulting template argument list is used to generate a single
12115     //   function template specialization, which is added to the set of
12116     //   overloaded functions considered.
12117     FunctionDecl *Specialization = nullptr;
12118     TemplateDeductionInfo Info(FailedCandidates.getLocation());
12119     if (Sema::TemplateDeductionResult Result
12120           = S.DeduceTemplateArguments(FunctionTemplate,
12121                                       &OvlExplicitTemplateArgs,
12122                                       TargetFunctionType, Specialization,
12123                                       Info, /*IsAddressOfFunction*/true)) {
12124       // Make a note of the failed deduction for diagnostics.
12125       FailedCandidates.addCandidate()
12126           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
12127                MakeDeductionFailureInfo(Context, Result, Info));
12128       return false;
12129     }
12130 
12131     // Template argument deduction ensures that we have an exact match or
12132     // compatible pointer-to-function arguments that would be adjusted by ICS.
12133     // This function template specicalization works.
12134     assert(S.isSameOrCompatibleFunctionType(
12135               Context.getCanonicalType(Specialization->getType()),
12136               Context.getCanonicalType(TargetFunctionType)));
12137 
12138     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
12139       return false;
12140 
12141     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
12142     return true;
12143   }
12144 
12145   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
12146                                       const DeclAccessPair& CurAccessFunPair) {
12147     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12148       // Skip non-static functions when converting to pointer, and static
12149       // when converting to member pointer.
12150       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
12151         return false;
12152     }
12153     else if (TargetTypeIsNonStaticMemberFunction)
12154       return false;
12155 
12156     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
12157       if (S.getLangOpts().CUDA)
12158         if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true))
12159           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
12160             return false;
12161       if (FunDecl->isMultiVersion()) {
12162         const auto *TA = FunDecl->getAttr<TargetAttr>();
12163         if (TA && !TA->isDefaultVersion())
12164           return false;
12165       }
12166 
12167       // If any candidate has a placeholder return type, trigger its deduction
12168       // now.
12169       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
12170                                Complain)) {
12171         HasComplained |= Complain;
12172         return false;
12173       }
12174 
12175       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
12176         return false;
12177 
12178       // If we're in C, we need to support types that aren't exactly identical.
12179       if (!S.getLangOpts().CPlusPlus ||
12180           candidateHasExactlyCorrectType(FunDecl)) {
12181         Matches.push_back(std::make_pair(
12182             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
12183         FoundNonTemplateFunction = true;
12184         return true;
12185       }
12186     }
12187 
12188     return false;
12189   }
12190 
12191   bool FindAllFunctionsThatMatchTargetTypeExactly() {
12192     bool Ret = false;
12193 
12194     // If the overload expression doesn't have the form of a pointer to
12195     // member, don't try to convert it to a pointer-to-member type.
12196     if (IsInvalidFormOfPointerToMemberFunction())
12197       return false;
12198 
12199     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12200                                E = OvlExpr->decls_end();
12201          I != E; ++I) {
12202       // Look through any using declarations to find the underlying function.
12203       NamedDecl *Fn = (*I)->getUnderlyingDecl();
12204 
12205       // C++ [over.over]p3:
12206       //   Non-member functions and static member functions match
12207       //   targets of type "pointer-to-function" or "reference-to-function."
12208       //   Nonstatic member functions match targets of
12209       //   type "pointer-to-member-function."
12210       // Note that according to DR 247, the containing class does not matter.
12211       if (FunctionTemplateDecl *FunctionTemplate
12212                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
12213         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
12214           Ret = true;
12215       }
12216       // If we have explicit template arguments supplied, skip non-templates.
12217       else if (!OvlExpr->hasExplicitTemplateArgs() &&
12218                AddMatchingNonTemplateFunction(Fn, I.getPair()))
12219         Ret = true;
12220     }
12221     assert(Ret || Matches.empty());
12222     return Ret;
12223   }
12224 
12225   void EliminateAllExceptMostSpecializedTemplate() {
12226     //   [...] and any given function template specialization F1 is
12227     //   eliminated if the set contains a second function template
12228     //   specialization whose function template is more specialized
12229     //   than the function template of F1 according to the partial
12230     //   ordering rules of 14.5.5.2.
12231 
12232     // The algorithm specified above is quadratic. We instead use a
12233     // two-pass algorithm (similar to the one used to identify the
12234     // best viable function in an overload set) that identifies the
12235     // best function template (if it exists).
12236 
12237     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
12238     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
12239       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
12240 
12241     // TODO: It looks like FailedCandidates does not serve much purpose
12242     // here, since the no_viable diagnostic has index 0.
12243     UnresolvedSetIterator Result = S.getMostSpecialized(
12244         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
12245         SourceExpr->getBeginLoc(), S.PDiag(),
12246         S.PDiag(diag::err_addr_ovl_ambiguous)
12247             << Matches[0].second->getDeclName(),
12248         S.PDiag(diag::note_ovl_candidate)
12249             << (unsigned)oc_function << (unsigned)ocs_described_template,
12250         Complain, TargetFunctionType);
12251 
12252     if (Result != MatchesCopy.end()) {
12253       // Make it the first and only element
12254       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
12255       Matches[0].second = cast<FunctionDecl>(*Result);
12256       Matches.resize(1);
12257     } else
12258       HasComplained |= Complain;
12259   }
12260 
12261   void EliminateAllTemplateMatches() {
12262     //   [...] any function template specializations in the set are
12263     //   eliminated if the set also contains a non-template function, [...]
12264     for (unsigned I = 0, N = Matches.size(); I != N; ) {
12265       if (Matches[I].second->getPrimaryTemplate() == nullptr)
12266         ++I;
12267       else {
12268         Matches[I] = Matches[--N];
12269         Matches.resize(N);
12270       }
12271     }
12272   }
12273 
12274   void EliminateSuboptimalCudaMatches() {
12275     S.EraseUnwantedCUDAMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
12276                                Matches);
12277   }
12278 
12279 public:
12280   void ComplainNoMatchesFound() const {
12281     assert(Matches.empty());
12282     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
12283         << OvlExpr->getName() << TargetFunctionType
12284         << OvlExpr->getSourceRange();
12285     if (FailedCandidates.empty())
12286       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12287                                   /*TakingAddress=*/true);
12288     else {
12289       // We have some deduction failure messages. Use them to diagnose
12290       // the function templates, and diagnose the non-template candidates
12291       // normally.
12292       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12293                                  IEnd = OvlExpr->decls_end();
12294            I != IEnd; ++I)
12295         if (FunctionDecl *Fun =
12296                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
12297           if (!functionHasPassObjectSizeParams(Fun))
12298             S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
12299                                     /*TakingAddress=*/true);
12300       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
12301     }
12302   }
12303 
12304   bool IsInvalidFormOfPointerToMemberFunction() const {
12305     return TargetTypeIsNonStaticMemberFunction &&
12306       !OvlExprInfo.HasFormOfMemberPointer;
12307   }
12308 
12309   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
12310       // TODO: Should we condition this on whether any functions might
12311       // have matched, or is it more appropriate to do that in callers?
12312       // TODO: a fixit wouldn't hurt.
12313       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
12314         << TargetType << OvlExpr->getSourceRange();
12315   }
12316 
12317   bool IsStaticMemberFunctionFromBoundPointer() const {
12318     return StaticMemberFunctionFromBoundPointer;
12319   }
12320 
12321   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
12322     S.Diag(OvlExpr->getBeginLoc(),
12323            diag::err_invalid_form_pointer_member_function)
12324         << OvlExpr->getSourceRange();
12325   }
12326 
12327   void ComplainOfInvalidConversion() const {
12328     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
12329         << OvlExpr->getName() << TargetType;
12330   }
12331 
12332   void ComplainMultipleMatchesFound() const {
12333     assert(Matches.size() > 1);
12334     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
12335         << OvlExpr->getName() << OvlExpr->getSourceRange();
12336     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12337                                 /*TakingAddress=*/true);
12338   }
12339 
12340   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
12341 
12342   int getNumMatches() const { return Matches.size(); }
12343 
12344   FunctionDecl* getMatchingFunctionDecl() const {
12345     if (Matches.size() != 1) return nullptr;
12346     return Matches[0].second;
12347   }
12348 
12349   const DeclAccessPair* getMatchingFunctionAccessPair() const {
12350     if (Matches.size() != 1) return nullptr;
12351     return &Matches[0].first;
12352   }
12353 };
12354 }
12355 
12356 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
12357 /// an overloaded function (C++ [over.over]), where @p From is an
12358 /// expression with overloaded function type and @p ToType is the type
12359 /// we're trying to resolve to. For example:
12360 ///
12361 /// @code
12362 /// int f(double);
12363 /// int f(int);
12364 ///
12365 /// int (*pfd)(double) = f; // selects f(double)
12366 /// @endcode
12367 ///
12368 /// This routine returns the resulting FunctionDecl if it could be
12369 /// resolved, and NULL otherwise. When @p Complain is true, this
12370 /// routine will emit diagnostics if there is an error.
12371 FunctionDecl *
12372 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
12373                                          QualType TargetType,
12374                                          bool Complain,
12375                                          DeclAccessPair &FoundResult,
12376                                          bool *pHadMultipleCandidates) {
12377   assert(AddressOfExpr->getType() == Context.OverloadTy);
12378 
12379   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
12380                                      Complain);
12381   int NumMatches = Resolver.getNumMatches();
12382   FunctionDecl *Fn = nullptr;
12383   bool ShouldComplain = Complain && !Resolver.hasComplained();
12384   if (NumMatches == 0 && ShouldComplain) {
12385     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
12386       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
12387     else
12388       Resolver.ComplainNoMatchesFound();
12389   }
12390   else if (NumMatches > 1 && ShouldComplain)
12391     Resolver.ComplainMultipleMatchesFound();
12392   else if (NumMatches == 1) {
12393     Fn = Resolver.getMatchingFunctionDecl();
12394     assert(Fn);
12395     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
12396       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
12397     FoundResult = *Resolver.getMatchingFunctionAccessPair();
12398     if (Complain) {
12399       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
12400         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
12401       else
12402         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
12403     }
12404   }
12405 
12406   if (pHadMultipleCandidates)
12407     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
12408   return Fn;
12409 }
12410 
12411 /// Given an expression that refers to an overloaded function, try to
12412 /// resolve that function to a single function that can have its address taken.
12413 /// This will modify `Pair` iff it returns non-null.
12414 ///
12415 /// This routine can only succeed if from all of the candidates in the overload
12416 /// set for SrcExpr that can have their addresses taken, there is one candidate
12417 /// that is more constrained than the rest.
12418 FunctionDecl *
12419 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
12420   OverloadExpr::FindResult R = OverloadExpr::find(E);
12421   OverloadExpr *Ovl = R.Expression;
12422   bool IsResultAmbiguous = false;
12423   FunctionDecl *Result = nullptr;
12424   DeclAccessPair DAP;
12425   SmallVector<FunctionDecl *, 2> AmbiguousDecls;
12426 
12427   auto CheckMoreConstrained =
12428       [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> {
12429         SmallVector<const Expr *, 1> AC1, AC2;
12430         FD1->getAssociatedConstraints(AC1);
12431         FD2->getAssociatedConstraints(AC2);
12432         bool AtLeastAsConstrained1, AtLeastAsConstrained2;
12433         if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
12434           return None;
12435         if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
12436           return None;
12437         if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
12438           return None;
12439         return AtLeastAsConstrained1;
12440       };
12441 
12442   // Don't use the AddressOfResolver because we're specifically looking for
12443   // cases where we have one overload candidate that lacks
12444   // enable_if/pass_object_size/...
12445   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
12446     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
12447     if (!FD)
12448       return nullptr;
12449 
12450     if (!checkAddressOfFunctionIsAvailable(FD))
12451       continue;
12452 
12453     // We have more than one result - see if it is more constrained than the
12454     // previous one.
12455     if (Result) {
12456       Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD,
12457                                                                         Result);
12458       if (!MoreConstrainedThanPrevious) {
12459         IsResultAmbiguous = true;
12460         AmbiguousDecls.push_back(FD);
12461         continue;
12462       }
12463       if (!*MoreConstrainedThanPrevious)
12464         continue;
12465       // FD is more constrained - replace Result with it.
12466     }
12467     IsResultAmbiguous = false;
12468     DAP = I.getPair();
12469     Result = FD;
12470   }
12471 
12472   if (IsResultAmbiguous)
12473     return nullptr;
12474 
12475   if (Result) {
12476     SmallVector<const Expr *, 1> ResultAC;
12477     // We skipped over some ambiguous declarations which might be ambiguous with
12478     // the selected result.
12479     for (FunctionDecl *Skipped : AmbiguousDecls)
12480       if (!CheckMoreConstrained(Skipped, Result).hasValue())
12481         return nullptr;
12482     Pair = DAP;
12483   }
12484   return Result;
12485 }
12486 
12487 /// Given an overloaded function, tries to turn it into a non-overloaded
12488 /// function reference using resolveAddressOfSingleOverloadCandidate. This
12489 /// will perform access checks, diagnose the use of the resultant decl, and, if
12490 /// requested, potentially perform a function-to-pointer decay.
12491 ///
12492 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
12493 /// Otherwise, returns true. This may emit diagnostics and return true.
12494 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
12495     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
12496   Expr *E = SrcExpr.get();
12497   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
12498 
12499   DeclAccessPair DAP;
12500   FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
12501   if (!Found || Found->isCPUDispatchMultiVersion() ||
12502       Found->isCPUSpecificMultiVersion())
12503     return false;
12504 
12505   // Emitting multiple diagnostics for a function that is both inaccessible and
12506   // unavailable is consistent with our behavior elsewhere. So, always check
12507   // for both.
12508   DiagnoseUseOfDecl(Found, E->getExprLoc());
12509   CheckAddressOfMemberAccess(E, DAP);
12510   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
12511   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
12512     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
12513   else
12514     SrcExpr = Fixed;
12515   return true;
12516 }
12517 
12518 /// Given an expression that refers to an overloaded function, try to
12519 /// resolve that overloaded function expression down to a single function.
12520 ///
12521 /// This routine can only resolve template-ids that refer to a single function
12522 /// template, where that template-id refers to a single template whose template
12523 /// arguments are either provided by the template-id or have defaults,
12524 /// as described in C++0x [temp.arg.explicit]p3.
12525 ///
12526 /// If no template-ids are found, no diagnostics are emitted and NULL is
12527 /// returned.
12528 FunctionDecl *
12529 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
12530                                                   bool Complain,
12531                                                   DeclAccessPair *FoundResult) {
12532   // C++ [over.over]p1:
12533   //   [...] [Note: any redundant set of parentheses surrounding the
12534   //   overloaded function name is ignored (5.1). ]
12535   // C++ [over.over]p1:
12536   //   [...] The overloaded function name can be preceded by the &
12537   //   operator.
12538 
12539   // If we didn't actually find any template-ids, we're done.
12540   if (!ovl->hasExplicitTemplateArgs())
12541     return nullptr;
12542 
12543   TemplateArgumentListInfo ExplicitTemplateArgs;
12544   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
12545   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
12546 
12547   // Look through all of the overloaded functions, searching for one
12548   // whose type matches exactly.
12549   FunctionDecl *Matched = nullptr;
12550   for (UnresolvedSetIterator I = ovl->decls_begin(),
12551          E = ovl->decls_end(); I != E; ++I) {
12552     // C++0x [temp.arg.explicit]p3:
12553     //   [...] In contexts where deduction is done and fails, or in contexts
12554     //   where deduction is not done, if a template argument list is
12555     //   specified and it, along with any default template arguments,
12556     //   identifies a single function template specialization, then the
12557     //   template-id is an lvalue for the function template specialization.
12558     FunctionTemplateDecl *FunctionTemplate
12559       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
12560 
12561     // C++ [over.over]p2:
12562     //   If the name is a function template, template argument deduction is
12563     //   done (14.8.2.2), and if the argument deduction succeeds, the
12564     //   resulting template argument list is used to generate a single
12565     //   function template specialization, which is added to the set of
12566     //   overloaded functions considered.
12567     FunctionDecl *Specialization = nullptr;
12568     TemplateDeductionInfo Info(FailedCandidates.getLocation());
12569     if (TemplateDeductionResult Result
12570           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
12571                                     Specialization, Info,
12572                                     /*IsAddressOfFunction*/true)) {
12573       // Make a note of the failed deduction for diagnostics.
12574       // TODO: Actually use the failed-deduction info?
12575       FailedCandidates.addCandidate()
12576           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
12577                MakeDeductionFailureInfo(Context, Result, Info));
12578       continue;
12579     }
12580 
12581     assert(Specialization && "no specialization and no error?");
12582 
12583     // Multiple matches; we can't resolve to a single declaration.
12584     if (Matched) {
12585       if (Complain) {
12586         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
12587           << ovl->getName();
12588         NoteAllOverloadCandidates(ovl);
12589       }
12590       return nullptr;
12591     }
12592 
12593     Matched = Specialization;
12594     if (FoundResult) *FoundResult = I.getPair();
12595   }
12596 
12597   if (Matched &&
12598       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
12599     return nullptr;
12600 
12601   return Matched;
12602 }
12603 
12604 // Resolve and fix an overloaded expression that can be resolved
12605 // because it identifies a single function template specialization.
12606 //
12607 // Last three arguments should only be supplied if Complain = true
12608 //
12609 // Return true if it was logically possible to so resolve the
12610 // expression, regardless of whether or not it succeeded.  Always
12611 // returns true if 'complain' is set.
12612 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
12613                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
12614                       bool complain, SourceRange OpRangeForComplaining,
12615                                            QualType DestTypeForComplaining,
12616                                             unsigned DiagIDForComplaining) {
12617   assert(SrcExpr.get()->getType() == Context.OverloadTy);
12618 
12619   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
12620 
12621   DeclAccessPair found;
12622   ExprResult SingleFunctionExpression;
12623   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
12624                            ovl.Expression, /*complain*/ false, &found)) {
12625     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
12626       SrcExpr = ExprError();
12627       return true;
12628     }
12629 
12630     // It is only correct to resolve to an instance method if we're
12631     // resolving a form that's permitted to be a pointer to member.
12632     // Otherwise we'll end up making a bound member expression, which
12633     // is illegal in all the contexts we resolve like this.
12634     if (!ovl.HasFormOfMemberPointer &&
12635         isa<CXXMethodDecl>(fn) &&
12636         cast<CXXMethodDecl>(fn)->isInstance()) {
12637       if (!complain) return false;
12638 
12639       Diag(ovl.Expression->getExprLoc(),
12640            diag::err_bound_member_function)
12641         << 0 << ovl.Expression->getSourceRange();
12642 
12643       // TODO: I believe we only end up here if there's a mix of
12644       // static and non-static candidates (otherwise the expression
12645       // would have 'bound member' type, not 'overload' type).
12646       // Ideally we would note which candidate was chosen and why
12647       // the static candidates were rejected.
12648       SrcExpr = ExprError();
12649       return true;
12650     }
12651 
12652     // Fix the expression to refer to 'fn'.
12653     SingleFunctionExpression =
12654         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
12655 
12656     // If desired, do function-to-pointer decay.
12657     if (doFunctionPointerConverion) {
12658       SingleFunctionExpression =
12659         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
12660       if (SingleFunctionExpression.isInvalid()) {
12661         SrcExpr = ExprError();
12662         return true;
12663       }
12664     }
12665   }
12666 
12667   if (!SingleFunctionExpression.isUsable()) {
12668     if (complain) {
12669       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
12670         << ovl.Expression->getName()
12671         << DestTypeForComplaining
12672         << OpRangeForComplaining
12673         << ovl.Expression->getQualifierLoc().getSourceRange();
12674       NoteAllOverloadCandidates(SrcExpr.get());
12675 
12676       SrcExpr = ExprError();
12677       return true;
12678     }
12679 
12680     return false;
12681   }
12682 
12683   SrcExpr = SingleFunctionExpression;
12684   return true;
12685 }
12686 
12687 /// Add a single candidate to the overload set.
12688 static void AddOverloadedCallCandidate(Sema &S,
12689                                        DeclAccessPair FoundDecl,
12690                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
12691                                        ArrayRef<Expr *> Args,
12692                                        OverloadCandidateSet &CandidateSet,
12693                                        bool PartialOverloading,
12694                                        bool KnownValid) {
12695   NamedDecl *Callee = FoundDecl.getDecl();
12696   if (isa<UsingShadowDecl>(Callee))
12697     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
12698 
12699   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
12700     if (ExplicitTemplateArgs) {
12701       assert(!KnownValid && "Explicit template arguments?");
12702       return;
12703     }
12704     // Prevent ill-formed function decls to be added as overload candidates.
12705     if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
12706       return;
12707 
12708     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
12709                            /*SuppressUserConversions=*/false,
12710                            PartialOverloading);
12711     return;
12712   }
12713 
12714   if (FunctionTemplateDecl *FuncTemplate
12715       = dyn_cast<FunctionTemplateDecl>(Callee)) {
12716     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
12717                                    ExplicitTemplateArgs, Args, CandidateSet,
12718                                    /*SuppressUserConversions=*/false,
12719                                    PartialOverloading);
12720     return;
12721   }
12722 
12723   assert(!KnownValid && "unhandled case in overloaded call candidate");
12724 }
12725 
12726 /// Add the overload candidates named by callee and/or found by argument
12727 /// dependent lookup to the given overload set.
12728 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
12729                                        ArrayRef<Expr *> Args,
12730                                        OverloadCandidateSet &CandidateSet,
12731                                        bool PartialOverloading) {
12732 
12733 #ifndef NDEBUG
12734   // Verify that ArgumentDependentLookup is consistent with the rules
12735   // in C++0x [basic.lookup.argdep]p3:
12736   //
12737   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
12738   //   and let Y be the lookup set produced by argument dependent
12739   //   lookup (defined as follows). If X contains
12740   //
12741   //     -- a declaration of a class member, or
12742   //
12743   //     -- a block-scope function declaration that is not a
12744   //        using-declaration, or
12745   //
12746   //     -- a declaration that is neither a function or a function
12747   //        template
12748   //
12749   //   then Y is empty.
12750 
12751   if (ULE->requiresADL()) {
12752     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12753            E = ULE->decls_end(); I != E; ++I) {
12754       assert(!(*I)->getDeclContext()->isRecord());
12755       assert(isa<UsingShadowDecl>(*I) ||
12756              !(*I)->getDeclContext()->isFunctionOrMethod());
12757       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
12758     }
12759   }
12760 #endif
12761 
12762   // It would be nice to avoid this copy.
12763   TemplateArgumentListInfo TABuffer;
12764   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12765   if (ULE->hasExplicitTemplateArgs()) {
12766     ULE->copyTemplateArgumentsInto(TABuffer);
12767     ExplicitTemplateArgs = &TABuffer;
12768   }
12769 
12770   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12771          E = ULE->decls_end(); I != E; ++I)
12772     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12773                                CandidateSet, PartialOverloading,
12774                                /*KnownValid*/ true);
12775 
12776   if (ULE->requiresADL())
12777     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
12778                                          Args, ExplicitTemplateArgs,
12779                                          CandidateSet, PartialOverloading);
12780 }
12781 
12782 /// Add the call candidates from the given set of lookup results to the given
12783 /// overload set. Non-function lookup results are ignored.
12784 void Sema::AddOverloadedCallCandidates(
12785     LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
12786     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
12787   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12788     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12789                                CandidateSet, false, /*KnownValid*/ false);
12790 }
12791 
12792 /// Determine whether a declaration with the specified name could be moved into
12793 /// a different namespace.
12794 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
12795   switch (Name.getCXXOverloadedOperator()) {
12796   case OO_New: case OO_Array_New:
12797   case OO_Delete: case OO_Array_Delete:
12798     return false;
12799 
12800   default:
12801     return true;
12802   }
12803 }
12804 
12805 /// Attempt to recover from an ill-formed use of a non-dependent name in a
12806 /// template, where the non-dependent name was declared after the template
12807 /// was defined. This is common in code written for a compilers which do not
12808 /// correctly implement two-stage name lookup.
12809 ///
12810 /// Returns true if a viable candidate was found and a diagnostic was issued.
12811 static bool DiagnoseTwoPhaseLookup(
12812     Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
12813     LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
12814     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
12815     CXXRecordDecl **FoundInClass = nullptr) {
12816   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
12817     return false;
12818 
12819   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
12820     if (DC->isTransparentContext())
12821       continue;
12822 
12823     SemaRef.LookupQualifiedName(R, DC);
12824 
12825     if (!R.empty()) {
12826       R.suppressDiagnostics();
12827 
12828       OverloadCandidateSet Candidates(FnLoc, CSK);
12829       SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
12830                                           Candidates);
12831 
12832       OverloadCandidateSet::iterator Best;
12833       OverloadingResult OR =
12834           Candidates.BestViableFunction(SemaRef, FnLoc, Best);
12835 
12836       if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
12837         // We either found non-function declarations or a best viable function
12838         // at class scope. A class-scope lookup result disables ADL. Don't
12839         // look past this, but let the caller know that we found something that
12840         // either is, or might be, usable in this class.
12841         if (FoundInClass) {
12842           *FoundInClass = RD;
12843           if (OR == OR_Success) {
12844             R.clear();
12845             R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
12846             R.resolveKind();
12847           }
12848         }
12849         return false;
12850       }
12851 
12852       if (OR != OR_Success) {
12853         // There wasn't a unique best function or function template.
12854         return false;
12855       }
12856 
12857       // Find the namespaces where ADL would have looked, and suggest
12858       // declaring the function there instead.
12859       Sema::AssociatedNamespaceSet AssociatedNamespaces;
12860       Sema::AssociatedClassSet AssociatedClasses;
12861       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
12862                                                  AssociatedNamespaces,
12863                                                  AssociatedClasses);
12864       Sema::AssociatedNamespaceSet SuggestedNamespaces;
12865       if (canBeDeclaredInNamespace(R.getLookupName())) {
12866         DeclContext *Std = SemaRef.getStdNamespace();
12867         for (Sema::AssociatedNamespaceSet::iterator
12868                it = AssociatedNamespaces.begin(),
12869                end = AssociatedNamespaces.end(); it != end; ++it) {
12870           // Never suggest declaring a function within namespace 'std'.
12871           if (Std && Std->Encloses(*it))
12872             continue;
12873 
12874           // Never suggest declaring a function within a namespace with a
12875           // reserved name, like __gnu_cxx.
12876           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
12877           if (NS &&
12878               NS->getQualifiedNameAsString().find("__") != std::string::npos)
12879             continue;
12880 
12881           SuggestedNamespaces.insert(*it);
12882         }
12883       }
12884 
12885       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
12886         << R.getLookupName();
12887       if (SuggestedNamespaces.empty()) {
12888         SemaRef.Diag(Best->Function->getLocation(),
12889                      diag::note_not_found_by_two_phase_lookup)
12890           << R.getLookupName() << 0;
12891       } else if (SuggestedNamespaces.size() == 1) {
12892         SemaRef.Diag(Best->Function->getLocation(),
12893                      diag::note_not_found_by_two_phase_lookup)
12894           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
12895       } else {
12896         // FIXME: It would be useful to list the associated namespaces here,
12897         // but the diagnostics infrastructure doesn't provide a way to produce
12898         // a localized representation of a list of items.
12899         SemaRef.Diag(Best->Function->getLocation(),
12900                      diag::note_not_found_by_two_phase_lookup)
12901           << R.getLookupName() << 2;
12902       }
12903 
12904       // Try to recover by calling this function.
12905       return true;
12906     }
12907 
12908     R.clear();
12909   }
12910 
12911   return false;
12912 }
12913 
12914 /// Attempt to recover from ill-formed use of a non-dependent operator in a
12915 /// template, where the non-dependent operator was declared after the template
12916 /// was defined.
12917 ///
12918 /// Returns true if a viable candidate was found and a diagnostic was issued.
12919 static bool
12920 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
12921                                SourceLocation OpLoc,
12922                                ArrayRef<Expr *> Args) {
12923   DeclarationName OpName =
12924     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
12925   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
12926   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
12927                                 OverloadCandidateSet::CSK_Operator,
12928                                 /*ExplicitTemplateArgs=*/nullptr, Args);
12929 }
12930 
12931 namespace {
12932 class BuildRecoveryCallExprRAII {
12933   Sema &SemaRef;
12934 public:
12935   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
12936     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
12937     SemaRef.IsBuildingRecoveryCallExpr = true;
12938   }
12939 
12940   ~BuildRecoveryCallExprRAII() {
12941     SemaRef.IsBuildingRecoveryCallExpr = false;
12942   }
12943 };
12944 
12945 }
12946 
12947 /// Attempts to recover from a call where no functions were found.
12948 ///
12949 /// This function will do one of three things:
12950 ///  * Diagnose, recover, and return a recovery expression.
12951 ///  * Diagnose, fail to recover, and return ExprError().
12952 ///  * Do not diagnose, do not recover, and return ExprResult(). The caller is
12953 ///    expected to diagnose as appropriate.
12954 static ExprResult
12955 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12956                       UnresolvedLookupExpr *ULE,
12957                       SourceLocation LParenLoc,
12958                       MutableArrayRef<Expr *> Args,
12959                       SourceLocation RParenLoc,
12960                       bool EmptyLookup, bool AllowTypoCorrection) {
12961   // Do not try to recover if it is already building a recovery call.
12962   // This stops infinite loops for template instantiations like
12963   //
12964   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
12965   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
12966   if (SemaRef.IsBuildingRecoveryCallExpr)
12967     return ExprResult();
12968   BuildRecoveryCallExprRAII RCE(SemaRef);
12969 
12970   CXXScopeSpec SS;
12971   SS.Adopt(ULE->getQualifierLoc());
12972   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
12973 
12974   TemplateArgumentListInfo TABuffer;
12975   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12976   if (ULE->hasExplicitTemplateArgs()) {
12977     ULE->copyTemplateArgumentsInto(TABuffer);
12978     ExplicitTemplateArgs = &TABuffer;
12979   }
12980 
12981   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
12982                  Sema::LookupOrdinaryName);
12983   CXXRecordDecl *FoundInClass = nullptr;
12984   if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
12985                              OverloadCandidateSet::CSK_Normal,
12986                              ExplicitTemplateArgs, Args, &FoundInClass)) {
12987     // OK, diagnosed a two-phase lookup issue.
12988   } else if (EmptyLookup) {
12989     // Try to recover from an empty lookup with typo correction.
12990     R.clear();
12991     NoTypoCorrectionCCC NoTypoValidator{};
12992     FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
12993                                                 ExplicitTemplateArgs != nullptr,
12994                                                 dyn_cast<MemberExpr>(Fn));
12995     CorrectionCandidateCallback &Validator =
12996         AllowTypoCorrection
12997             ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
12998             : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
12999     if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
13000                                     Args))
13001       return ExprError();
13002   } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
13003     // We found a usable declaration of the name in a dependent base of some
13004     // enclosing class.
13005     // FIXME: We should also explain why the candidates found by name lookup
13006     // were not viable.
13007     if (SemaRef.DiagnoseDependentMemberLookup(R))
13008       return ExprError();
13009   } else {
13010     // We had viable candidates and couldn't recover; let the caller diagnose
13011     // this.
13012     return ExprResult();
13013   }
13014 
13015   // If we get here, we should have issued a diagnostic and formed a recovery
13016   // lookup result.
13017   assert(!R.empty() && "lookup results empty despite recovery");
13018 
13019   // If recovery created an ambiguity, just bail out.
13020   if (R.isAmbiguous()) {
13021     R.suppressDiagnostics();
13022     return ExprError();
13023   }
13024 
13025   // Build an implicit member call if appropriate.  Just drop the
13026   // casts and such from the call, we don't really care.
13027   ExprResult NewFn = ExprError();
13028   if ((*R.begin())->isCXXClassMember())
13029     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
13030                                                     ExplicitTemplateArgs, S);
13031   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
13032     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
13033                                         ExplicitTemplateArgs);
13034   else
13035     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
13036 
13037   if (NewFn.isInvalid())
13038     return ExprError();
13039 
13040   // This shouldn't cause an infinite loop because we're giving it
13041   // an expression with viable lookup results, which should never
13042   // end up here.
13043   return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
13044                                MultiExprArg(Args.data(), Args.size()),
13045                                RParenLoc);
13046 }
13047 
13048 /// Constructs and populates an OverloadedCandidateSet from
13049 /// the given function.
13050 /// \returns true when an the ExprResult output parameter has been set.
13051 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
13052                                   UnresolvedLookupExpr *ULE,
13053                                   MultiExprArg Args,
13054                                   SourceLocation RParenLoc,
13055                                   OverloadCandidateSet *CandidateSet,
13056                                   ExprResult *Result) {
13057 #ifndef NDEBUG
13058   if (ULE->requiresADL()) {
13059     // To do ADL, we must have found an unqualified name.
13060     assert(!ULE->getQualifier() && "qualified name with ADL");
13061 
13062     // We don't perform ADL for implicit declarations of builtins.
13063     // Verify that this was correctly set up.
13064     FunctionDecl *F;
13065     if (ULE->decls_begin() != ULE->decls_end() &&
13066         ULE->decls_begin() + 1 == ULE->decls_end() &&
13067         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
13068         F->getBuiltinID() && F->isImplicit())
13069       llvm_unreachable("performing ADL for builtin");
13070 
13071     // We don't perform ADL in C.
13072     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
13073   }
13074 #endif
13075 
13076   UnbridgedCastsSet UnbridgedCasts;
13077   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
13078     *Result = ExprError();
13079     return true;
13080   }
13081 
13082   // Add the functions denoted by the callee to the set of candidate
13083   // functions, including those from argument-dependent lookup.
13084   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
13085 
13086   if (getLangOpts().MSVCCompat &&
13087       CurContext->isDependentContext() && !isSFINAEContext() &&
13088       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
13089 
13090     OverloadCandidateSet::iterator Best;
13091     if (CandidateSet->empty() ||
13092         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
13093             OR_No_Viable_Function) {
13094       // In Microsoft mode, if we are inside a template class member function
13095       // then create a type dependent CallExpr. The goal is to postpone name
13096       // lookup to instantiation time to be able to search into type dependent
13097       // base classes.
13098       CallExpr *CE =
13099           CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
13100                            RParenLoc, CurFPFeatureOverrides());
13101       CE->markDependentForPostponedNameLookup();
13102       *Result = CE;
13103       return true;
13104     }
13105   }
13106 
13107   if (CandidateSet->empty())
13108     return false;
13109 
13110   UnbridgedCasts.restore();
13111   return false;
13112 }
13113 
13114 // Guess at what the return type for an unresolvable overload should be.
13115 static QualType chooseRecoveryType(OverloadCandidateSet &CS,
13116                                    OverloadCandidateSet::iterator *Best) {
13117   llvm::Optional<QualType> Result;
13118   // Adjust Type after seeing a candidate.
13119   auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
13120     if (!Candidate.Function)
13121       return;
13122     if (Candidate.Function->isInvalidDecl())
13123       return;
13124     QualType T = Candidate.Function->getReturnType();
13125     if (T.isNull())
13126       return;
13127     if (!Result)
13128       Result = T;
13129     else if (Result != T)
13130       Result = QualType();
13131   };
13132 
13133   // Look for an unambiguous type from a progressively larger subset.
13134   // e.g. if types disagree, but all *viable* overloads return int, choose int.
13135   //
13136   // First, consider only the best candidate.
13137   if (Best && *Best != CS.end())
13138     ConsiderCandidate(**Best);
13139   // Next, consider only viable candidates.
13140   if (!Result)
13141     for (const auto &C : CS)
13142       if (C.Viable)
13143         ConsiderCandidate(C);
13144   // Finally, consider all candidates.
13145   if (!Result)
13146     for (const auto &C : CS)
13147       ConsiderCandidate(C);
13148 
13149   if (!Result)
13150     return QualType();
13151   auto Value = Result.getValue();
13152   if (Value.isNull() || Value->isUndeducedType())
13153     return QualType();
13154   return Value;
13155 }
13156 
13157 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
13158 /// the completed call expression. If overload resolution fails, emits
13159 /// diagnostics and returns ExprError()
13160 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
13161                                            UnresolvedLookupExpr *ULE,
13162                                            SourceLocation LParenLoc,
13163                                            MultiExprArg Args,
13164                                            SourceLocation RParenLoc,
13165                                            Expr *ExecConfig,
13166                                            OverloadCandidateSet *CandidateSet,
13167                                            OverloadCandidateSet::iterator *Best,
13168                                            OverloadingResult OverloadResult,
13169                                            bool AllowTypoCorrection) {
13170   switch (OverloadResult) {
13171   case OR_Success: {
13172     FunctionDecl *FDecl = (*Best)->Function;
13173     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
13174     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
13175       return ExprError();
13176     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13177     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
13178                                          ExecConfig, /*IsExecConfig=*/false,
13179                                          (*Best)->IsADLCandidate);
13180   }
13181 
13182   case OR_No_Viable_Function: {
13183     // Try to recover by looking for viable functions which the user might
13184     // have meant to call.
13185     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
13186                                                 Args, RParenLoc,
13187                                                 CandidateSet->empty(),
13188                                                 AllowTypoCorrection);
13189     if (Recovery.isInvalid() || Recovery.isUsable())
13190       return Recovery;
13191 
13192     // If the user passes in a function that we can't take the address of, we
13193     // generally end up emitting really bad error messages. Here, we attempt to
13194     // emit better ones.
13195     for (const Expr *Arg : Args) {
13196       if (!Arg->getType()->isFunctionType())
13197         continue;
13198       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
13199         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13200         if (FD &&
13201             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13202                                                        Arg->getExprLoc()))
13203           return ExprError();
13204       }
13205     }
13206 
13207     CandidateSet->NoteCandidates(
13208         PartialDiagnosticAt(
13209             Fn->getBeginLoc(),
13210             SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
13211                 << ULE->getName() << Fn->getSourceRange()),
13212         SemaRef, OCD_AllCandidates, Args);
13213     break;
13214   }
13215 
13216   case OR_Ambiguous:
13217     CandidateSet->NoteCandidates(
13218         PartialDiagnosticAt(Fn->getBeginLoc(),
13219                             SemaRef.PDiag(diag::err_ovl_ambiguous_call)
13220                                 << ULE->getName() << Fn->getSourceRange()),
13221         SemaRef, OCD_AmbiguousCandidates, Args);
13222     break;
13223 
13224   case OR_Deleted: {
13225     CandidateSet->NoteCandidates(
13226         PartialDiagnosticAt(Fn->getBeginLoc(),
13227                             SemaRef.PDiag(diag::err_ovl_deleted_call)
13228                                 << ULE->getName() << Fn->getSourceRange()),
13229         SemaRef, OCD_AllCandidates, Args);
13230 
13231     // We emitted an error for the unavailable/deleted function call but keep
13232     // the call in the AST.
13233     FunctionDecl *FDecl = (*Best)->Function;
13234     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13235     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
13236                                          ExecConfig, /*IsExecConfig=*/false,
13237                                          (*Best)->IsADLCandidate);
13238   }
13239   }
13240 
13241   // Overload resolution failed, try to recover.
13242   SmallVector<Expr *, 8> SubExprs = {Fn};
13243   SubExprs.append(Args.begin(), Args.end());
13244   return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
13245                                     chooseRecoveryType(*CandidateSet, Best));
13246 }
13247 
13248 static void markUnaddressableCandidatesUnviable(Sema &S,
13249                                                 OverloadCandidateSet &CS) {
13250   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
13251     if (I->Viable &&
13252         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
13253       I->Viable = false;
13254       I->FailureKind = ovl_fail_addr_not_available;
13255     }
13256   }
13257 }
13258 
13259 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
13260 /// (which eventually refers to the declaration Func) and the call
13261 /// arguments Args/NumArgs, attempt to resolve the function call down
13262 /// to a specific function. If overload resolution succeeds, returns
13263 /// the call expression produced by overload resolution.
13264 /// Otherwise, emits diagnostics and returns ExprError.
13265 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
13266                                          UnresolvedLookupExpr *ULE,
13267                                          SourceLocation LParenLoc,
13268                                          MultiExprArg Args,
13269                                          SourceLocation RParenLoc,
13270                                          Expr *ExecConfig,
13271                                          bool AllowTypoCorrection,
13272                                          bool CalleesAddressIsTaken) {
13273   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
13274                                     OverloadCandidateSet::CSK_Normal);
13275   ExprResult result;
13276 
13277   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
13278                              &result))
13279     return result;
13280 
13281   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
13282   // functions that aren't addressible are considered unviable.
13283   if (CalleesAddressIsTaken)
13284     markUnaddressableCandidatesUnviable(*this, CandidateSet);
13285 
13286   OverloadCandidateSet::iterator Best;
13287   OverloadingResult OverloadResult =
13288       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
13289 
13290   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
13291                                   ExecConfig, &CandidateSet, &Best,
13292                                   OverloadResult, AllowTypoCorrection);
13293 }
13294 
13295 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
13296   return Functions.size() > 1 ||
13297          (Functions.size() == 1 &&
13298           isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl()));
13299 }
13300 
13301 ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
13302                                             NestedNameSpecifierLoc NNSLoc,
13303                                             DeclarationNameInfo DNI,
13304                                             const UnresolvedSetImpl &Fns,
13305                                             bool PerformADL) {
13306   return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI,
13307                                       PerformADL, IsOverloaded(Fns),
13308                                       Fns.begin(), Fns.end());
13309 }
13310 
13311 /// Create a unary operation that may resolve to an overloaded
13312 /// operator.
13313 ///
13314 /// \param OpLoc The location of the operator itself (e.g., '*').
13315 ///
13316 /// \param Opc The UnaryOperatorKind that describes this operator.
13317 ///
13318 /// \param Fns The set of non-member functions that will be
13319 /// considered by overload resolution. The caller needs to build this
13320 /// set based on the context using, e.g.,
13321 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13322 /// set should not contain any member functions; those will be added
13323 /// by CreateOverloadedUnaryOp().
13324 ///
13325 /// \param Input The input argument.
13326 ExprResult
13327 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
13328                               const UnresolvedSetImpl &Fns,
13329                               Expr *Input, bool PerformADL) {
13330   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
13331   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
13332   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13333   // TODO: provide better source location info.
13334   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13335 
13336   if (checkPlaceholderForOverload(*this, Input))
13337     return ExprError();
13338 
13339   Expr *Args[2] = { Input, nullptr };
13340   unsigned NumArgs = 1;
13341 
13342   // For post-increment and post-decrement, add the implicit '0' as
13343   // the second argument, so that we know this is a post-increment or
13344   // post-decrement.
13345   if (Opc == UO_PostInc || Opc == UO_PostDec) {
13346     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13347     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
13348                                      SourceLocation());
13349     NumArgs = 2;
13350   }
13351 
13352   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
13353 
13354   if (Input->isTypeDependent()) {
13355     if (Fns.empty())
13356       return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy,
13357                                    VK_PRValue, OK_Ordinary, OpLoc, false,
13358                                    CurFPFeatureOverrides());
13359 
13360     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13361     ExprResult Fn = CreateUnresolvedLookupExpr(
13362         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
13363     if (Fn.isInvalid())
13364       return ExprError();
13365     return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
13366                                        Context.DependentTy, VK_PRValue, OpLoc,
13367                                        CurFPFeatureOverrides());
13368   }
13369 
13370   // Build an empty overload set.
13371   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
13372 
13373   // Add the candidates from the given function set.
13374   AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
13375 
13376   // Add operator candidates that are member functions.
13377   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13378 
13379   // Add candidates from ADL.
13380   if (PerformADL) {
13381     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
13382                                          /*ExplicitTemplateArgs*/nullptr,
13383                                          CandidateSet);
13384   }
13385 
13386   // Add builtin operator candidates.
13387   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13388 
13389   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13390 
13391   // Perform overload resolution.
13392   OverloadCandidateSet::iterator Best;
13393   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13394   case OR_Success: {
13395     // We found a built-in operator or an overloaded operator.
13396     FunctionDecl *FnDecl = Best->Function;
13397 
13398     if (FnDecl) {
13399       Expr *Base = nullptr;
13400       // We matched an overloaded operator. Build a call to that
13401       // operator.
13402 
13403       // Convert the arguments.
13404       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13405         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
13406 
13407         ExprResult InputRes =
13408           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
13409                                               Best->FoundDecl, Method);
13410         if (InputRes.isInvalid())
13411           return ExprError();
13412         Base = Input = InputRes.get();
13413       } else {
13414         // Convert the arguments.
13415         ExprResult InputInit
13416           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13417                                                       Context,
13418                                                       FnDecl->getParamDecl(0)),
13419                                       SourceLocation(),
13420                                       Input);
13421         if (InputInit.isInvalid())
13422           return ExprError();
13423         Input = InputInit.get();
13424       }
13425 
13426       // Build the actual expression node.
13427       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
13428                                                 Base, HadMultipleCandidates,
13429                                                 OpLoc);
13430       if (FnExpr.isInvalid())
13431         return ExprError();
13432 
13433       // Determine the result type.
13434       QualType ResultTy = FnDecl->getReturnType();
13435       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13436       ResultTy = ResultTy.getNonLValueExprType(Context);
13437 
13438       Args[0] = Input;
13439       CallExpr *TheCall = CXXOperatorCallExpr::Create(
13440           Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
13441           CurFPFeatureOverrides(), Best->IsADLCandidate);
13442 
13443       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
13444         return ExprError();
13445 
13446       if (CheckFunctionCall(FnDecl, TheCall,
13447                             FnDecl->getType()->castAs<FunctionProtoType>()))
13448         return ExprError();
13449       return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
13450     } else {
13451       // We matched a built-in operator. Convert the arguments, then
13452       // break out so that we will build the appropriate built-in
13453       // operator node.
13454       ExprResult InputRes = PerformImplicitConversion(
13455           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
13456           CCK_ForBuiltinOverloadedOp);
13457       if (InputRes.isInvalid())
13458         return ExprError();
13459       Input = InputRes.get();
13460       break;
13461     }
13462   }
13463 
13464   case OR_No_Viable_Function:
13465     // This is an erroneous use of an operator which can be overloaded by
13466     // a non-member function. Check for non-member operators which were
13467     // defined too late to be candidates.
13468     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
13469       // FIXME: Recover by calling the found function.
13470       return ExprError();
13471 
13472     // No viable function; fall through to handling this as a
13473     // built-in operator, which will produce an error message for us.
13474     break;
13475 
13476   case OR_Ambiguous:
13477     CandidateSet.NoteCandidates(
13478         PartialDiagnosticAt(OpLoc,
13479                             PDiag(diag::err_ovl_ambiguous_oper_unary)
13480                                 << UnaryOperator::getOpcodeStr(Opc)
13481                                 << Input->getType() << Input->getSourceRange()),
13482         *this, OCD_AmbiguousCandidates, ArgsArray,
13483         UnaryOperator::getOpcodeStr(Opc), OpLoc);
13484     return ExprError();
13485 
13486   case OR_Deleted:
13487     CandidateSet.NoteCandidates(
13488         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
13489                                        << UnaryOperator::getOpcodeStr(Opc)
13490                                        << Input->getSourceRange()),
13491         *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
13492         OpLoc);
13493     return ExprError();
13494   }
13495 
13496   // Either we found no viable overloaded operator or we matched a
13497   // built-in operator. In either case, fall through to trying to
13498   // build a built-in operation.
13499   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13500 }
13501 
13502 /// Perform lookup for an overloaded binary operator.
13503 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
13504                                  OverloadedOperatorKind Op,
13505                                  const UnresolvedSetImpl &Fns,
13506                                  ArrayRef<Expr *> Args, bool PerformADL) {
13507   SourceLocation OpLoc = CandidateSet.getLocation();
13508 
13509   OverloadedOperatorKind ExtraOp =
13510       CandidateSet.getRewriteInfo().AllowRewrittenCandidates
13511           ? getRewrittenOverloadedOperator(Op)
13512           : OO_None;
13513 
13514   // Add the candidates from the given function set. This also adds the
13515   // rewritten candidates using these functions if necessary.
13516   AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
13517 
13518   // Add operator candidates that are member functions.
13519   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13520   if (CandidateSet.getRewriteInfo().shouldAddReversed(Op))
13521     AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
13522                                 OverloadCandidateParamOrder::Reversed);
13523 
13524   // In C++20, also add any rewritten member candidates.
13525   if (ExtraOp) {
13526     AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
13527     if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp))
13528       AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
13529                                   CandidateSet,
13530                                   OverloadCandidateParamOrder::Reversed);
13531   }
13532 
13533   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
13534   // performed for an assignment operator (nor for operator[] nor operator->,
13535   // which don't get here).
13536   if (Op != OO_Equal && PerformADL) {
13537     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13538     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
13539                                          /*ExplicitTemplateArgs*/ nullptr,
13540                                          CandidateSet);
13541     if (ExtraOp) {
13542       DeclarationName ExtraOpName =
13543           Context.DeclarationNames.getCXXOperatorName(ExtraOp);
13544       AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
13545                                            /*ExplicitTemplateArgs*/ nullptr,
13546                                            CandidateSet);
13547     }
13548   }
13549 
13550   // Add builtin operator candidates.
13551   //
13552   // FIXME: We don't add any rewritten candidates here. This is strictly
13553   // incorrect; a builtin candidate could be hidden by a non-viable candidate,
13554   // resulting in our selecting a rewritten builtin candidate. For example:
13555   //
13556   //   enum class E { e };
13557   //   bool operator!=(E, E) requires false;
13558   //   bool k = E::e != E::e;
13559   //
13560   // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
13561   // it seems unreasonable to consider rewritten builtin candidates. A core
13562   // issue has been filed proposing to removed this requirement.
13563   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13564 }
13565 
13566 /// Create a binary operation that may resolve to an overloaded
13567 /// operator.
13568 ///
13569 /// \param OpLoc The location of the operator itself (e.g., '+').
13570 ///
13571 /// \param Opc The BinaryOperatorKind that describes this operator.
13572 ///
13573 /// \param Fns The set of non-member functions that will be
13574 /// considered by overload resolution. The caller needs to build this
13575 /// set based on the context using, e.g.,
13576 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13577 /// set should not contain any member functions; those will be added
13578 /// by CreateOverloadedBinOp().
13579 ///
13580 /// \param LHS Left-hand argument.
13581 /// \param RHS Right-hand argument.
13582 /// \param PerformADL Whether to consider operator candidates found by ADL.
13583 /// \param AllowRewrittenCandidates Whether to consider candidates found by
13584 ///        C++20 operator rewrites.
13585 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
13586 ///        the function in question. Such a function is never a candidate in
13587 ///        our overload resolution. This also enables synthesizing a three-way
13588 ///        comparison from < and == as described in C++20 [class.spaceship]p1.
13589 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
13590                                        BinaryOperatorKind Opc,
13591                                        const UnresolvedSetImpl &Fns, Expr *LHS,
13592                                        Expr *RHS, bool PerformADL,
13593                                        bool AllowRewrittenCandidates,
13594                                        FunctionDecl *DefaultedFn) {
13595   Expr *Args[2] = { LHS, RHS };
13596   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
13597 
13598   if (!getLangOpts().CPlusPlus20)
13599     AllowRewrittenCandidates = false;
13600 
13601   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
13602 
13603   // If either side is type-dependent, create an appropriate dependent
13604   // expression.
13605   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13606     if (Fns.empty()) {
13607       // If there are no functions to store, just build a dependent
13608       // BinaryOperator or CompoundAssignment.
13609       if (BinaryOperator::isCompoundAssignmentOp(Opc))
13610         return CompoundAssignOperator::Create(
13611             Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
13612             OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
13613             Context.DependentTy);
13614       return BinaryOperator::Create(
13615           Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
13616           OK_Ordinary, OpLoc, CurFPFeatureOverrides());
13617     }
13618 
13619     // FIXME: save results of ADL from here?
13620     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13621     // TODO: provide better source location info in DNLoc component.
13622     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13623     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13624     ExprResult Fn = CreateUnresolvedLookupExpr(
13625         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
13626     if (Fn.isInvalid())
13627       return ExprError();
13628     return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
13629                                        Context.DependentTy, VK_PRValue, OpLoc,
13630                                        CurFPFeatureOverrides());
13631   }
13632 
13633   // Always do placeholder-like conversions on the RHS.
13634   if (checkPlaceholderForOverload(*this, Args[1]))
13635     return ExprError();
13636 
13637   // Do placeholder-like conversion on the LHS; note that we should
13638   // not get here with a PseudoObject LHS.
13639   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
13640   if (checkPlaceholderForOverload(*this, Args[0]))
13641     return ExprError();
13642 
13643   // If this is the assignment operator, we only perform overload resolution
13644   // if the left-hand side is a class or enumeration type. This is actually
13645   // a hack. The standard requires that we do overload resolution between the
13646   // various built-in candidates, but as DR507 points out, this can lead to
13647   // problems. So we do it this way, which pretty much follows what GCC does.
13648   // Note that we go the traditional code path for compound assignment forms.
13649   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
13650     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13651 
13652   // If this is the .* operator, which is not overloadable, just
13653   // create a built-in binary operator.
13654   if (Opc == BO_PtrMemD)
13655     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13656 
13657   // Build the overload set.
13658   OverloadCandidateSet CandidateSet(
13659       OpLoc, OverloadCandidateSet::CSK_Operator,
13660       OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates));
13661   if (DefaultedFn)
13662     CandidateSet.exclude(DefaultedFn);
13663   LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
13664 
13665   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13666 
13667   // Perform overload resolution.
13668   OverloadCandidateSet::iterator Best;
13669   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13670     case OR_Success: {
13671       // We found a built-in operator or an overloaded operator.
13672       FunctionDecl *FnDecl = Best->Function;
13673 
13674       bool IsReversed = Best->isReversed();
13675       if (IsReversed)
13676         std::swap(Args[0], Args[1]);
13677 
13678       if (FnDecl) {
13679         Expr *Base = nullptr;
13680         // We matched an overloaded operator. Build a call to that
13681         // operator.
13682 
13683         OverloadedOperatorKind ChosenOp =
13684             FnDecl->getDeclName().getCXXOverloadedOperator();
13685 
13686         // C++2a [over.match.oper]p9:
13687         //   If a rewritten operator== candidate is selected by overload
13688         //   resolution for an operator@, its return type shall be cv bool
13689         if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
13690             !FnDecl->getReturnType()->isBooleanType()) {
13691           bool IsExtension =
13692               FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
13693           Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
13694                                   : diag::err_ovl_rewrite_equalequal_not_bool)
13695               << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
13696               << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13697           Diag(FnDecl->getLocation(), diag::note_declared_at);
13698           if (!IsExtension)
13699             return ExprError();
13700         }
13701 
13702         if (AllowRewrittenCandidates && !IsReversed &&
13703             CandidateSet.getRewriteInfo().isReversible()) {
13704           // We could have reversed this operator, but didn't. Check if some
13705           // reversed form was a viable candidate, and if so, if it had a
13706           // better conversion for either parameter. If so, this call is
13707           // formally ambiguous, and allowing it is an extension.
13708           llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
13709           for (OverloadCandidate &Cand : CandidateSet) {
13710             if (Cand.Viable && Cand.Function && Cand.isReversed() &&
13711                 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) {
13712               for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
13713                 if (CompareImplicitConversionSequences(
13714                         *this, OpLoc, Cand.Conversions[ArgIdx],
13715                         Best->Conversions[ArgIdx]) ==
13716                     ImplicitConversionSequence::Better) {
13717                   AmbiguousWith.push_back(Cand.Function);
13718                   break;
13719                 }
13720               }
13721             }
13722           }
13723 
13724           if (!AmbiguousWith.empty()) {
13725             bool AmbiguousWithSelf =
13726                 AmbiguousWith.size() == 1 &&
13727                 declaresSameEntity(AmbiguousWith.front(), FnDecl);
13728             Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
13729                 << BinaryOperator::getOpcodeStr(Opc)
13730                 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
13731                 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13732             if (AmbiguousWithSelf) {
13733               Diag(FnDecl->getLocation(),
13734                    diag::note_ovl_ambiguous_oper_binary_reversed_self);
13735             } else {
13736               Diag(FnDecl->getLocation(),
13737                    diag::note_ovl_ambiguous_oper_binary_selected_candidate);
13738               for (auto *F : AmbiguousWith)
13739                 Diag(F->getLocation(),
13740                      diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
13741             }
13742           }
13743         }
13744 
13745         // Convert the arguments.
13746         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13747           // Best->Access is only meaningful for class members.
13748           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
13749 
13750           ExprResult Arg1 =
13751             PerformCopyInitialization(
13752               InitializedEntity::InitializeParameter(Context,
13753                                                      FnDecl->getParamDecl(0)),
13754               SourceLocation(), Args[1]);
13755           if (Arg1.isInvalid())
13756             return ExprError();
13757 
13758           ExprResult Arg0 =
13759             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13760                                                 Best->FoundDecl, Method);
13761           if (Arg0.isInvalid())
13762             return ExprError();
13763           Base = Args[0] = Arg0.getAs<Expr>();
13764           Args[1] = RHS = Arg1.getAs<Expr>();
13765         } else {
13766           // Convert the arguments.
13767           ExprResult Arg0 = PerformCopyInitialization(
13768             InitializedEntity::InitializeParameter(Context,
13769                                                    FnDecl->getParamDecl(0)),
13770             SourceLocation(), Args[0]);
13771           if (Arg0.isInvalid())
13772             return ExprError();
13773 
13774           ExprResult Arg1 =
13775             PerformCopyInitialization(
13776               InitializedEntity::InitializeParameter(Context,
13777                                                      FnDecl->getParamDecl(1)),
13778               SourceLocation(), Args[1]);
13779           if (Arg1.isInvalid())
13780             return ExprError();
13781           Args[0] = LHS = Arg0.getAs<Expr>();
13782           Args[1] = RHS = Arg1.getAs<Expr>();
13783         }
13784 
13785         // Build the actual expression node.
13786         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13787                                                   Best->FoundDecl, Base,
13788                                                   HadMultipleCandidates, OpLoc);
13789         if (FnExpr.isInvalid())
13790           return ExprError();
13791 
13792         // Determine the result type.
13793         QualType ResultTy = FnDecl->getReturnType();
13794         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13795         ResultTy = ResultTy.getNonLValueExprType(Context);
13796 
13797         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13798             Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
13799             CurFPFeatureOverrides(), Best->IsADLCandidate);
13800 
13801         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
13802                                 FnDecl))
13803           return ExprError();
13804 
13805         ArrayRef<const Expr *> ArgsArray(Args, 2);
13806         const Expr *ImplicitThis = nullptr;
13807         // Cut off the implicit 'this'.
13808         if (isa<CXXMethodDecl>(FnDecl)) {
13809           ImplicitThis = ArgsArray[0];
13810           ArgsArray = ArgsArray.slice(1);
13811         }
13812 
13813         // Check for a self move.
13814         if (Op == OO_Equal)
13815           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
13816 
13817         if (ImplicitThis) {
13818           QualType ThisType = Context.getPointerType(ImplicitThis->getType());
13819           QualType ThisTypeFromDecl = Context.getPointerType(
13820               cast<CXXMethodDecl>(FnDecl)->getThisObjectType());
13821 
13822           CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
13823                             ThisTypeFromDecl);
13824         }
13825 
13826         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
13827                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
13828                   VariadicDoesNotApply);
13829 
13830         ExprResult R = MaybeBindToTemporary(TheCall);
13831         if (R.isInvalid())
13832           return ExprError();
13833 
13834         R = CheckForImmediateInvocation(R, FnDecl);
13835         if (R.isInvalid())
13836           return ExprError();
13837 
13838         // For a rewritten candidate, we've already reversed the arguments
13839         // if needed. Perform the rest of the rewrite now.
13840         if ((Best->RewriteKind & CRK_DifferentOperator) ||
13841             (Op == OO_Spaceship && IsReversed)) {
13842           if (Op == OO_ExclaimEqual) {
13843             assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
13844             R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
13845           } else {
13846             assert(ChosenOp == OO_Spaceship && "unexpected operator name");
13847             llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13848             Expr *ZeroLiteral =
13849                 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
13850 
13851             Sema::CodeSynthesisContext Ctx;
13852             Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
13853             Ctx.Entity = FnDecl;
13854             pushCodeSynthesisContext(Ctx);
13855 
13856             R = CreateOverloadedBinOp(
13857                 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
13858                 IsReversed ? R.get() : ZeroLiteral, PerformADL,
13859                 /*AllowRewrittenCandidates=*/false);
13860 
13861             popCodeSynthesisContext();
13862           }
13863           if (R.isInvalid())
13864             return ExprError();
13865         } else {
13866           assert(ChosenOp == Op && "unexpected operator name");
13867         }
13868 
13869         // Make a note in the AST if we did any rewriting.
13870         if (Best->RewriteKind != CRK_None)
13871           R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
13872 
13873         return R;
13874       } else {
13875         // We matched a built-in operator. Convert the arguments, then
13876         // break out so that we will build the appropriate built-in
13877         // operator node.
13878         ExprResult ArgsRes0 = PerformImplicitConversion(
13879             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13880             AA_Passing, CCK_ForBuiltinOverloadedOp);
13881         if (ArgsRes0.isInvalid())
13882           return ExprError();
13883         Args[0] = ArgsRes0.get();
13884 
13885         ExprResult ArgsRes1 = PerformImplicitConversion(
13886             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13887             AA_Passing, CCK_ForBuiltinOverloadedOp);
13888         if (ArgsRes1.isInvalid())
13889           return ExprError();
13890         Args[1] = ArgsRes1.get();
13891         break;
13892       }
13893     }
13894 
13895     case OR_No_Viable_Function: {
13896       // C++ [over.match.oper]p9:
13897       //   If the operator is the operator , [...] and there are no
13898       //   viable functions, then the operator is assumed to be the
13899       //   built-in operator and interpreted according to clause 5.
13900       if (Opc == BO_Comma)
13901         break;
13902 
13903       // When defaulting an 'operator<=>', we can try to synthesize a three-way
13904       // compare result using '==' and '<'.
13905       if (DefaultedFn && Opc == BO_Cmp) {
13906         ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
13907                                                           Args[1], DefaultedFn);
13908         if (E.isInvalid() || E.isUsable())
13909           return E;
13910       }
13911 
13912       // For class as left operand for assignment or compound assignment
13913       // operator do not fall through to handling in built-in, but report that
13914       // no overloaded assignment operator found
13915       ExprResult Result = ExprError();
13916       StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
13917       auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
13918                                                    Args, OpLoc);
13919       DeferDiagsRAII DDR(*this,
13920                          CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
13921       if (Args[0]->getType()->isRecordType() &&
13922           Opc >= BO_Assign && Opc <= BO_OrAssign) {
13923         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
13924              << BinaryOperator::getOpcodeStr(Opc)
13925              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13926         if (Args[0]->getType()->isIncompleteType()) {
13927           Diag(OpLoc, diag::note_assign_lhs_incomplete)
13928             << Args[0]->getType()
13929             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13930         }
13931       } else {
13932         // This is an erroneous use of an operator which can be overloaded by
13933         // a non-member function. Check for non-member operators which were
13934         // defined too late to be candidates.
13935         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
13936           // FIXME: Recover by calling the found function.
13937           return ExprError();
13938 
13939         // No viable function; try to create a built-in operation, which will
13940         // produce an error. Then, show the non-viable candidates.
13941         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13942       }
13943       assert(Result.isInvalid() &&
13944              "C++ binary operator overloading is missing candidates!");
13945       CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
13946       return Result;
13947     }
13948 
13949     case OR_Ambiguous:
13950       CandidateSet.NoteCandidates(
13951           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13952                                          << BinaryOperator::getOpcodeStr(Opc)
13953                                          << Args[0]->getType()
13954                                          << Args[1]->getType()
13955                                          << Args[0]->getSourceRange()
13956                                          << Args[1]->getSourceRange()),
13957           *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13958           OpLoc);
13959       return ExprError();
13960 
13961     case OR_Deleted:
13962       if (isImplicitlyDeleted(Best->Function)) {
13963         FunctionDecl *DeletedFD = Best->Function;
13964         DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
13965         if (DFK.isSpecialMember()) {
13966           Diag(OpLoc, diag::err_ovl_deleted_special_oper)
13967             << Args[0]->getType() << DFK.asSpecialMember();
13968         } else {
13969           assert(DFK.isComparison());
13970           Diag(OpLoc, diag::err_ovl_deleted_comparison)
13971             << Args[0]->getType() << DeletedFD;
13972         }
13973 
13974         // The user probably meant to call this special member. Just
13975         // explain why it's deleted.
13976         NoteDeletedFunction(DeletedFD);
13977         return ExprError();
13978       }
13979       CandidateSet.NoteCandidates(
13980           PartialDiagnosticAt(
13981               OpLoc, PDiag(diag::err_ovl_deleted_oper)
13982                          << getOperatorSpelling(Best->Function->getDeclName()
13983                                                     .getCXXOverloadedOperator())
13984                          << Args[0]->getSourceRange()
13985                          << Args[1]->getSourceRange()),
13986           *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13987           OpLoc);
13988       return ExprError();
13989   }
13990 
13991   // We matched a built-in operator; build it.
13992   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13993 }
13994 
13995 ExprResult Sema::BuildSynthesizedThreeWayComparison(
13996     SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
13997     FunctionDecl *DefaultedFn) {
13998   const ComparisonCategoryInfo *Info =
13999       Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
14000   // If we're not producing a known comparison category type, we can't
14001   // synthesize a three-way comparison. Let the caller diagnose this.
14002   if (!Info)
14003     return ExprResult((Expr*)nullptr);
14004 
14005   // If we ever want to perform this synthesis more generally, we will need to
14006   // apply the temporary materialization conversion to the operands.
14007   assert(LHS->isGLValue() && RHS->isGLValue() &&
14008          "cannot use prvalue expressions more than once");
14009   Expr *OrigLHS = LHS;
14010   Expr *OrigRHS = RHS;
14011 
14012   // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
14013   // each of them multiple times below.
14014   LHS = new (Context)
14015       OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
14016                       LHS->getObjectKind(), LHS);
14017   RHS = new (Context)
14018       OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
14019                       RHS->getObjectKind(), RHS);
14020 
14021   ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
14022                                         DefaultedFn);
14023   if (Eq.isInvalid())
14024     return ExprError();
14025 
14026   ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
14027                                           true, DefaultedFn);
14028   if (Less.isInvalid())
14029     return ExprError();
14030 
14031   ExprResult Greater;
14032   if (Info->isPartial()) {
14033     Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
14034                                     DefaultedFn);
14035     if (Greater.isInvalid())
14036       return ExprError();
14037   }
14038 
14039   // Form the list of comparisons we're going to perform.
14040   struct Comparison {
14041     ExprResult Cmp;
14042     ComparisonCategoryResult Result;
14043   } Comparisons[4] =
14044   { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
14045                           : ComparisonCategoryResult::Equivalent},
14046     {Less, ComparisonCategoryResult::Less},
14047     {Greater, ComparisonCategoryResult::Greater},
14048     {ExprResult(), ComparisonCategoryResult::Unordered},
14049   };
14050 
14051   int I = Info->isPartial() ? 3 : 2;
14052 
14053   // Combine the comparisons with suitable conditional expressions.
14054   ExprResult Result;
14055   for (; I >= 0; --I) {
14056     // Build a reference to the comparison category constant.
14057     auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
14058     // FIXME: Missing a constant for a comparison category. Diagnose this?
14059     if (!VI)
14060       return ExprResult((Expr*)nullptr);
14061     ExprResult ThisResult =
14062         BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
14063     if (ThisResult.isInvalid())
14064       return ExprError();
14065 
14066     // Build a conditional unless this is the final case.
14067     if (Result.get()) {
14068       Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
14069                                   ThisResult.get(), Result.get());
14070       if (Result.isInvalid())
14071         return ExprError();
14072     } else {
14073       Result = ThisResult;
14074     }
14075   }
14076 
14077   // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
14078   // bind the OpaqueValueExprs before they're (repeatedly) used.
14079   Expr *SyntacticForm = BinaryOperator::Create(
14080       Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
14081       Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
14082       CurFPFeatureOverrides());
14083   Expr *SemanticForm[] = {LHS, RHS, Result.get()};
14084   return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
14085 }
14086 
14087 static bool PrepareArgumentsForCallToObjectOfClassType(
14088     Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
14089     MultiExprArg Args, SourceLocation LParenLoc) {
14090 
14091   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14092   unsigned NumParams = Proto->getNumParams();
14093   unsigned NumArgsSlots =
14094       MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
14095   // Build the full argument list for the method call (the implicit object
14096   // parameter is placed at the beginning of the list).
14097   MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
14098   bool IsError = false;
14099   // Initialize the implicit object parameter.
14100   // Check the argument types.
14101   for (unsigned i = 0; i != NumParams; i++) {
14102     Expr *Arg;
14103     if (i < Args.size()) {
14104       Arg = Args[i];
14105       ExprResult InputInit =
14106           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
14107                                           S.Context, Method->getParamDecl(i)),
14108                                       SourceLocation(), Arg);
14109       IsError |= InputInit.isInvalid();
14110       Arg = InputInit.getAs<Expr>();
14111     } else {
14112       ExprResult DefArg =
14113           S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14114       if (DefArg.isInvalid()) {
14115         IsError = true;
14116         break;
14117       }
14118       Arg = DefArg.getAs<Expr>();
14119     }
14120 
14121     MethodArgs.push_back(Arg);
14122   }
14123   return IsError;
14124 }
14125 
14126 ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
14127                                                     SourceLocation RLoc,
14128                                                     Expr *Base,
14129                                                     MultiExprArg ArgExpr) {
14130   SmallVector<Expr *, 2> Args;
14131   Args.push_back(Base);
14132   for (auto e : ArgExpr) {
14133     Args.push_back(e);
14134   }
14135   DeclarationName OpName =
14136       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
14137 
14138   SourceRange Range = ArgExpr.empty()
14139                           ? SourceRange{}
14140                           : SourceRange(ArgExpr.front()->getBeginLoc(),
14141                                         ArgExpr.back()->getEndLoc());
14142 
14143   // If either side is type-dependent, create an appropriate dependent
14144   // expression.
14145   if (Expr::hasAnyTypeDependentArguments(Args)) {
14146 
14147     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14148     // CHECKME: no 'operator' keyword?
14149     DeclarationNameInfo OpNameInfo(OpName, LLoc);
14150     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
14151     ExprResult Fn = CreateUnresolvedLookupExpr(
14152         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
14153     if (Fn.isInvalid())
14154       return ExprError();
14155     // Can't add any actual overloads yet
14156 
14157     return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
14158                                        Context.DependentTy, VK_PRValue, RLoc,
14159                                        CurFPFeatureOverrides());
14160   }
14161 
14162   // Handle placeholders
14163   UnbridgedCastsSet UnbridgedCasts;
14164   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14165     return ExprError();
14166   }
14167   // Build an empty overload set.
14168   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
14169 
14170   // Subscript can only be overloaded as a member function.
14171 
14172   // Add operator candidates that are member functions.
14173   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
14174 
14175   // Add builtin operator candidates.
14176   if (Args.size() == 2)
14177     AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
14178 
14179   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14180 
14181   // Perform overload resolution.
14182   OverloadCandidateSet::iterator Best;
14183   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
14184     case OR_Success: {
14185       // We found a built-in operator or an overloaded operator.
14186       FunctionDecl *FnDecl = Best->Function;
14187 
14188       if (FnDecl) {
14189         // We matched an overloaded operator. Build a call to that
14190         // operator.
14191 
14192         CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
14193 
14194         // Convert the arguments.
14195         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
14196         SmallVector<Expr *, 2> MethodArgs;
14197         ExprResult Arg0 = PerformObjectArgumentInitialization(
14198             Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14199         if (Arg0.isInvalid())
14200           return ExprError();
14201 
14202         MethodArgs.push_back(Arg0.get());
14203         bool IsError = PrepareArgumentsForCallToObjectOfClassType(
14204             *this, MethodArgs, Method, ArgExpr, LLoc);
14205         if (IsError)
14206           return ExprError();
14207 
14208         // Build the actual expression node.
14209         DeclarationNameInfo OpLocInfo(OpName, LLoc);
14210         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
14211         ExprResult FnExpr = CreateFunctionRefExpr(
14212             *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
14213             OpLocInfo.getLoc(), OpLocInfo.getInfo());
14214         if (FnExpr.isInvalid())
14215           return ExprError();
14216 
14217         // Determine the result type
14218         QualType ResultTy = FnDecl->getReturnType();
14219         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14220         ResultTy = ResultTy.getNonLValueExprType(Context);
14221 
14222         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14223             Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
14224             CurFPFeatureOverrides());
14225         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
14226           return ExprError();
14227 
14228         if (CheckFunctionCall(Method, TheCall,
14229                               Method->getType()->castAs<FunctionProtoType>()))
14230           return ExprError();
14231 
14232         return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14233                                            FnDecl);
14234       } else {
14235         // We matched a built-in operator. Convert the arguments, then
14236         // break out so that we will build the appropriate built-in
14237         // operator node.
14238         ExprResult ArgsRes0 = PerformImplicitConversion(
14239             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
14240             AA_Passing, CCK_ForBuiltinOverloadedOp);
14241         if (ArgsRes0.isInvalid())
14242           return ExprError();
14243         Args[0] = ArgsRes0.get();
14244 
14245         ExprResult ArgsRes1 = PerformImplicitConversion(
14246             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
14247             AA_Passing, CCK_ForBuiltinOverloadedOp);
14248         if (ArgsRes1.isInvalid())
14249           return ExprError();
14250         Args[1] = ArgsRes1.get();
14251 
14252         break;
14253       }
14254     }
14255 
14256     case OR_No_Viable_Function: {
14257       PartialDiagnostic PD =
14258           CandidateSet.empty()
14259               ? (PDiag(diag::err_ovl_no_oper)
14260                  << Args[0]->getType() << /*subscript*/ 0
14261                  << Args[0]->getSourceRange() << Range)
14262               : (PDiag(diag::err_ovl_no_viable_subscript)
14263                  << Args[0]->getType() << Args[0]->getSourceRange() << Range);
14264       CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
14265                                   OCD_AllCandidates, ArgExpr, "[]", LLoc);
14266       return ExprError();
14267     }
14268 
14269     case OR_Ambiguous:
14270       if (Args.size() == 2) {
14271         CandidateSet.NoteCandidates(
14272             PartialDiagnosticAt(
14273                 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
14274                           << "[]" << Args[0]->getType() << Args[1]->getType()
14275                           << Args[0]->getSourceRange() << Range),
14276             *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
14277       } else {
14278         CandidateSet.NoteCandidates(
14279             PartialDiagnosticAt(LLoc,
14280                                 PDiag(diag::err_ovl_ambiguous_subscript_call)
14281                                     << Args[0]->getType()
14282                                     << Args[0]->getSourceRange() << Range),
14283             *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
14284       }
14285       return ExprError();
14286 
14287     case OR_Deleted:
14288       CandidateSet.NoteCandidates(
14289           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
14290                                         << "[]" << Args[0]->getSourceRange()
14291                                         << Range),
14292           *this, OCD_AllCandidates, Args, "[]", LLoc);
14293       return ExprError();
14294     }
14295 
14296   // We matched a built-in operator; build it.
14297   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
14298 }
14299 
14300 /// BuildCallToMemberFunction - Build a call to a member
14301 /// function. MemExpr is the expression that refers to the member
14302 /// function (and includes the object parameter), Args/NumArgs are the
14303 /// arguments to the function call (not including the object
14304 /// parameter). The caller needs to validate that the member
14305 /// expression refers to a non-static member function or an overloaded
14306 /// member function.
14307 ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
14308                                            SourceLocation LParenLoc,
14309                                            MultiExprArg Args,
14310                                            SourceLocation RParenLoc,
14311                                            Expr *ExecConfig, bool IsExecConfig,
14312                                            bool AllowRecovery) {
14313   assert(MemExprE->getType() == Context.BoundMemberTy ||
14314          MemExprE->getType() == Context.OverloadTy);
14315 
14316   // Dig out the member expression. This holds both the object
14317   // argument and the member function we're referring to.
14318   Expr *NakedMemExpr = MemExprE->IgnoreParens();
14319 
14320   // Determine whether this is a call to a pointer-to-member function.
14321   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
14322     assert(op->getType() == Context.BoundMemberTy);
14323     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
14324 
14325     QualType fnType =
14326       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
14327 
14328     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
14329     QualType resultType = proto->getCallResultType(Context);
14330     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
14331 
14332     // Check that the object type isn't more qualified than the
14333     // member function we're calling.
14334     Qualifiers funcQuals = proto->getMethodQuals();
14335 
14336     QualType objectType = op->getLHS()->getType();
14337     if (op->getOpcode() == BO_PtrMemI)
14338       objectType = objectType->castAs<PointerType>()->getPointeeType();
14339     Qualifiers objectQuals = objectType.getQualifiers();
14340 
14341     Qualifiers difference = objectQuals - funcQuals;
14342     difference.removeObjCGCAttr();
14343     difference.removeAddressSpace();
14344     if (difference) {
14345       std::string qualsString = difference.getAsString();
14346       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
14347         << fnType.getUnqualifiedType()
14348         << qualsString
14349         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
14350     }
14351 
14352     CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
14353         Context, MemExprE, Args, resultType, valueKind, RParenLoc,
14354         CurFPFeatureOverrides(), proto->getNumParams());
14355 
14356     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
14357                             call, nullptr))
14358       return ExprError();
14359 
14360     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
14361       return ExprError();
14362 
14363     if (CheckOtherCall(call, proto))
14364       return ExprError();
14365 
14366     return MaybeBindToTemporary(call);
14367   }
14368 
14369   // We only try to build a recovery expr at this level if we can preserve
14370   // the return type, otherwise we return ExprError() and let the caller
14371   // recover.
14372   auto BuildRecoveryExpr = [&](QualType Type) {
14373     if (!AllowRecovery)
14374       return ExprError();
14375     std::vector<Expr *> SubExprs = {MemExprE};
14376     llvm::append_range(SubExprs, Args);
14377     return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
14378                               Type);
14379   };
14380   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
14381     return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
14382                             RParenLoc, CurFPFeatureOverrides());
14383 
14384   UnbridgedCastsSet UnbridgedCasts;
14385   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14386     return ExprError();
14387 
14388   MemberExpr *MemExpr;
14389   CXXMethodDecl *Method = nullptr;
14390   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
14391   NestedNameSpecifier *Qualifier = nullptr;
14392   if (isa<MemberExpr>(NakedMemExpr)) {
14393     MemExpr = cast<MemberExpr>(NakedMemExpr);
14394     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
14395     FoundDecl = MemExpr->getFoundDecl();
14396     Qualifier = MemExpr->getQualifier();
14397     UnbridgedCasts.restore();
14398   } else {
14399     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
14400     Qualifier = UnresExpr->getQualifier();
14401 
14402     QualType ObjectType = UnresExpr->getBaseType();
14403     Expr::Classification ObjectClassification
14404       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
14405                             : UnresExpr->getBase()->Classify(Context);
14406 
14407     // Add overload candidates
14408     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
14409                                       OverloadCandidateSet::CSK_Normal);
14410 
14411     // FIXME: avoid copy.
14412     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14413     if (UnresExpr->hasExplicitTemplateArgs()) {
14414       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14415       TemplateArgs = &TemplateArgsBuffer;
14416     }
14417 
14418     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
14419            E = UnresExpr->decls_end(); I != E; ++I) {
14420 
14421       NamedDecl *Func = *I;
14422       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
14423       if (isa<UsingShadowDecl>(Func))
14424         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
14425 
14426 
14427       // Microsoft supports direct constructor calls.
14428       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
14429         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
14430                              CandidateSet,
14431                              /*SuppressUserConversions*/ false);
14432       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
14433         // If explicit template arguments were provided, we can't call a
14434         // non-template member function.
14435         if (TemplateArgs)
14436           continue;
14437 
14438         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
14439                            ObjectClassification, Args, CandidateSet,
14440                            /*SuppressUserConversions=*/false);
14441       } else {
14442         AddMethodTemplateCandidate(
14443             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
14444             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
14445             /*SuppressUserConversions=*/false);
14446       }
14447     }
14448 
14449     DeclarationName DeclName = UnresExpr->getMemberName();
14450 
14451     UnbridgedCasts.restore();
14452 
14453     OverloadCandidateSet::iterator Best;
14454     bool Succeeded = false;
14455     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
14456                                             Best)) {
14457     case OR_Success:
14458       Method = cast<CXXMethodDecl>(Best->Function);
14459       FoundDecl = Best->FoundDecl;
14460       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
14461       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
14462         break;
14463       // If FoundDecl is different from Method (such as if one is a template
14464       // and the other a specialization), make sure DiagnoseUseOfDecl is
14465       // called on both.
14466       // FIXME: This would be more comprehensively addressed by modifying
14467       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
14468       // being used.
14469       if (Method != FoundDecl.getDecl() &&
14470                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
14471         break;
14472       Succeeded = true;
14473       break;
14474 
14475     case OR_No_Viable_Function:
14476       CandidateSet.NoteCandidates(
14477           PartialDiagnosticAt(
14478               UnresExpr->getMemberLoc(),
14479               PDiag(diag::err_ovl_no_viable_member_function_in_call)
14480                   << DeclName << MemExprE->getSourceRange()),
14481           *this, OCD_AllCandidates, Args);
14482       break;
14483     case OR_Ambiguous:
14484       CandidateSet.NoteCandidates(
14485           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14486                               PDiag(diag::err_ovl_ambiguous_member_call)
14487                                   << DeclName << MemExprE->getSourceRange()),
14488           *this, OCD_AmbiguousCandidates, Args);
14489       break;
14490     case OR_Deleted:
14491       CandidateSet.NoteCandidates(
14492           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14493                               PDiag(diag::err_ovl_deleted_member_call)
14494                                   << DeclName << MemExprE->getSourceRange()),
14495           *this, OCD_AllCandidates, Args);
14496       break;
14497     }
14498     // Overload resolution fails, try to recover.
14499     if (!Succeeded)
14500       return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
14501 
14502     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
14503 
14504     // If overload resolution picked a static member, build a
14505     // non-member call based on that function.
14506     if (Method->isStatic()) {
14507       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
14508                                    ExecConfig, IsExecConfig);
14509     }
14510 
14511     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
14512   }
14513 
14514   QualType ResultType = Method->getReturnType();
14515   ExprValueKind VK = Expr::getValueKindForType(ResultType);
14516   ResultType = ResultType.getNonLValueExprType(Context);
14517 
14518   assert(Method && "Member call to something that isn't a method?");
14519   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14520   CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create(
14521       Context, MemExprE, Args, ResultType, VK, RParenLoc,
14522       CurFPFeatureOverrides(), Proto->getNumParams());
14523 
14524   // Check for a valid return type.
14525   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
14526                           TheCall, Method))
14527     return BuildRecoveryExpr(ResultType);
14528 
14529   // Convert the object argument (for a non-static member function call).
14530   // We only need to do this if there was actually an overload; otherwise
14531   // it was done at lookup.
14532   if (!Method->isStatic()) {
14533     ExprResult ObjectArg =
14534       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
14535                                           FoundDecl, Method);
14536     if (ObjectArg.isInvalid())
14537       return ExprError();
14538     MemExpr->setBase(ObjectArg.get());
14539   }
14540 
14541   // Convert the rest of the arguments
14542   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
14543                               RParenLoc))
14544     return BuildRecoveryExpr(ResultType);
14545 
14546   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14547 
14548   if (CheckFunctionCall(Method, TheCall, Proto))
14549     return ExprError();
14550 
14551   // In the case the method to call was not selected by the overloading
14552   // resolution process, we still need to handle the enable_if attribute. Do
14553   // that here, so it will not hide previous -- and more relevant -- errors.
14554   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
14555     if (const EnableIfAttr *Attr =
14556             CheckEnableIf(Method, LParenLoc, Args, true)) {
14557       Diag(MemE->getMemberLoc(),
14558            diag::err_ovl_no_viable_member_function_in_call)
14559           << Method << Method->getSourceRange();
14560       Diag(Method->getLocation(),
14561            diag::note_ovl_candidate_disabled_by_function_cond_attr)
14562           << Attr->getCond()->getSourceRange() << Attr->getMessage();
14563       return ExprError();
14564     }
14565   }
14566 
14567   if ((isa<CXXConstructorDecl>(CurContext) ||
14568        isa<CXXDestructorDecl>(CurContext)) &&
14569       TheCall->getMethodDecl()->isPure()) {
14570     const CXXMethodDecl *MD = TheCall->getMethodDecl();
14571 
14572     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
14573         MemExpr->performsVirtualDispatch(getLangOpts())) {
14574       Diag(MemExpr->getBeginLoc(),
14575            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
14576           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
14577           << MD->getParent();
14578 
14579       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
14580       if (getLangOpts().AppleKext)
14581         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
14582             << MD->getParent() << MD->getDeclName();
14583     }
14584   }
14585 
14586   if (CXXDestructorDecl *DD =
14587           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
14588     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
14589     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
14590     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
14591                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
14592                          MemExpr->getMemberLoc());
14593   }
14594 
14595   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14596                                      TheCall->getMethodDecl());
14597 }
14598 
14599 /// BuildCallToObjectOfClassType - Build a call to an object of class
14600 /// type (C++ [over.call.object]), which can end up invoking an
14601 /// overloaded function call operator (@c operator()) or performing a
14602 /// user-defined conversion on the object argument.
14603 ExprResult
14604 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
14605                                    SourceLocation LParenLoc,
14606                                    MultiExprArg Args,
14607                                    SourceLocation RParenLoc) {
14608   if (checkPlaceholderForOverload(*this, Obj))
14609     return ExprError();
14610   ExprResult Object = Obj;
14611 
14612   UnbridgedCastsSet UnbridgedCasts;
14613   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14614     return ExprError();
14615 
14616   assert(Object.get()->getType()->isRecordType() &&
14617          "Requires object type argument");
14618 
14619   // C++ [over.call.object]p1:
14620   //  If the primary-expression E in the function call syntax
14621   //  evaluates to a class object of type "cv T", then the set of
14622   //  candidate functions includes at least the function call
14623   //  operators of T. The function call operators of T are obtained by
14624   //  ordinary lookup of the name operator() in the context of
14625   //  (E).operator().
14626   OverloadCandidateSet CandidateSet(LParenLoc,
14627                                     OverloadCandidateSet::CSK_Operator);
14628   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
14629 
14630   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
14631                           diag::err_incomplete_object_call, Object.get()))
14632     return true;
14633 
14634   const auto *Record = Object.get()->getType()->castAs<RecordType>();
14635   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
14636   LookupQualifiedName(R, Record->getDecl());
14637   R.suppressDiagnostics();
14638 
14639   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14640        Oper != OperEnd; ++Oper) {
14641     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
14642                        Object.get()->Classify(Context), Args, CandidateSet,
14643                        /*SuppressUserConversion=*/false);
14644   }
14645 
14646   // C++ [over.call.object]p2:
14647   //   In addition, for each (non-explicit in C++0x) conversion function
14648   //   declared in T of the form
14649   //
14650   //        operator conversion-type-id () cv-qualifier;
14651   //
14652   //   where cv-qualifier is the same cv-qualification as, or a
14653   //   greater cv-qualification than, cv, and where conversion-type-id
14654   //   denotes the type "pointer to function of (P1,...,Pn) returning
14655   //   R", or the type "reference to pointer to function of
14656   //   (P1,...,Pn) returning R", or the type "reference to function
14657   //   of (P1,...,Pn) returning R", a surrogate call function [...]
14658   //   is also considered as a candidate function. Similarly,
14659   //   surrogate call functions are added to the set of candidate
14660   //   functions for each conversion function declared in an
14661   //   accessible base class provided the function is not hidden
14662   //   within T by another intervening declaration.
14663   const auto &Conversions =
14664       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
14665   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
14666     NamedDecl *D = *I;
14667     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
14668     if (isa<UsingShadowDecl>(D))
14669       D = cast<UsingShadowDecl>(D)->getTargetDecl();
14670 
14671     // Skip over templated conversion functions; they aren't
14672     // surrogates.
14673     if (isa<FunctionTemplateDecl>(D))
14674       continue;
14675 
14676     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
14677     if (!Conv->isExplicit()) {
14678       // Strip the reference type (if any) and then the pointer type (if
14679       // any) to get down to what might be a function type.
14680       QualType ConvType = Conv->getConversionType().getNonReferenceType();
14681       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
14682         ConvType = ConvPtrType->getPointeeType();
14683 
14684       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
14685       {
14686         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
14687                               Object.get(), Args, CandidateSet);
14688       }
14689     }
14690   }
14691 
14692   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14693 
14694   // Perform overload resolution.
14695   OverloadCandidateSet::iterator Best;
14696   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
14697                                           Best)) {
14698   case OR_Success:
14699     // Overload resolution succeeded; we'll build the appropriate call
14700     // below.
14701     break;
14702 
14703   case OR_No_Viable_Function: {
14704     PartialDiagnostic PD =
14705         CandidateSet.empty()
14706             ? (PDiag(diag::err_ovl_no_oper)
14707                << Object.get()->getType() << /*call*/ 1
14708                << Object.get()->getSourceRange())
14709             : (PDiag(diag::err_ovl_no_viable_object_call)
14710                << Object.get()->getType() << Object.get()->getSourceRange());
14711     CandidateSet.NoteCandidates(
14712         PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
14713         OCD_AllCandidates, Args);
14714     break;
14715   }
14716   case OR_Ambiguous:
14717     CandidateSet.NoteCandidates(
14718         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14719                             PDiag(diag::err_ovl_ambiguous_object_call)
14720                                 << Object.get()->getType()
14721                                 << Object.get()->getSourceRange()),
14722         *this, OCD_AmbiguousCandidates, Args);
14723     break;
14724 
14725   case OR_Deleted:
14726     CandidateSet.NoteCandidates(
14727         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14728                             PDiag(diag::err_ovl_deleted_object_call)
14729                                 << Object.get()->getType()
14730                                 << Object.get()->getSourceRange()),
14731         *this, OCD_AllCandidates, Args);
14732     break;
14733   }
14734 
14735   if (Best == CandidateSet.end())
14736     return true;
14737 
14738   UnbridgedCasts.restore();
14739 
14740   if (Best->Function == nullptr) {
14741     // Since there is no function declaration, this is one of the
14742     // surrogate candidates. Dig out the conversion function.
14743     CXXConversionDecl *Conv
14744       = cast<CXXConversionDecl>(
14745                          Best->Conversions[0].UserDefined.ConversionFunction);
14746 
14747     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
14748                               Best->FoundDecl);
14749     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
14750       return ExprError();
14751     assert(Conv == Best->FoundDecl.getDecl() &&
14752              "Found Decl & conversion-to-functionptr should be same, right?!");
14753     // We selected one of the surrogate functions that converts the
14754     // object parameter to a function pointer. Perform the conversion
14755     // on the object argument, then let BuildCallExpr finish the job.
14756 
14757     // Create an implicit member expr to refer to the conversion operator.
14758     // and then call it.
14759     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
14760                                              Conv, HadMultipleCandidates);
14761     if (Call.isInvalid())
14762       return ExprError();
14763     // Record usage of conversion in an implicit cast.
14764     Call = ImplicitCastExpr::Create(
14765         Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
14766         nullptr, VK_PRValue, CurFPFeatureOverrides());
14767 
14768     return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
14769   }
14770 
14771   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
14772 
14773   // We found an overloaded operator(). Build a CXXOperatorCallExpr
14774   // that calls this method, using Object for the implicit object
14775   // parameter and passing along the remaining arguments.
14776   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14777 
14778   // An error diagnostic has already been printed when parsing the declaration.
14779   if (Method->isInvalidDecl())
14780     return ExprError();
14781 
14782   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14783   unsigned NumParams = Proto->getNumParams();
14784 
14785   DeclarationNameInfo OpLocInfo(
14786                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
14787   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
14788   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14789                                            Obj, HadMultipleCandidates,
14790                                            OpLocInfo.getLoc(),
14791                                            OpLocInfo.getInfo());
14792   if (NewFn.isInvalid())
14793     return true;
14794 
14795   SmallVector<Expr *, 8> MethodArgs;
14796   MethodArgs.reserve(NumParams + 1);
14797 
14798   bool IsError = false;
14799 
14800   // Initialize the implicit object parameter.
14801   ExprResult ObjRes =
14802     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
14803                                         Best->FoundDecl, Method);
14804   if (ObjRes.isInvalid())
14805     IsError = true;
14806   else
14807     Object = ObjRes;
14808   MethodArgs.push_back(Object.get());
14809 
14810   IsError |= PrepareArgumentsForCallToObjectOfClassType(
14811       *this, MethodArgs, Method, Args, LParenLoc);
14812 
14813   // If this is a variadic call, handle args passed through "...".
14814   if (Proto->isVariadic()) {
14815     // Promote the arguments (C99 6.5.2.2p7).
14816     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
14817       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
14818                                                         nullptr);
14819       IsError |= Arg.isInvalid();
14820       MethodArgs.push_back(Arg.get());
14821     }
14822   }
14823 
14824   if (IsError)
14825     return true;
14826 
14827   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14828 
14829   // Once we've built TheCall, all of the expressions are properly owned.
14830   QualType ResultTy = Method->getReturnType();
14831   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14832   ResultTy = ResultTy.getNonLValueExprType(Context);
14833 
14834   CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14835       Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
14836       CurFPFeatureOverrides());
14837 
14838   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
14839     return true;
14840 
14841   if (CheckFunctionCall(Method, TheCall, Proto))
14842     return true;
14843 
14844   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
14845 }
14846 
14847 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
14848 ///  (if one exists), where @c Base is an expression of class type and
14849 /// @c Member is the name of the member we're trying to find.
14850 ExprResult
14851 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
14852                                bool *NoArrowOperatorFound) {
14853   assert(Base->getType()->isRecordType() &&
14854          "left-hand side must have class type");
14855 
14856   if (checkPlaceholderForOverload(*this, Base))
14857     return ExprError();
14858 
14859   SourceLocation Loc = Base->getExprLoc();
14860 
14861   // C++ [over.ref]p1:
14862   //
14863   //   [...] An expression x->m is interpreted as (x.operator->())->m
14864   //   for a class object x of type T if T::operator->() exists and if
14865   //   the operator is selected as the best match function by the
14866   //   overload resolution mechanism (13.3).
14867   DeclarationName OpName =
14868     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
14869   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
14870 
14871   if (RequireCompleteType(Loc, Base->getType(),
14872                           diag::err_typecheck_incomplete_tag, Base))
14873     return ExprError();
14874 
14875   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
14876   LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
14877   R.suppressDiagnostics();
14878 
14879   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14880        Oper != OperEnd; ++Oper) {
14881     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
14882                        None, CandidateSet, /*SuppressUserConversion=*/false);
14883   }
14884 
14885   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14886 
14887   // Perform overload resolution.
14888   OverloadCandidateSet::iterator Best;
14889   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14890   case OR_Success:
14891     // Overload resolution succeeded; we'll build the call below.
14892     break;
14893 
14894   case OR_No_Viable_Function: {
14895     auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
14896     if (CandidateSet.empty()) {
14897       QualType BaseType = Base->getType();
14898       if (NoArrowOperatorFound) {
14899         // Report this specific error to the caller instead of emitting a
14900         // diagnostic, as requested.
14901         *NoArrowOperatorFound = true;
14902         return ExprError();
14903       }
14904       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
14905         << BaseType << Base->getSourceRange();
14906       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
14907         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
14908           << FixItHint::CreateReplacement(OpLoc, ".");
14909       }
14910     } else
14911       Diag(OpLoc, diag::err_ovl_no_viable_oper)
14912         << "operator->" << Base->getSourceRange();
14913     CandidateSet.NoteCandidates(*this, Base, Cands);
14914     return ExprError();
14915   }
14916   case OR_Ambiguous:
14917     CandidateSet.NoteCandidates(
14918         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
14919                                        << "->" << Base->getType()
14920                                        << Base->getSourceRange()),
14921         *this, OCD_AmbiguousCandidates, Base);
14922     return ExprError();
14923 
14924   case OR_Deleted:
14925     CandidateSet.NoteCandidates(
14926         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14927                                        << "->" << Base->getSourceRange()),
14928         *this, OCD_AllCandidates, Base);
14929     return ExprError();
14930   }
14931 
14932   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
14933 
14934   // Convert the object parameter.
14935   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14936   ExprResult BaseResult =
14937     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
14938                                         Best->FoundDecl, Method);
14939   if (BaseResult.isInvalid())
14940     return ExprError();
14941   Base = BaseResult.get();
14942 
14943   // Build the operator call.
14944   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14945                                             Base, HadMultipleCandidates, OpLoc);
14946   if (FnExpr.isInvalid())
14947     return ExprError();
14948 
14949   QualType ResultTy = Method->getReturnType();
14950   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14951   ResultTy = ResultTy.getNonLValueExprType(Context);
14952   CXXOperatorCallExpr *TheCall =
14953       CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
14954                                   ResultTy, VK, OpLoc, CurFPFeatureOverrides());
14955 
14956   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
14957     return ExprError();
14958 
14959   if (CheckFunctionCall(Method, TheCall,
14960                         Method->getType()->castAs<FunctionProtoType>()))
14961     return ExprError();
14962 
14963   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
14964 }
14965 
14966 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
14967 /// a literal operator described by the provided lookup results.
14968 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
14969                                           DeclarationNameInfo &SuffixInfo,
14970                                           ArrayRef<Expr*> Args,
14971                                           SourceLocation LitEndLoc,
14972                                        TemplateArgumentListInfo *TemplateArgs) {
14973   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
14974 
14975   OverloadCandidateSet CandidateSet(UDSuffixLoc,
14976                                     OverloadCandidateSet::CSK_Normal);
14977   AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
14978                                  TemplateArgs);
14979 
14980   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14981 
14982   // Perform overload resolution. This will usually be trivial, but might need
14983   // to perform substitutions for a literal operator template.
14984   OverloadCandidateSet::iterator Best;
14985   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
14986   case OR_Success:
14987   case OR_Deleted:
14988     break;
14989 
14990   case OR_No_Viable_Function:
14991     CandidateSet.NoteCandidates(
14992         PartialDiagnosticAt(UDSuffixLoc,
14993                             PDiag(diag::err_ovl_no_viable_function_in_call)
14994                                 << R.getLookupName()),
14995         *this, OCD_AllCandidates, Args);
14996     return ExprError();
14997 
14998   case OR_Ambiguous:
14999     CandidateSet.NoteCandidates(
15000         PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
15001                                                 << R.getLookupName()),
15002         *this, OCD_AmbiguousCandidates, Args);
15003     return ExprError();
15004   }
15005 
15006   FunctionDecl *FD = Best->Function;
15007   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
15008                                         nullptr, HadMultipleCandidates,
15009                                         SuffixInfo.getLoc(),
15010                                         SuffixInfo.getInfo());
15011   if (Fn.isInvalid())
15012     return true;
15013 
15014   // Check the argument types. This should almost always be a no-op, except
15015   // that array-to-pointer decay is applied to string literals.
15016   Expr *ConvArgs[2];
15017   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
15018     ExprResult InputInit = PerformCopyInitialization(
15019       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
15020       SourceLocation(), Args[ArgIdx]);
15021     if (InputInit.isInvalid())
15022       return true;
15023     ConvArgs[ArgIdx] = InputInit.get();
15024   }
15025 
15026   QualType ResultTy = FD->getReturnType();
15027   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15028   ResultTy = ResultTy.getNonLValueExprType(Context);
15029 
15030   UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
15031       Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
15032       VK, LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
15033 
15034   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
15035     return ExprError();
15036 
15037   if (CheckFunctionCall(FD, UDL, nullptr))
15038     return ExprError();
15039 
15040   return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
15041 }
15042 
15043 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
15044 /// given LookupResult is non-empty, it is assumed to describe a member which
15045 /// will be invoked. Otherwise, the function will be found via argument
15046 /// dependent lookup.
15047 /// CallExpr is set to a valid expression and FRS_Success returned on success,
15048 /// otherwise CallExpr is set to ExprError() and some non-success value
15049 /// is returned.
15050 Sema::ForRangeStatus
15051 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
15052                                 SourceLocation RangeLoc,
15053                                 const DeclarationNameInfo &NameInfo,
15054                                 LookupResult &MemberLookup,
15055                                 OverloadCandidateSet *CandidateSet,
15056                                 Expr *Range, ExprResult *CallExpr) {
15057   Scope *S = nullptr;
15058 
15059   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
15060   if (!MemberLookup.empty()) {
15061     ExprResult MemberRef =
15062         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
15063                                  /*IsPtr=*/false, CXXScopeSpec(),
15064                                  /*TemplateKWLoc=*/SourceLocation(),
15065                                  /*FirstQualifierInScope=*/nullptr,
15066                                  MemberLookup,
15067                                  /*TemplateArgs=*/nullptr, S);
15068     if (MemberRef.isInvalid()) {
15069       *CallExpr = ExprError();
15070       return FRS_DiagnosticIssued;
15071     }
15072     *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
15073     if (CallExpr->isInvalid()) {
15074       *CallExpr = ExprError();
15075       return FRS_DiagnosticIssued;
15076     }
15077   } else {
15078     ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
15079                                                 NestedNameSpecifierLoc(),
15080                                                 NameInfo, UnresolvedSet<0>());
15081     if (FnR.isInvalid())
15082       return FRS_DiagnosticIssued;
15083     UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
15084 
15085     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
15086                                                     CandidateSet, CallExpr);
15087     if (CandidateSet->empty() || CandidateSetError) {
15088       *CallExpr = ExprError();
15089       return FRS_NoViableFunction;
15090     }
15091     OverloadCandidateSet::iterator Best;
15092     OverloadingResult OverloadResult =
15093         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
15094 
15095     if (OverloadResult == OR_No_Viable_Function) {
15096       *CallExpr = ExprError();
15097       return FRS_NoViableFunction;
15098     }
15099     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
15100                                          Loc, nullptr, CandidateSet, &Best,
15101                                          OverloadResult,
15102                                          /*AllowTypoCorrection=*/false);
15103     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
15104       *CallExpr = ExprError();
15105       return FRS_DiagnosticIssued;
15106     }
15107   }
15108   return FRS_Success;
15109 }
15110 
15111 
15112 /// FixOverloadedFunctionReference - E is an expression that refers to
15113 /// a C++ overloaded function (possibly with some parentheses and
15114 /// perhaps a '&' around it). We have resolved the overloaded function
15115 /// to the function declaration Fn, so patch up the expression E to
15116 /// refer (possibly indirectly) to Fn. Returns the new expr.
15117 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
15118                                            FunctionDecl *Fn) {
15119   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
15120     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
15121                                                    Found, Fn);
15122     if (SubExpr == PE->getSubExpr())
15123       return PE;
15124 
15125     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
15126   }
15127 
15128   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
15129     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
15130                                                    Found, Fn);
15131     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
15132                                SubExpr->getType()) &&
15133            "Implicit cast type cannot be determined from overload");
15134     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
15135     if (SubExpr == ICE->getSubExpr())
15136       return ICE;
15137 
15138     return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
15139                                     SubExpr, nullptr, ICE->getValueKind(),
15140                                     CurFPFeatureOverrides());
15141   }
15142 
15143   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
15144     if (!GSE->isResultDependent()) {
15145       Expr *SubExpr =
15146           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
15147       if (SubExpr == GSE->getResultExpr())
15148         return GSE;
15149 
15150       // Replace the resulting type information before rebuilding the generic
15151       // selection expression.
15152       ArrayRef<Expr *> A = GSE->getAssocExprs();
15153       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
15154       unsigned ResultIdx = GSE->getResultIndex();
15155       AssocExprs[ResultIdx] = SubExpr;
15156 
15157       return GenericSelectionExpr::Create(
15158           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
15159           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
15160           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
15161           ResultIdx);
15162     }
15163     // Rather than fall through to the unreachable, return the original generic
15164     // selection expression.
15165     return GSE;
15166   }
15167 
15168   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
15169     assert(UnOp->getOpcode() == UO_AddrOf &&
15170            "Can only take the address of an overloaded function");
15171     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
15172       if (Method->isStatic()) {
15173         // Do nothing: static member functions aren't any different
15174         // from non-member functions.
15175       } else {
15176         // Fix the subexpression, which really has to be an
15177         // UnresolvedLookupExpr holding an overloaded member function
15178         // or template.
15179         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
15180                                                        Found, Fn);
15181         if (SubExpr == UnOp->getSubExpr())
15182           return UnOp;
15183 
15184         assert(isa<DeclRefExpr>(SubExpr)
15185                && "fixed to something other than a decl ref");
15186         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
15187                && "fixed to a member ref with no nested name qualifier");
15188 
15189         // We have taken the address of a pointer to member
15190         // function. Perform the computation here so that we get the
15191         // appropriate pointer to member type.
15192         QualType ClassType
15193           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
15194         QualType MemPtrType
15195           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
15196         // Under the MS ABI, lock down the inheritance model now.
15197         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15198           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
15199 
15200         return UnaryOperator::Create(
15201             Context, SubExpr, UO_AddrOf, MemPtrType, VK_PRValue, OK_Ordinary,
15202             UnOp->getOperatorLoc(), false, CurFPFeatureOverrides());
15203       }
15204     }
15205     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
15206                                                    Found, Fn);
15207     if (SubExpr == UnOp->getSubExpr())
15208       return UnOp;
15209 
15210     // FIXME: This can't currently fail, but in principle it could.
15211     return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf, SubExpr)
15212         .get();
15213   }
15214 
15215   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15216     // FIXME: avoid copy.
15217     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15218     if (ULE->hasExplicitTemplateArgs()) {
15219       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
15220       TemplateArgs = &TemplateArgsBuffer;
15221     }
15222 
15223     QualType Type = Fn->getType();
15224     ExprValueKind ValueKind = getLangOpts().CPlusPlus ? VK_LValue : VK_PRValue;
15225 
15226     // FIXME: Duplicated from BuildDeclarationNameExpr.
15227     if (unsigned BID = Fn->getBuiltinID()) {
15228       if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
15229         Type = Context.BuiltinFnTy;
15230         ValueKind = VK_PRValue;
15231       }
15232     }
15233 
15234     DeclRefExpr *DRE = BuildDeclRefExpr(
15235         Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
15236         Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
15237     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
15238     return DRE;
15239   }
15240 
15241   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
15242     // FIXME: avoid copy.
15243     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15244     if (MemExpr->hasExplicitTemplateArgs()) {
15245       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
15246       TemplateArgs = &TemplateArgsBuffer;
15247     }
15248 
15249     Expr *Base;
15250 
15251     // If we're filling in a static method where we used to have an
15252     // implicit member access, rewrite to a simple decl ref.
15253     if (MemExpr->isImplicitAccess()) {
15254       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
15255         DeclRefExpr *DRE = BuildDeclRefExpr(
15256             Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
15257             MemExpr->getQualifierLoc(), Found.getDecl(),
15258             MemExpr->getTemplateKeywordLoc(), TemplateArgs);
15259         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
15260         return DRE;
15261       } else {
15262         SourceLocation Loc = MemExpr->getMemberLoc();
15263         if (MemExpr->getQualifier())
15264           Loc = MemExpr->getQualifierLoc().getBeginLoc();
15265         Base =
15266             BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
15267       }
15268     } else
15269       Base = MemExpr->getBase();
15270 
15271     ExprValueKind valueKind;
15272     QualType type;
15273     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
15274       valueKind = VK_LValue;
15275       type = Fn->getType();
15276     } else {
15277       valueKind = VK_PRValue;
15278       type = Context.BoundMemberTy;
15279     }
15280 
15281     return BuildMemberExpr(
15282         Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
15283         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
15284         /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
15285         type, valueKind, OK_Ordinary, TemplateArgs);
15286   }
15287 
15288   llvm_unreachable("Invalid reference to overloaded function");
15289 }
15290 
15291 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
15292                                                 DeclAccessPair Found,
15293                                                 FunctionDecl *Fn) {
15294   return FixOverloadedFunctionReference(E.get(), Found, Fn);
15295 }
15296 
15297 bool clang::shouldEnforceArgLimit(bool PartialOverloading,
15298                                   FunctionDecl *Function) {
15299   if (!PartialOverloading || !Function)
15300     return true;
15301   if (Function->isVariadic())
15302     return false;
15303   if (const auto *Proto =
15304           dyn_cast<FunctionProtoType>(Function->getFunctionType()))
15305     if (Proto->isTemplateVariadic())
15306       return false;
15307   if (auto *Pattern = Function->getTemplateInstantiationPattern())
15308     if (const auto *Proto =
15309             dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
15310       if (Proto->isTemplateVariadic())
15311         return false;
15312   return true;
15313 }
15314