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 =
67       DeclRefExpr::Create(S.Context, Fn->getQualifierLoc(), SourceLocation(),
68                           Fn, false, Loc, Fn->getType(), VK_LValue, FoundDecl);
69   if (HadMultipleCandidates)
70     DRE->setHadMultipleCandidates(true);
71 
72   S.MarkDeclRefReferenced(DRE, Base);
73   if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
74     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
75       S.ResolveExceptionSpec(Loc, FPT);
76       DRE->setType(Fn->getType());
77     }
78   }
79   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
80                              CK_FunctionToPointerDecay);
81 }
82 
83 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
84                                  bool InOverloadResolution,
85                                  StandardConversionSequence &SCS,
86                                  bool CStyle,
87                                  bool AllowObjCWritebackConversion);
88 
89 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
90                                                  QualType &ToType,
91                                                  bool InOverloadResolution,
92                                                  StandardConversionSequence &SCS,
93                                                  bool CStyle);
94 static OverloadingResult
95 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
96                         UserDefinedConversionSequence& User,
97                         OverloadCandidateSet& Conversions,
98                         AllowedExplicit AllowExplicit,
99                         bool AllowObjCConversionOnExplicit);
100 
101 static ImplicitConversionSequence::CompareKind
102 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
103                                    const StandardConversionSequence& SCS1,
104                                    const StandardConversionSequence& SCS2);
105 
106 static ImplicitConversionSequence::CompareKind
107 CompareQualificationConversions(Sema &S,
108                                 const StandardConversionSequence& SCS1,
109                                 const StandardConversionSequence& SCS2);
110 
111 static ImplicitConversionSequence::CompareKind
112 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
113                                 const StandardConversionSequence& SCS1,
114                                 const StandardConversionSequence& SCS2);
115 
116 /// GetConversionRank - Retrieve the implicit conversion rank
117 /// corresponding to the given implicit conversion kind.
118 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
119   static const ImplicitConversionRank
120     Rank[(int)ICK_Num_Conversion_Kinds] = {
121     ICR_Exact_Match,
122     ICR_Exact_Match,
123     ICR_Exact_Match,
124     ICR_Exact_Match,
125     ICR_Exact_Match,
126     ICR_Exact_Match,
127     ICR_Promotion,
128     ICR_Promotion,
129     ICR_Promotion,
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_Conversion,
141     ICR_OCL_Scalar_Widening,
142     ICR_Complex_Real_Conversion,
143     ICR_Conversion,
144     ICR_Conversion,
145     ICR_Writeback_Conversion,
146     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
147                      // it was omitted by the patch that added
148                      // ICK_Zero_Event_Conversion
149     ICR_C_Conversion,
150     ICR_C_Conversion_Extension
151   };
152   return Rank[(int)Kind];
153 }
154 
155 /// GetImplicitConversionName - Return the name of this kind of
156 /// implicit conversion.
157 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
158   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
159     "No conversion",
160     "Lvalue-to-rvalue",
161     "Array-to-pointer",
162     "Function-to-pointer",
163     "Function pointer conversion",
164     "Qualification",
165     "Integral promotion",
166     "Floating point promotion",
167     "Complex promotion",
168     "Integral conversion",
169     "Floating conversion",
170     "Complex conversion",
171     "Floating-integral conversion",
172     "Pointer conversion",
173     "Pointer-to-member conversion",
174     "Boolean conversion",
175     "Compatible-types conversion",
176     "Derived-to-base conversion",
177     "Vector conversion",
178     "SVE Vector conversion",
179     "Vector splat",
180     "Complex-real conversion",
181     "Block Pointer conversion",
182     "Transparent Union Conversion",
183     "Writeback conversion",
184     "OpenCL Zero Event Conversion",
185     "C specific type conversion",
186     "Incompatible pointer conversion"
187   };
188   return Name[Kind];
189 }
190 
191 /// StandardConversionSequence - Set the standard conversion
192 /// sequence to the identity conversion.
193 void StandardConversionSequence::setAsIdentityConversion() {
194   First = ICK_Identity;
195   Second = ICK_Identity;
196   Third = ICK_Identity;
197   DeprecatedStringLiteralToCharPtr = false;
198   QualificationIncludesObjCLifetime = false;
199   ReferenceBinding = false;
200   DirectBinding = false;
201   IsLvalueReference = true;
202   BindsToFunctionLvalue = false;
203   BindsToRvalue = false;
204   BindsImplicitObjectArgumentWithoutRefQualifier = false;
205   ObjCLifetimeConversionBinding = false;
206   CopyConstructor = nullptr;
207 }
208 
209 /// getRank - Retrieve the rank of this standard conversion sequence
210 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
211 /// implicit conversions.
212 ImplicitConversionRank StandardConversionSequence::getRank() const {
213   ImplicitConversionRank Rank = ICR_Exact_Match;
214   if  (GetConversionRank(First) > Rank)
215     Rank = GetConversionRank(First);
216   if  (GetConversionRank(Second) > Rank)
217     Rank = GetConversionRank(Second);
218   if  (GetConversionRank(Third) > Rank)
219     Rank = GetConversionRank(Third);
220   return Rank;
221 }
222 
223 /// isPointerConversionToBool - Determines whether this conversion is
224 /// a conversion of a pointer or pointer-to-member to bool. This is
225 /// used as part of the ranking of standard conversion sequences
226 /// (C++ 13.3.3.2p4).
227 bool StandardConversionSequence::isPointerConversionToBool() const {
228   // Note that FromType has not necessarily been transformed by the
229   // array-to-pointer or function-to-pointer implicit conversions, so
230   // check for their presence as well as checking whether FromType is
231   // a pointer.
232   if (getToType(1)->isBooleanType() &&
233       (getFromType()->isPointerType() ||
234        getFromType()->isMemberPointerType() ||
235        getFromType()->isObjCObjectPointerType() ||
236        getFromType()->isBlockPointerType() ||
237        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
238     return true;
239 
240   return false;
241 }
242 
243 /// isPointerConversionToVoidPointer - Determines whether this
244 /// conversion is a conversion of a pointer to a void pointer. This is
245 /// used as part of the ranking of standard conversion sequences (C++
246 /// 13.3.3.2p4).
247 bool
248 StandardConversionSequence::
249 isPointerConversionToVoidPointer(ASTContext& Context) const {
250   QualType FromType = getFromType();
251   QualType ToType = getToType(1);
252 
253   // Note that FromType has not necessarily been transformed by the
254   // array-to-pointer implicit conversion, so check for its presence
255   // and redo the conversion to get a pointer.
256   if (First == ICK_Array_To_Pointer)
257     FromType = Context.getArrayDecayedType(FromType);
258 
259   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
260     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
261       return ToPtrType->getPointeeType()->isVoidType();
262 
263   return false;
264 }
265 
266 /// Skip any implicit casts which could be either part of a narrowing conversion
267 /// or after one in an implicit conversion.
268 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
269                                              const Expr *Converted) {
270   // We can have cleanups wrapping the converted expression; these need to be
271   // preserved so that destructors run if necessary.
272   if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
273     Expr *Inner =
274         const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
275     return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
276                                     EWC->getObjects());
277   }
278 
279   while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
280     switch (ICE->getCastKind()) {
281     case CK_NoOp:
282     case CK_IntegralCast:
283     case CK_IntegralToBoolean:
284     case CK_IntegralToFloating:
285     case CK_BooleanToSignedIntegral:
286     case CK_FloatingToIntegral:
287     case CK_FloatingToBoolean:
288     case CK_FloatingCast:
289       Converted = ICE->getSubExpr();
290       continue;
291 
292     default:
293       return Converted;
294     }
295   }
296 
297   return Converted;
298 }
299 
300 /// Check if this standard conversion sequence represents a narrowing
301 /// conversion, according to C++11 [dcl.init.list]p7.
302 ///
303 /// \param Ctx  The AST context.
304 /// \param Converted  The result of applying this standard conversion sequence.
305 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
306 ///        value of the expression prior to the narrowing conversion.
307 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
308 ///        type of the expression prior to the narrowing conversion.
309 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
310 ///        from floating point types to integral types should be ignored.
311 NarrowingKind StandardConversionSequence::getNarrowingKind(
312     ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
313     QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
314   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
315 
316   // C++11 [dcl.init.list]p7:
317   //   A narrowing conversion is an implicit conversion ...
318   QualType FromType = getToType(0);
319   QualType ToType = getToType(1);
320 
321   // A conversion to an enumeration type is narrowing if the conversion to
322   // the underlying type is narrowing. This only arises for expressions of
323   // the form 'Enum{init}'.
324   if (auto *ET = ToType->getAs<EnumType>())
325     ToType = ET->getDecl()->getIntegerType();
326 
327   switch (Second) {
328   // 'bool' is an integral type; dispatch to the right place to handle it.
329   case ICK_Boolean_Conversion:
330     if (FromType->isRealFloatingType())
331       goto FloatingIntegralConversion;
332     if (FromType->isIntegralOrUnscopedEnumerationType())
333       goto IntegralConversion;
334     // -- from a pointer type or pointer-to-member type to bool, or
335     return NK_Type_Narrowing;
336 
337   // -- from a floating-point type to an integer type, or
338   //
339   // -- from an integer type or unscoped enumeration type to a floating-point
340   //    type, except where the source is a constant expression and the actual
341   //    value after conversion will fit into the target type and will produce
342   //    the original value when converted back to the original type, or
343   case ICK_Floating_Integral:
344   FloatingIntegralConversion:
345     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
346       return NK_Type_Narrowing;
347     } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
348                ToType->isRealFloatingType()) {
349       if (IgnoreFloatToIntegralConversion)
350         return NK_Not_Narrowing;
351       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
352       assert(Initializer && "Unknown conversion expression");
353 
354       // If it's value-dependent, we can't tell whether it's narrowing.
355       if (Initializer->isValueDependent())
356         return NK_Dependent_Narrowing;
357 
358       if (Optional<llvm::APSInt> IntConstantValue =
359               Initializer->getIntegerConstantExpr(Ctx)) {
360         // Convert the integer to the floating type.
361         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
362         Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
363                                 llvm::APFloat::rmNearestTiesToEven);
364         // And back.
365         llvm::APSInt ConvertedValue = *IntConstantValue;
366         bool ignored;
367         Result.convertToInteger(ConvertedValue,
368                                 llvm::APFloat::rmTowardZero, &ignored);
369         // If the resulting value is different, this was a narrowing conversion.
370         if (*IntConstantValue != ConvertedValue) {
371           ConstantValue = APValue(*IntConstantValue);
372           ConstantType = Initializer->getType();
373           return NK_Constant_Narrowing;
374         }
375       } else {
376         // Variables are always narrowings.
377         return NK_Variable_Narrowing;
378       }
379     }
380     return NK_Not_Narrowing;
381 
382   // -- from long double to double or float, or from double to float, except
383   //    where the source is a constant expression and the actual value after
384   //    conversion is within the range of values that can be represented (even
385   //    if it cannot be represented exactly), or
386   case ICK_Floating_Conversion:
387     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
388         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
389       // FromType is larger than ToType.
390       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
391 
392       // If it's value-dependent, we can't tell whether it's narrowing.
393       if (Initializer->isValueDependent())
394         return NK_Dependent_Narrowing;
395 
396       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
397         // Constant!
398         assert(ConstantValue.isFloat());
399         llvm::APFloat FloatVal = ConstantValue.getFloat();
400         // Convert the source value into the target type.
401         bool ignored;
402         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
403           Ctx.getFloatTypeSemantics(ToType),
404           llvm::APFloat::rmNearestTiesToEven, &ignored);
405         // If there was no overflow, the source value is within the range of
406         // values that can be represented.
407         if (ConvertStatus & llvm::APFloat::opOverflow) {
408           ConstantType = Initializer->getType();
409           return NK_Constant_Narrowing;
410         }
411       } else {
412         return NK_Variable_Narrowing;
413       }
414     }
415     return NK_Not_Narrowing;
416 
417   // -- from an integer type or unscoped enumeration type to an integer type
418   //    that cannot represent all the values of the original type, except where
419   //    the source is a constant expression and the actual value after
420   //    conversion will fit into the target type and will produce the original
421   //    value when converted back to the original type.
422   case ICK_Integral_Conversion:
423   IntegralConversion: {
424     assert(FromType->isIntegralOrUnscopedEnumerationType());
425     assert(ToType->isIntegralOrUnscopedEnumerationType());
426     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
427     const unsigned FromWidth = Ctx.getIntWidth(FromType);
428     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
429     const unsigned ToWidth = Ctx.getIntWidth(ToType);
430 
431     if (FromWidth > ToWidth ||
432         (FromWidth == ToWidth && FromSigned != ToSigned) ||
433         (FromSigned && !ToSigned)) {
434       // Not all values of FromType can be represented in ToType.
435       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
436 
437       // If it's value-dependent, we can't tell whether it's narrowing.
438       if (Initializer->isValueDependent())
439         return NK_Dependent_Narrowing;
440 
441       Optional<llvm::APSInt> OptInitializerValue;
442       if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) {
443         // Such conversions on variables are always narrowing.
444         return NK_Variable_Narrowing;
445       }
446       llvm::APSInt &InitializerValue = *OptInitializerValue;
447       bool Narrowing = false;
448       if (FromWidth < ToWidth) {
449         // Negative -> unsigned is narrowing. Otherwise, more bits is never
450         // narrowing.
451         if (InitializerValue.isSigned() && InitializerValue.isNegative())
452           Narrowing = true;
453       } else {
454         // Add a bit to the InitializerValue so we don't have to worry about
455         // signed vs. unsigned comparisons.
456         InitializerValue = InitializerValue.extend(
457           InitializerValue.getBitWidth() + 1);
458         // Convert the initializer to and from the target width and signed-ness.
459         llvm::APSInt ConvertedValue = InitializerValue;
460         ConvertedValue = ConvertedValue.trunc(ToWidth);
461         ConvertedValue.setIsSigned(ToSigned);
462         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
463         ConvertedValue.setIsSigned(InitializerValue.isSigned());
464         // If the result is different, this was a narrowing conversion.
465         if (ConvertedValue != InitializerValue)
466           Narrowing = true;
467       }
468       if (Narrowing) {
469         ConstantType = Initializer->getType();
470         ConstantValue = APValue(InitializerValue);
471         return NK_Constant_Narrowing;
472       }
473     }
474     return NK_Not_Narrowing;
475   }
476 
477   default:
478     // Other kinds of conversions are not narrowings.
479     return NK_Not_Narrowing;
480   }
481 }
482 
483 /// dump - Print this standard conversion sequence to standard
484 /// error. Useful for debugging overloading issues.
485 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
486   raw_ostream &OS = llvm::errs();
487   bool PrintedSomething = false;
488   if (First != ICK_Identity) {
489     OS << GetImplicitConversionName(First);
490     PrintedSomething = true;
491   }
492 
493   if (Second != ICK_Identity) {
494     if (PrintedSomething) {
495       OS << " -> ";
496     }
497     OS << GetImplicitConversionName(Second);
498 
499     if (CopyConstructor) {
500       OS << " (by copy constructor)";
501     } else if (DirectBinding) {
502       OS << " (direct reference binding)";
503     } else if (ReferenceBinding) {
504       OS << " (reference binding)";
505     }
506     PrintedSomething = true;
507   }
508 
509   if (Third != ICK_Identity) {
510     if (PrintedSomething) {
511       OS << " -> ";
512     }
513     OS << GetImplicitConversionName(Third);
514     PrintedSomething = true;
515   }
516 
517   if (!PrintedSomething) {
518     OS << "No conversions required";
519   }
520 }
521 
522 /// dump - Print this user-defined conversion sequence to standard
523 /// error. Useful for debugging overloading issues.
524 void UserDefinedConversionSequence::dump() const {
525   raw_ostream &OS = llvm::errs();
526   if (Before.First || Before.Second || Before.Third) {
527     Before.dump();
528     OS << " -> ";
529   }
530   if (ConversionFunction)
531     OS << '\'' << *ConversionFunction << '\'';
532   else
533     OS << "aggregate initialization";
534   if (After.First || After.Second || After.Third) {
535     OS << " -> ";
536     After.dump();
537   }
538 }
539 
540 /// dump - Print this implicit conversion sequence to standard
541 /// error. Useful for debugging overloading issues.
542 void ImplicitConversionSequence::dump() const {
543   raw_ostream &OS = llvm::errs();
544   if (hasInitializerListContainerType())
545     OS << "Worst list element conversion: ";
546   switch (ConversionKind) {
547   case StandardConversion:
548     OS << "Standard conversion: ";
549     Standard.dump();
550     break;
551   case UserDefinedConversion:
552     OS << "User-defined conversion: ";
553     UserDefined.dump();
554     break;
555   case EllipsisConversion:
556     OS << "Ellipsis conversion";
557     break;
558   case AmbiguousConversion:
559     OS << "Ambiguous conversion";
560     break;
561   case BadConversion:
562     OS << "Bad conversion";
563     break;
564   }
565 
566   OS << "\n";
567 }
568 
569 void AmbiguousConversionSequence::construct() {
570   new (&conversions()) ConversionSet();
571 }
572 
573 void AmbiguousConversionSequence::destruct() {
574   conversions().~ConversionSet();
575 }
576 
577 void
578 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
579   FromTypePtr = O.FromTypePtr;
580   ToTypePtr = O.ToTypePtr;
581   new (&conversions()) ConversionSet(O.conversions());
582 }
583 
584 namespace {
585   // Structure used by DeductionFailureInfo to store
586   // template argument information.
587   struct DFIArguments {
588     TemplateArgument FirstArg;
589     TemplateArgument SecondArg;
590   };
591   // Structure used by DeductionFailureInfo to store
592   // template parameter and template argument information.
593   struct DFIParamWithArguments : DFIArguments {
594     TemplateParameter Param;
595   };
596   // Structure used by DeductionFailureInfo to store template argument
597   // information and the index of the problematic call argument.
598   struct DFIDeducedMismatchArgs : DFIArguments {
599     TemplateArgumentList *TemplateArgs;
600     unsigned CallArgIndex;
601   };
602   // Structure used by DeductionFailureInfo to store information about
603   // unsatisfied constraints.
604   struct CNSInfo {
605     TemplateArgumentList *TemplateArgs;
606     ConstraintSatisfaction Satisfaction;
607   };
608 }
609 
610 /// Convert from Sema's representation of template deduction information
611 /// to the form used in overload-candidate information.
612 DeductionFailureInfo
613 clang::MakeDeductionFailureInfo(ASTContext &Context,
614                                 Sema::TemplateDeductionResult TDK,
615                                 TemplateDeductionInfo &Info) {
616   DeductionFailureInfo Result;
617   Result.Result = static_cast<unsigned>(TDK);
618   Result.HasDiagnostic = false;
619   switch (TDK) {
620   case Sema::TDK_Invalid:
621   case Sema::TDK_InstantiationDepth:
622   case Sema::TDK_TooManyArguments:
623   case Sema::TDK_TooFewArguments:
624   case Sema::TDK_MiscellaneousDeductionFailure:
625   case Sema::TDK_CUDATargetMismatch:
626     Result.Data = nullptr;
627     break;
628 
629   case Sema::TDK_Incomplete:
630   case Sema::TDK_InvalidExplicitArguments:
631     Result.Data = Info.Param.getOpaqueValue();
632     break;
633 
634   case Sema::TDK_DeducedMismatch:
635   case Sema::TDK_DeducedMismatchNested: {
636     // FIXME: Should allocate from normal heap so that we can free this later.
637     auto *Saved = new (Context) DFIDeducedMismatchArgs;
638     Saved->FirstArg = Info.FirstArg;
639     Saved->SecondArg = Info.SecondArg;
640     Saved->TemplateArgs = Info.take();
641     Saved->CallArgIndex = Info.CallArgIndex;
642     Result.Data = Saved;
643     break;
644   }
645 
646   case Sema::TDK_NonDeducedMismatch: {
647     // FIXME: Should allocate from normal heap so that we can free this later.
648     DFIArguments *Saved = new (Context) DFIArguments;
649     Saved->FirstArg = Info.FirstArg;
650     Saved->SecondArg = Info.SecondArg;
651     Result.Data = Saved;
652     break;
653   }
654 
655   case Sema::TDK_IncompletePack:
656     // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
657   case Sema::TDK_Inconsistent:
658   case Sema::TDK_Underqualified: {
659     // FIXME: Should allocate from normal heap so that we can free this later.
660     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
661     Saved->Param = Info.Param;
662     Saved->FirstArg = Info.FirstArg;
663     Saved->SecondArg = Info.SecondArg;
664     Result.Data = Saved;
665     break;
666   }
667 
668   case Sema::TDK_SubstitutionFailure:
669     Result.Data = Info.take();
670     if (Info.hasSFINAEDiagnostic()) {
671       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
672           SourceLocation(), PartialDiagnostic::NullDiagnostic());
673       Info.takeSFINAEDiagnostic(*Diag);
674       Result.HasDiagnostic = true;
675     }
676     break;
677 
678   case Sema::TDK_ConstraintsNotSatisfied: {
679     CNSInfo *Saved = new (Context) CNSInfo;
680     Saved->TemplateArgs = Info.take();
681     Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
682     Result.Data = Saved;
683     break;
684   }
685 
686   case Sema::TDK_Success:
687   case Sema::TDK_NonDependentConversionFailure:
688     llvm_unreachable("not a deduction failure");
689   }
690 
691   return Result;
692 }
693 
694 void DeductionFailureInfo::Destroy() {
695   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
696   case Sema::TDK_Success:
697   case Sema::TDK_Invalid:
698   case Sema::TDK_InstantiationDepth:
699   case Sema::TDK_Incomplete:
700   case Sema::TDK_TooManyArguments:
701   case Sema::TDK_TooFewArguments:
702   case Sema::TDK_InvalidExplicitArguments:
703   case Sema::TDK_CUDATargetMismatch:
704   case Sema::TDK_NonDependentConversionFailure:
705     break;
706 
707   case Sema::TDK_IncompletePack:
708   case Sema::TDK_Inconsistent:
709   case Sema::TDK_Underqualified:
710   case Sema::TDK_DeducedMismatch:
711   case Sema::TDK_DeducedMismatchNested:
712   case Sema::TDK_NonDeducedMismatch:
713     // FIXME: Destroy the data?
714     Data = nullptr;
715     break;
716 
717   case Sema::TDK_SubstitutionFailure:
718     // FIXME: Destroy the template argument list?
719     Data = nullptr;
720     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
721       Diag->~PartialDiagnosticAt();
722       HasDiagnostic = false;
723     }
724     break;
725 
726   case Sema::TDK_ConstraintsNotSatisfied:
727     // FIXME: Destroy the template argument list?
728     Data = nullptr;
729     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
730       Diag->~PartialDiagnosticAt();
731       HasDiagnostic = false;
732     }
733     break;
734 
735   // Unhandled
736   case Sema::TDK_MiscellaneousDeductionFailure:
737     break;
738   }
739 }
740 
741 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
742   if (HasDiagnostic)
743     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
744   return nullptr;
745 }
746 
747 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
748   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
749   case Sema::TDK_Success:
750   case Sema::TDK_Invalid:
751   case Sema::TDK_InstantiationDepth:
752   case Sema::TDK_TooManyArguments:
753   case Sema::TDK_TooFewArguments:
754   case Sema::TDK_SubstitutionFailure:
755   case Sema::TDK_DeducedMismatch:
756   case Sema::TDK_DeducedMismatchNested:
757   case Sema::TDK_NonDeducedMismatch:
758   case Sema::TDK_CUDATargetMismatch:
759   case Sema::TDK_NonDependentConversionFailure:
760   case Sema::TDK_ConstraintsNotSatisfied:
761     return TemplateParameter();
762 
763   case Sema::TDK_Incomplete:
764   case Sema::TDK_InvalidExplicitArguments:
765     return TemplateParameter::getFromOpaqueValue(Data);
766 
767   case Sema::TDK_IncompletePack:
768   case Sema::TDK_Inconsistent:
769   case Sema::TDK_Underqualified:
770     return static_cast<DFIParamWithArguments*>(Data)->Param;
771 
772   // Unhandled
773   case Sema::TDK_MiscellaneousDeductionFailure:
774     break;
775   }
776 
777   return TemplateParameter();
778 }
779 
780 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
781   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
782   case Sema::TDK_Success:
783   case Sema::TDK_Invalid:
784   case Sema::TDK_InstantiationDepth:
785   case Sema::TDK_TooManyArguments:
786   case Sema::TDK_TooFewArguments:
787   case Sema::TDK_Incomplete:
788   case Sema::TDK_IncompletePack:
789   case Sema::TDK_InvalidExplicitArguments:
790   case Sema::TDK_Inconsistent:
791   case Sema::TDK_Underqualified:
792   case Sema::TDK_NonDeducedMismatch:
793   case Sema::TDK_CUDATargetMismatch:
794   case Sema::TDK_NonDependentConversionFailure:
795     return nullptr;
796 
797   case Sema::TDK_DeducedMismatch:
798   case Sema::TDK_DeducedMismatchNested:
799     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
800 
801   case Sema::TDK_SubstitutionFailure:
802     return static_cast<TemplateArgumentList*>(Data);
803 
804   case Sema::TDK_ConstraintsNotSatisfied:
805     return static_cast<CNSInfo*>(Data)->TemplateArgs;
806 
807   // Unhandled
808   case Sema::TDK_MiscellaneousDeductionFailure:
809     break;
810   }
811 
812   return nullptr;
813 }
814 
815 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
816   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
817   case Sema::TDK_Success:
818   case Sema::TDK_Invalid:
819   case Sema::TDK_InstantiationDepth:
820   case Sema::TDK_Incomplete:
821   case Sema::TDK_TooManyArguments:
822   case Sema::TDK_TooFewArguments:
823   case Sema::TDK_InvalidExplicitArguments:
824   case Sema::TDK_SubstitutionFailure:
825   case Sema::TDK_CUDATargetMismatch:
826   case Sema::TDK_NonDependentConversionFailure:
827   case Sema::TDK_ConstraintsNotSatisfied:
828     return nullptr;
829 
830   case Sema::TDK_IncompletePack:
831   case Sema::TDK_Inconsistent:
832   case Sema::TDK_Underqualified:
833   case Sema::TDK_DeducedMismatch:
834   case Sema::TDK_DeducedMismatchNested:
835   case Sema::TDK_NonDeducedMismatch:
836     return &static_cast<DFIArguments*>(Data)->FirstArg;
837 
838   // Unhandled
839   case Sema::TDK_MiscellaneousDeductionFailure:
840     break;
841   }
842 
843   return nullptr;
844 }
845 
846 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
847   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
848   case Sema::TDK_Success:
849   case Sema::TDK_Invalid:
850   case Sema::TDK_InstantiationDepth:
851   case Sema::TDK_Incomplete:
852   case Sema::TDK_IncompletePack:
853   case Sema::TDK_TooManyArguments:
854   case Sema::TDK_TooFewArguments:
855   case Sema::TDK_InvalidExplicitArguments:
856   case Sema::TDK_SubstitutionFailure:
857   case Sema::TDK_CUDATargetMismatch:
858   case Sema::TDK_NonDependentConversionFailure:
859   case Sema::TDK_ConstraintsNotSatisfied:
860     return nullptr;
861 
862   case Sema::TDK_Inconsistent:
863   case Sema::TDK_Underqualified:
864   case Sema::TDK_DeducedMismatch:
865   case Sema::TDK_DeducedMismatchNested:
866   case Sema::TDK_NonDeducedMismatch:
867     return &static_cast<DFIArguments*>(Data)->SecondArg;
868 
869   // Unhandled
870   case Sema::TDK_MiscellaneousDeductionFailure:
871     break;
872   }
873 
874   return nullptr;
875 }
876 
877 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
878   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
879   case Sema::TDK_DeducedMismatch:
880   case Sema::TDK_DeducedMismatchNested:
881     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
882 
883   default:
884     return llvm::None;
885   }
886 }
887 
888 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
889     OverloadedOperatorKind Op) {
890   if (!AllowRewrittenCandidates)
891     return false;
892   return Op == OO_EqualEqual || Op == OO_Spaceship;
893 }
894 
895 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
896     ASTContext &Ctx, const FunctionDecl *FD) {
897   if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator()))
898     return false;
899   // Don't bother adding a reversed candidate that can never be a better
900   // match than the non-reversed version.
901   return FD->getNumParams() != 2 ||
902          !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
903                                      FD->getParamDecl(1)->getType()) ||
904          FD->hasAttr<EnableIfAttr>();
905 }
906 
907 void OverloadCandidateSet::destroyCandidates() {
908   for (iterator i = begin(), e = end(); i != e; ++i) {
909     for (auto &C : i->Conversions)
910       C.~ImplicitConversionSequence();
911     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
912       i->DeductionFailure.Destroy();
913   }
914 }
915 
916 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
917   destroyCandidates();
918   SlabAllocator.Reset();
919   NumInlineBytesUsed = 0;
920   Candidates.clear();
921   Functions.clear();
922   Kind = CSK;
923 }
924 
925 namespace {
926   class UnbridgedCastsSet {
927     struct Entry {
928       Expr **Addr;
929       Expr *Saved;
930     };
931     SmallVector<Entry, 2> Entries;
932 
933   public:
934     void save(Sema &S, Expr *&E) {
935       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
936       Entry entry = { &E, E };
937       Entries.push_back(entry);
938       E = S.stripARCUnbridgedCast(E);
939     }
940 
941     void restore() {
942       for (SmallVectorImpl<Entry>::iterator
943              i = Entries.begin(), e = Entries.end(); i != e; ++i)
944         *i->Addr = i->Saved;
945     }
946   };
947 }
948 
949 /// checkPlaceholderForOverload - Do any interesting placeholder-like
950 /// preprocessing on the given expression.
951 ///
952 /// \param unbridgedCasts a collection to which to add unbridged casts;
953 ///   without this, they will be immediately diagnosed as errors
954 ///
955 /// Return true on unrecoverable error.
956 static bool
957 checkPlaceholderForOverload(Sema &S, Expr *&E,
958                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
959   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
960     // We can't handle overloaded expressions here because overload
961     // resolution might reasonably tweak them.
962     if (placeholder->getKind() == BuiltinType::Overload) return false;
963 
964     // If the context potentially accepts unbridged ARC casts, strip
965     // the unbridged cast and add it to the collection for later restoration.
966     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
967         unbridgedCasts) {
968       unbridgedCasts->save(S, E);
969       return false;
970     }
971 
972     // Go ahead and check everything else.
973     ExprResult result = S.CheckPlaceholderExpr(E);
974     if (result.isInvalid())
975       return true;
976 
977     E = result.get();
978     return false;
979   }
980 
981   // Nothing to do.
982   return false;
983 }
984 
985 /// checkArgPlaceholdersForOverload - Check a set of call operands for
986 /// placeholders.
987 static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args,
988                                             UnbridgedCastsSet &unbridged) {
989   for (unsigned i = 0, e = Args.size(); i != e; ++i)
990     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
991       return true;
992 
993   return false;
994 }
995 
996 /// Determine whether the given New declaration is an overload of the
997 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
998 /// New and Old cannot be overloaded, e.g., if New has the same signature as
999 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
1000 /// functions (or function templates) at all. When it does return Ovl_Match or
1001 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1002 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1003 /// declaration.
1004 ///
1005 /// Example: Given the following input:
1006 ///
1007 ///   void f(int, float); // #1
1008 ///   void f(int, int); // #2
1009 ///   int f(int, int); // #3
1010 ///
1011 /// When we process #1, there is no previous declaration of "f", so IsOverload
1012 /// will not be used.
1013 ///
1014 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1015 /// the parameter types, we see that #1 and #2 are overloaded (since they have
1016 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1017 /// unchanged.
1018 ///
1019 /// When we process #3, Old is an overload set containing #1 and #2. We compare
1020 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1021 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1022 /// functions are not part of the signature), IsOverload returns Ovl_Match and
1023 /// MatchedDecl will be set to point to the FunctionDecl for #2.
1024 ///
1025 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1026 /// by a using declaration. The rules for whether to hide shadow declarations
1027 /// ignore some properties which otherwise figure into a function template's
1028 /// signature.
1029 Sema::OverloadKind
1030 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1031                     NamedDecl *&Match, bool NewIsUsingDecl) {
1032   for (LookupResult::iterator I = Old.begin(), E = Old.end();
1033          I != E; ++I) {
1034     NamedDecl *OldD = *I;
1035 
1036     bool OldIsUsingDecl = false;
1037     if (isa<UsingShadowDecl>(OldD)) {
1038       OldIsUsingDecl = true;
1039 
1040       // We can always introduce two using declarations into the same
1041       // context, even if they have identical signatures.
1042       if (NewIsUsingDecl) continue;
1043 
1044       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1045     }
1046 
1047     // A using-declaration does not conflict with another declaration
1048     // if one of them is hidden.
1049     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1050       continue;
1051 
1052     // If either declaration was introduced by a using declaration,
1053     // we'll need to use slightly different rules for matching.
1054     // Essentially, these rules are the normal rules, except that
1055     // function templates hide function templates with different
1056     // return types or template parameter lists.
1057     bool UseMemberUsingDeclRules =
1058       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1059       !New->getFriendObjectKind();
1060 
1061     if (FunctionDecl *OldF = OldD->getAsFunction()) {
1062       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1063         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1064           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1065           continue;
1066         }
1067 
1068         if (!isa<FunctionTemplateDecl>(OldD) &&
1069             !shouldLinkPossiblyHiddenDecl(*I, New))
1070           continue;
1071 
1072         Match = *I;
1073         return Ovl_Match;
1074       }
1075 
1076       // Builtins that have custom typechecking or have a reference should
1077       // not be overloadable or redeclarable.
1078       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1079         Match = *I;
1080         return Ovl_NonFunction;
1081       }
1082     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1083       // We can overload with these, which can show up when doing
1084       // redeclaration checks for UsingDecls.
1085       assert(Old.getLookupKind() == LookupUsingDeclName);
1086     } else if (isa<TagDecl>(OldD)) {
1087       // We can always overload with tags by hiding them.
1088     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1089       // Optimistically assume that an unresolved using decl will
1090       // overload; if it doesn't, we'll have to diagnose during
1091       // template instantiation.
1092       //
1093       // Exception: if the scope is dependent and this is not a class
1094       // member, the using declaration can only introduce an enumerator.
1095       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1096         Match = *I;
1097         return Ovl_NonFunction;
1098       }
1099     } else {
1100       // (C++ 13p1):
1101       //   Only function declarations can be overloaded; object and type
1102       //   declarations cannot be overloaded.
1103       Match = *I;
1104       return Ovl_NonFunction;
1105     }
1106   }
1107 
1108   // C++ [temp.friend]p1:
1109   //   For a friend function declaration that is not a template declaration:
1110   //    -- if the name of the friend is a qualified or unqualified template-id,
1111   //       [...], otherwise
1112   //    -- if the name of the friend is a qualified-id and a matching
1113   //       non-template function is found in the specified class or namespace,
1114   //       the friend declaration refers to that function, otherwise,
1115   //    -- if the name of the friend is a qualified-id and a matching function
1116   //       template is found in the specified class or namespace, the friend
1117   //       declaration refers to the deduced specialization of that function
1118   //       template, otherwise
1119   //    -- the name shall be an unqualified-id [...]
1120   // If we get here for a qualified friend declaration, we've just reached the
1121   // third bullet. If the type of the friend is dependent, skip this lookup
1122   // until instantiation.
1123   if (New->getFriendObjectKind() && New->getQualifier() &&
1124       !New->getDescribedFunctionTemplate() &&
1125       !New->getDependentSpecializationInfo() &&
1126       !New->getType()->isDependentType()) {
1127     LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1128     TemplateSpecResult.addAllDecls(Old);
1129     if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1130                                             /*QualifiedFriend*/true)) {
1131       New->setInvalidDecl();
1132       return Ovl_Overload;
1133     }
1134 
1135     Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1136     return Ovl_Match;
1137   }
1138 
1139   return Ovl_Overload;
1140 }
1141 
1142 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1143                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs,
1144                       bool ConsiderRequiresClauses) {
1145   // C++ [basic.start.main]p2: This function shall not be overloaded.
1146   if (New->isMain())
1147     return false;
1148 
1149   // MSVCRT user defined entry points cannot be overloaded.
1150   if (New->isMSVCRTEntryPoint())
1151     return false;
1152 
1153   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1154   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1155 
1156   // C++ [temp.fct]p2:
1157   //   A function template can be overloaded with other function templates
1158   //   and with normal (non-template) functions.
1159   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1160     return true;
1161 
1162   // Is the function New an overload of the function Old?
1163   QualType OldQType = Context.getCanonicalType(Old->getType());
1164   QualType NewQType = Context.getCanonicalType(New->getType());
1165 
1166   // Compare the signatures (C++ 1.3.10) of the two functions to
1167   // determine whether they are overloads. If we find any mismatch
1168   // in the signature, they are overloads.
1169 
1170   // If either of these functions is a K&R-style function (no
1171   // prototype), then we consider them to have matching signatures.
1172   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1173       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1174     return false;
1175 
1176   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1177   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1178 
1179   // The signature of a function includes the types of its
1180   // parameters (C++ 1.3.10), which includes the presence or absence
1181   // of the ellipsis; see C++ DR 357).
1182   if (OldQType != NewQType &&
1183       (OldType->getNumParams() != NewType->getNumParams() ||
1184        OldType->isVariadic() != NewType->isVariadic() ||
1185        !FunctionParamTypesAreEqual(OldType, NewType)))
1186     return true;
1187 
1188   // C++ [temp.over.link]p4:
1189   //   The signature of a function template consists of its function
1190   //   signature, its return type and its template parameter list. The names
1191   //   of the template parameters are significant only for establishing the
1192   //   relationship between the template parameters and the rest of the
1193   //   signature.
1194   //
1195   // We check the return type and template parameter lists for function
1196   // templates first; the remaining checks follow.
1197   //
1198   // However, we don't consider either of these when deciding whether
1199   // a member introduced by a shadow declaration is hidden.
1200   if (!UseMemberUsingDeclRules && NewTemplate &&
1201       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1202                                        OldTemplate->getTemplateParameters(),
1203                                        false, TPL_TemplateMatch) ||
1204        !Context.hasSameType(Old->getDeclaredReturnType(),
1205                             New->getDeclaredReturnType())))
1206     return true;
1207 
1208   // If the function is a class member, its signature includes the
1209   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1210   //
1211   // As part of this, also check whether one of the member functions
1212   // is static, in which case they are not overloads (C++
1213   // 13.1p2). While not part of the definition of the signature,
1214   // this check is important to determine whether these functions
1215   // can be overloaded.
1216   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1217   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1218   if (OldMethod && NewMethod &&
1219       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1220     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1221       if (!UseMemberUsingDeclRules &&
1222           (OldMethod->getRefQualifier() == RQ_None ||
1223            NewMethod->getRefQualifier() == RQ_None)) {
1224         // C++0x [over.load]p2:
1225         //   - Member function declarations with the same name and the same
1226         //     parameter-type-list as well as member function template
1227         //     declarations with the same name, the same parameter-type-list, and
1228         //     the same template parameter lists cannot be overloaded if any of
1229         //     them, but not all, have a ref-qualifier (8.3.5).
1230         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1231           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1232         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1233       }
1234       return true;
1235     }
1236 
1237     // We may not have applied the implicit const for a constexpr member
1238     // function yet (because we haven't yet resolved whether this is a static
1239     // or non-static member function). Add it now, on the assumption that this
1240     // is a redeclaration of OldMethod.
1241     auto OldQuals = OldMethod->getMethodQualifiers();
1242     auto NewQuals = NewMethod->getMethodQualifiers();
1243     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1244         !isa<CXXConstructorDecl>(NewMethod))
1245       NewQuals.addConst();
1246     // We do not allow overloading based off of '__restrict'.
1247     OldQuals.removeRestrict();
1248     NewQuals.removeRestrict();
1249     if (OldQuals != NewQuals)
1250       return true;
1251   }
1252 
1253   // Though pass_object_size is placed on parameters and takes an argument, we
1254   // consider it to be a function-level modifier for the sake of function
1255   // identity. Either the function has one or more parameters with
1256   // pass_object_size or it doesn't.
1257   if (functionHasPassObjectSizeParams(New) !=
1258       functionHasPassObjectSizeParams(Old))
1259     return true;
1260 
1261   // enable_if attributes are an order-sensitive part of the signature.
1262   for (specific_attr_iterator<EnableIfAttr>
1263          NewI = New->specific_attr_begin<EnableIfAttr>(),
1264          NewE = New->specific_attr_end<EnableIfAttr>(),
1265          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1266          OldE = Old->specific_attr_end<EnableIfAttr>();
1267        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1268     if (NewI == NewE || OldI == OldE)
1269       return true;
1270     llvm::FoldingSetNodeID NewID, OldID;
1271     NewI->getCond()->Profile(NewID, Context, true);
1272     OldI->getCond()->Profile(OldID, Context, true);
1273     if (NewID != OldID)
1274       return true;
1275   }
1276 
1277   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1278     // Don't allow overloading of destructors.  (In theory we could, but it
1279     // would be a giant change to clang.)
1280     if (!isa<CXXDestructorDecl>(New)) {
1281       CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1282                          OldTarget = IdentifyCUDATarget(Old);
1283       if (NewTarget != CFT_InvalidTarget) {
1284         assert((OldTarget != CFT_InvalidTarget) &&
1285                "Unexpected invalid target.");
1286 
1287         // Allow overloading of functions with same signature and different CUDA
1288         // target attributes.
1289         if (NewTarget != OldTarget)
1290           return true;
1291       }
1292     }
1293   }
1294 
1295   if (ConsiderRequiresClauses) {
1296     Expr *NewRC = New->getTrailingRequiresClause(),
1297          *OldRC = Old->getTrailingRequiresClause();
1298     if ((NewRC != nullptr) != (OldRC != nullptr))
1299       // RC are most certainly different - these are overloads.
1300       return true;
1301 
1302     if (NewRC) {
1303       llvm::FoldingSetNodeID NewID, OldID;
1304       NewRC->Profile(NewID, Context, /*Canonical=*/true);
1305       OldRC->Profile(OldID, Context, /*Canonical=*/true);
1306       if (NewID != OldID)
1307         // RCs are not equivalent - these are overloads.
1308         return true;
1309     }
1310   }
1311 
1312   // The signatures match; this is not an overload.
1313   return false;
1314 }
1315 
1316 /// Tries a user-defined conversion from From to ToType.
1317 ///
1318 /// Produces an implicit conversion sequence for when a standard conversion
1319 /// is not an option. See TryImplicitConversion for more information.
1320 static ImplicitConversionSequence
1321 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1322                          bool SuppressUserConversions,
1323                          AllowedExplicit AllowExplicit,
1324                          bool InOverloadResolution,
1325                          bool CStyle,
1326                          bool AllowObjCWritebackConversion,
1327                          bool AllowObjCConversionOnExplicit) {
1328   ImplicitConversionSequence ICS;
1329 
1330   if (SuppressUserConversions) {
1331     // We're not in the case above, so there is no conversion that
1332     // we can perform.
1333     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1334     return ICS;
1335   }
1336 
1337   // Attempt user-defined conversion.
1338   OverloadCandidateSet Conversions(From->getExprLoc(),
1339                                    OverloadCandidateSet::CSK_Normal);
1340   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1341                                   Conversions, AllowExplicit,
1342                                   AllowObjCConversionOnExplicit)) {
1343   case OR_Success:
1344   case OR_Deleted:
1345     ICS.setUserDefined();
1346     // C++ [over.ics.user]p4:
1347     //   A conversion of an expression of class type to the same class
1348     //   type is given Exact Match rank, and a conversion of an
1349     //   expression of class type to a base class of that type is
1350     //   given Conversion rank, in spite of the fact that a copy
1351     //   constructor (i.e., a user-defined conversion function) is
1352     //   called for those cases.
1353     if (CXXConstructorDecl *Constructor
1354           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1355       QualType FromCanon
1356         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1357       QualType ToCanon
1358         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1359       if (Constructor->isCopyConstructor() &&
1360           (FromCanon == ToCanon ||
1361            S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1362         // Turn this into a "standard" conversion sequence, so that it
1363         // gets ranked with standard conversion sequences.
1364         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1365         ICS.setStandard();
1366         ICS.Standard.setAsIdentityConversion();
1367         ICS.Standard.setFromType(From->getType());
1368         ICS.Standard.setAllToTypes(ToType);
1369         ICS.Standard.CopyConstructor = Constructor;
1370         ICS.Standard.FoundCopyConstructor = Found;
1371         if (ToCanon != FromCanon)
1372           ICS.Standard.Second = ICK_Derived_To_Base;
1373       }
1374     }
1375     break;
1376 
1377   case OR_Ambiguous:
1378     ICS.setAmbiguous();
1379     ICS.Ambiguous.setFromType(From->getType());
1380     ICS.Ambiguous.setToType(ToType);
1381     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1382          Cand != Conversions.end(); ++Cand)
1383       if (Cand->Best)
1384         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1385     break;
1386 
1387     // Fall through.
1388   case OR_No_Viable_Function:
1389     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1390     break;
1391   }
1392 
1393   return ICS;
1394 }
1395 
1396 /// TryImplicitConversion - Attempt to perform an implicit conversion
1397 /// from the given expression (Expr) to the given type (ToType). This
1398 /// function returns an implicit conversion sequence that can be used
1399 /// to perform the initialization. Given
1400 ///
1401 ///   void f(float f);
1402 ///   void g(int i) { f(i); }
1403 ///
1404 /// this routine would produce an implicit conversion sequence to
1405 /// describe the initialization of f from i, which will be a standard
1406 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1407 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1408 //
1409 /// Note that this routine only determines how the conversion can be
1410 /// performed; it does not actually perform the conversion. As such,
1411 /// it will not produce any diagnostics if no conversion is available,
1412 /// but will instead return an implicit conversion sequence of kind
1413 /// "BadConversion".
1414 ///
1415 /// If @p SuppressUserConversions, then user-defined conversions are
1416 /// not permitted.
1417 /// If @p AllowExplicit, then explicit user-defined conversions are
1418 /// permitted.
1419 ///
1420 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1421 /// writeback conversion, which allows __autoreleasing id* parameters to
1422 /// be initialized with __strong id* or __weak id* arguments.
1423 static ImplicitConversionSequence
1424 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1425                       bool SuppressUserConversions,
1426                       AllowedExplicit AllowExplicit,
1427                       bool InOverloadResolution,
1428                       bool CStyle,
1429                       bool AllowObjCWritebackConversion,
1430                       bool AllowObjCConversionOnExplicit) {
1431   ImplicitConversionSequence ICS;
1432   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1433                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1434     ICS.setStandard();
1435     return ICS;
1436   }
1437 
1438   if (!S.getLangOpts().CPlusPlus) {
1439     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1440     return ICS;
1441   }
1442 
1443   // C++ [over.ics.user]p4:
1444   //   A conversion of an expression of class type to the same class
1445   //   type is given Exact Match rank, and a conversion of an
1446   //   expression of class type to a base class of that type is
1447   //   given Conversion rank, in spite of the fact that a copy/move
1448   //   constructor (i.e., a user-defined conversion function) is
1449   //   called for those cases.
1450   QualType FromType = From->getType();
1451   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1452       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1453        S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1454     ICS.setStandard();
1455     ICS.Standard.setAsIdentityConversion();
1456     ICS.Standard.setFromType(FromType);
1457     ICS.Standard.setAllToTypes(ToType);
1458 
1459     // We don't actually check at this point whether there is a valid
1460     // copy/move constructor, since overloading just assumes that it
1461     // exists. When we actually perform initialization, we'll find the
1462     // appropriate constructor to copy the returned object, if needed.
1463     ICS.Standard.CopyConstructor = nullptr;
1464 
1465     // Determine whether this is considered a derived-to-base conversion.
1466     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1467       ICS.Standard.Second = ICK_Derived_To_Base;
1468 
1469     return ICS;
1470   }
1471 
1472   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1473                                   AllowExplicit, InOverloadResolution, CStyle,
1474                                   AllowObjCWritebackConversion,
1475                                   AllowObjCConversionOnExplicit);
1476 }
1477 
1478 ImplicitConversionSequence
1479 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1480                             bool SuppressUserConversions,
1481                             AllowedExplicit AllowExplicit,
1482                             bool InOverloadResolution,
1483                             bool CStyle,
1484                             bool AllowObjCWritebackConversion) {
1485   return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1486                                  AllowExplicit, InOverloadResolution, CStyle,
1487                                  AllowObjCWritebackConversion,
1488                                  /*AllowObjCConversionOnExplicit=*/false);
1489 }
1490 
1491 /// PerformImplicitConversion - Perform an implicit conversion of the
1492 /// expression From to the type ToType. Returns the
1493 /// converted expression. Flavor is the kind of conversion we're
1494 /// performing, used in the error message. If @p AllowExplicit,
1495 /// explicit user-defined conversions are permitted.
1496 ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1497                                            AssignmentAction Action,
1498                                            bool AllowExplicit) {
1499   if (checkPlaceholderForOverload(*this, From))
1500     return ExprError();
1501 
1502   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1503   bool AllowObjCWritebackConversion
1504     = getLangOpts().ObjCAutoRefCount &&
1505       (Action == AA_Passing || Action == AA_Sending);
1506   if (getLangOpts().ObjC)
1507     CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1508                                       From->getType(), From);
1509   ImplicitConversionSequence ICS = ::TryImplicitConversion(
1510       *this, From, ToType,
1511       /*SuppressUserConversions=*/false,
1512       AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1513       /*InOverloadResolution=*/false,
1514       /*CStyle=*/false, AllowObjCWritebackConversion,
1515       /*AllowObjCConversionOnExplicit=*/false);
1516   return PerformImplicitConversion(From, ToType, ICS, Action);
1517 }
1518 
1519 /// Determine whether the conversion from FromType to ToType is a valid
1520 /// conversion that strips "noexcept" or "noreturn" off the nested function
1521 /// type.
1522 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1523                                 QualType &ResultTy) {
1524   if (Context.hasSameUnqualifiedType(FromType, ToType))
1525     return false;
1526 
1527   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1528   //                    or F(t noexcept) -> F(t)
1529   // where F adds one of the following at most once:
1530   //   - a pointer
1531   //   - a member pointer
1532   //   - a block pointer
1533   // Changes here need matching changes in FindCompositePointerType.
1534   CanQualType CanTo = Context.getCanonicalType(ToType);
1535   CanQualType CanFrom = Context.getCanonicalType(FromType);
1536   Type::TypeClass TyClass = CanTo->getTypeClass();
1537   if (TyClass != CanFrom->getTypeClass()) return false;
1538   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1539     if (TyClass == Type::Pointer) {
1540       CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1541       CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1542     } else if (TyClass == Type::BlockPointer) {
1543       CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1544       CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1545     } else if (TyClass == Type::MemberPointer) {
1546       auto ToMPT = CanTo.castAs<MemberPointerType>();
1547       auto FromMPT = CanFrom.castAs<MemberPointerType>();
1548       // A function pointer conversion cannot change the class of the function.
1549       if (ToMPT->getClass() != FromMPT->getClass())
1550         return false;
1551       CanTo = ToMPT->getPointeeType();
1552       CanFrom = FromMPT->getPointeeType();
1553     } else {
1554       return false;
1555     }
1556 
1557     TyClass = CanTo->getTypeClass();
1558     if (TyClass != CanFrom->getTypeClass()) return false;
1559     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1560       return false;
1561   }
1562 
1563   const auto *FromFn = cast<FunctionType>(CanFrom);
1564   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1565 
1566   const auto *ToFn = cast<FunctionType>(CanTo);
1567   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1568 
1569   bool Changed = false;
1570 
1571   // Drop 'noreturn' if not present in target type.
1572   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1573     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1574     Changed = true;
1575   }
1576 
1577   // Drop 'noexcept' if not present in target type.
1578   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1579     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1580     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1581       FromFn = cast<FunctionType>(
1582           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1583                                                    EST_None)
1584                  .getTypePtr());
1585       Changed = true;
1586     }
1587 
1588     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1589     // only if the ExtParameterInfo lists of the two function prototypes can be
1590     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1591     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1592     bool CanUseToFPT, CanUseFromFPT;
1593     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1594                                       CanUseFromFPT, NewParamInfos) &&
1595         CanUseToFPT && !CanUseFromFPT) {
1596       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1597       ExtInfo.ExtParameterInfos =
1598           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1599       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1600                                             FromFPT->getParamTypes(), ExtInfo);
1601       FromFn = QT->getAs<FunctionType>();
1602       Changed = true;
1603     }
1604   }
1605 
1606   if (!Changed)
1607     return false;
1608 
1609   assert(QualType(FromFn, 0).isCanonical());
1610   if (QualType(FromFn, 0) != CanTo) return false;
1611 
1612   ResultTy = ToType;
1613   return true;
1614 }
1615 
1616 /// Determine whether the conversion from FromType to ToType is a valid
1617 /// vector conversion.
1618 ///
1619 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1620 /// conversion.
1621 static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
1622                                ImplicitConversionKind &ICK, Expr *From,
1623                                bool InOverloadResolution) {
1624   // We need at least one of these types to be a vector type to have a vector
1625   // conversion.
1626   if (!ToType->isVectorType() && !FromType->isVectorType())
1627     return false;
1628 
1629   // Identical types require no conversions.
1630   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1631     return false;
1632 
1633   // There are no conversions between extended vector types, only identity.
1634   if (ToType->isExtVectorType()) {
1635     // There are no conversions between extended vector types other than the
1636     // identity conversion.
1637     if (FromType->isExtVectorType())
1638       return false;
1639 
1640     // Vector splat from any arithmetic type to a vector.
1641     if (FromType->isArithmeticType()) {
1642       ICK = ICK_Vector_Splat;
1643       return true;
1644     }
1645   }
1646 
1647   if (ToType->isSizelessBuiltinType() || FromType->isSizelessBuiltinType())
1648     if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
1649         S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
1650       ICK = ICK_SVE_Vector_Conversion;
1651       return true;
1652     }
1653 
1654   // We can perform the conversion between vector types in the following cases:
1655   // 1)vector types are equivalent AltiVec and GCC vector types
1656   // 2)lax vector conversions are permitted and the vector types are of the
1657   //   same size
1658   // 3)the destination type does not have the ARM MVE strict-polymorphism
1659   //   attribute, which inhibits lax vector conversion for overload resolution
1660   //   only
1661   if (ToType->isVectorType() && FromType->isVectorType()) {
1662     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1663         (S.isLaxVectorConversion(FromType, ToType) &&
1664          !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
1665       if (S.isLaxVectorConversion(FromType, ToType) &&
1666           S.anyAltivecTypes(FromType, ToType) &&
1667           !S.areSameVectorElemTypes(FromType, ToType) &&
1668           !InOverloadResolution) {
1669         S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
1670             << FromType << ToType;
1671       }
1672       ICK = ICK_Vector_Conversion;
1673       return true;
1674     }
1675   }
1676 
1677   return false;
1678 }
1679 
1680 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1681                                 bool InOverloadResolution,
1682                                 StandardConversionSequence &SCS,
1683                                 bool CStyle);
1684 
1685 /// IsStandardConversion - Determines whether there is a standard
1686 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1687 /// expression From to the type ToType. Standard conversion sequences
1688 /// only consider non-class types; for conversions that involve class
1689 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1690 /// contain the standard conversion sequence required to perform this
1691 /// conversion and this routine will return true. Otherwise, this
1692 /// routine will return false and the value of SCS is unspecified.
1693 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1694                                  bool InOverloadResolution,
1695                                  StandardConversionSequence &SCS,
1696                                  bool CStyle,
1697                                  bool AllowObjCWritebackConversion) {
1698   QualType FromType = From->getType();
1699 
1700   // Standard conversions (C++ [conv])
1701   SCS.setAsIdentityConversion();
1702   SCS.IncompatibleObjC = false;
1703   SCS.setFromType(FromType);
1704   SCS.CopyConstructor = nullptr;
1705 
1706   // There are no standard conversions for class types in C++, so
1707   // abort early. When overloading in C, however, we do permit them.
1708   if (S.getLangOpts().CPlusPlus &&
1709       (FromType->isRecordType() || ToType->isRecordType()))
1710     return false;
1711 
1712   // The first conversion can be an lvalue-to-rvalue conversion,
1713   // array-to-pointer conversion, or function-to-pointer conversion
1714   // (C++ 4p1).
1715 
1716   if (FromType == S.Context.OverloadTy) {
1717     DeclAccessPair AccessPair;
1718     if (FunctionDecl *Fn
1719           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1720                                                  AccessPair)) {
1721       // We were able to resolve the address of the overloaded function,
1722       // so we can convert to the type of that function.
1723       FromType = Fn->getType();
1724       SCS.setFromType(FromType);
1725 
1726       // we can sometimes resolve &foo<int> regardless of ToType, so check
1727       // if the type matches (identity) or we are converting to bool
1728       if (!S.Context.hasSameUnqualifiedType(
1729                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1730         QualType resultTy;
1731         // if the function type matches except for [[noreturn]], it's ok
1732         if (!S.IsFunctionConversion(FromType,
1733               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1734           // otherwise, only a boolean conversion is standard
1735           if (!ToType->isBooleanType())
1736             return false;
1737       }
1738 
1739       // Check if the "from" expression is taking the address of an overloaded
1740       // function and recompute the FromType accordingly. Take advantage of the
1741       // fact that non-static member functions *must* have such an address-of
1742       // expression.
1743       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1744       if (Method && !Method->isStatic()) {
1745         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1746                "Non-unary operator on non-static member address");
1747         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1748                == UO_AddrOf &&
1749                "Non-address-of operator on non-static member address");
1750         const Type *ClassType
1751           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1752         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1753       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1754         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1755                UO_AddrOf &&
1756                "Non-address-of operator for overloaded function expression");
1757         FromType = S.Context.getPointerType(FromType);
1758       }
1759     } else {
1760       return false;
1761     }
1762   }
1763   // Lvalue-to-rvalue conversion (C++11 4.1):
1764   //   A glvalue (3.10) of a non-function, non-array type T can
1765   //   be converted to a prvalue.
1766   bool argIsLValue = From->isGLValue();
1767   if (argIsLValue &&
1768       !FromType->isFunctionType() && !FromType->isArrayType() &&
1769       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1770     SCS.First = ICK_Lvalue_To_Rvalue;
1771 
1772     // C11 6.3.2.1p2:
1773     //   ... if the lvalue has atomic type, the value has the non-atomic version
1774     //   of the type of the lvalue ...
1775     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1776       FromType = Atomic->getValueType();
1777 
1778     // If T is a non-class type, the type of the rvalue is the
1779     // cv-unqualified version of T. Otherwise, the type of the rvalue
1780     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1781     // just strip the qualifiers because they don't matter.
1782     FromType = FromType.getUnqualifiedType();
1783   } else if (FromType->isArrayType()) {
1784     // Array-to-pointer conversion (C++ 4.2)
1785     SCS.First = ICK_Array_To_Pointer;
1786 
1787     // An lvalue or rvalue of type "array of N T" or "array of unknown
1788     // bound of T" can be converted to an rvalue of type "pointer to
1789     // T" (C++ 4.2p1).
1790     FromType = S.Context.getArrayDecayedType(FromType);
1791 
1792     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1793       // This conversion is deprecated in C++03 (D.4)
1794       SCS.DeprecatedStringLiteralToCharPtr = true;
1795 
1796       // For the purpose of ranking in overload resolution
1797       // (13.3.3.1.1), this conversion is considered an
1798       // array-to-pointer conversion followed by a qualification
1799       // conversion (4.4). (C++ 4.2p2)
1800       SCS.Second = ICK_Identity;
1801       SCS.Third = ICK_Qualification;
1802       SCS.QualificationIncludesObjCLifetime = false;
1803       SCS.setAllToTypes(FromType);
1804       return true;
1805     }
1806   } else if (FromType->isFunctionType() && argIsLValue) {
1807     // Function-to-pointer conversion (C++ 4.3).
1808     SCS.First = ICK_Function_To_Pointer;
1809 
1810     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1811       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1812         if (!S.checkAddressOfFunctionIsAvailable(FD))
1813           return false;
1814 
1815     // An lvalue of function type T can be converted to an rvalue of
1816     // type "pointer to T." The result is a pointer to the
1817     // function. (C++ 4.3p1).
1818     FromType = S.Context.getPointerType(FromType);
1819   } else {
1820     // We don't require any conversions for the first step.
1821     SCS.First = ICK_Identity;
1822   }
1823   SCS.setToType(0, FromType);
1824 
1825   // The second conversion can be an integral promotion, floating
1826   // point promotion, integral conversion, floating point conversion,
1827   // floating-integral conversion, pointer conversion,
1828   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1829   // For overloading in C, this can also be a "compatible-type"
1830   // conversion.
1831   bool IncompatibleObjC = false;
1832   ImplicitConversionKind SecondICK = ICK_Identity;
1833   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1834     // The unqualified versions of the types are the same: there's no
1835     // conversion to do.
1836     SCS.Second = ICK_Identity;
1837   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1838     // Integral promotion (C++ 4.5).
1839     SCS.Second = ICK_Integral_Promotion;
1840     FromType = ToType.getUnqualifiedType();
1841   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1842     // Floating point promotion (C++ 4.6).
1843     SCS.Second = ICK_Floating_Promotion;
1844     FromType = ToType.getUnqualifiedType();
1845   } else if (S.IsComplexPromotion(FromType, ToType)) {
1846     // Complex promotion (Clang extension)
1847     SCS.Second = ICK_Complex_Promotion;
1848     FromType = ToType.getUnqualifiedType();
1849   } else if (ToType->isBooleanType() &&
1850              (FromType->isArithmeticType() ||
1851               FromType->isAnyPointerType() ||
1852               FromType->isBlockPointerType() ||
1853               FromType->isMemberPointerType())) {
1854     // Boolean conversions (C++ 4.12).
1855     SCS.Second = ICK_Boolean_Conversion;
1856     FromType = S.Context.BoolTy;
1857   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1858              ToType->isIntegralType(S.Context)) {
1859     // Integral conversions (C++ 4.7).
1860     SCS.Second = ICK_Integral_Conversion;
1861     FromType = ToType.getUnqualifiedType();
1862   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1863     // Complex conversions (C99 6.3.1.6)
1864     SCS.Second = ICK_Complex_Conversion;
1865     FromType = ToType.getUnqualifiedType();
1866   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1867              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1868     // Complex-real conversions (C99 6.3.1.7)
1869     SCS.Second = ICK_Complex_Real;
1870     FromType = ToType.getUnqualifiedType();
1871   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1872     // FIXME: disable conversions between long double, __ibm128 and __float128
1873     // if their representation is different until there is back end support
1874     // We of course allow this conversion if long double is really double.
1875 
1876     // Conversions between bfloat and other floats are not permitted.
1877     if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty)
1878       return false;
1879 
1880     // Conversions between IEEE-quad and IBM-extended semantics are not
1881     // permitted.
1882     const llvm::fltSemantics &FromSem =
1883         S.Context.getFloatTypeSemantics(FromType);
1884     const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
1885     if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
1886          &ToSem == &llvm::APFloat::IEEEquad()) ||
1887         (&FromSem == &llvm::APFloat::IEEEquad() &&
1888          &ToSem == &llvm::APFloat::PPCDoubleDouble()))
1889       return false;
1890 
1891     // Floating point conversions (C++ 4.8).
1892     SCS.Second = ICK_Floating_Conversion;
1893     FromType = ToType.getUnqualifiedType();
1894   } else if ((FromType->isRealFloatingType() &&
1895               ToType->isIntegralType(S.Context)) ||
1896              (FromType->isIntegralOrUnscopedEnumerationType() &&
1897               ToType->isRealFloatingType())) {
1898     // Conversions between bfloat and int are not permitted.
1899     if (FromType->isBFloat16Type() || ToType->isBFloat16Type())
1900       return false;
1901 
1902     // Floating-integral conversions (C++ 4.9).
1903     SCS.Second = ICK_Floating_Integral;
1904     FromType = ToType.getUnqualifiedType();
1905   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1906     SCS.Second = ICK_Block_Pointer_Conversion;
1907   } else if (AllowObjCWritebackConversion &&
1908              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1909     SCS.Second = ICK_Writeback_Conversion;
1910   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1911                                    FromType, IncompatibleObjC)) {
1912     // Pointer conversions (C++ 4.10).
1913     SCS.Second = ICK_Pointer_Conversion;
1914     SCS.IncompatibleObjC = IncompatibleObjC;
1915     FromType = FromType.getUnqualifiedType();
1916   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1917                                          InOverloadResolution, FromType)) {
1918     // Pointer to member conversions (4.11).
1919     SCS.Second = ICK_Pointer_Member;
1920   } else if (IsVectorConversion(S, FromType, ToType, SecondICK, From,
1921                                 InOverloadResolution)) {
1922     SCS.Second = SecondICK;
1923     FromType = ToType.getUnqualifiedType();
1924   } else if (!S.getLangOpts().CPlusPlus &&
1925              S.Context.typesAreCompatible(ToType, FromType)) {
1926     // Compatible conversions (Clang extension for C function overloading)
1927     SCS.Second = ICK_Compatible_Conversion;
1928     FromType = ToType.getUnqualifiedType();
1929   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1930                                              InOverloadResolution,
1931                                              SCS, CStyle)) {
1932     SCS.Second = ICK_TransparentUnionConversion;
1933     FromType = ToType;
1934   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1935                                  CStyle)) {
1936     // tryAtomicConversion has updated the standard conversion sequence
1937     // appropriately.
1938     return true;
1939   } else if (ToType->isEventT() &&
1940              From->isIntegerConstantExpr(S.getASTContext()) &&
1941              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1942     SCS.Second = ICK_Zero_Event_Conversion;
1943     FromType = ToType;
1944   } else if (ToType->isQueueT() &&
1945              From->isIntegerConstantExpr(S.getASTContext()) &&
1946              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1947     SCS.Second = ICK_Zero_Queue_Conversion;
1948     FromType = ToType;
1949   } else if (ToType->isSamplerT() &&
1950              From->isIntegerConstantExpr(S.getASTContext())) {
1951     SCS.Second = ICK_Compatible_Conversion;
1952     FromType = ToType;
1953   } else {
1954     // No second conversion required.
1955     SCS.Second = ICK_Identity;
1956   }
1957   SCS.setToType(1, FromType);
1958 
1959   // The third conversion can be a function pointer conversion or a
1960   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1961   bool ObjCLifetimeConversion;
1962   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1963     // Function pointer conversions (removing 'noexcept') including removal of
1964     // 'noreturn' (Clang extension).
1965     SCS.Third = ICK_Function_Conversion;
1966   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1967                                          ObjCLifetimeConversion)) {
1968     SCS.Third = ICK_Qualification;
1969     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1970     FromType = ToType;
1971   } else {
1972     // No conversion required
1973     SCS.Third = ICK_Identity;
1974   }
1975 
1976   // C++ [over.best.ics]p6:
1977   //   [...] Any difference in top-level cv-qualification is
1978   //   subsumed by the initialization itself and does not constitute
1979   //   a conversion. [...]
1980   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1981   QualType CanonTo = S.Context.getCanonicalType(ToType);
1982   if (CanonFrom.getLocalUnqualifiedType()
1983                                      == CanonTo.getLocalUnqualifiedType() &&
1984       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1985     FromType = ToType;
1986     CanonFrom = CanonTo;
1987   }
1988 
1989   SCS.setToType(2, FromType);
1990 
1991   if (CanonFrom == CanonTo)
1992     return true;
1993 
1994   // If we have not converted the argument type to the parameter type,
1995   // this is a bad conversion sequence, unless we're resolving an overload in C.
1996   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1997     return false;
1998 
1999   ExprResult ER = ExprResult{From};
2000   Sema::AssignConvertType Conv =
2001       S.CheckSingleAssignmentConstraints(ToType, ER,
2002                                          /*Diagnose=*/false,
2003                                          /*DiagnoseCFAudited=*/false,
2004                                          /*ConvertRHS=*/false);
2005   ImplicitConversionKind SecondConv;
2006   switch (Conv) {
2007   case Sema::Compatible:
2008     SecondConv = ICK_C_Only_Conversion;
2009     break;
2010   // For our purposes, discarding qualifiers is just as bad as using an
2011   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2012   // qualifiers, as well.
2013   case Sema::CompatiblePointerDiscardsQualifiers:
2014   case Sema::IncompatiblePointer:
2015   case Sema::IncompatiblePointerSign:
2016     SecondConv = ICK_Incompatible_Pointer_Conversion;
2017     break;
2018   default:
2019     return false;
2020   }
2021 
2022   // First can only be an lvalue conversion, so we pretend that this was the
2023   // second conversion. First should already be valid from earlier in the
2024   // function.
2025   SCS.Second = SecondConv;
2026   SCS.setToType(1, ToType);
2027 
2028   // Third is Identity, because Second should rank us worse than any other
2029   // conversion. This could also be ICK_Qualification, but it's simpler to just
2030   // lump everything in with the second conversion, and we don't gain anything
2031   // from making this ICK_Qualification.
2032   SCS.Third = ICK_Identity;
2033   SCS.setToType(2, ToType);
2034   return true;
2035 }
2036 
2037 static bool
2038 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2039                                      QualType &ToType,
2040                                      bool InOverloadResolution,
2041                                      StandardConversionSequence &SCS,
2042                                      bool CStyle) {
2043 
2044   const RecordType *UT = ToType->getAsUnionType();
2045   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2046     return false;
2047   // The field to initialize within the transparent union.
2048   RecordDecl *UD = UT->getDecl();
2049   // It's compatible if the expression matches any of the fields.
2050   for (const auto *it : UD->fields()) {
2051     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2052                              CStyle, /*AllowObjCWritebackConversion=*/false)) {
2053       ToType = it->getType();
2054       return true;
2055     }
2056   }
2057   return false;
2058 }
2059 
2060 /// IsIntegralPromotion - Determines whether the conversion from the
2061 /// expression From (whose potentially-adjusted type is FromType) to
2062 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
2063 /// sets PromotedType to the promoted type.
2064 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2065   const BuiltinType *To = ToType->getAs<BuiltinType>();
2066   // All integers are built-in.
2067   if (!To) {
2068     return false;
2069   }
2070 
2071   // An rvalue of type char, signed char, unsigned char, short int, or
2072   // unsigned short int can be converted to an rvalue of type int if
2073   // int can represent all the values of the source type; otherwise,
2074   // the source rvalue can be converted to an rvalue of type unsigned
2075   // int (C++ 4.5p1).
2076   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
2077       !FromType->isEnumeralType()) {
2078     if (// We can promote any signed, promotable integer type to an int
2079         (FromType->isSignedIntegerType() ||
2080          // We can promote any unsigned integer type whose size is
2081          // less than int to an int.
2082          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2083       return To->getKind() == BuiltinType::Int;
2084     }
2085 
2086     return To->getKind() == BuiltinType::UInt;
2087   }
2088 
2089   // C++11 [conv.prom]p3:
2090   //   A prvalue of an unscoped enumeration type whose underlying type is not
2091   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2092   //   following types that can represent all the values of the enumeration
2093   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
2094   //   unsigned int, long int, unsigned long int, long long int, or unsigned
2095   //   long long int. If none of the types in that list can represent all the
2096   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2097   //   type can be converted to an rvalue a prvalue of the extended integer type
2098   //   with lowest integer conversion rank (4.13) greater than the rank of long
2099   //   long in which all the values of the enumeration can be represented. If
2100   //   there are two such extended types, the signed one is chosen.
2101   // C++11 [conv.prom]p4:
2102   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
2103   //   can be converted to a prvalue of its underlying type. Moreover, if
2104   //   integral promotion can be applied to its underlying type, a prvalue of an
2105   //   unscoped enumeration type whose underlying type is fixed can also be
2106   //   converted to a prvalue of the promoted underlying type.
2107   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2108     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2109     // provided for a scoped enumeration.
2110     if (FromEnumType->getDecl()->isScoped())
2111       return false;
2112 
2113     // We can perform an integral promotion to the underlying type of the enum,
2114     // even if that's not the promoted type. Note that the check for promoting
2115     // the underlying type is based on the type alone, and does not consider
2116     // the bitfield-ness of the actual source expression.
2117     if (FromEnumType->getDecl()->isFixed()) {
2118       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2119       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2120              IsIntegralPromotion(nullptr, Underlying, ToType);
2121     }
2122 
2123     // We have already pre-calculated the promotion type, so this is trivial.
2124     if (ToType->isIntegerType() &&
2125         isCompleteType(From->getBeginLoc(), FromType))
2126       return Context.hasSameUnqualifiedType(
2127           ToType, FromEnumType->getDecl()->getPromotionType());
2128 
2129     // C++ [conv.prom]p5:
2130     //   If the bit-field has an enumerated type, it is treated as any other
2131     //   value of that type for promotion purposes.
2132     //
2133     // ... so do not fall through into the bit-field checks below in C++.
2134     if (getLangOpts().CPlusPlus)
2135       return false;
2136   }
2137 
2138   // C++0x [conv.prom]p2:
2139   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2140   //   to an rvalue a prvalue of the first of the following types that can
2141   //   represent all the values of its underlying type: int, unsigned int,
2142   //   long int, unsigned long int, long long int, or unsigned long long int.
2143   //   If none of the types in that list can represent all the values of its
2144   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2145   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2146   //   type.
2147   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2148       ToType->isIntegerType()) {
2149     // Determine whether the type we're converting from is signed or
2150     // unsigned.
2151     bool FromIsSigned = FromType->isSignedIntegerType();
2152     uint64_t FromSize = Context.getTypeSize(FromType);
2153 
2154     // The types we'll try to promote to, in the appropriate
2155     // order. Try each of these types.
2156     QualType PromoteTypes[6] = {
2157       Context.IntTy, Context.UnsignedIntTy,
2158       Context.LongTy, Context.UnsignedLongTy ,
2159       Context.LongLongTy, Context.UnsignedLongLongTy
2160     };
2161     for (int Idx = 0; Idx < 6; ++Idx) {
2162       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2163       if (FromSize < ToSize ||
2164           (FromSize == ToSize &&
2165            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2166         // We found the type that we can promote to. If this is the
2167         // type we wanted, we have a promotion. Otherwise, no
2168         // promotion.
2169         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2170       }
2171     }
2172   }
2173 
2174   // An rvalue for an integral bit-field (9.6) can be converted to an
2175   // rvalue of type int if int can represent all the values of the
2176   // bit-field; otherwise, it can be converted to unsigned int if
2177   // unsigned int can represent all the values of the bit-field. If
2178   // the bit-field is larger yet, no integral promotion applies to
2179   // it. If the bit-field has an enumerated type, it is treated as any
2180   // other value of that type for promotion purposes (C++ 4.5p3).
2181   // FIXME: We should delay checking of bit-fields until we actually perform the
2182   // conversion.
2183   //
2184   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2185   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2186   // bit-fields and those whose underlying type is larger than int) for GCC
2187   // compatibility.
2188   if (From) {
2189     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2190       Optional<llvm::APSInt> BitWidth;
2191       if (FromType->isIntegralType(Context) &&
2192           (BitWidth =
2193                MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2194         llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2195         ToSize = Context.getTypeSize(ToType);
2196 
2197         // Are we promoting to an int from a bitfield that fits in an int?
2198         if (*BitWidth < ToSize ||
2199             (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2200           return To->getKind() == BuiltinType::Int;
2201         }
2202 
2203         // Are we promoting to an unsigned int from an unsigned bitfield
2204         // that fits into an unsigned int?
2205         if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2206           return To->getKind() == BuiltinType::UInt;
2207         }
2208 
2209         return false;
2210       }
2211     }
2212   }
2213 
2214   // An rvalue of type bool can be converted to an rvalue of type int,
2215   // with false becoming zero and true becoming one (C++ 4.5p4).
2216   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2217     return true;
2218   }
2219 
2220   return false;
2221 }
2222 
2223 /// IsFloatingPointPromotion - Determines whether the conversion from
2224 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2225 /// returns true and sets PromotedType to the promoted type.
2226 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2227   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2228     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2229       /// An rvalue of type float can be converted to an rvalue of type
2230       /// double. (C++ 4.6p1).
2231       if (FromBuiltin->getKind() == BuiltinType::Float &&
2232           ToBuiltin->getKind() == BuiltinType::Double)
2233         return true;
2234 
2235       // C99 6.3.1.5p1:
2236       //   When a float is promoted to double or long double, or a
2237       //   double is promoted to long double [...].
2238       if (!getLangOpts().CPlusPlus &&
2239           (FromBuiltin->getKind() == BuiltinType::Float ||
2240            FromBuiltin->getKind() == BuiltinType::Double) &&
2241           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2242            ToBuiltin->getKind() == BuiltinType::Float128 ||
2243            ToBuiltin->getKind() == BuiltinType::Ibm128))
2244         return true;
2245 
2246       // Half can be promoted to float.
2247       if (!getLangOpts().NativeHalfType &&
2248            FromBuiltin->getKind() == BuiltinType::Half &&
2249           ToBuiltin->getKind() == BuiltinType::Float)
2250         return true;
2251     }
2252 
2253   return false;
2254 }
2255 
2256 /// Determine if a conversion is a complex promotion.
2257 ///
2258 /// A complex promotion is defined as a complex -> complex conversion
2259 /// where the conversion between the underlying real types is a
2260 /// floating-point or integral promotion.
2261 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2262   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2263   if (!FromComplex)
2264     return false;
2265 
2266   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2267   if (!ToComplex)
2268     return false;
2269 
2270   return IsFloatingPointPromotion(FromComplex->getElementType(),
2271                                   ToComplex->getElementType()) ||
2272     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2273                         ToComplex->getElementType());
2274 }
2275 
2276 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2277 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2278 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2279 /// if non-empty, will be a pointer to ToType that may or may not have
2280 /// the right set of qualifiers on its pointee.
2281 ///
2282 static QualType
2283 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2284                                    QualType ToPointee, QualType ToType,
2285                                    ASTContext &Context,
2286                                    bool StripObjCLifetime = false) {
2287   assert((FromPtr->getTypeClass() == Type::Pointer ||
2288           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2289          "Invalid similarly-qualified pointer type");
2290 
2291   /// Conversions to 'id' subsume cv-qualifier conversions.
2292   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2293     return ToType.getUnqualifiedType();
2294 
2295   QualType CanonFromPointee
2296     = Context.getCanonicalType(FromPtr->getPointeeType());
2297   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2298   Qualifiers Quals = CanonFromPointee.getQualifiers();
2299 
2300   if (StripObjCLifetime)
2301     Quals.removeObjCLifetime();
2302 
2303   // Exact qualifier match -> return the pointer type we're converting to.
2304   if (CanonToPointee.getLocalQualifiers() == Quals) {
2305     // ToType is exactly what we need. Return it.
2306     if (!ToType.isNull())
2307       return ToType.getUnqualifiedType();
2308 
2309     // Build a pointer to ToPointee. It has the right qualifiers
2310     // already.
2311     if (isa<ObjCObjectPointerType>(ToType))
2312       return Context.getObjCObjectPointerType(ToPointee);
2313     return Context.getPointerType(ToPointee);
2314   }
2315 
2316   // Just build a canonical type that has the right qualifiers.
2317   QualType QualifiedCanonToPointee
2318     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2319 
2320   if (isa<ObjCObjectPointerType>(ToType))
2321     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2322   return Context.getPointerType(QualifiedCanonToPointee);
2323 }
2324 
2325 static bool isNullPointerConstantForConversion(Expr *Expr,
2326                                                bool InOverloadResolution,
2327                                                ASTContext &Context) {
2328   // Handle value-dependent integral null pointer constants correctly.
2329   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2330   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2331       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2332     return !InOverloadResolution;
2333 
2334   return Expr->isNullPointerConstant(Context,
2335                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2336                                         : Expr::NPC_ValueDependentIsNull);
2337 }
2338 
2339 /// IsPointerConversion - Determines whether the conversion of the
2340 /// expression From, which has the (possibly adjusted) type FromType,
2341 /// can be converted to the type ToType via a pointer conversion (C++
2342 /// 4.10). If so, returns true and places the converted type (that
2343 /// might differ from ToType in its cv-qualifiers at some level) into
2344 /// ConvertedType.
2345 ///
2346 /// This routine also supports conversions to and from block pointers
2347 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2348 /// pointers to interfaces. FIXME: Once we've determined the
2349 /// appropriate overloading rules for Objective-C, we may want to
2350 /// split the Objective-C checks into a different routine; however,
2351 /// GCC seems to consider all of these conversions to be pointer
2352 /// conversions, so for now they live here. IncompatibleObjC will be
2353 /// set if the conversion is an allowed Objective-C conversion that
2354 /// should result in a warning.
2355 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2356                                bool InOverloadResolution,
2357                                QualType& ConvertedType,
2358                                bool &IncompatibleObjC) {
2359   IncompatibleObjC = false;
2360   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2361                               IncompatibleObjC))
2362     return true;
2363 
2364   // Conversion from a null pointer constant to any Objective-C pointer type.
2365   if (ToType->isObjCObjectPointerType() &&
2366       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2367     ConvertedType = ToType;
2368     return true;
2369   }
2370 
2371   // Blocks: Block pointers can be converted to void*.
2372   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2373       ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2374     ConvertedType = ToType;
2375     return true;
2376   }
2377   // Blocks: A null pointer constant can be converted to a block
2378   // pointer type.
2379   if (ToType->isBlockPointerType() &&
2380       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2381     ConvertedType = ToType;
2382     return true;
2383   }
2384 
2385   // If the left-hand-side is nullptr_t, the right side can be a null
2386   // pointer constant.
2387   if (ToType->isNullPtrType() &&
2388       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2389     ConvertedType = ToType;
2390     return true;
2391   }
2392 
2393   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2394   if (!ToTypePtr)
2395     return false;
2396 
2397   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2398   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2399     ConvertedType = ToType;
2400     return true;
2401   }
2402 
2403   // Beyond this point, both types need to be pointers
2404   // , including objective-c pointers.
2405   QualType ToPointeeType = ToTypePtr->getPointeeType();
2406   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2407       !getLangOpts().ObjCAutoRefCount) {
2408     ConvertedType = BuildSimilarlyQualifiedPointerType(
2409         FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2410         Context);
2411     return true;
2412   }
2413   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2414   if (!FromTypePtr)
2415     return false;
2416 
2417   QualType FromPointeeType = FromTypePtr->getPointeeType();
2418 
2419   // If the unqualified pointee types are the same, this can't be a
2420   // pointer conversion, so don't do all of the work below.
2421   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2422     return false;
2423 
2424   // An rvalue of type "pointer to cv T," where T is an object type,
2425   // can be converted to an rvalue of type "pointer to cv void" (C++
2426   // 4.10p2).
2427   if (FromPointeeType->isIncompleteOrObjectType() &&
2428       ToPointeeType->isVoidType()) {
2429     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2430                                                        ToPointeeType,
2431                                                        ToType, Context,
2432                                                    /*StripObjCLifetime=*/true);
2433     return true;
2434   }
2435 
2436   // MSVC allows implicit function to void* type conversion.
2437   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2438       ToPointeeType->isVoidType()) {
2439     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2440                                                        ToPointeeType,
2441                                                        ToType, Context);
2442     return true;
2443   }
2444 
2445   // When we're overloading in C, we allow a special kind of pointer
2446   // conversion for compatible-but-not-identical pointee types.
2447   if (!getLangOpts().CPlusPlus &&
2448       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2449     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2450                                                        ToPointeeType,
2451                                                        ToType, Context);
2452     return true;
2453   }
2454 
2455   // C++ [conv.ptr]p3:
2456   //
2457   //   An rvalue of type "pointer to cv D," where D is a class type,
2458   //   can be converted to an rvalue of type "pointer to cv B," where
2459   //   B is a base class (clause 10) of D. If B is an inaccessible
2460   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2461   //   necessitates this conversion is ill-formed. The result of the
2462   //   conversion is a pointer to the base class sub-object of the
2463   //   derived class object. The null pointer value is converted to
2464   //   the null pointer value of the destination type.
2465   //
2466   // Note that we do not check for ambiguity or inaccessibility
2467   // here. That is handled by CheckPointerConversion.
2468   if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2469       ToPointeeType->isRecordType() &&
2470       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2471       IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2472     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2473                                                        ToPointeeType,
2474                                                        ToType, Context);
2475     return true;
2476   }
2477 
2478   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2479       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2480     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2481                                                        ToPointeeType,
2482                                                        ToType, Context);
2483     return true;
2484   }
2485 
2486   return false;
2487 }
2488 
2489 /// Adopt the given qualifiers for the given type.
2490 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2491   Qualifiers TQs = T.getQualifiers();
2492 
2493   // Check whether qualifiers already match.
2494   if (TQs == Qs)
2495     return T;
2496 
2497   if (Qs.compatiblyIncludes(TQs))
2498     return Context.getQualifiedType(T, Qs);
2499 
2500   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2501 }
2502 
2503 /// isObjCPointerConversion - Determines whether this is an
2504 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2505 /// with the same arguments and return values.
2506 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2507                                    QualType& ConvertedType,
2508                                    bool &IncompatibleObjC) {
2509   if (!getLangOpts().ObjC)
2510     return false;
2511 
2512   // The set of qualifiers on the type we're converting from.
2513   Qualifiers FromQualifiers = FromType.getQualifiers();
2514 
2515   // First, we handle all conversions on ObjC object pointer types.
2516   const ObjCObjectPointerType* ToObjCPtr =
2517     ToType->getAs<ObjCObjectPointerType>();
2518   const ObjCObjectPointerType *FromObjCPtr =
2519     FromType->getAs<ObjCObjectPointerType>();
2520 
2521   if (ToObjCPtr && FromObjCPtr) {
2522     // If the pointee types are the same (ignoring qualifications),
2523     // then this is not a pointer conversion.
2524     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2525                                        FromObjCPtr->getPointeeType()))
2526       return false;
2527 
2528     // Conversion between Objective-C pointers.
2529     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2530       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2531       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2532       if (getLangOpts().CPlusPlus && LHS && RHS &&
2533           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2534                                                 FromObjCPtr->getPointeeType()))
2535         return false;
2536       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2537                                                    ToObjCPtr->getPointeeType(),
2538                                                          ToType, Context);
2539       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2540       return true;
2541     }
2542 
2543     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2544       // Okay: this is some kind of implicit downcast of Objective-C
2545       // interfaces, which is permitted. However, we're going to
2546       // complain about it.
2547       IncompatibleObjC = true;
2548       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2549                                                    ToObjCPtr->getPointeeType(),
2550                                                          ToType, Context);
2551       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2552       return true;
2553     }
2554   }
2555   // Beyond this point, both types need to be C pointers or block pointers.
2556   QualType ToPointeeType;
2557   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2558     ToPointeeType = ToCPtr->getPointeeType();
2559   else if (const BlockPointerType *ToBlockPtr =
2560             ToType->getAs<BlockPointerType>()) {
2561     // Objective C++: We're able to convert from a pointer to any object
2562     // to a block pointer type.
2563     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2564       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2565       return true;
2566     }
2567     ToPointeeType = ToBlockPtr->getPointeeType();
2568   }
2569   else if (FromType->getAs<BlockPointerType>() &&
2570            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2571     // Objective C++: We're able to convert from a block pointer type to a
2572     // pointer to any object.
2573     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2574     return true;
2575   }
2576   else
2577     return false;
2578 
2579   QualType FromPointeeType;
2580   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2581     FromPointeeType = FromCPtr->getPointeeType();
2582   else if (const BlockPointerType *FromBlockPtr =
2583            FromType->getAs<BlockPointerType>())
2584     FromPointeeType = FromBlockPtr->getPointeeType();
2585   else
2586     return false;
2587 
2588   // If we have pointers to pointers, recursively check whether this
2589   // is an Objective-C conversion.
2590   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2591       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2592                               IncompatibleObjC)) {
2593     // We always complain about this conversion.
2594     IncompatibleObjC = true;
2595     ConvertedType = Context.getPointerType(ConvertedType);
2596     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2597     return true;
2598   }
2599   // Allow conversion of pointee being objective-c pointer to another one;
2600   // as in I* to id.
2601   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2602       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2603       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2604                               IncompatibleObjC)) {
2605 
2606     ConvertedType = Context.getPointerType(ConvertedType);
2607     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2608     return true;
2609   }
2610 
2611   // If we have pointers to functions or blocks, check whether the only
2612   // differences in the argument and result types are in Objective-C
2613   // pointer conversions. If so, we permit the conversion (but
2614   // complain about it).
2615   const FunctionProtoType *FromFunctionType
2616     = FromPointeeType->getAs<FunctionProtoType>();
2617   const FunctionProtoType *ToFunctionType
2618     = ToPointeeType->getAs<FunctionProtoType>();
2619   if (FromFunctionType && ToFunctionType) {
2620     // If the function types are exactly the same, this isn't an
2621     // Objective-C pointer conversion.
2622     if (Context.getCanonicalType(FromPointeeType)
2623           == Context.getCanonicalType(ToPointeeType))
2624       return false;
2625 
2626     // Perform the quick checks that will tell us whether these
2627     // function types are obviously different.
2628     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2629         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2630         FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2631       return false;
2632 
2633     bool HasObjCConversion = false;
2634     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2635         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2636       // Okay, the types match exactly. Nothing to do.
2637     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2638                                        ToFunctionType->getReturnType(),
2639                                        ConvertedType, IncompatibleObjC)) {
2640       // Okay, we have an Objective-C pointer conversion.
2641       HasObjCConversion = true;
2642     } else {
2643       // Function types are too different. Abort.
2644       return false;
2645     }
2646 
2647     // Check argument types.
2648     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2649          ArgIdx != NumArgs; ++ArgIdx) {
2650       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2651       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2652       if (Context.getCanonicalType(FromArgType)
2653             == Context.getCanonicalType(ToArgType)) {
2654         // Okay, the types match exactly. Nothing to do.
2655       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2656                                          ConvertedType, IncompatibleObjC)) {
2657         // Okay, we have an Objective-C pointer conversion.
2658         HasObjCConversion = true;
2659       } else {
2660         // Argument types are too different. Abort.
2661         return false;
2662       }
2663     }
2664 
2665     if (HasObjCConversion) {
2666       // We had an Objective-C conversion. Allow this pointer
2667       // conversion, but complain about it.
2668       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2669       IncompatibleObjC = true;
2670       return true;
2671     }
2672   }
2673 
2674   return false;
2675 }
2676 
2677 /// Determine whether this is an Objective-C writeback conversion,
2678 /// used for parameter passing when performing automatic reference counting.
2679 ///
2680 /// \param FromType The type we're converting form.
2681 ///
2682 /// \param ToType The type we're converting to.
2683 ///
2684 /// \param ConvertedType The type that will be produced after applying
2685 /// this conversion.
2686 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2687                                      QualType &ConvertedType) {
2688   if (!getLangOpts().ObjCAutoRefCount ||
2689       Context.hasSameUnqualifiedType(FromType, ToType))
2690     return false;
2691 
2692   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2693   QualType ToPointee;
2694   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2695     ToPointee = ToPointer->getPointeeType();
2696   else
2697     return false;
2698 
2699   Qualifiers ToQuals = ToPointee.getQualifiers();
2700   if (!ToPointee->isObjCLifetimeType() ||
2701       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2702       !ToQuals.withoutObjCLifetime().empty())
2703     return false;
2704 
2705   // Argument must be a pointer to __strong to __weak.
2706   QualType FromPointee;
2707   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2708     FromPointee = FromPointer->getPointeeType();
2709   else
2710     return false;
2711 
2712   Qualifiers FromQuals = FromPointee.getQualifiers();
2713   if (!FromPointee->isObjCLifetimeType() ||
2714       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2715        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2716     return false;
2717 
2718   // Make sure that we have compatible qualifiers.
2719   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2720   if (!ToQuals.compatiblyIncludes(FromQuals))
2721     return false;
2722 
2723   // Remove qualifiers from the pointee type we're converting from; they
2724   // aren't used in the compatibility check belong, and we'll be adding back
2725   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2726   FromPointee = FromPointee.getUnqualifiedType();
2727 
2728   // The unqualified form of the pointee types must be compatible.
2729   ToPointee = ToPointee.getUnqualifiedType();
2730   bool IncompatibleObjC;
2731   if (Context.typesAreCompatible(FromPointee, ToPointee))
2732     FromPointee = ToPointee;
2733   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2734                                     IncompatibleObjC))
2735     return false;
2736 
2737   /// Construct the type we're converting to, which is a pointer to
2738   /// __autoreleasing pointee.
2739   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2740   ConvertedType = Context.getPointerType(FromPointee);
2741   return true;
2742 }
2743 
2744 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2745                                     QualType& ConvertedType) {
2746   QualType ToPointeeType;
2747   if (const BlockPointerType *ToBlockPtr =
2748         ToType->getAs<BlockPointerType>())
2749     ToPointeeType = ToBlockPtr->getPointeeType();
2750   else
2751     return false;
2752 
2753   QualType FromPointeeType;
2754   if (const BlockPointerType *FromBlockPtr =
2755       FromType->getAs<BlockPointerType>())
2756     FromPointeeType = FromBlockPtr->getPointeeType();
2757   else
2758     return false;
2759   // We have pointer to blocks, check whether the only
2760   // differences in the argument and result types are in Objective-C
2761   // pointer conversions. If so, we permit the conversion.
2762 
2763   const FunctionProtoType *FromFunctionType
2764     = FromPointeeType->getAs<FunctionProtoType>();
2765   const FunctionProtoType *ToFunctionType
2766     = ToPointeeType->getAs<FunctionProtoType>();
2767 
2768   if (!FromFunctionType || !ToFunctionType)
2769     return false;
2770 
2771   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2772     return true;
2773 
2774   // Perform the quick checks that will tell us whether these
2775   // function types are obviously different.
2776   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2777       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2778     return false;
2779 
2780   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2781   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2782   if (FromEInfo != ToEInfo)
2783     return false;
2784 
2785   bool IncompatibleObjC = false;
2786   if (Context.hasSameType(FromFunctionType->getReturnType(),
2787                           ToFunctionType->getReturnType())) {
2788     // Okay, the types match exactly. Nothing to do.
2789   } else {
2790     QualType RHS = FromFunctionType->getReturnType();
2791     QualType LHS = ToFunctionType->getReturnType();
2792     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2793         !RHS.hasQualifiers() && LHS.hasQualifiers())
2794        LHS = LHS.getUnqualifiedType();
2795 
2796      if (Context.hasSameType(RHS,LHS)) {
2797        // OK exact match.
2798      } else if (isObjCPointerConversion(RHS, LHS,
2799                                         ConvertedType, IncompatibleObjC)) {
2800      if (IncompatibleObjC)
2801        return false;
2802      // Okay, we have an Objective-C pointer conversion.
2803      }
2804      else
2805        return false;
2806    }
2807 
2808    // Check argument types.
2809    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2810         ArgIdx != NumArgs; ++ArgIdx) {
2811      IncompatibleObjC = false;
2812      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2813      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2814      if (Context.hasSameType(FromArgType, ToArgType)) {
2815        // Okay, the types match exactly. Nothing to do.
2816      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2817                                         ConvertedType, IncompatibleObjC)) {
2818        if (IncompatibleObjC)
2819          return false;
2820        // Okay, we have an Objective-C pointer conversion.
2821      } else
2822        // Argument types are too different. Abort.
2823        return false;
2824    }
2825 
2826    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2827    bool CanUseToFPT, CanUseFromFPT;
2828    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2829                                       CanUseToFPT, CanUseFromFPT,
2830                                       NewParamInfos))
2831      return false;
2832 
2833    ConvertedType = ToType;
2834    return true;
2835 }
2836 
2837 enum {
2838   ft_default,
2839   ft_different_class,
2840   ft_parameter_arity,
2841   ft_parameter_mismatch,
2842   ft_return_type,
2843   ft_qualifer_mismatch,
2844   ft_noexcept
2845 };
2846 
2847 /// Attempts to get the FunctionProtoType from a Type. Handles
2848 /// MemberFunctionPointers properly.
2849 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2850   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2851     return FPT;
2852 
2853   if (auto *MPT = FromType->getAs<MemberPointerType>())
2854     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2855 
2856   return nullptr;
2857 }
2858 
2859 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2860 /// function types.  Catches different number of parameter, mismatch in
2861 /// parameter types, and different return types.
2862 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2863                                       QualType FromType, QualType ToType) {
2864   // If either type is not valid, include no extra info.
2865   if (FromType.isNull() || ToType.isNull()) {
2866     PDiag << ft_default;
2867     return;
2868   }
2869 
2870   // Get the function type from the pointers.
2871   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2872     const auto *FromMember = FromType->castAs<MemberPointerType>(),
2873                *ToMember = ToType->castAs<MemberPointerType>();
2874     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2875       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2876             << QualType(FromMember->getClass(), 0);
2877       return;
2878     }
2879     FromType = FromMember->getPointeeType();
2880     ToType = ToMember->getPointeeType();
2881   }
2882 
2883   if (FromType->isPointerType())
2884     FromType = FromType->getPointeeType();
2885   if (ToType->isPointerType())
2886     ToType = ToType->getPointeeType();
2887 
2888   // Remove references.
2889   FromType = FromType.getNonReferenceType();
2890   ToType = ToType.getNonReferenceType();
2891 
2892   // Don't print extra info for non-specialized template functions.
2893   if (FromType->isInstantiationDependentType() &&
2894       !FromType->getAs<TemplateSpecializationType>()) {
2895     PDiag << ft_default;
2896     return;
2897   }
2898 
2899   // No extra info for same types.
2900   if (Context.hasSameType(FromType, ToType)) {
2901     PDiag << ft_default;
2902     return;
2903   }
2904 
2905   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2906                           *ToFunction = tryGetFunctionProtoType(ToType);
2907 
2908   // Both types need to be function types.
2909   if (!FromFunction || !ToFunction) {
2910     PDiag << ft_default;
2911     return;
2912   }
2913 
2914   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2915     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2916           << FromFunction->getNumParams();
2917     return;
2918   }
2919 
2920   // Handle different parameter types.
2921   unsigned ArgPos;
2922   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2923     PDiag << ft_parameter_mismatch << ArgPos + 1
2924           << ToFunction->getParamType(ArgPos)
2925           << FromFunction->getParamType(ArgPos);
2926     return;
2927   }
2928 
2929   // Handle different return type.
2930   if (!Context.hasSameType(FromFunction->getReturnType(),
2931                            ToFunction->getReturnType())) {
2932     PDiag << ft_return_type << ToFunction->getReturnType()
2933           << FromFunction->getReturnType();
2934     return;
2935   }
2936 
2937   if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2938     PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2939           << FromFunction->getMethodQuals();
2940     return;
2941   }
2942 
2943   // Handle exception specification differences on canonical type (in C++17
2944   // onwards).
2945   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2946           ->isNothrow() !=
2947       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2948           ->isNothrow()) {
2949     PDiag << ft_noexcept;
2950     return;
2951   }
2952 
2953   // Unable to find a difference, so add no extra info.
2954   PDiag << ft_default;
2955 }
2956 
2957 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2958 /// for equality of their parameter types. Caller has already checked that
2959 /// they have same number of parameters.  If the parameters are different,
2960 /// ArgPos will have the parameter index of the first different parameter.
2961 /// If `Reversed` is true, the parameters of `NewType` will be compared in
2962 /// reverse order. That's useful if one of the functions is being used as a C++20
2963 /// synthesized operator overload with a reversed parameter order.
2964 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2965                                       const FunctionProtoType *NewType,
2966                                       unsigned *ArgPos, bool Reversed) {
2967   assert(OldType->getNumParams() == NewType->getNumParams() &&
2968          "Can't compare parameters of functions with different number of "
2969          "parameters!");
2970   for (size_t I = 0; I < OldType->getNumParams(); I++) {
2971     // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
2972     size_t J = Reversed ? (OldType->getNumParams() - I - 1) : I;
2973 
2974     // Ignore address spaces in pointee type. This is to disallow overloading
2975     // on __ptr32/__ptr64 address spaces.
2976     QualType Old = Context.removePtrSizeAddrSpace(OldType->getParamType(I).getUnqualifiedType());
2977     QualType New = Context.removePtrSizeAddrSpace(NewType->getParamType(J).getUnqualifiedType());
2978 
2979     if (!Context.hasSameType(Old, New)) {
2980       if (ArgPos)
2981         *ArgPos = I;
2982       return false;
2983     }
2984   }
2985   return true;
2986 }
2987 
2988 /// CheckPointerConversion - Check the pointer conversion from the
2989 /// expression From to the type ToType. This routine checks for
2990 /// ambiguous or inaccessible derived-to-base pointer
2991 /// conversions for which IsPointerConversion has already returned
2992 /// true. It returns true and produces a diagnostic if there was an
2993 /// error, or returns false otherwise.
2994 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2995                                   CastKind &Kind,
2996                                   CXXCastPath& BasePath,
2997                                   bool IgnoreBaseAccess,
2998                                   bool Diagnose) {
2999   QualType FromType = From->getType();
3000   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3001 
3002   Kind = CK_BitCast;
3003 
3004   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3005       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
3006           Expr::NPCK_ZeroExpression) {
3007     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3008       DiagRuntimeBehavior(From->getExprLoc(), From,
3009                           PDiag(diag::warn_impcast_bool_to_null_pointer)
3010                             << ToType << From->getSourceRange());
3011     else if (!isUnevaluatedContext())
3012       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3013         << ToType << From->getSourceRange();
3014   }
3015   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3016     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3017       QualType FromPointeeType = FromPtrType->getPointeeType(),
3018                ToPointeeType   = ToPtrType->getPointeeType();
3019 
3020       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3021           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3022         // We must have a derived-to-base conversion. Check an
3023         // ambiguous or inaccessible conversion.
3024         unsigned InaccessibleID = 0;
3025         unsigned AmbiguousID = 0;
3026         if (Diagnose) {
3027           InaccessibleID = diag::err_upcast_to_inaccessible_base;
3028           AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3029         }
3030         if (CheckDerivedToBaseConversion(
3031                 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3032                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3033                 &BasePath, IgnoreBaseAccess))
3034           return true;
3035 
3036         // The conversion was successful.
3037         Kind = CK_DerivedToBase;
3038       }
3039 
3040       if (Diagnose && !IsCStyleOrFunctionalCast &&
3041           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3042         assert(getLangOpts().MSVCCompat &&
3043                "this should only be possible with MSVCCompat!");
3044         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3045             << From->getSourceRange();
3046       }
3047     }
3048   } else if (const ObjCObjectPointerType *ToPtrType =
3049                ToType->getAs<ObjCObjectPointerType>()) {
3050     if (const ObjCObjectPointerType *FromPtrType =
3051           FromType->getAs<ObjCObjectPointerType>()) {
3052       // Objective-C++ conversions are always okay.
3053       // FIXME: We should have a different class of conversions for the
3054       // Objective-C++ implicit conversions.
3055       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3056         return false;
3057     } else if (FromType->isBlockPointerType()) {
3058       Kind = CK_BlockPointerToObjCPointerCast;
3059     } else {
3060       Kind = CK_CPointerToObjCPointerCast;
3061     }
3062   } else if (ToType->isBlockPointerType()) {
3063     if (!FromType->isBlockPointerType())
3064       Kind = CK_AnyPointerToBlockPointerCast;
3065   }
3066 
3067   // We shouldn't fall into this case unless it's valid for other
3068   // reasons.
3069   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3070     Kind = CK_NullToPointer;
3071 
3072   return false;
3073 }
3074 
3075 /// IsMemberPointerConversion - Determines whether the conversion of the
3076 /// expression From, which has the (possibly adjusted) type FromType, can be
3077 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
3078 /// If so, returns true and places the converted type (that might differ from
3079 /// ToType in its cv-qualifiers at some level) into ConvertedType.
3080 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3081                                      QualType ToType,
3082                                      bool InOverloadResolution,
3083                                      QualType &ConvertedType) {
3084   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3085   if (!ToTypePtr)
3086     return false;
3087 
3088   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3089   if (From->isNullPointerConstant(Context,
3090                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3091                                         : Expr::NPC_ValueDependentIsNull)) {
3092     ConvertedType = ToType;
3093     return true;
3094   }
3095 
3096   // Otherwise, both types have to be member pointers.
3097   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3098   if (!FromTypePtr)
3099     return false;
3100 
3101   // A pointer to member of B can be converted to a pointer to member of D,
3102   // where D is derived from B (C++ 4.11p2).
3103   QualType FromClass(FromTypePtr->getClass(), 0);
3104   QualType ToClass(ToTypePtr->getClass(), 0);
3105 
3106   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3107       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3108     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3109                                                  ToClass.getTypePtr());
3110     return true;
3111   }
3112 
3113   return false;
3114 }
3115 
3116 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3117 /// expression From to the type ToType. This routine checks for ambiguous or
3118 /// virtual or inaccessible base-to-derived member pointer conversions
3119 /// for which IsMemberPointerConversion has already returned true. It returns
3120 /// true and produces a diagnostic if there was an error, or returns false
3121 /// otherwise.
3122 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3123                                         CastKind &Kind,
3124                                         CXXCastPath &BasePath,
3125                                         bool IgnoreBaseAccess) {
3126   QualType FromType = From->getType();
3127   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3128   if (!FromPtrType) {
3129     // This must be a null pointer to member pointer conversion
3130     assert(From->isNullPointerConstant(Context,
3131                                        Expr::NPC_ValueDependentIsNull) &&
3132            "Expr must be null pointer constant!");
3133     Kind = CK_NullToMemberPointer;
3134     return false;
3135   }
3136 
3137   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3138   assert(ToPtrType && "No member pointer cast has a target type "
3139                       "that is not a member pointer.");
3140 
3141   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3142   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3143 
3144   // FIXME: What about dependent types?
3145   assert(FromClass->isRecordType() && "Pointer into non-class.");
3146   assert(ToClass->isRecordType() && "Pointer into non-class.");
3147 
3148   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3149                      /*DetectVirtual=*/true);
3150   bool DerivationOkay =
3151       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3152   assert(DerivationOkay &&
3153          "Should not have been called if derivation isn't OK.");
3154   (void)DerivationOkay;
3155 
3156   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3157                                   getUnqualifiedType())) {
3158     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3159     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3160       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3161     return true;
3162   }
3163 
3164   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3165     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3166       << FromClass << ToClass << QualType(VBase, 0)
3167       << From->getSourceRange();
3168     return true;
3169   }
3170 
3171   if (!IgnoreBaseAccess)
3172     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3173                          Paths.front(),
3174                          diag::err_downcast_from_inaccessible_base);
3175 
3176   // Must be a base to derived member conversion.
3177   BuildBasePathArray(Paths, BasePath);
3178   Kind = CK_BaseToDerivedMemberPointer;
3179   return false;
3180 }
3181 
3182 /// Determine whether the lifetime conversion between the two given
3183 /// qualifiers sets is nontrivial.
3184 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3185                                                Qualifiers ToQuals) {
3186   // Converting anything to const __unsafe_unretained is trivial.
3187   if (ToQuals.hasConst() &&
3188       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3189     return false;
3190 
3191   return true;
3192 }
3193 
3194 /// Perform a single iteration of the loop for checking if a qualification
3195 /// conversion is valid.
3196 ///
3197 /// Specifically, check whether any change between the qualifiers of \p
3198 /// FromType and \p ToType is permissible, given knowledge about whether every
3199 /// outer layer is const-qualified.
3200 static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3201                                           bool CStyle, bool IsTopLevel,
3202                                           bool &PreviousToQualsIncludeConst,
3203                                           bool &ObjCLifetimeConversion) {
3204   Qualifiers FromQuals = FromType.getQualifiers();
3205   Qualifiers ToQuals = ToType.getQualifiers();
3206 
3207   // Ignore __unaligned qualifier.
3208   FromQuals.removeUnaligned();
3209 
3210   // Objective-C ARC:
3211   //   Check Objective-C lifetime conversions.
3212   if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3213     if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3214       if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3215         ObjCLifetimeConversion = true;
3216       FromQuals.removeObjCLifetime();
3217       ToQuals.removeObjCLifetime();
3218     } else {
3219       // Qualification conversions cannot cast between different
3220       // Objective-C lifetime qualifiers.
3221       return false;
3222     }
3223   }
3224 
3225   // Allow addition/removal of GC attributes but not changing GC attributes.
3226   if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3227       (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3228     FromQuals.removeObjCGCAttr();
3229     ToQuals.removeObjCGCAttr();
3230   }
3231 
3232   //   -- for every j > 0, if const is in cv 1,j then const is in cv
3233   //      2,j, and similarly for volatile.
3234   if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3235     return false;
3236 
3237   // If address spaces mismatch:
3238   //  - in top level it is only valid to convert to addr space that is a
3239   //    superset in all cases apart from C-style casts where we allow
3240   //    conversions between overlapping address spaces.
3241   //  - in non-top levels it is not a valid conversion.
3242   if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3243       (!IsTopLevel ||
3244        !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3245          (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3246     return false;
3247 
3248   //   -- if the cv 1,j and cv 2,j are different, then const is in
3249   //      every cv for 0 < k < j.
3250   if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3251       !PreviousToQualsIncludeConst)
3252     return false;
3253 
3254   // The following wording is from C++20, where the result of the conversion
3255   // is T3, not T2.
3256   //   -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3257   //      "array of unknown bound of"
3258   if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3259     return false;
3260 
3261   //   -- if the resulting P3,i is different from P1,i [...], then const is
3262   //      added to every cv 3_k for 0 < k < i.
3263   if (!CStyle && FromType->isConstantArrayType() &&
3264       ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3265     return false;
3266 
3267   // Keep track of whether all prior cv-qualifiers in the "to" type
3268   // include const.
3269   PreviousToQualsIncludeConst =
3270       PreviousToQualsIncludeConst && ToQuals.hasConst();
3271   return true;
3272 }
3273 
3274 /// IsQualificationConversion - Determines whether the conversion from
3275 /// an rvalue of type FromType to ToType is a qualification conversion
3276 /// (C++ 4.4).
3277 ///
3278 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3279 /// when the qualification conversion involves a change in the Objective-C
3280 /// object lifetime.
3281 bool
3282 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3283                                 bool CStyle, bool &ObjCLifetimeConversion) {
3284   FromType = Context.getCanonicalType(FromType);
3285   ToType = Context.getCanonicalType(ToType);
3286   ObjCLifetimeConversion = false;
3287 
3288   // If FromType and ToType are the same type, this is not a
3289   // qualification conversion.
3290   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3291     return false;
3292 
3293   // (C++ 4.4p4):
3294   //   A conversion can add cv-qualifiers at levels other than the first
3295   //   in multi-level pointers, subject to the following rules: [...]
3296   bool PreviousToQualsIncludeConst = true;
3297   bool UnwrappedAnyPointer = false;
3298   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3299     if (!isQualificationConversionStep(
3300             FromType, ToType, CStyle, !UnwrappedAnyPointer,
3301             PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3302       return false;
3303     UnwrappedAnyPointer = true;
3304   }
3305 
3306   // We are left with FromType and ToType being the pointee types
3307   // after unwrapping the original FromType and ToType the same number
3308   // of times. If we unwrapped any pointers, and if FromType and
3309   // ToType have the same unqualified type (since we checked
3310   // qualifiers above), then this is a qualification conversion.
3311   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3312 }
3313 
3314 /// - Determine whether this is a conversion from a scalar type to an
3315 /// atomic type.
3316 ///
3317 /// If successful, updates \c SCS's second and third steps in the conversion
3318 /// sequence to finish the conversion.
3319 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3320                                 bool InOverloadResolution,
3321                                 StandardConversionSequence &SCS,
3322                                 bool CStyle) {
3323   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3324   if (!ToAtomic)
3325     return false;
3326 
3327   StandardConversionSequence InnerSCS;
3328   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3329                             InOverloadResolution, InnerSCS,
3330                             CStyle, /*AllowObjCWritebackConversion=*/false))
3331     return false;
3332 
3333   SCS.Second = InnerSCS.Second;
3334   SCS.setToType(1, InnerSCS.getToType(1));
3335   SCS.Third = InnerSCS.Third;
3336   SCS.QualificationIncludesObjCLifetime
3337     = InnerSCS.QualificationIncludesObjCLifetime;
3338   SCS.setToType(2, InnerSCS.getToType(2));
3339   return true;
3340 }
3341 
3342 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3343                                               CXXConstructorDecl *Constructor,
3344                                               QualType Type) {
3345   const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3346   if (CtorType->getNumParams() > 0) {
3347     QualType FirstArg = CtorType->getParamType(0);
3348     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3349       return true;
3350   }
3351   return false;
3352 }
3353 
3354 static OverloadingResult
3355 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3356                                        CXXRecordDecl *To,
3357                                        UserDefinedConversionSequence &User,
3358                                        OverloadCandidateSet &CandidateSet,
3359                                        bool AllowExplicit) {
3360   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3361   for (auto *D : S.LookupConstructors(To)) {
3362     auto Info = getConstructorInfo(D);
3363     if (!Info)
3364       continue;
3365 
3366     bool Usable = !Info.Constructor->isInvalidDecl() &&
3367                   S.isInitListConstructor(Info.Constructor);
3368     if (Usable) {
3369       bool SuppressUserConversions = false;
3370       if (Info.ConstructorTmpl)
3371         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3372                                        /*ExplicitArgs*/ nullptr, From,
3373                                        CandidateSet, SuppressUserConversions,
3374                                        /*PartialOverloading*/ false,
3375                                        AllowExplicit);
3376       else
3377         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3378                                CandidateSet, SuppressUserConversions,
3379                                /*PartialOverloading*/ false, AllowExplicit);
3380     }
3381   }
3382 
3383   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3384 
3385   OverloadCandidateSet::iterator Best;
3386   switch (auto Result =
3387               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3388   case OR_Deleted:
3389   case OR_Success: {
3390     // Record the standard conversion we used and the conversion function.
3391     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3392     QualType ThisType = Constructor->getThisType();
3393     // Initializer lists don't have conversions as such.
3394     User.Before.setAsIdentityConversion();
3395     User.HadMultipleCandidates = HadMultipleCandidates;
3396     User.ConversionFunction = Constructor;
3397     User.FoundConversionFunction = Best->FoundDecl;
3398     User.After.setAsIdentityConversion();
3399     User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3400     User.After.setAllToTypes(ToType);
3401     return Result;
3402   }
3403 
3404   case OR_No_Viable_Function:
3405     return OR_No_Viable_Function;
3406   case OR_Ambiguous:
3407     return OR_Ambiguous;
3408   }
3409 
3410   llvm_unreachable("Invalid OverloadResult!");
3411 }
3412 
3413 /// Determines whether there is a user-defined conversion sequence
3414 /// (C++ [over.ics.user]) that converts expression From to the type
3415 /// ToType. If such a conversion exists, User will contain the
3416 /// user-defined conversion sequence that performs such a conversion
3417 /// and this routine will return true. Otherwise, this routine returns
3418 /// false and User is unspecified.
3419 ///
3420 /// \param AllowExplicit  true if the conversion should consider C++0x
3421 /// "explicit" conversion functions as well as non-explicit conversion
3422 /// functions (C++0x [class.conv.fct]p2).
3423 ///
3424 /// \param AllowObjCConversionOnExplicit true if the conversion should
3425 /// allow an extra Objective-C pointer conversion on uses of explicit
3426 /// constructors. Requires \c AllowExplicit to also be set.
3427 static OverloadingResult
3428 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3429                         UserDefinedConversionSequence &User,
3430                         OverloadCandidateSet &CandidateSet,
3431                         AllowedExplicit AllowExplicit,
3432                         bool AllowObjCConversionOnExplicit) {
3433   assert(AllowExplicit != AllowedExplicit::None ||
3434          !AllowObjCConversionOnExplicit);
3435   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3436 
3437   // Whether we will only visit constructors.
3438   bool ConstructorsOnly = false;
3439 
3440   // If the type we are conversion to is a class type, enumerate its
3441   // constructors.
3442   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3443     // C++ [over.match.ctor]p1:
3444     //   When objects of class type are direct-initialized (8.5), or
3445     //   copy-initialized from an expression of the same or a
3446     //   derived class type (8.5), overload resolution selects the
3447     //   constructor. [...] For copy-initialization, the candidate
3448     //   functions are all the converting constructors (12.3.1) of
3449     //   that class. The argument list is the expression-list within
3450     //   the parentheses of the initializer.
3451     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3452         (From->getType()->getAs<RecordType>() &&
3453          S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3454       ConstructorsOnly = true;
3455 
3456     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3457       // We're not going to find any constructors.
3458     } else if (CXXRecordDecl *ToRecordDecl
3459                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3460 
3461       Expr **Args = &From;
3462       unsigned NumArgs = 1;
3463       bool ListInitializing = false;
3464       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3465         // But first, see if there is an init-list-constructor that will work.
3466         OverloadingResult Result = IsInitializerListConstructorConversion(
3467             S, From, ToType, ToRecordDecl, User, CandidateSet,
3468             AllowExplicit == AllowedExplicit::All);
3469         if (Result != OR_No_Viable_Function)
3470           return Result;
3471         // Never mind.
3472         CandidateSet.clear(
3473             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3474 
3475         // If we're list-initializing, we pass the individual elements as
3476         // arguments, not the entire list.
3477         Args = InitList->getInits();
3478         NumArgs = InitList->getNumInits();
3479         ListInitializing = true;
3480       }
3481 
3482       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3483         auto Info = getConstructorInfo(D);
3484         if (!Info)
3485           continue;
3486 
3487         bool Usable = !Info.Constructor->isInvalidDecl();
3488         if (!ListInitializing)
3489           Usable = Usable && Info.Constructor->isConvertingConstructor(
3490                                  /*AllowExplicit*/ true);
3491         if (Usable) {
3492           bool SuppressUserConversions = !ConstructorsOnly;
3493           // C++20 [over.best.ics.general]/4.5:
3494           //   if the target is the first parameter of a constructor [of class
3495           //   X] and the constructor [...] is a candidate by [...] the second
3496           //   phase of [over.match.list] when the initializer list has exactly
3497           //   one element that is itself an initializer list, [...] and the
3498           //   conversion is to X or reference to cv X, user-defined conversion
3499           //   sequences are not cnosidered.
3500           if (SuppressUserConversions && ListInitializing) {
3501             SuppressUserConversions =
3502                 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
3503                 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3504                                                   ToType);
3505           }
3506           if (Info.ConstructorTmpl)
3507             S.AddTemplateOverloadCandidate(
3508                 Info.ConstructorTmpl, Info.FoundDecl,
3509                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3510                 CandidateSet, SuppressUserConversions,
3511                 /*PartialOverloading*/ false,
3512                 AllowExplicit == AllowedExplicit::All);
3513           else
3514             // Allow one user-defined conversion when user specifies a
3515             // From->ToType conversion via an static cast (c-style, etc).
3516             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3517                                    llvm::makeArrayRef(Args, NumArgs),
3518                                    CandidateSet, SuppressUserConversions,
3519                                    /*PartialOverloading*/ false,
3520                                    AllowExplicit == AllowedExplicit::All);
3521         }
3522       }
3523     }
3524   }
3525 
3526   // Enumerate conversion functions, if we're allowed to.
3527   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3528   } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3529     // No conversion functions from incomplete types.
3530   } else if (const RecordType *FromRecordType =
3531                  From->getType()->getAs<RecordType>()) {
3532     if (CXXRecordDecl *FromRecordDecl
3533          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3534       // Add all of the conversion functions as candidates.
3535       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3536       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3537         DeclAccessPair FoundDecl = I.getPair();
3538         NamedDecl *D = FoundDecl.getDecl();
3539         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3540         if (isa<UsingShadowDecl>(D))
3541           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3542 
3543         CXXConversionDecl *Conv;
3544         FunctionTemplateDecl *ConvTemplate;
3545         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3546           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3547         else
3548           Conv = cast<CXXConversionDecl>(D);
3549 
3550         if (ConvTemplate)
3551           S.AddTemplateConversionCandidate(
3552               ConvTemplate, FoundDecl, ActingContext, From, ToType,
3553               CandidateSet, AllowObjCConversionOnExplicit,
3554               AllowExplicit != AllowedExplicit::None);
3555         else
3556           S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3557                                    CandidateSet, AllowObjCConversionOnExplicit,
3558                                    AllowExplicit != AllowedExplicit::None);
3559       }
3560     }
3561   }
3562 
3563   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3564 
3565   OverloadCandidateSet::iterator Best;
3566   switch (auto Result =
3567               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3568   case OR_Success:
3569   case OR_Deleted:
3570     // Record the standard conversion we used and the conversion function.
3571     if (CXXConstructorDecl *Constructor
3572           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3573       // C++ [over.ics.user]p1:
3574       //   If the user-defined conversion is specified by a
3575       //   constructor (12.3.1), the initial standard conversion
3576       //   sequence converts the source type to the type required by
3577       //   the argument of the constructor.
3578       //
3579       QualType ThisType = Constructor->getThisType();
3580       if (isa<InitListExpr>(From)) {
3581         // Initializer lists don't have conversions as such.
3582         User.Before.setAsIdentityConversion();
3583       } else {
3584         if (Best->Conversions[0].isEllipsis())
3585           User.EllipsisConversion = true;
3586         else {
3587           User.Before = Best->Conversions[0].Standard;
3588           User.EllipsisConversion = false;
3589         }
3590       }
3591       User.HadMultipleCandidates = HadMultipleCandidates;
3592       User.ConversionFunction = Constructor;
3593       User.FoundConversionFunction = Best->FoundDecl;
3594       User.After.setAsIdentityConversion();
3595       User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3596       User.After.setAllToTypes(ToType);
3597       return Result;
3598     }
3599     if (CXXConversionDecl *Conversion
3600                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3601       // C++ [over.ics.user]p1:
3602       //
3603       //   [...] If the user-defined conversion is specified by a
3604       //   conversion function (12.3.2), the initial standard
3605       //   conversion sequence converts the source type to the
3606       //   implicit object parameter of the conversion function.
3607       User.Before = Best->Conversions[0].Standard;
3608       User.HadMultipleCandidates = HadMultipleCandidates;
3609       User.ConversionFunction = Conversion;
3610       User.FoundConversionFunction = Best->FoundDecl;
3611       User.EllipsisConversion = false;
3612 
3613       // C++ [over.ics.user]p2:
3614       //   The second standard conversion sequence converts the
3615       //   result of the user-defined conversion to the target type
3616       //   for the sequence. Since an implicit conversion sequence
3617       //   is an initialization, the special rules for
3618       //   initialization by user-defined conversion apply when
3619       //   selecting the best user-defined conversion for a
3620       //   user-defined conversion sequence (see 13.3.3 and
3621       //   13.3.3.1).
3622       User.After = Best->FinalConversion;
3623       return Result;
3624     }
3625     llvm_unreachable("Not a constructor or conversion function?");
3626 
3627   case OR_No_Viable_Function:
3628     return OR_No_Viable_Function;
3629 
3630   case OR_Ambiguous:
3631     return OR_Ambiguous;
3632   }
3633 
3634   llvm_unreachable("Invalid OverloadResult!");
3635 }
3636 
3637 bool
3638 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3639   ImplicitConversionSequence ICS;
3640   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3641                                     OverloadCandidateSet::CSK_Normal);
3642   OverloadingResult OvResult =
3643     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3644                             CandidateSet, AllowedExplicit::None, false);
3645 
3646   if (!(OvResult == OR_Ambiguous ||
3647         (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3648     return false;
3649 
3650   auto Cands = CandidateSet.CompleteCandidates(
3651       *this,
3652       OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3653       From);
3654   if (OvResult == OR_Ambiguous)
3655     Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3656         << From->getType() << ToType << From->getSourceRange();
3657   else { // OR_No_Viable_Function && !CandidateSet.empty()
3658     if (!RequireCompleteType(From->getBeginLoc(), ToType,
3659                              diag::err_typecheck_nonviable_condition_incomplete,
3660                              From->getType(), From->getSourceRange()))
3661       Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3662           << false << From->getType() << From->getSourceRange() << ToType;
3663   }
3664 
3665   CandidateSet.NoteCandidates(
3666                               *this, From, Cands);
3667   return true;
3668 }
3669 
3670 // Helper for compareConversionFunctions that gets the FunctionType that the
3671 // conversion-operator return  value 'points' to, or nullptr.
3672 static const FunctionType *
3673 getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
3674   const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
3675   const PointerType *RetPtrTy =
3676       ConvFuncTy->getReturnType()->getAs<PointerType>();
3677 
3678   if (!RetPtrTy)
3679     return nullptr;
3680 
3681   return RetPtrTy->getPointeeType()->getAs<FunctionType>();
3682 }
3683 
3684 /// Compare the user-defined conversion functions or constructors
3685 /// of two user-defined conversion sequences to determine whether any ordering
3686 /// is possible.
3687 static ImplicitConversionSequence::CompareKind
3688 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3689                            FunctionDecl *Function2) {
3690   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3691   CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
3692   if (!Conv1 || !Conv2)
3693     return ImplicitConversionSequence::Indistinguishable;
3694 
3695   if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
3696     return ImplicitConversionSequence::Indistinguishable;
3697 
3698   // Objective-C++:
3699   //   If both conversion functions are implicitly-declared conversions from
3700   //   a lambda closure type to a function pointer and a block pointer,
3701   //   respectively, always prefer the conversion to a function pointer,
3702   //   because the function pointer is more lightweight and is more likely
3703   //   to keep code working.
3704   if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
3705     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3706     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3707     if (Block1 != Block2)
3708       return Block1 ? ImplicitConversionSequence::Worse
3709                     : ImplicitConversionSequence::Better;
3710   }
3711 
3712   // In order to support multiple calling conventions for the lambda conversion
3713   // operator (such as when the free and member function calling convention is
3714   // different), prefer the 'free' mechanism, followed by the calling-convention
3715   // of operator(). The latter is in place to support the MSVC-like solution of
3716   // defining ALL of the possible conversions in regards to calling-convention.
3717   const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
3718   const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
3719 
3720   if (Conv1FuncRet && Conv2FuncRet &&
3721       Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
3722     CallingConv Conv1CC = Conv1FuncRet->getCallConv();
3723     CallingConv Conv2CC = Conv2FuncRet->getCallConv();
3724 
3725     CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
3726     const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
3727 
3728     CallingConv CallOpCC =
3729         CallOp->getType()->castAs<FunctionType>()->getCallConv();
3730     CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
3731         CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
3732     CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
3733         CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
3734 
3735     CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
3736     for (CallingConv CC : PrefOrder) {
3737       if (Conv1CC == CC)
3738         return ImplicitConversionSequence::Better;
3739       if (Conv2CC == CC)
3740         return ImplicitConversionSequence::Worse;
3741     }
3742   }
3743 
3744   return ImplicitConversionSequence::Indistinguishable;
3745 }
3746 
3747 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3748     const ImplicitConversionSequence &ICS) {
3749   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3750          (ICS.isUserDefined() &&
3751           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3752 }
3753 
3754 /// CompareImplicitConversionSequences - Compare two implicit
3755 /// conversion sequences to determine whether one is better than the
3756 /// other or if they are indistinguishable (C++ 13.3.3.2).
3757 static ImplicitConversionSequence::CompareKind
3758 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3759                                    const ImplicitConversionSequence& ICS1,
3760                                    const ImplicitConversionSequence& ICS2)
3761 {
3762   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3763   // conversion sequences (as defined in 13.3.3.1)
3764   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3765   //      conversion sequence than a user-defined conversion sequence or
3766   //      an ellipsis conversion sequence, and
3767   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3768   //      conversion sequence than an ellipsis conversion sequence
3769   //      (13.3.3.1.3).
3770   //
3771   // C++0x [over.best.ics]p10:
3772   //   For the purpose of ranking implicit conversion sequences as
3773   //   described in 13.3.3.2, the ambiguous conversion sequence is
3774   //   treated as a user-defined sequence that is indistinguishable
3775   //   from any other user-defined conversion sequence.
3776 
3777   // String literal to 'char *' conversion has been deprecated in C++03. It has
3778   // been removed from C++11. We still accept this conversion, if it happens at
3779   // the best viable function. Otherwise, this conversion is considered worse
3780   // than ellipsis conversion. Consider this as an extension; this is not in the
3781   // standard. For example:
3782   //
3783   // int &f(...);    // #1
3784   // void f(char*);  // #2
3785   // void g() { int &r = f("foo"); }
3786   //
3787   // In C++03, we pick #2 as the best viable function.
3788   // In C++11, we pick #1 as the best viable function, because ellipsis
3789   // conversion is better than string-literal to char* conversion (since there
3790   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3791   // convert arguments, #2 would be the best viable function in C++11.
3792   // If the best viable function has this conversion, a warning will be issued
3793   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3794 
3795   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3796       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3797           hasDeprecatedStringLiteralToCharPtrConversion(ICS2) &&
3798       // Ill-formedness must not differ
3799       ICS1.isBad() == ICS2.isBad())
3800     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3801                ? ImplicitConversionSequence::Worse
3802                : ImplicitConversionSequence::Better;
3803 
3804   if (ICS1.getKindRank() < ICS2.getKindRank())
3805     return ImplicitConversionSequence::Better;
3806   if (ICS2.getKindRank() < ICS1.getKindRank())
3807     return ImplicitConversionSequence::Worse;
3808 
3809   // The following checks require both conversion sequences to be of
3810   // the same kind.
3811   if (ICS1.getKind() != ICS2.getKind())
3812     return ImplicitConversionSequence::Indistinguishable;
3813 
3814   ImplicitConversionSequence::CompareKind Result =
3815       ImplicitConversionSequence::Indistinguishable;
3816 
3817   // Two implicit conversion sequences of the same form are
3818   // indistinguishable conversion sequences unless one of the
3819   // following rules apply: (C++ 13.3.3.2p3):
3820 
3821   // List-initialization sequence L1 is a better conversion sequence than
3822   // list-initialization sequence L2 if:
3823   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3824   //   if not that,
3825   // — L1 and L2 convert to arrays of the same element type, and either the
3826   //   number of elements n_1 initialized by L1 is less than the number of
3827   //   elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
3828   //   an array of unknown bound and L1 does not,
3829   // even if one of the other rules in this paragraph would otherwise apply.
3830   if (!ICS1.isBad()) {
3831     bool StdInit1 = false, StdInit2 = false;
3832     if (ICS1.hasInitializerListContainerType())
3833       StdInit1 = S.isStdInitializerList(ICS1.getInitializerListContainerType(),
3834                                         nullptr);
3835     if (ICS2.hasInitializerListContainerType())
3836       StdInit2 = S.isStdInitializerList(ICS2.getInitializerListContainerType(),
3837                                         nullptr);
3838     if (StdInit1 != StdInit2)
3839       return StdInit1 ? ImplicitConversionSequence::Better
3840                       : ImplicitConversionSequence::Worse;
3841 
3842     if (ICS1.hasInitializerListContainerType() &&
3843         ICS2.hasInitializerListContainerType())
3844       if (auto *CAT1 = S.Context.getAsConstantArrayType(
3845               ICS1.getInitializerListContainerType()))
3846         if (auto *CAT2 = S.Context.getAsConstantArrayType(
3847                 ICS2.getInitializerListContainerType())) {
3848           if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
3849                                                CAT2->getElementType())) {
3850             // Both to arrays of the same element type
3851             if (CAT1->getSize() != CAT2->getSize())
3852               // Different sized, the smaller wins
3853               return CAT1->getSize().ult(CAT2->getSize())
3854                          ? ImplicitConversionSequence::Better
3855                          : ImplicitConversionSequence::Worse;
3856             if (ICS1.isInitializerListOfIncompleteArray() !=
3857                 ICS2.isInitializerListOfIncompleteArray())
3858               // One is incomplete, it loses
3859               return ICS2.isInitializerListOfIncompleteArray()
3860                          ? ImplicitConversionSequence::Better
3861                          : ImplicitConversionSequence::Worse;
3862           }
3863         }
3864   }
3865 
3866   if (ICS1.isStandard())
3867     // Standard conversion sequence S1 is a better conversion sequence than
3868     // standard conversion sequence S2 if [...]
3869     Result = CompareStandardConversionSequences(S, Loc,
3870                                                 ICS1.Standard, ICS2.Standard);
3871   else if (ICS1.isUserDefined()) {
3872     // User-defined conversion sequence U1 is a better conversion
3873     // sequence than another user-defined conversion sequence U2 if
3874     // they contain the same user-defined conversion function or
3875     // constructor and if the second standard conversion sequence of
3876     // U1 is better than the second standard conversion sequence of
3877     // U2 (C++ 13.3.3.2p3).
3878     if (ICS1.UserDefined.ConversionFunction ==
3879           ICS2.UserDefined.ConversionFunction)
3880       Result = CompareStandardConversionSequences(S, Loc,
3881                                                   ICS1.UserDefined.After,
3882                                                   ICS2.UserDefined.After);
3883     else
3884       Result = compareConversionFunctions(S,
3885                                           ICS1.UserDefined.ConversionFunction,
3886                                           ICS2.UserDefined.ConversionFunction);
3887   }
3888 
3889   return Result;
3890 }
3891 
3892 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3893 // determine if one is a proper subset of the other.
3894 static ImplicitConversionSequence::CompareKind
3895 compareStandardConversionSubsets(ASTContext &Context,
3896                                  const StandardConversionSequence& SCS1,
3897                                  const StandardConversionSequence& SCS2) {
3898   ImplicitConversionSequence::CompareKind Result
3899     = ImplicitConversionSequence::Indistinguishable;
3900 
3901   // the identity conversion sequence is considered to be a subsequence of
3902   // any non-identity conversion sequence
3903   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3904     return ImplicitConversionSequence::Better;
3905   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3906     return ImplicitConversionSequence::Worse;
3907 
3908   if (SCS1.Second != SCS2.Second) {
3909     if (SCS1.Second == ICK_Identity)
3910       Result = ImplicitConversionSequence::Better;
3911     else if (SCS2.Second == ICK_Identity)
3912       Result = ImplicitConversionSequence::Worse;
3913     else
3914       return ImplicitConversionSequence::Indistinguishable;
3915   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3916     return ImplicitConversionSequence::Indistinguishable;
3917 
3918   if (SCS1.Third == SCS2.Third) {
3919     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3920                              : ImplicitConversionSequence::Indistinguishable;
3921   }
3922 
3923   if (SCS1.Third == ICK_Identity)
3924     return Result == ImplicitConversionSequence::Worse
3925              ? ImplicitConversionSequence::Indistinguishable
3926              : ImplicitConversionSequence::Better;
3927 
3928   if (SCS2.Third == ICK_Identity)
3929     return Result == ImplicitConversionSequence::Better
3930              ? ImplicitConversionSequence::Indistinguishable
3931              : ImplicitConversionSequence::Worse;
3932 
3933   return ImplicitConversionSequence::Indistinguishable;
3934 }
3935 
3936 /// Determine whether one of the given reference bindings is better
3937 /// than the other based on what kind of bindings they are.
3938 static bool
3939 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3940                              const StandardConversionSequence &SCS2) {
3941   // C++0x [over.ics.rank]p3b4:
3942   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3943   //      implicit object parameter of a non-static member function declared
3944   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3945   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3946   //      lvalue reference to a function lvalue and S2 binds an rvalue
3947   //      reference*.
3948   //
3949   // FIXME: Rvalue references. We're going rogue with the above edits,
3950   // because the semantics in the current C++0x working paper (N3225 at the
3951   // time of this writing) break the standard definition of std::forward
3952   // and std::reference_wrapper when dealing with references to functions.
3953   // Proposed wording changes submitted to CWG for consideration.
3954   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3955       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3956     return false;
3957 
3958   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3959           SCS2.IsLvalueReference) ||
3960          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3961           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3962 }
3963 
3964 enum class FixedEnumPromotion {
3965   None,
3966   ToUnderlyingType,
3967   ToPromotedUnderlyingType
3968 };
3969 
3970 /// Returns kind of fixed enum promotion the \a SCS uses.
3971 static FixedEnumPromotion
3972 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
3973 
3974   if (SCS.Second != ICK_Integral_Promotion)
3975     return FixedEnumPromotion::None;
3976 
3977   QualType FromType = SCS.getFromType();
3978   if (!FromType->isEnumeralType())
3979     return FixedEnumPromotion::None;
3980 
3981   EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
3982   if (!Enum->isFixed())
3983     return FixedEnumPromotion::None;
3984 
3985   QualType UnderlyingType = Enum->getIntegerType();
3986   if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
3987     return FixedEnumPromotion::ToUnderlyingType;
3988 
3989   return FixedEnumPromotion::ToPromotedUnderlyingType;
3990 }
3991 
3992 /// CompareStandardConversionSequences - Compare two standard
3993 /// conversion sequences to determine whether one is better than the
3994 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3995 static ImplicitConversionSequence::CompareKind
3996 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3997                                    const StandardConversionSequence& SCS1,
3998                                    const StandardConversionSequence& SCS2)
3999 {
4000   // Standard conversion sequence S1 is a better conversion sequence
4001   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4002 
4003   //  -- S1 is a proper subsequence of S2 (comparing the conversion
4004   //     sequences in the canonical form defined by 13.3.3.1.1,
4005   //     excluding any Lvalue Transformation; the identity conversion
4006   //     sequence is considered to be a subsequence of any
4007   //     non-identity conversion sequence) or, if not that,
4008   if (ImplicitConversionSequence::CompareKind CK
4009         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
4010     return CK;
4011 
4012   //  -- the rank of S1 is better than the rank of S2 (by the rules
4013   //     defined below), or, if not that,
4014   ImplicitConversionRank Rank1 = SCS1.getRank();
4015   ImplicitConversionRank Rank2 = SCS2.getRank();
4016   if (Rank1 < Rank2)
4017     return ImplicitConversionSequence::Better;
4018   else if (Rank2 < Rank1)
4019     return ImplicitConversionSequence::Worse;
4020 
4021   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4022   // are indistinguishable unless one of the following rules
4023   // applies:
4024 
4025   //   A conversion that is not a conversion of a pointer, or
4026   //   pointer to member, to bool is better than another conversion
4027   //   that is such a conversion.
4028   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4029     return SCS2.isPointerConversionToBool()
4030              ? ImplicitConversionSequence::Better
4031              : ImplicitConversionSequence::Worse;
4032 
4033   // C++14 [over.ics.rank]p4b2:
4034   // This is retroactively applied to C++11 by CWG 1601.
4035   //
4036   //   A conversion that promotes an enumeration whose underlying type is fixed
4037   //   to its underlying type is better than one that promotes to the promoted
4038   //   underlying type, if the two are different.
4039   FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
4040   FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
4041   if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4042       FEP1 != FEP2)
4043     return FEP1 == FixedEnumPromotion::ToUnderlyingType
4044                ? ImplicitConversionSequence::Better
4045                : ImplicitConversionSequence::Worse;
4046 
4047   // C++ [over.ics.rank]p4b2:
4048   //
4049   //   If class B is derived directly or indirectly from class A,
4050   //   conversion of B* to A* is better than conversion of B* to
4051   //   void*, and conversion of A* to void* is better than conversion
4052   //   of B* to void*.
4053   bool SCS1ConvertsToVoid
4054     = SCS1.isPointerConversionToVoidPointer(S.Context);
4055   bool SCS2ConvertsToVoid
4056     = SCS2.isPointerConversionToVoidPointer(S.Context);
4057   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4058     // Exactly one of the conversion sequences is a conversion to
4059     // a void pointer; it's the worse conversion.
4060     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4061                               : ImplicitConversionSequence::Worse;
4062   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4063     // Neither conversion sequence converts to a void pointer; compare
4064     // their derived-to-base conversions.
4065     if (ImplicitConversionSequence::CompareKind DerivedCK
4066           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4067       return DerivedCK;
4068   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4069              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4070     // Both conversion sequences are conversions to void
4071     // pointers. Compare the source types to determine if there's an
4072     // inheritance relationship in their sources.
4073     QualType FromType1 = SCS1.getFromType();
4074     QualType FromType2 = SCS2.getFromType();
4075 
4076     // Adjust the types we're converting from via the array-to-pointer
4077     // conversion, if we need to.
4078     if (SCS1.First == ICK_Array_To_Pointer)
4079       FromType1 = S.Context.getArrayDecayedType(FromType1);
4080     if (SCS2.First == ICK_Array_To_Pointer)
4081       FromType2 = S.Context.getArrayDecayedType(FromType2);
4082 
4083     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4084     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4085 
4086     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4087       return ImplicitConversionSequence::Better;
4088     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4089       return ImplicitConversionSequence::Worse;
4090 
4091     // Objective-C++: If one interface is more specific than the
4092     // other, it is the better one.
4093     const ObjCObjectPointerType* FromObjCPtr1
4094       = FromType1->getAs<ObjCObjectPointerType>();
4095     const ObjCObjectPointerType* FromObjCPtr2
4096       = FromType2->getAs<ObjCObjectPointerType>();
4097     if (FromObjCPtr1 && FromObjCPtr2) {
4098       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4099                                                           FromObjCPtr2);
4100       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4101                                                            FromObjCPtr1);
4102       if (AssignLeft != AssignRight) {
4103         return AssignLeft? ImplicitConversionSequence::Better
4104                          : ImplicitConversionSequence::Worse;
4105       }
4106     }
4107   }
4108 
4109   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4110     // Check for a better reference binding based on the kind of bindings.
4111     if (isBetterReferenceBindingKind(SCS1, SCS2))
4112       return ImplicitConversionSequence::Better;
4113     else if (isBetterReferenceBindingKind(SCS2, SCS1))
4114       return ImplicitConversionSequence::Worse;
4115   }
4116 
4117   // Compare based on qualification conversions (C++ 13.3.3.2p3,
4118   // bullet 3).
4119   if (ImplicitConversionSequence::CompareKind QualCK
4120         = CompareQualificationConversions(S, SCS1, SCS2))
4121     return QualCK;
4122 
4123   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4124     // C++ [over.ics.rank]p3b4:
4125     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
4126     //      which the references refer are the same type except for
4127     //      top-level cv-qualifiers, and the type to which the reference
4128     //      initialized by S2 refers is more cv-qualified than the type
4129     //      to which the reference initialized by S1 refers.
4130     QualType T1 = SCS1.getToType(2);
4131     QualType T2 = SCS2.getToType(2);
4132     T1 = S.Context.getCanonicalType(T1);
4133     T2 = S.Context.getCanonicalType(T2);
4134     Qualifiers T1Quals, T2Quals;
4135     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4136     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4137     if (UnqualT1 == UnqualT2) {
4138       // Objective-C++ ARC: If the references refer to objects with different
4139       // lifetimes, prefer bindings that don't change lifetime.
4140       if (SCS1.ObjCLifetimeConversionBinding !=
4141                                           SCS2.ObjCLifetimeConversionBinding) {
4142         return SCS1.ObjCLifetimeConversionBinding
4143                                            ? ImplicitConversionSequence::Worse
4144                                            : ImplicitConversionSequence::Better;
4145       }
4146 
4147       // If the type is an array type, promote the element qualifiers to the
4148       // type for comparison.
4149       if (isa<ArrayType>(T1) && T1Quals)
4150         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4151       if (isa<ArrayType>(T2) && T2Quals)
4152         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4153       if (T2.isMoreQualifiedThan(T1))
4154         return ImplicitConversionSequence::Better;
4155       if (T1.isMoreQualifiedThan(T2))
4156         return ImplicitConversionSequence::Worse;
4157     }
4158   }
4159 
4160   // In Microsoft mode (below 19.28), prefer an integral conversion to a
4161   // floating-to-integral conversion if the integral conversion
4162   // is between types of the same size.
4163   // For example:
4164   // void f(float);
4165   // void f(int);
4166   // int main {
4167   //    long a;
4168   //    f(a);
4169   // }
4170   // Here, MSVC will call f(int) instead of generating a compile error
4171   // as clang will do in standard mode.
4172   if (S.getLangOpts().MSVCCompat &&
4173       !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) &&
4174       SCS1.Second == ICK_Integral_Conversion &&
4175       SCS2.Second == ICK_Floating_Integral &&
4176       S.Context.getTypeSize(SCS1.getFromType()) ==
4177           S.Context.getTypeSize(SCS1.getToType(2)))
4178     return ImplicitConversionSequence::Better;
4179 
4180   // Prefer a compatible vector conversion over a lax vector conversion
4181   // For example:
4182   //
4183   // typedef float __v4sf __attribute__((__vector_size__(16)));
4184   // void f(vector float);
4185   // void f(vector signed int);
4186   // int main() {
4187   //   __v4sf a;
4188   //   f(a);
4189   // }
4190   // Here, we'd like to choose f(vector float) and not
4191   // report an ambiguous call error
4192   if (SCS1.Second == ICK_Vector_Conversion &&
4193       SCS2.Second == ICK_Vector_Conversion) {
4194     bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4195         SCS1.getFromType(), SCS1.getToType(2));
4196     bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4197         SCS2.getFromType(), SCS2.getToType(2));
4198 
4199     if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4200       return SCS1IsCompatibleVectorConversion
4201                  ? ImplicitConversionSequence::Better
4202                  : ImplicitConversionSequence::Worse;
4203   }
4204 
4205   if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4206       SCS2.Second == ICK_SVE_Vector_Conversion) {
4207     bool SCS1IsCompatibleSVEVectorConversion =
4208         S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4209     bool SCS2IsCompatibleSVEVectorConversion =
4210         S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4211 
4212     if (SCS1IsCompatibleSVEVectorConversion !=
4213         SCS2IsCompatibleSVEVectorConversion)
4214       return SCS1IsCompatibleSVEVectorConversion
4215                  ? ImplicitConversionSequence::Better
4216                  : ImplicitConversionSequence::Worse;
4217   }
4218 
4219   return ImplicitConversionSequence::Indistinguishable;
4220 }
4221 
4222 /// CompareQualificationConversions - Compares two standard conversion
4223 /// sequences to determine whether they can be ranked based on their
4224 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4225 static ImplicitConversionSequence::CompareKind
4226 CompareQualificationConversions(Sema &S,
4227                                 const StandardConversionSequence& SCS1,
4228                                 const StandardConversionSequence& SCS2) {
4229   // C++ [over.ics.rank]p3:
4230   //  -- S1 and S2 differ only in their qualification conversion and
4231   //     yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4232   // [C++98]
4233   //     [...] and the cv-qualification signature of type T1 is a proper subset
4234   //     of the cv-qualification signature of type T2, and S1 is not the
4235   //     deprecated string literal array-to-pointer conversion (4.2).
4236   // [C++2a]
4237   //     [...] where T1 can be converted to T2 by a qualification conversion.
4238   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4239       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4240     return ImplicitConversionSequence::Indistinguishable;
4241 
4242   // FIXME: the example in the standard doesn't use a qualification
4243   // conversion (!)
4244   QualType T1 = SCS1.getToType(2);
4245   QualType T2 = SCS2.getToType(2);
4246   T1 = S.Context.getCanonicalType(T1);
4247   T2 = S.Context.getCanonicalType(T2);
4248   assert(!T1->isReferenceType() && !T2->isReferenceType());
4249   Qualifiers T1Quals, T2Quals;
4250   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4251   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4252 
4253   // If the types are the same, we won't learn anything by unwrapping
4254   // them.
4255   if (UnqualT1 == UnqualT2)
4256     return ImplicitConversionSequence::Indistinguishable;
4257 
4258   // Don't ever prefer a standard conversion sequence that uses the deprecated
4259   // string literal array to pointer conversion.
4260   bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4261   bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4262 
4263   // Objective-C++ ARC:
4264   //   Prefer qualification conversions not involving a change in lifetime
4265   //   to qualification conversions that do change lifetime.
4266   if (SCS1.QualificationIncludesObjCLifetime &&
4267       !SCS2.QualificationIncludesObjCLifetime)
4268     CanPick1 = false;
4269   if (SCS2.QualificationIncludesObjCLifetime &&
4270       !SCS1.QualificationIncludesObjCLifetime)
4271     CanPick2 = false;
4272 
4273   bool ObjCLifetimeConversion;
4274   if (CanPick1 &&
4275       !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4276     CanPick1 = false;
4277   // FIXME: In Objective-C ARC, we can have qualification conversions in both
4278   // directions, so we can't short-cut this second check in general.
4279   if (CanPick2 &&
4280       !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4281     CanPick2 = false;
4282 
4283   if (CanPick1 != CanPick2)
4284     return CanPick1 ? ImplicitConversionSequence::Better
4285                     : ImplicitConversionSequence::Worse;
4286   return ImplicitConversionSequence::Indistinguishable;
4287 }
4288 
4289 /// CompareDerivedToBaseConversions - Compares two standard conversion
4290 /// sequences to determine whether they can be ranked based on their
4291 /// various kinds of derived-to-base conversions (C++
4292 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4293 /// conversions between Objective-C interface types.
4294 static ImplicitConversionSequence::CompareKind
4295 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4296                                 const StandardConversionSequence& SCS1,
4297                                 const StandardConversionSequence& SCS2) {
4298   QualType FromType1 = SCS1.getFromType();
4299   QualType ToType1 = SCS1.getToType(1);
4300   QualType FromType2 = SCS2.getFromType();
4301   QualType ToType2 = SCS2.getToType(1);
4302 
4303   // Adjust the types we're converting from via the array-to-pointer
4304   // conversion, if we need to.
4305   if (SCS1.First == ICK_Array_To_Pointer)
4306     FromType1 = S.Context.getArrayDecayedType(FromType1);
4307   if (SCS2.First == ICK_Array_To_Pointer)
4308     FromType2 = S.Context.getArrayDecayedType(FromType2);
4309 
4310   // Canonicalize all of the types.
4311   FromType1 = S.Context.getCanonicalType(FromType1);
4312   ToType1 = S.Context.getCanonicalType(ToType1);
4313   FromType2 = S.Context.getCanonicalType(FromType2);
4314   ToType2 = S.Context.getCanonicalType(ToType2);
4315 
4316   // C++ [over.ics.rank]p4b3:
4317   //
4318   //   If class B is derived directly or indirectly from class A and
4319   //   class C is derived directly or indirectly from B,
4320   //
4321   // Compare based on pointer conversions.
4322   if (SCS1.Second == ICK_Pointer_Conversion &&
4323       SCS2.Second == ICK_Pointer_Conversion &&
4324       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4325       FromType1->isPointerType() && FromType2->isPointerType() &&
4326       ToType1->isPointerType() && ToType2->isPointerType()) {
4327     QualType FromPointee1 =
4328         FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4329     QualType ToPointee1 =
4330         ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4331     QualType FromPointee2 =
4332         FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4333     QualType ToPointee2 =
4334         ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4335 
4336     //   -- conversion of C* to B* is better than conversion of C* to A*,
4337     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4338       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4339         return ImplicitConversionSequence::Better;
4340       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4341         return ImplicitConversionSequence::Worse;
4342     }
4343 
4344     //   -- conversion of B* to A* is better than conversion of C* to A*,
4345     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4346       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4347         return ImplicitConversionSequence::Better;
4348       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4349         return ImplicitConversionSequence::Worse;
4350     }
4351   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4352              SCS2.Second == ICK_Pointer_Conversion) {
4353     const ObjCObjectPointerType *FromPtr1
4354       = FromType1->getAs<ObjCObjectPointerType>();
4355     const ObjCObjectPointerType *FromPtr2
4356       = FromType2->getAs<ObjCObjectPointerType>();
4357     const ObjCObjectPointerType *ToPtr1
4358       = ToType1->getAs<ObjCObjectPointerType>();
4359     const ObjCObjectPointerType *ToPtr2
4360       = ToType2->getAs<ObjCObjectPointerType>();
4361 
4362     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4363       // Apply the same conversion ranking rules for Objective-C pointer types
4364       // that we do for C++ pointers to class types. However, we employ the
4365       // Objective-C pseudo-subtyping relationship used for assignment of
4366       // Objective-C pointer types.
4367       bool FromAssignLeft
4368         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4369       bool FromAssignRight
4370         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4371       bool ToAssignLeft
4372         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4373       bool ToAssignRight
4374         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4375 
4376       // A conversion to an a non-id object pointer type or qualified 'id'
4377       // type is better than a conversion to 'id'.
4378       if (ToPtr1->isObjCIdType() &&
4379           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4380         return ImplicitConversionSequence::Worse;
4381       if (ToPtr2->isObjCIdType() &&
4382           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4383         return ImplicitConversionSequence::Better;
4384 
4385       // A conversion to a non-id object pointer type is better than a
4386       // conversion to a qualified 'id' type
4387       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4388         return ImplicitConversionSequence::Worse;
4389       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4390         return ImplicitConversionSequence::Better;
4391 
4392       // A conversion to an a non-Class object pointer type or qualified 'Class'
4393       // type is better than a conversion to 'Class'.
4394       if (ToPtr1->isObjCClassType() &&
4395           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4396         return ImplicitConversionSequence::Worse;
4397       if (ToPtr2->isObjCClassType() &&
4398           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4399         return ImplicitConversionSequence::Better;
4400 
4401       // A conversion to a non-Class object pointer type is better than a
4402       // conversion to a qualified 'Class' type.
4403       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4404         return ImplicitConversionSequence::Worse;
4405       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4406         return ImplicitConversionSequence::Better;
4407 
4408       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4409       if (S.Context.hasSameType(FromType1, FromType2) &&
4410           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4411           (ToAssignLeft != ToAssignRight)) {
4412         if (FromPtr1->isSpecialized()) {
4413           // "conversion of B<A> * to B * is better than conversion of B * to
4414           // C *.
4415           bool IsFirstSame =
4416               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4417           bool IsSecondSame =
4418               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4419           if (IsFirstSame) {
4420             if (!IsSecondSame)
4421               return ImplicitConversionSequence::Better;
4422           } else if (IsSecondSame)
4423             return ImplicitConversionSequence::Worse;
4424         }
4425         return ToAssignLeft? ImplicitConversionSequence::Worse
4426                            : ImplicitConversionSequence::Better;
4427       }
4428 
4429       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4430       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4431           (FromAssignLeft != FromAssignRight))
4432         return FromAssignLeft? ImplicitConversionSequence::Better
4433         : ImplicitConversionSequence::Worse;
4434     }
4435   }
4436 
4437   // Ranking of member-pointer types.
4438   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4439       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4440       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4441     const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4442     const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4443     const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4444     const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4445     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4446     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4447     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4448     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4449     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4450     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4451     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4452     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4453     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4454     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4455       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4456         return ImplicitConversionSequence::Worse;
4457       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4458         return ImplicitConversionSequence::Better;
4459     }
4460     // conversion of B::* to C::* is better than conversion of A::* to C::*
4461     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4462       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4463         return ImplicitConversionSequence::Better;
4464       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4465         return ImplicitConversionSequence::Worse;
4466     }
4467   }
4468 
4469   if (SCS1.Second == ICK_Derived_To_Base) {
4470     //   -- conversion of C to B is better than conversion of C to A,
4471     //   -- binding of an expression of type C to a reference of type
4472     //      B& is better than binding an expression of type C to a
4473     //      reference of type A&,
4474     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4475         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4476       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4477         return ImplicitConversionSequence::Better;
4478       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4479         return ImplicitConversionSequence::Worse;
4480     }
4481 
4482     //   -- conversion of B to A is better than conversion of C to A.
4483     //   -- binding of an expression of type B to a reference of type
4484     //      A& is better than binding an expression of type C to a
4485     //      reference of type A&,
4486     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4487         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4488       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4489         return ImplicitConversionSequence::Better;
4490       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4491         return ImplicitConversionSequence::Worse;
4492     }
4493   }
4494 
4495   return ImplicitConversionSequence::Indistinguishable;
4496 }
4497 
4498 /// Determine whether the given type is valid, e.g., it is not an invalid
4499 /// C++ class.
4500 static bool isTypeValid(QualType T) {
4501   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4502     return !Record->isInvalidDecl();
4503 
4504   return true;
4505 }
4506 
4507 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4508   if (!T.getQualifiers().hasUnaligned())
4509     return T;
4510 
4511   Qualifiers Q;
4512   T = Ctx.getUnqualifiedArrayType(T, Q);
4513   Q.removeUnaligned();
4514   return Ctx.getQualifiedType(T, Q);
4515 }
4516 
4517 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4518 /// determine whether they are reference-compatible,
4519 /// reference-related, or incompatible, for use in C++ initialization by
4520 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4521 /// type, and the first type (T1) is the pointee type of the reference
4522 /// type being initialized.
4523 Sema::ReferenceCompareResult
4524 Sema::CompareReferenceRelationship(SourceLocation Loc,
4525                                    QualType OrigT1, QualType OrigT2,
4526                                    ReferenceConversions *ConvOut) {
4527   assert(!OrigT1->isReferenceType() &&
4528     "T1 must be the pointee type of the reference type");
4529   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4530 
4531   QualType T1 = Context.getCanonicalType(OrigT1);
4532   QualType T2 = Context.getCanonicalType(OrigT2);
4533   Qualifiers T1Quals, T2Quals;
4534   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4535   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4536 
4537   ReferenceConversions ConvTmp;
4538   ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4539   Conv = ReferenceConversions();
4540 
4541   // C++2a [dcl.init.ref]p4:
4542   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4543   //   reference-related to "cv2 T2" if T1 is similar to T2, or
4544   //   T1 is a base class of T2.
4545   //   "cv1 T1" is reference-compatible with "cv2 T2" if
4546   //   a prvalue of type "pointer to cv2 T2" can be converted to the type
4547   //   "pointer to cv1 T1" via a standard conversion sequence.
4548 
4549   // Check for standard conversions we can apply to pointers: derived-to-base
4550   // conversions, ObjC pointer conversions, and function pointer conversions.
4551   // (Qualification conversions are checked last.)
4552   QualType ConvertedT2;
4553   if (UnqualT1 == UnqualT2) {
4554     // Nothing to do.
4555   } else if (isCompleteType(Loc, OrigT2) &&
4556              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4557              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4558     Conv |= ReferenceConversions::DerivedToBase;
4559   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4560            UnqualT2->isObjCObjectOrInterfaceType() &&
4561            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4562     Conv |= ReferenceConversions::ObjC;
4563   else if (UnqualT2->isFunctionType() &&
4564            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4565     Conv |= ReferenceConversions::Function;
4566     // No need to check qualifiers; function types don't have them.
4567     return Ref_Compatible;
4568   }
4569   bool ConvertedReferent = Conv != 0;
4570 
4571   // We can have a qualification conversion. Compute whether the types are
4572   // similar at the same time.
4573   bool PreviousToQualsIncludeConst = true;
4574   bool TopLevel = true;
4575   do {
4576     if (T1 == T2)
4577       break;
4578 
4579     // We will need a qualification conversion.
4580     Conv |= ReferenceConversions::Qualification;
4581 
4582     // Track whether we performed a qualification conversion anywhere other
4583     // than the top level. This matters for ranking reference bindings in
4584     // overload resolution.
4585     if (!TopLevel)
4586       Conv |= ReferenceConversions::NestedQualification;
4587 
4588     // MS compiler ignores __unaligned qualifier for references; do the same.
4589     T1 = withoutUnaligned(Context, T1);
4590     T2 = withoutUnaligned(Context, T2);
4591 
4592     // If we find a qualifier mismatch, the types are not reference-compatible,
4593     // but are still be reference-related if they're similar.
4594     bool ObjCLifetimeConversion = false;
4595     if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4596                                        PreviousToQualsIncludeConst,
4597                                        ObjCLifetimeConversion))
4598       return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4599                  ? Ref_Related
4600                  : Ref_Incompatible;
4601 
4602     // FIXME: Should we track this for any level other than the first?
4603     if (ObjCLifetimeConversion)
4604       Conv |= ReferenceConversions::ObjCLifetime;
4605 
4606     TopLevel = false;
4607   } while (Context.UnwrapSimilarTypes(T1, T2));
4608 
4609   // At this point, if the types are reference-related, we must either have the
4610   // same inner type (ignoring qualifiers), or must have already worked out how
4611   // to convert the referent.
4612   return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4613              ? Ref_Compatible
4614              : Ref_Incompatible;
4615 }
4616 
4617 /// Look for a user-defined conversion to a value reference-compatible
4618 ///        with DeclType. Return true if something definite is found.
4619 static bool
4620 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4621                          QualType DeclType, SourceLocation DeclLoc,
4622                          Expr *Init, QualType T2, bool AllowRvalues,
4623                          bool AllowExplicit) {
4624   assert(T2->isRecordType() && "Can only find conversions of record types.");
4625   auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4626 
4627   OverloadCandidateSet CandidateSet(
4628       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4629   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4630   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4631     NamedDecl *D = *I;
4632     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4633     if (isa<UsingShadowDecl>(D))
4634       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4635 
4636     FunctionTemplateDecl *ConvTemplate
4637       = dyn_cast<FunctionTemplateDecl>(D);
4638     CXXConversionDecl *Conv;
4639     if (ConvTemplate)
4640       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4641     else
4642       Conv = cast<CXXConversionDecl>(D);
4643 
4644     if (AllowRvalues) {
4645       // If we are initializing an rvalue reference, don't permit conversion
4646       // functions that return lvalues.
4647       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4648         const ReferenceType *RefType
4649           = Conv->getConversionType()->getAs<LValueReferenceType>();
4650         if (RefType && !RefType->getPointeeType()->isFunctionType())
4651           continue;
4652       }
4653 
4654       if (!ConvTemplate &&
4655           S.CompareReferenceRelationship(
4656               DeclLoc,
4657               Conv->getConversionType()
4658                   .getNonReferenceType()
4659                   .getUnqualifiedType(),
4660               DeclType.getNonReferenceType().getUnqualifiedType()) ==
4661               Sema::Ref_Incompatible)
4662         continue;
4663     } else {
4664       // If the conversion function doesn't return a reference type,
4665       // it can't be considered for this conversion. An rvalue reference
4666       // is only acceptable if its referencee is a function type.
4667 
4668       const ReferenceType *RefType =
4669         Conv->getConversionType()->getAs<ReferenceType>();
4670       if (!RefType ||
4671           (!RefType->isLValueReferenceType() &&
4672            !RefType->getPointeeType()->isFunctionType()))
4673         continue;
4674     }
4675 
4676     if (ConvTemplate)
4677       S.AddTemplateConversionCandidate(
4678           ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4679           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4680     else
4681       S.AddConversionCandidate(
4682           Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4683           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4684   }
4685 
4686   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4687 
4688   OverloadCandidateSet::iterator Best;
4689   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4690   case OR_Success:
4691     // C++ [over.ics.ref]p1:
4692     //
4693     //   [...] If the parameter binds directly to the result of
4694     //   applying a conversion function to the argument
4695     //   expression, the implicit conversion sequence is a
4696     //   user-defined conversion sequence (13.3.3.1.2), with the
4697     //   second standard conversion sequence either an identity
4698     //   conversion or, if the conversion function returns an
4699     //   entity of a type that is a derived class of the parameter
4700     //   type, a derived-to-base Conversion.
4701     if (!Best->FinalConversion.DirectBinding)
4702       return false;
4703 
4704     ICS.setUserDefined();
4705     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4706     ICS.UserDefined.After = Best->FinalConversion;
4707     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4708     ICS.UserDefined.ConversionFunction = Best->Function;
4709     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4710     ICS.UserDefined.EllipsisConversion = false;
4711     assert(ICS.UserDefined.After.ReferenceBinding &&
4712            ICS.UserDefined.After.DirectBinding &&
4713            "Expected a direct reference binding!");
4714     return true;
4715 
4716   case OR_Ambiguous:
4717     ICS.setAmbiguous();
4718     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4719          Cand != CandidateSet.end(); ++Cand)
4720       if (Cand->Best)
4721         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4722     return true;
4723 
4724   case OR_No_Viable_Function:
4725   case OR_Deleted:
4726     // There was no suitable conversion, or we found a deleted
4727     // conversion; continue with other checks.
4728     return false;
4729   }
4730 
4731   llvm_unreachable("Invalid OverloadResult!");
4732 }
4733 
4734 /// Compute an implicit conversion sequence for reference
4735 /// initialization.
4736 static ImplicitConversionSequence
4737 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4738                  SourceLocation DeclLoc,
4739                  bool SuppressUserConversions,
4740                  bool AllowExplicit) {
4741   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4742 
4743   // Most paths end in a failed conversion.
4744   ImplicitConversionSequence ICS;
4745   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4746 
4747   QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4748   QualType T2 = Init->getType();
4749 
4750   // If the initializer is the address of an overloaded function, try
4751   // to resolve the overloaded function. If all goes well, T2 is the
4752   // type of the resulting function.
4753   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4754     DeclAccessPair Found;
4755     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4756                                                                 false, Found))
4757       T2 = Fn->getType();
4758   }
4759 
4760   // Compute some basic properties of the types and the initializer.
4761   bool isRValRef = DeclType->isRValueReferenceType();
4762   Expr::Classification InitCategory = Init->Classify(S.Context);
4763 
4764   Sema::ReferenceConversions RefConv;
4765   Sema::ReferenceCompareResult RefRelationship =
4766       S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4767 
4768   auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4769     ICS.setStandard();
4770     ICS.Standard.First = ICK_Identity;
4771     // FIXME: A reference binding can be a function conversion too. We should
4772     // consider that when ordering reference-to-function bindings.
4773     ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4774                               ? ICK_Derived_To_Base
4775                               : (RefConv & Sema::ReferenceConversions::ObjC)
4776                                     ? ICK_Compatible_Conversion
4777                                     : ICK_Identity;
4778     // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4779     // a reference binding that performs a non-top-level qualification
4780     // conversion as a qualification conversion, not as an identity conversion.
4781     ICS.Standard.Third = (RefConv &
4782                               Sema::ReferenceConversions::NestedQualification)
4783                              ? ICK_Qualification
4784                              : ICK_Identity;
4785     ICS.Standard.setFromType(T2);
4786     ICS.Standard.setToType(0, T2);
4787     ICS.Standard.setToType(1, T1);
4788     ICS.Standard.setToType(2, T1);
4789     ICS.Standard.ReferenceBinding = true;
4790     ICS.Standard.DirectBinding = BindsDirectly;
4791     ICS.Standard.IsLvalueReference = !isRValRef;
4792     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4793     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4794     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4795     ICS.Standard.ObjCLifetimeConversionBinding =
4796         (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4797     ICS.Standard.CopyConstructor = nullptr;
4798     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4799   };
4800 
4801   // C++0x [dcl.init.ref]p5:
4802   //   A reference to type "cv1 T1" is initialized by an expression
4803   //   of type "cv2 T2" as follows:
4804 
4805   //     -- If reference is an lvalue reference and the initializer expression
4806   if (!isRValRef) {
4807     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4808     //        reference-compatible with "cv2 T2," or
4809     //
4810     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4811     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4812       // C++ [over.ics.ref]p1:
4813       //   When a parameter of reference type binds directly (8.5.3)
4814       //   to an argument expression, the implicit conversion sequence
4815       //   is the identity conversion, unless the argument expression
4816       //   has a type that is a derived class of the parameter type,
4817       //   in which case the implicit conversion sequence is a
4818       //   derived-to-base Conversion (13.3.3.1).
4819       SetAsReferenceBinding(/*BindsDirectly=*/true);
4820 
4821       // Nothing more to do: the inaccessibility/ambiguity check for
4822       // derived-to-base conversions is suppressed when we're
4823       // computing the implicit conversion sequence (C++
4824       // [over.best.ics]p2).
4825       return ICS;
4826     }
4827 
4828     //       -- has a class type (i.e., T2 is a class type), where T1 is
4829     //          not reference-related to T2, and can be implicitly
4830     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4831     //          is reference-compatible with "cv3 T3" 92) (this
4832     //          conversion is selected by enumerating the applicable
4833     //          conversion functions (13.3.1.6) and choosing the best
4834     //          one through overload resolution (13.3)),
4835     if (!SuppressUserConversions && T2->isRecordType() &&
4836         S.isCompleteType(DeclLoc, T2) &&
4837         RefRelationship == Sema::Ref_Incompatible) {
4838       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4839                                    Init, T2, /*AllowRvalues=*/false,
4840                                    AllowExplicit))
4841         return ICS;
4842     }
4843   }
4844 
4845   //     -- Otherwise, the reference shall be an lvalue reference to a
4846   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4847   //        shall be an rvalue reference.
4848   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
4849     if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
4850       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4851     return ICS;
4852   }
4853 
4854   //       -- If the initializer expression
4855   //
4856   //            -- is an xvalue, class prvalue, array prvalue or function
4857   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4858   if (RefRelationship == Sema::Ref_Compatible &&
4859       (InitCategory.isXValue() ||
4860        (InitCategory.isPRValue() &&
4861           (T2->isRecordType() || T2->isArrayType())) ||
4862        (InitCategory.isLValue() && T2->isFunctionType()))) {
4863     // In C++11, this is always a direct binding. In C++98/03, it's a direct
4864     // binding unless we're binding to a class prvalue.
4865     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4866     // allow the use of rvalue references in C++98/03 for the benefit of
4867     // standard library implementors; therefore, we need the xvalue check here.
4868     SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4869                           !(InitCategory.isPRValue() || T2->isRecordType()));
4870     return ICS;
4871   }
4872 
4873   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4874   //               reference-related to T2, and can be implicitly converted to
4875   //               an xvalue, class prvalue, or function lvalue of type
4876   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4877   //               "cv3 T3",
4878   //
4879   //          then the reference is bound to the value of the initializer
4880   //          expression in the first case and to the result of the conversion
4881   //          in the second case (or, in either case, to an appropriate base
4882   //          class subobject).
4883   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4884       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4885       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4886                                Init, T2, /*AllowRvalues=*/true,
4887                                AllowExplicit)) {
4888     // In the second case, if the reference is an rvalue reference
4889     // and the second standard conversion sequence of the
4890     // user-defined conversion sequence includes an lvalue-to-rvalue
4891     // conversion, the program is ill-formed.
4892     if (ICS.isUserDefined() && isRValRef &&
4893         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4894       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4895 
4896     return ICS;
4897   }
4898 
4899   // A temporary of function type cannot be created; don't even try.
4900   if (T1->isFunctionType())
4901     return ICS;
4902 
4903   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4904   //          initialized from the initializer expression using the
4905   //          rules for a non-reference copy initialization (8.5). The
4906   //          reference is then bound to the temporary. If T1 is
4907   //          reference-related to T2, cv1 must be the same
4908   //          cv-qualification as, or greater cv-qualification than,
4909   //          cv2; otherwise, the program is ill-formed.
4910   if (RefRelationship == Sema::Ref_Related) {
4911     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4912     // we would be reference-compatible or reference-compatible with
4913     // added qualification. But that wasn't the case, so the reference
4914     // initialization fails.
4915     //
4916     // Note that we only want to check address spaces and cvr-qualifiers here.
4917     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4918     Qualifiers T1Quals = T1.getQualifiers();
4919     Qualifiers T2Quals = T2.getQualifiers();
4920     T1Quals.removeObjCGCAttr();
4921     T1Quals.removeObjCLifetime();
4922     T2Quals.removeObjCGCAttr();
4923     T2Quals.removeObjCLifetime();
4924     // MS compiler ignores __unaligned qualifier for references; do the same.
4925     T1Quals.removeUnaligned();
4926     T2Quals.removeUnaligned();
4927     if (!T1Quals.compatiblyIncludes(T2Quals))
4928       return ICS;
4929   }
4930 
4931   // If at least one of the types is a class type, the types are not
4932   // related, and we aren't allowed any user conversions, the
4933   // reference binding fails. This case is important for breaking
4934   // recursion, since TryImplicitConversion below will attempt to
4935   // create a temporary through the use of a copy constructor.
4936   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4937       (T1->isRecordType() || T2->isRecordType()))
4938     return ICS;
4939 
4940   // If T1 is reference-related to T2 and the reference is an rvalue
4941   // reference, the initializer expression shall not be an lvalue.
4942   if (RefRelationship >= Sema::Ref_Related && isRValRef &&
4943       Init->Classify(S.Context).isLValue()) {
4944     ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType);
4945     return ICS;
4946   }
4947 
4948   // C++ [over.ics.ref]p2:
4949   //   When a parameter of reference type is not bound directly to
4950   //   an argument expression, the conversion sequence is the one
4951   //   required to convert the argument expression to the
4952   //   underlying type of the reference according to
4953   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4954   //   to copy-initializing a temporary of the underlying type with
4955   //   the argument expression. Any difference in top-level
4956   //   cv-qualification is subsumed by the initialization itself
4957   //   and does not constitute a conversion.
4958   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4959                               AllowedExplicit::None,
4960                               /*InOverloadResolution=*/false,
4961                               /*CStyle=*/false,
4962                               /*AllowObjCWritebackConversion=*/false,
4963                               /*AllowObjCConversionOnExplicit=*/false);
4964 
4965   // Of course, that's still a reference binding.
4966   if (ICS.isStandard()) {
4967     ICS.Standard.ReferenceBinding = true;
4968     ICS.Standard.IsLvalueReference = !isRValRef;
4969     ICS.Standard.BindsToFunctionLvalue = false;
4970     ICS.Standard.BindsToRvalue = true;
4971     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4972     ICS.Standard.ObjCLifetimeConversionBinding = false;
4973   } else if (ICS.isUserDefined()) {
4974     const ReferenceType *LValRefType =
4975         ICS.UserDefined.ConversionFunction->getReturnType()
4976             ->getAs<LValueReferenceType>();
4977 
4978     // C++ [over.ics.ref]p3:
4979     //   Except for an implicit object parameter, for which see 13.3.1, a
4980     //   standard conversion sequence cannot be formed if it requires [...]
4981     //   binding an rvalue reference to an lvalue other than a function
4982     //   lvalue.
4983     // Note that the function case is not possible here.
4984     if (isRValRef && LValRefType) {
4985       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4986       return ICS;
4987     }
4988 
4989     ICS.UserDefined.After.ReferenceBinding = true;
4990     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4991     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4992     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4993     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4994     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4995   }
4996 
4997   return ICS;
4998 }
4999 
5000 static ImplicitConversionSequence
5001 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5002                       bool SuppressUserConversions,
5003                       bool InOverloadResolution,
5004                       bool AllowObjCWritebackConversion,
5005                       bool AllowExplicit = false);
5006 
5007 /// TryListConversion - Try to copy-initialize a value of type ToType from the
5008 /// initializer list From.
5009 static ImplicitConversionSequence
5010 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5011                   bool SuppressUserConversions,
5012                   bool InOverloadResolution,
5013                   bool AllowObjCWritebackConversion) {
5014   // C++11 [over.ics.list]p1:
5015   //   When an argument is an initializer list, it is not an expression and
5016   //   special rules apply for converting it to a parameter type.
5017 
5018   ImplicitConversionSequence Result;
5019   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5020 
5021   // We need a complete type for what follows.  With one C++20 exception,
5022   // incomplete types can never be initialized from init lists.
5023   QualType InitTy = ToType;
5024   const ArrayType *AT = S.Context.getAsArrayType(ToType);
5025   if (AT && S.getLangOpts().CPlusPlus20)
5026     if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5027       // C++20 allows list initialization of an incomplete array type.
5028       InitTy = IAT->getElementType();
5029   if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5030     return Result;
5031 
5032   // Per DR1467:
5033   //   If the parameter type is a class X and the initializer list has a single
5034   //   element of type cv U, where U is X or a class derived from X, the
5035   //   implicit conversion sequence is the one required to convert the element
5036   //   to the parameter type.
5037   //
5038   //   Otherwise, if the parameter type is a character array [... ]
5039   //   and the initializer list has a single element that is an
5040   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5041   //   implicit conversion sequence is the identity conversion.
5042   if (From->getNumInits() == 1) {
5043     if (ToType->isRecordType()) {
5044       QualType InitType = From->getInit(0)->getType();
5045       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5046           S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5047         return TryCopyInitialization(S, From->getInit(0), ToType,
5048                                      SuppressUserConversions,
5049                                      InOverloadResolution,
5050                                      AllowObjCWritebackConversion);
5051     }
5052 
5053     if (AT && S.IsStringInit(From->getInit(0), AT)) {
5054       InitializedEntity Entity =
5055           InitializedEntity::InitializeParameter(S.Context, ToType,
5056                                                  /*Consumed=*/false);
5057       if (S.CanPerformCopyInitialization(Entity, From)) {
5058         Result.setStandard();
5059         Result.Standard.setAsIdentityConversion();
5060         Result.Standard.setFromType(ToType);
5061         Result.Standard.setAllToTypes(ToType);
5062         return Result;
5063       }
5064     }
5065   }
5066 
5067   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5068   // C++11 [over.ics.list]p2:
5069   //   If the parameter type is std::initializer_list<X> or "array of X" and
5070   //   all the elements can be implicitly converted to X, the implicit
5071   //   conversion sequence is the worst conversion necessary to convert an
5072   //   element of the list to X.
5073   //
5074   // C++14 [over.ics.list]p3:
5075   //   Otherwise, if the parameter type is "array of N X", if the initializer
5076   //   list has exactly N elements or if it has fewer than N elements and X is
5077   //   default-constructible, and if all the elements of the initializer list
5078   //   can be implicitly converted to X, the implicit conversion sequence is
5079   //   the worst conversion necessary to convert an element of the list to X.
5080   if (AT || S.isStdInitializerList(ToType, &InitTy)) {
5081     unsigned e = From->getNumInits();
5082     ImplicitConversionSequence DfltElt;
5083     DfltElt.setBad(BadConversionSequence::no_conversion, QualType(),
5084                    QualType());
5085     QualType ContTy = ToType;
5086     bool IsUnbounded = false;
5087     if (AT) {
5088       InitTy = AT->getElementType();
5089       if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5090         if (CT->getSize().ult(e)) {
5091           // Too many inits, fatally bad
5092           Result.setBad(BadConversionSequence::too_many_initializers, From,
5093                         ToType);
5094           Result.setInitializerListContainerType(ContTy, IsUnbounded);
5095           return Result;
5096         }
5097         if (CT->getSize().ugt(e)) {
5098           // Need an init from empty {}, is there one?
5099           InitListExpr EmptyList(S.Context, From->getEndLoc(), None,
5100                                  From->getEndLoc());
5101           EmptyList.setType(S.Context.VoidTy);
5102           DfltElt = TryListConversion(
5103               S, &EmptyList, InitTy, SuppressUserConversions,
5104               InOverloadResolution, AllowObjCWritebackConversion);
5105           if (DfltElt.isBad()) {
5106             // No {} init, fatally bad
5107             Result.setBad(BadConversionSequence::too_few_initializers, From,
5108                           ToType);
5109             Result.setInitializerListContainerType(ContTy, IsUnbounded);
5110             return Result;
5111           }
5112         }
5113       } else {
5114         assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5115         IsUnbounded = true;
5116         if (!e) {
5117           // Cannot convert to zero-sized.
5118           Result.setBad(BadConversionSequence::too_few_initializers, From,
5119                         ToType);
5120           Result.setInitializerListContainerType(ContTy, IsUnbounded);
5121           return Result;
5122         }
5123         llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5124         ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5125                                                 ArrayType::Normal, 0);
5126       }
5127     }
5128 
5129     Result.setStandard();
5130     Result.Standard.setAsIdentityConversion();
5131     Result.Standard.setFromType(InitTy);
5132     Result.Standard.setAllToTypes(InitTy);
5133     for (unsigned i = 0; i < e; ++i) {
5134       Expr *Init = From->getInit(i);
5135       ImplicitConversionSequence ICS = TryCopyInitialization(
5136           S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5137           AllowObjCWritebackConversion);
5138 
5139       // Keep the worse conversion seen so far.
5140       // FIXME: Sequences are not totally ordered, so 'worse' can be
5141       // ambiguous. CWG has been informed.
5142       if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS,
5143                                              Result) ==
5144           ImplicitConversionSequence::Worse) {
5145         Result = ICS;
5146         // Bail as soon as we find something unconvertible.
5147         if (Result.isBad()) {
5148           Result.setInitializerListContainerType(ContTy, IsUnbounded);
5149           return Result;
5150         }
5151       }
5152     }
5153 
5154     // If we needed any implicit {} initialization, compare that now.
5155     // over.ics.list/6 indicates we should compare that conversion.  Again CWG
5156     // has been informed that this might not be the best thing.
5157     if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5158                                 S, From->getEndLoc(), DfltElt, Result) ==
5159                                 ImplicitConversionSequence::Worse)
5160       Result = DfltElt;
5161     // Record the type being initialized so that we may compare sequences
5162     Result.setInitializerListContainerType(ContTy, IsUnbounded);
5163     return Result;
5164   }
5165 
5166   // C++14 [over.ics.list]p4:
5167   // C++11 [over.ics.list]p3:
5168   //   Otherwise, if the parameter is a non-aggregate class X and overload
5169   //   resolution chooses a single best constructor [...] the implicit
5170   //   conversion sequence is a user-defined conversion sequence. If multiple
5171   //   constructors are viable but none is better than the others, the
5172   //   implicit conversion sequence is a user-defined conversion sequence.
5173   if (ToType->isRecordType() && !ToType->isAggregateType()) {
5174     // This function can deal with initializer lists.
5175     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5176                                     AllowedExplicit::None,
5177                                     InOverloadResolution, /*CStyle=*/false,
5178                                     AllowObjCWritebackConversion,
5179                                     /*AllowObjCConversionOnExplicit=*/false);
5180   }
5181 
5182   // C++14 [over.ics.list]p5:
5183   // C++11 [over.ics.list]p4:
5184   //   Otherwise, if the parameter has an aggregate type which can be
5185   //   initialized from the initializer list [...] the implicit conversion
5186   //   sequence is a user-defined conversion sequence.
5187   if (ToType->isAggregateType()) {
5188     // Type is an aggregate, argument is an init list. At this point it comes
5189     // down to checking whether the initialization works.
5190     // FIXME: Find out whether this parameter is consumed or not.
5191     InitializedEntity Entity =
5192         InitializedEntity::InitializeParameter(S.Context, ToType,
5193                                                /*Consumed=*/false);
5194     if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5195                                                                  From)) {
5196       Result.setUserDefined();
5197       Result.UserDefined.Before.setAsIdentityConversion();
5198       // Initializer lists don't have a type.
5199       Result.UserDefined.Before.setFromType(QualType());
5200       Result.UserDefined.Before.setAllToTypes(QualType());
5201 
5202       Result.UserDefined.After.setAsIdentityConversion();
5203       Result.UserDefined.After.setFromType(ToType);
5204       Result.UserDefined.After.setAllToTypes(ToType);
5205       Result.UserDefined.ConversionFunction = nullptr;
5206     }
5207     return Result;
5208   }
5209 
5210   // C++14 [over.ics.list]p6:
5211   // C++11 [over.ics.list]p5:
5212   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5213   if (ToType->isReferenceType()) {
5214     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5215     // mention initializer lists in any way. So we go by what list-
5216     // initialization would do and try to extrapolate from that.
5217 
5218     QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5219 
5220     // If the initializer list has a single element that is reference-related
5221     // to the parameter type, we initialize the reference from that.
5222     if (From->getNumInits() == 1) {
5223       Expr *Init = From->getInit(0);
5224 
5225       QualType T2 = Init->getType();
5226 
5227       // If the initializer is the address of an overloaded function, try
5228       // to resolve the overloaded function. If all goes well, T2 is the
5229       // type of the resulting function.
5230       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5231         DeclAccessPair Found;
5232         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5233                                    Init, ToType, false, Found))
5234           T2 = Fn->getType();
5235       }
5236 
5237       // Compute some basic properties of the types and the initializer.
5238       Sema::ReferenceCompareResult RefRelationship =
5239           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5240 
5241       if (RefRelationship >= Sema::Ref_Related) {
5242         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5243                                 SuppressUserConversions,
5244                                 /*AllowExplicit=*/false);
5245       }
5246     }
5247 
5248     // Otherwise, we bind the reference to a temporary created from the
5249     // initializer list.
5250     Result = TryListConversion(S, From, T1, SuppressUserConversions,
5251                                InOverloadResolution,
5252                                AllowObjCWritebackConversion);
5253     if (Result.isFailure())
5254       return Result;
5255     assert(!Result.isEllipsis() &&
5256            "Sub-initialization cannot result in ellipsis conversion.");
5257 
5258     // Can we even bind to a temporary?
5259     if (ToType->isRValueReferenceType() ||
5260         (T1.isConstQualified() && !T1.isVolatileQualified())) {
5261       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5262                                             Result.UserDefined.After;
5263       SCS.ReferenceBinding = true;
5264       SCS.IsLvalueReference = ToType->isLValueReferenceType();
5265       SCS.BindsToRvalue = true;
5266       SCS.BindsToFunctionLvalue = false;
5267       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5268       SCS.ObjCLifetimeConversionBinding = false;
5269     } else
5270       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5271                     From, ToType);
5272     return Result;
5273   }
5274 
5275   // C++14 [over.ics.list]p7:
5276   // C++11 [over.ics.list]p6:
5277   //   Otherwise, if the parameter type is not a class:
5278   if (!ToType->isRecordType()) {
5279     //    - if the initializer list has one element that is not itself an
5280     //      initializer list, the implicit conversion sequence is the one
5281     //      required to convert the element to the parameter type.
5282     unsigned NumInits = From->getNumInits();
5283     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5284       Result = TryCopyInitialization(S, From->getInit(0), ToType,
5285                                      SuppressUserConversions,
5286                                      InOverloadResolution,
5287                                      AllowObjCWritebackConversion);
5288     //    - if the initializer list has no elements, the implicit conversion
5289     //      sequence is the identity conversion.
5290     else if (NumInits == 0) {
5291       Result.setStandard();
5292       Result.Standard.setAsIdentityConversion();
5293       Result.Standard.setFromType(ToType);
5294       Result.Standard.setAllToTypes(ToType);
5295     }
5296     return Result;
5297   }
5298 
5299   // C++14 [over.ics.list]p8:
5300   // C++11 [over.ics.list]p7:
5301   //   In all cases other than those enumerated above, no conversion is possible
5302   return Result;
5303 }
5304 
5305 /// TryCopyInitialization - Try to copy-initialize a value of type
5306 /// ToType from the expression From. Return the implicit conversion
5307 /// sequence required to pass this argument, which may be a bad
5308 /// conversion sequence (meaning that the argument cannot be passed to
5309 /// a parameter of this type). If @p SuppressUserConversions, then we
5310 /// do not permit any user-defined conversion sequences.
5311 static ImplicitConversionSequence
5312 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5313                       bool SuppressUserConversions,
5314                       bool InOverloadResolution,
5315                       bool AllowObjCWritebackConversion,
5316                       bool AllowExplicit) {
5317   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5318     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5319                              InOverloadResolution,AllowObjCWritebackConversion);
5320 
5321   if (ToType->isReferenceType())
5322     return TryReferenceInit(S, From, ToType,
5323                             /*FIXME:*/ From->getBeginLoc(),
5324                             SuppressUserConversions, AllowExplicit);
5325 
5326   return TryImplicitConversion(S, From, ToType,
5327                                SuppressUserConversions,
5328                                AllowedExplicit::None,
5329                                InOverloadResolution,
5330                                /*CStyle=*/false,
5331                                AllowObjCWritebackConversion,
5332                                /*AllowObjCConversionOnExplicit=*/false);
5333 }
5334 
5335 static bool TryCopyInitialization(const CanQualType FromQTy,
5336                                   const CanQualType ToQTy,
5337                                   Sema &S,
5338                                   SourceLocation Loc,
5339                                   ExprValueKind FromVK) {
5340   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5341   ImplicitConversionSequence ICS =
5342     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5343 
5344   return !ICS.isBad();
5345 }
5346 
5347 /// TryObjectArgumentInitialization - Try to initialize the object
5348 /// parameter of the given member function (@c Method) from the
5349 /// expression @p From.
5350 static ImplicitConversionSequence
5351 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5352                                 Expr::Classification FromClassification,
5353                                 CXXMethodDecl *Method,
5354                                 CXXRecordDecl *ActingContext) {
5355   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5356   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5357   //                 const volatile object.
5358   Qualifiers Quals = Method->getMethodQualifiers();
5359   if (isa<CXXDestructorDecl>(Method)) {
5360     Quals.addConst();
5361     Quals.addVolatile();
5362   }
5363 
5364   QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5365 
5366   // Set up the conversion sequence as a "bad" conversion, to allow us
5367   // to exit early.
5368   ImplicitConversionSequence ICS;
5369 
5370   // We need to have an object of class type.
5371   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5372     FromType = PT->getPointeeType();
5373 
5374     // When we had a pointer, it's implicitly dereferenced, so we
5375     // better have an lvalue.
5376     assert(FromClassification.isLValue());
5377   }
5378 
5379   assert(FromType->isRecordType());
5380 
5381   // C++0x [over.match.funcs]p4:
5382   //   For non-static member functions, the type of the implicit object
5383   //   parameter is
5384   //
5385   //     - "lvalue reference to cv X" for functions declared without a
5386   //        ref-qualifier or with the & ref-qualifier
5387   //     - "rvalue reference to cv X" for functions declared with the &&
5388   //        ref-qualifier
5389   //
5390   // where X is the class of which the function is a member and cv is the
5391   // cv-qualification on the member function declaration.
5392   //
5393   // However, when finding an implicit conversion sequence for the argument, we
5394   // are not allowed to perform user-defined conversions
5395   // (C++ [over.match.funcs]p5). We perform a simplified version of
5396   // reference binding here, that allows class rvalues to bind to
5397   // non-constant references.
5398 
5399   // First check the qualifiers.
5400   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5401   if (ImplicitParamType.getCVRQualifiers()
5402                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5403       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5404     ICS.setBad(BadConversionSequence::bad_qualifiers,
5405                FromType, ImplicitParamType);
5406     return ICS;
5407   }
5408 
5409   if (FromTypeCanon.hasAddressSpace()) {
5410     Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5411     Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5412     if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5413       ICS.setBad(BadConversionSequence::bad_qualifiers,
5414                  FromType, ImplicitParamType);
5415       return ICS;
5416     }
5417   }
5418 
5419   // Check that we have either the same type or a derived type. It
5420   // affects the conversion rank.
5421   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5422   ImplicitConversionKind SecondKind;
5423   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5424     SecondKind = ICK_Identity;
5425   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5426     SecondKind = ICK_Derived_To_Base;
5427   else {
5428     ICS.setBad(BadConversionSequence::unrelated_class,
5429                FromType, ImplicitParamType);
5430     return ICS;
5431   }
5432 
5433   // Check the ref-qualifier.
5434   switch (Method->getRefQualifier()) {
5435   case RQ_None:
5436     // Do nothing; we don't care about lvalueness or rvalueness.
5437     break;
5438 
5439   case RQ_LValue:
5440     if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5441       // non-const lvalue reference cannot bind to an rvalue
5442       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5443                  ImplicitParamType);
5444       return ICS;
5445     }
5446     break;
5447 
5448   case RQ_RValue:
5449     if (!FromClassification.isRValue()) {
5450       // rvalue reference cannot bind to an lvalue
5451       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5452                  ImplicitParamType);
5453       return ICS;
5454     }
5455     break;
5456   }
5457 
5458   // Success. Mark this as a reference binding.
5459   ICS.setStandard();
5460   ICS.Standard.setAsIdentityConversion();
5461   ICS.Standard.Second = SecondKind;
5462   ICS.Standard.setFromType(FromType);
5463   ICS.Standard.setAllToTypes(ImplicitParamType);
5464   ICS.Standard.ReferenceBinding = true;
5465   ICS.Standard.DirectBinding = true;
5466   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5467   ICS.Standard.BindsToFunctionLvalue = false;
5468   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5469   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5470     = (Method->getRefQualifier() == RQ_None);
5471   return ICS;
5472 }
5473 
5474 /// PerformObjectArgumentInitialization - Perform initialization of
5475 /// the implicit object parameter for the given Method with the given
5476 /// expression.
5477 ExprResult
5478 Sema::PerformObjectArgumentInitialization(Expr *From,
5479                                           NestedNameSpecifier *Qualifier,
5480                                           NamedDecl *FoundDecl,
5481                                           CXXMethodDecl *Method) {
5482   QualType FromRecordType, DestType;
5483   QualType ImplicitParamRecordType  =
5484     Method->getThisType()->castAs<PointerType>()->getPointeeType();
5485 
5486   Expr::Classification FromClassification;
5487   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5488     FromRecordType = PT->getPointeeType();
5489     DestType = Method->getThisType();
5490     FromClassification = Expr::Classification::makeSimpleLValue();
5491   } else {
5492     FromRecordType = From->getType();
5493     DestType = ImplicitParamRecordType;
5494     FromClassification = From->Classify(Context);
5495 
5496     // When performing member access on a prvalue, materialize a temporary.
5497     if (From->isPRValue()) {
5498       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5499                                             Method->getRefQualifier() !=
5500                                                 RefQualifierKind::RQ_RValue);
5501     }
5502   }
5503 
5504   // Note that we always use the true parent context when performing
5505   // the actual argument initialization.
5506   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5507       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5508       Method->getParent());
5509   if (ICS.isBad()) {
5510     switch (ICS.Bad.Kind) {
5511     case BadConversionSequence::bad_qualifiers: {
5512       Qualifiers FromQs = FromRecordType.getQualifiers();
5513       Qualifiers ToQs = DestType.getQualifiers();
5514       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5515       if (CVR) {
5516         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5517             << Method->getDeclName() << FromRecordType << (CVR - 1)
5518             << From->getSourceRange();
5519         Diag(Method->getLocation(), diag::note_previous_decl)
5520           << Method->getDeclName();
5521         return ExprError();
5522       }
5523       break;
5524     }
5525 
5526     case BadConversionSequence::lvalue_ref_to_rvalue:
5527     case BadConversionSequence::rvalue_ref_to_lvalue: {
5528       bool IsRValueQualified =
5529         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5530       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5531           << Method->getDeclName() << FromClassification.isRValue()
5532           << IsRValueQualified;
5533       Diag(Method->getLocation(), diag::note_previous_decl)
5534         << Method->getDeclName();
5535       return ExprError();
5536     }
5537 
5538     case BadConversionSequence::no_conversion:
5539     case BadConversionSequence::unrelated_class:
5540       break;
5541 
5542     case BadConversionSequence::too_few_initializers:
5543     case BadConversionSequence::too_many_initializers:
5544       llvm_unreachable("Lists are not objects");
5545     }
5546 
5547     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5548            << ImplicitParamRecordType << FromRecordType
5549            << From->getSourceRange();
5550   }
5551 
5552   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5553     ExprResult FromRes =
5554       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5555     if (FromRes.isInvalid())
5556       return ExprError();
5557     From = FromRes.get();
5558   }
5559 
5560   if (!Context.hasSameType(From->getType(), DestType)) {
5561     CastKind CK;
5562     QualType PteeTy = DestType->getPointeeType();
5563     LangAS DestAS =
5564         PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5565     if (FromRecordType.getAddressSpace() != DestAS)
5566       CK = CK_AddressSpaceConversion;
5567     else
5568       CK = CK_NoOp;
5569     From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5570   }
5571   return From;
5572 }
5573 
5574 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5575 /// expression From to bool (C++0x [conv]p3).
5576 static ImplicitConversionSequence
5577 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5578   // C++ [dcl.init]/17.8:
5579   //   - Otherwise, if the initialization is direct-initialization, the source
5580   //     type is std::nullptr_t, and the destination type is bool, the initial
5581   //     value of the object being initialized is false.
5582   if (From->getType()->isNullPtrType())
5583     return ImplicitConversionSequence::getNullptrToBool(From->getType(),
5584                                                         S.Context.BoolTy,
5585                                                         From->isGLValue());
5586 
5587   // All other direct-initialization of bool is equivalent to an implicit
5588   // conversion to bool in which explicit conversions are permitted.
5589   return TryImplicitConversion(S, From, S.Context.BoolTy,
5590                                /*SuppressUserConversions=*/false,
5591                                AllowedExplicit::Conversions,
5592                                /*InOverloadResolution=*/false,
5593                                /*CStyle=*/false,
5594                                /*AllowObjCWritebackConversion=*/false,
5595                                /*AllowObjCConversionOnExplicit=*/false);
5596 }
5597 
5598 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5599 /// of the expression From to bool (C++0x [conv]p3).
5600 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5601   if (checkPlaceholderForOverload(*this, From))
5602     return ExprError();
5603 
5604   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5605   if (!ICS.isBad())
5606     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5607 
5608   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5609     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5610            << From->getType() << From->getSourceRange();
5611   return ExprError();
5612 }
5613 
5614 /// Check that the specified conversion is permitted in a converted constant
5615 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5616 /// is acceptable.
5617 static bool CheckConvertedConstantConversions(Sema &S,
5618                                               StandardConversionSequence &SCS) {
5619   // Since we know that the target type is an integral or unscoped enumeration
5620   // type, most conversion kinds are impossible. All possible First and Third
5621   // conversions are fine.
5622   switch (SCS.Second) {
5623   case ICK_Identity:
5624   case ICK_Integral_Promotion:
5625   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5626   case ICK_Zero_Queue_Conversion:
5627     return true;
5628 
5629   case ICK_Boolean_Conversion:
5630     // Conversion from an integral or unscoped enumeration type to bool is
5631     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5632     // conversion, so we allow it in a converted constant expression.
5633     //
5634     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5635     // a lot of popular code. We should at least add a warning for this
5636     // (non-conforming) extension.
5637     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5638            SCS.getToType(2)->isBooleanType();
5639 
5640   case ICK_Pointer_Conversion:
5641   case ICK_Pointer_Member:
5642     // C++1z: null pointer conversions and null member pointer conversions are
5643     // only permitted if the source type is std::nullptr_t.
5644     return SCS.getFromType()->isNullPtrType();
5645 
5646   case ICK_Floating_Promotion:
5647   case ICK_Complex_Promotion:
5648   case ICK_Floating_Conversion:
5649   case ICK_Complex_Conversion:
5650   case ICK_Floating_Integral:
5651   case ICK_Compatible_Conversion:
5652   case ICK_Derived_To_Base:
5653   case ICK_Vector_Conversion:
5654   case ICK_SVE_Vector_Conversion:
5655   case ICK_Vector_Splat:
5656   case ICK_Complex_Real:
5657   case ICK_Block_Pointer_Conversion:
5658   case ICK_TransparentUnionConversion:
5659   case ICK_Writeback_Conversion:
5660   case ICK_Zero_Event_Conversion:
5661   case ICK_C_Only_Conversion:
5662   case ICK_Incompatible_Pointer_Conversion:
5663     return false;
5664 
5665   case ICK_Lvalue_To_Rvalue:
5666   case ICK_Array_To_Pointer:
5667   case ICK_Function_To_Pointer:
5668     llvm_unreachable("found a first conversion kind in Second");
5669 
5670   case ICK_Function_Conversion:
5671   case ICK_Qualification:
5672     llvm_unreachable("found a third conversion kind in Second");
5673 
5674   case ICK_Num_Conversion_Kinds:
5675     break;
5676   }
5677 
5678   llvm_unreachable("unknown conversion kind");
5679 }
5680 
5681 /// CheckConvertedConstantExpression - Check that the expression From is a
5682 /// converted constant expression of type T, perform the conversion and produce
5683 /// the converted expression, per C++11 [expr.const]p3.
5684 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5685                                                    QualType T, APValue &Value,
5686                                                    Sema::CCEKind CCE,
5687                                                    bool RequireInt,
5688                                                    NamedDecl *Dest) {
5689   assert(S.getLangOpts().CPlusPlus11 &&
5690          "converted constant expression outside C++11");
5691 
5692   if (checkPlaceholderForOverload(S, From))
5693     return ExprError();
5694 
5695   // C++1z [expr.const]p3:
5696   //  A converted constant expression of type T is an expression,
5697   //  implicitly converted to type T, where the converted
5698   //  expression is a constant expression and the implicit conversion
5699   //  sequence contains only [... list of conversions ...].
5700   ImplicitConversionSequence ICS =
5701       (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept)
5702           ? TryContextuallyConvertToBool(S, From)
5703           : TryCopyInitialization(S, From, T,
5704                                   /*SuppressUserConversions=*/false,
5705                                   /*InOverloadResolution=*/false,
5706                                   /*AllowObjCWritebackConversion=*/false,
5707                                   /*AllowExplicit=*/false);
5708   StandardConversionSequence *SCS = nullptr;
5709   switch (ICS.getKind()) {
5710   case ImplicitConversionSequence::StandardConversion:
5711     SCS = &ICS.Standard;
5712     break;
5713   case ImplicitConversionSequence::UserDefinedConversion:
5714     if (T->isRecordType())
5715       SCS = &ICS.UserDefined.Before;
5716     else
5717       SCS = &ICS.UserDefined.After;
5718     break;
5719   case ImplicitConversionSequence::AmbiguousConversion:
5720   case ImplicitConversionSequence::BadConversion:
5721     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5722       return S.Diag(From->getBeginLoc(),
5723                     diag::err_typecheck_converted_constant_expression)
5724              << From->getType() << From->getSourceRange() << T;
5725     return ExprError();
5726 
5727   case ImplicitConversionSequence::EllipsisConversion:
5728     llvm_unreachable("ellipsis conversion in converted constant expression");
5729   }
5730 
5731   // Check that we would only use permitted conversions.
5732   if (!CheckConvertedConstantConversions(S, *SCS)) {
5733     return S.Diag(From->getBeginLoc(),
5734                   diag::err_typecheck_converted_constant_expression_disallowed)
5735            << From->getType() << From->getSourceRange() << T;
5736   }
5737   // [...] and where the reference binding (if any) binds directly.
5738   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5739     return S.Diag(From->getBeginLoc(),
5740                   diag::err_typecheck_converted_constant_expression_indirect)
5741            << From->getType() << From->getSourceRange() << T;
5742   }
5743 
5744   // Usually we can simply apply the ImplicitConversionSequence we formed
5745   // earlier, but that's not guaranteed to work when initializing an object of
5746   // class type.
5747   ExprResult Result;
5748   if (T->isRecordType()) {
5749     assert(CCE == Sema::CCEK_TemplateArg &&
5750            "unexpected class type converted constant expr");
5751     Result = S.PerformCopyInitialization(
5752         InitializedEntity::InitializeTemplateParameter(
5753             T, cast<NonTypeTemplateParmDecl>(Dest)),
5754         SourceLocation(), From);
5755   } else {
5756     Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5757   }
5758   if (Result.isInvalid())
5759     return Result;
5760 
5761   // C++2a [intro.execution]p5:
5762   //   A full-expression is [...] a constant-expression [...]
5763   Result =
5764       S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5765                             /*DiscardedValue=*/false, /*IsConstexpr=*/true);
5766   if (Result.isInvalid())
5767     return Result;
5768 
5769   // Check for a narrowing implicit conversion.
5770   bool ReturnPreNarrowingValue = false;
5771   APValue PreNarrowingValue;
5772   QualType PreNarrowingType;
5773   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5774                                 PreNarrowingType)) {
5775   case NK_Dependent_Narrowing:
5776     // Implicit conversion to a narrower type, but the expression is
5777     // value-dependent so we can't tell whether it's actually narrowing.
5778   case NK_Variable_Narrowing:
5779     // Implicit conversion to a narrower type, and the value is not a constant
5780     // expression. We'll diagnose this in a moment.
5781   case NK_Not_Narrowing:
5782     break;
5783 
5784   case NK_Constant_Narrowing:
5785     if (CCE == Sema::CCEK_ArrayBound &&
5786         PreNarrowingType->isIntegralOrEnumerationType() &&
5787         PreNarrowingValue.isInt()) {
5788       // Don't diagnose array bound narrowing here; we produce more precise
5789       // errors by allowing the un-narrowed value through.
5790       ReturnPreNarrowingValue = true;
5791       break;
5792     }
5793     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5794         << CCE << /*Constant*/ 1
5795         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5796     break;
5797 
5798   case NK_Type_Narrowing:
5799     // FIXME: It would be better to diagnose that the expression is not a
5800     // constant expression.
5801     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5802         << CCE << /*Constant*/ 0 << From->getType() << T;
5803     break;
5804   }
5805 
5806   if (Result.get()->isValueDependent()) {
5807     Value = APValue();
5808     return Result;
5809   }
5810 
5811   // Check the expression is a constant expression.
5812   SmallVector<PartialDiagnosticAt, 8> Notes;
5813   Expr::EvalResult Eval;
5814   Eval.Diag = &Notes;
5815 
5816   ConstantExprKind Kind;
5817   if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
5818     Kind = ConstantExprKind::ClassTemplateArgument;
5819   else if (CCE == Sema::CCEK_TemplateArg)
5820     Kind = ConstantExprKind::NonClassTemplateArgument;
5821   else
5822     Kind = ConstantExprKind::Normal;
5823 
5824   if (!Result.get()->EvaluateAsConstantExpr(Eval, S.Context, Kind) ||
5825       (RequireInt && !Eval.Val.isInt())) {
5826     // The expression can't be folded, so we can't keep it at this position in
5827     // the AST.
5828     Result = ExprError();
5829   } else {
5830     Value = Eval.Val;
5831 
5832     if (Notes.empty()) {
5833       // It's a constant expression.
5834       Expr *E = ConstantExpr::Create(S.Context, Result.get(), Value);
5835       if (ReturnPreNarrowingValue)
5836         Value = std::move(PreNarrowingValue);
5837       return E;
5838     }
5839   }
5840 
5841   // It's not a constant expression. Produce an appropriate diagnostic.
5842   if (Notes.size() == 1 &&
5843       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
5844     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5845   } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
5846                                    diag::note_constexpr_invalid_template_arg) {
5847     Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
5848     for (unsigned I = 0; I < Notes.size(); ++I)
5849       S.Diag(Notes[I].first, Notes[I].second);
5850   } else {
5851     S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5852         << CCE << From->getSourceRange();
5853     for (unsigned I = 0; I < Notes.size(); ++I)
5854       S.Diag(Notes[I].first, Notes[I].second);
5855   }
5856   return ExprError();
5857 }
5858 
5859 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5860                                                   APValue &Value, CCEKind CCE,
5861                                                   NamedDecl *Dest) {
5862   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
5863                                             Dest);
5864 }
5865 
5866 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5867                                                   llvm::APSInt &Value,
5868                                                   CCEKind CCE) {
5869   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5870 
5871   APValue V;
5872   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
5873                                               /*Dest=*/nullptr);
5874   if (!R.isInvalid() && !R.get()->isValueDependent())
5875     Value = V.getInt();
5876   return R;
5877 }
5878 
5879 
5880 /// dropPointerConversions - If the given standard conversion sequence
5881 /// involves any pointer conversions, remove them.  This may change
5882 /// the result type of the conversion sequence.
5883 static void dropPointerConversion(StandardConversionSequence &SCS) {
5884   if (SCS.Second == ICK_Pointer_Conversion) {
5885     SCS.Second = ICK_Identity;
5886     SCS.Third = ICK_Identity;
5887     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5888   }
5889 }
5890 
5891 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5892 /// convert the expression From to an Objective-C pointer type.
5893 static ImplicitConversionSequence
5894 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5895   // Do an implicit conversion to 'id'.
5896   QualType Ty = S.Context.getObjCIdType();
5897   ImplicitConversionSequence ICS
5898     = TryImplicitConversion(S, From, Ty,
5899                             // FIXME: Are these flags correct?
5900                             /*SuppressUserConversions=*/false,
5901                             AllowedExplicit::Conversions,
5902                             /*InOverloadResolution=*/false,
5903                             /*CStyle=*/false,
5904                             /*AllowObjCWritebackConversion=*/false,
5905                             /*AllowObjCConversionOnExplicit=*/true);
5906 
5907   // Strip off any final conversions to 'id'.
5908   switch (ICS.getKind()) {
5909   case ImplicitConversionSequence::BadConversion:
5910   case ImplicitConversionSequence::AmbiguousConversion:
5911   case ImplicitConversionSequence::EllipsisConversion:
5912     break;
5913 
5914   case ImplicitConversionSequence::UserDefinedConversion:
5915     dropPointerConversion(ICS.UserDefined.After);
5916     break;
5917 
5918   case ImplicitConversionSequence::StandardConversion:
5919     dropPointerConversion(ICS.Standard);
5920     break;
5921   }
5922 
5923   return ICS;
5924 }
5925 
5926 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5927 /// conversion of the expression From to an Objective-C pointer type.
5928 /// Returns a valid but null ExprResult if no conversion sequence exists.
5929 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5930   if (checkPlaceholderForOverload(*this, From))
5931     return ExprError();
5932 
5933   QualType Ty = Context.getObjCIdType();
5934   ImplicitConversionSequence ICS =
5935     TryContextuallyConvertToObjCPointer(*this, From);
5936   if (!ICS.isBad())
5937     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5938   return ExprResult();
5939 }
5940 
5941 /// Determine whether the provided type is an integral type, or an enumeration
5942 /// type of a permitted flavor.
5943 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5944   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5945                                  : T->isIntegralOrUnscopedEnumerationType();
5946 }
5947 
5948 static ExprResult
5949 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5950                             Sema::ContextualImplicitConverter &Converter,
5951                             QualType T, UnresolvedSetImpl &ViableConversions) {
5952 
5953   if (Converter.Suppress)
5954     return ExprError();
5955 
5956   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5957   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5958     CXXConversionDecl *Conv =
5959         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5960     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5961     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5962   }
5963   return From;
5964 }
5965 
5966 static bool
5967 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5968                            Sema::ContextualImplicitConverter &Converter,
5969                            QualType T, bool HadMultipleCandidates,
5970                            UnresolvedSetImpl &ExplicitConversions) {
5971   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5972     DeclAccessPair Found = ExplicitConversions[0];
5973     CXXConversionDecl *Conversion =
5974         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5975 
5976     // The user probably meant to invoke the given explicit
5977     // conversion; use it.
5978     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5979     std::string TypeStr;
5980     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5981 
5982     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5983         << FixItHint::CreateInsertion(From->getBeginLoc(),
5984                                       "static_cast<" + TypeStr + ">(")
5985         << FixItHint::CreateInsertion(
5986                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5987     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5988 
5989     // If we aren't in a SFINAE context, build a call to the
5990     // explicit conversion function.
5991     if (SemaRef.isSFINAEContext())
5992       return true;
5993 
5994     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5995     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5996                                                        HadMultipleCandidates);
5997     if (Result.isInvalid())
5998       return true;
5999     // Record usage of conversion in an implicit cast.
6000     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6001                                     CK_UserDefinedConversion, Result.get(),
6002                                     nullptr, Result.get()->getValueKind(),
6003                                     SemaRef.CurFPFeatureOverrides());
6004   }
6005   return false;
6006 }
6007 
6008 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6009                              Sema::ContextualImplicitConverter &Converter,
6010                              QualType T, bool HadMultipleCandidates,
6011                              DeclAccessPair &Found) {
6012   CXXConversionDecl *Conversion =
6013       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6014   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6015 
6016   QualType ToType = Conversion->getConversionType().getNonReferenceType();
6017   if (!Converter.SuppressConversion) {
6018     if (SemaRef.isSFINAEContext())
6019       return true;
6020 
6021     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6022         << From->getSourceRange();
6023   }
6024 
6025   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6026                                                      HadMultipleCandidates);
6027   if (Result.isInvalid())
6028     return true;
6029   // Record usage of conversion in an implicit cast.
6030   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6031                                   CK_UserDefinedConversion, Result.get(),
6032                                   nullptr, Result.get()->getValueKind(),
6033                                   SemaRef.CurFPFeatureOverrides());
6034   return false;
6035 }
6036 
6037 static ExprResult finishContextualImplicitConversion(
6038     Sema &SemaRef, SourceLocation Loc, Expr *From,
6039     Sema::ContextualImplicitConverter &Converter) {
6040   if (!Converter.match(From->getType()) && !Converter.Suppress)
6041     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6042         << From->getSourceRange();
6043 
6044   return SemaRef.DefaultLvalueConversion(From);
6045 }
6046 
6047 static void
6048 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
6049                                   UnresolvedSetImpl &ViableConversions,
6050                                   OverloadCandidateSet &CandidateSet) {
6051   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6052     DeclAccessPair FoundDecl = ViableConversions[I];
6053     NamedDecl *D = FoundDecl.getDecl();
6054     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6055     if (isa<UsingShadowDecl>(D))
6056       D = cast<UsingShadowDecl>(D)->getTargetDecl();
6057 
6058     CXXConversionDecl *Conv;
6059     FunctionTemplateDecl *ConvTemplate;
6060     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
6061       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6062     else
6063       Conv = cast<CXXConversionDecl>(D);
6064 
6065     if (ConvTemplate)
6066       SemaRef.AddTemplateConversionCandidate(
6067           ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6068           /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
6069     else
6070       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
6071                                      ToType, CandidateSet,
6072                                      /*AllowObjCConversionOnExplicit=*/false,
6073                                      /*AllowExplicit*/ true);
6074   }
6075 }
6076 
6077 /// Attempt to convert the given expression to a type which is accepted
6078 /// by the given converter.
6079 ///
6080 /// This routine will attempt to convert an expression of class type to a
6081 /// type accepted by the specified converter. In C++11 and before, the class
6082 /// must have a single non-explicit conversion function converting to a matching
6083 /// type. In C++1y, there can be multiple such conversion functions, but only
6084 /// one target type.
6085 ///
6086 /// \param Loc The source location of the construct that requires the
6087 /// conversion.
6088 ///
6089 /// \param From The expression we're converting from.
6090 ///
6091 /// \param Converter Used to control and diagnose the conversion process.
6092 ///
6093 /// \returns The expression, converted to an integral or enumeration type if
6094 /// successful.
6095 ExprResult Sema::PerformContextualImplicitConversion(
6096     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6097   // We can't perform any more checking for type-dependent expressions.
6098   if (From->isTypeDependent())
6099     return From;
6100 
6101   // Process placeholders immediately.
6102   if (From->hasPlaceholderType()) {
6103     ExprResult result = CheckPlaceholderExpr(From);
6104     if (result.isInvalid())
6105       return result;
6106     From = result.get();
6107   }
6108 
6109   // If the expression already has a matching type, we're golden.
6110   QualType T = From->getType();
6111   if (Converter.match(T))
6112     return DefaultLvalueConversion(From);
6113 
6114   // FIXME: Check for missing '()' if T is a function type?
6115 
6116   // We can only perform contextual implicit conversions on objects of class
6117   // type.
6118   const RecordType *RecordTy = T->getAs<RecordType>();
6119   if (!RecordTy || !getLangOpts().CPlusPlus) {
6120     if (!Converter.Suppress)
6121       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6122     return From;
6123   }
6124 
6125   // We must have a complete class type.
6126   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6127     ContextualImplicitConverter &Converter;
6128     Expr *From;
6129 
6130     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6131         : Converter(Converter), From(From) {}
6132 
6133     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6134       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6135     }
6136   } IncompleteDiagnoser(Converter, From);
6137 
6138   if (Converter.Suppress ? !isCompleteType(Loc, T)
6139                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6140     return From;
6141 
6142   // Look for a conversion to an integral or enumeration type.
6143   UnresolvedSet<4>
6144       ViableConversions; // These are *potentially* viable in C++1y.
6145   UnresolvedSet<4> ExplicitConversions;
6146   const auto &Conversions =
6147       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
6148 
6149   bool HadMultipleCandidates =
6150       (std::distance(Conversions.begin(), Conversions.end()) > 1);
6151 
6152   // To check that there is only one target type, in C++1y:
6153   QualType ToType;
6154   bool HasUniqueTargetType = true;
6155 
6156   // Collect explicit or viable (potentially in C++1y) conversions.
6157   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6158     NamedDecl *D = (*I)->getUnderlyingDecl();
6159     CXXConversionDecl *Conversion;
6160     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6161     if (ConvTemplate) {
6162       if (getLangOpts().CPlusPlus14)
6163         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6164       else
6165         continue; // C++11 does not consider conversion operator templates(?).
6166     } else
6167       Conversion = cast<CXXConversionDecl>(D);
6168 
6169     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6170            "Conversion operator templates are considered potentially "
6171            "viable in C++1y");
6172 
6173     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6174     if (Converter.match(CurToType) || ConvTemplate) {
6175 
6176       if (Conversion->isExplicit()) {
6177         // FIXME: For C++1y, do we need this restriction?
6178         // cf. diagnoseNoViableConversion()
6179         if (!ConvTemplate)
6180           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6181       } else {
6182         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6183           if (ToType.isNull())
6184             ToType = CurToType.getUnqualifiedType();
6185           else if (HasUniqueTargetType &&
6186                    (CurToType.getUnqualifiedType() != ToType))
6187             HasUniqueTargetType = false;
6188         }
6189         ViableConversions.addDecl(I.getDecl(), I.getAccess());
6190       }
6191     }
6192   }
6193 
6194   if (getLangOpts().CPlusPlus14) {
6195     // C++1y [conv]p6:
6196     // ... An expression e of class type E appearing in such a context
6197     // is said to be contextually implicitly converted to a specified
6198     // type T and is well-formed if and only if e can be implicitly
6199     // converted to a type T that is determined as follows: E is searched
6200     // for conversion functions whose return type is cv T or reference to
6201     // cv T such that T is allowed by the context. There shall be
6202     // exactly one such T.
6203 
6204     // If no unique T is found:
6205     if (ToType.isNull()) {
6206       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6207                                      HadMultipleCandidates,
6208                                      ExplicitConversions))
6209         return ExprError();
6210       return finishContextualImplicitConversion(*this, Loc, From, Converter);
6211     }
6212 
6213     // If more than one unique Ts are found:
6214     if (!HasUniqueTargetType)
6215       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6216                                          ViableConversions);
6217 
6218     // If one unique T is found:
6219     // First, build a candidate set from the previously recorded
6220     // potentially viable conversions.
6221     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6222     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6223                                       CandidateSet);
6224 
6225     // Then, perform overload resolution over the candidate set.
6226     OverloadCandidateSet::iterator Best;
6227     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6228     case OR_Success: {
6229       // Apply this conversion.
6230       DeclAccessPair Found =
6231           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6232       if (recordConversion(*this, Loc, From, Converter, T,
6233                            HadMultipleCandidates, Found))
6234         return ExprError();
6235       break;
6236     }
6237     case OR_Ambiguous:
6238       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6239                                          ViableConversions);
6240     case OR_No_Viable_Function:
6241       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6242                                      HadMultipleCandidates,
6243                                      ExplicitConversions))
6244         return ExprError();
6245       LLVM_FALLTHROUGH;
6246     case OR_Deleted:
6247       // We'll complain below about a non-integral condition type.
6248       break;
6249     }
6250   } else {
6251     switch (ViableConversions.size()) {
6252     case 0: {
6253       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6254                                      HadMultipleCandidates,
6255                                      ExplicitConversions))
6256         return ExprError();
6257 
6258       // We'll complain below about a non-integral condition type.
6259       break;
6260     }
6261     case 1: {
6262       // Apply this conversion.
6263       DeclAccessPair Found = ViableConversions[0];
6264       if (recordConversion(*this, Loc, From, Converter, T,
6265                            HadMultipleCandidates, Found))
6266         return ExprError();
6267       break;
6268     }
6269     default:
6270       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6271                                          ViableConversions);
6272     }
6273   }
6274 
6275   return finishContextualImplicitConversion(*this, Loc, From, Converter);
6276 }
6277 
6278 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6279 /// an acceptable non-member overloaded operator for a call whose
6280 /// arguments have types T1 (and, if non-empty, T2). This routine
6281 /// implements the check in C++ [over.match.oper]p3b2 concerning
6282 /// enumeration types.
6283 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6284                                                    FunctionDecl *Fn,
6285                                                    ArrayRef<Expr *> Args) {
6286   QualType T1 = Args[0]->getType();
6287   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6288 
6289   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6290     return true;
6291 
6292   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6293     return true;
6294 
6295   const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6296   if (Proto->getNumParams() < 1)
6297     return false;
6298 
6299   if (T1->isEnumeralType()) {
6300     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6301     if (Context.hasSameUnqualifiedType(T1, ArgType))
6302       return true;
6303   }
6304 
6305   if (Proto->getNumParams() < 2)
6306     return false;
6307 
6308   if (!T2.isNull() && T2->isEnumeralType()) {
6309     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6310     if (Context.hasSameUnqualifiedType(T2, ArgType))
6311       return true;
6312   }
6313 
6314   return false;
6315 }
6316 
6317 /// AddOverloadCandidate - Adds the given function to the set of
6318 /// candidate functions, using the given function call arguments.  If
6319 /// @p SuppressUserConversions, then don't allow user-defined
6320 /// conversions via constructors or conversion operators.
6321 ///
6322 /// \param PartialOverloading true if we are performing "partial" overloading
6323 /// based on an incomplete set of function arguments. This feature is used by
6324 /// code completion.
6325 void Sema::AddOverloadCandidate(
6326     FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6327     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6328     bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6329     ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6330     OverloadCandidateParamOrder PO) {
6331   const FunctionProtoType *Proto
6332     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6333   assert(Proto && "Functions without a prototype cannot be overloaded");
6334   assert(!Function->getDescribedFunctionTemplate() &&
6335          "Use AddTemplateOverloadCandidate for function templates");
6336 
6337   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6338     if (!isa<CXXConstructorDecl>(Method)) {
6339       // If we get here, it's because we're calling a member function
6340       // that is named without a member access expression (e.g.,
6341       // "this->f") that was either written explicitly or created
6342       // implicitly. This can happen with a qualified call to a member
6343       // function, e.g., X::f(). We use an empty type for the implied
6344       // object argument (C++ [over.call.func]p3), and the acting context
6345       // is irrelevant.
6346       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6347                          Expr::Classification::makeSimpleLValue(), Args,
6348                          CandidateSet, SuppressUserConversions,
6349                          PartialOverloading, EarlyConversions, PO);
6350       return;
6351     }
6352     // We treat a constructor like a non-member function, since its object
6353     // argument doesn't participate in overload resolution.
6354   }
6355 
6356   if (!CandidateSet.isNewCandidate(Function, PO))
6357     return;
6358 
6359   // C++11 [class.copy]p11: [DR1402]
6360   //   A defaulted move constructor that is defined as deleted is ignored by
6361   //   overload resolution.
6362   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6363   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6364       Constructor->isMoveConstructor())
6365     return;
6366 
6367   // Overload resolution is always an unevaluated context.
6368   EnterExpressionEvaluationContext Unevaluated(
6369       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6370 
6371   // C++ [over.match.oper]p3:
6372   //   if no operand has a class type, only those non-member functions in the
6373   //   lookup set that have a first parameter of type T1 or "reference to
6374   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6375   //   is a right operand) a second parameter of type T2 or "reference to
6376   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
6377   //   candidate functions.
6378   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6379       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6380     return;
6381 
6382   // Add this candidate
6383   OverloadCandidate &Candidate =
6384       CandidateSet.addCandidate(Args.size(), EarlyConversions);
6385   Candidate.FoundDecl = FoundDecl;
6386   Candidate.Function = Function;
6387   Candidate.Viable = true;
6388   Candidate.RewriteKind =
6389       CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6390   Candidate.IsSurrogate = false;
6391   Candidate.IsADLCandidate = IsADLCandidate;
6392   Candidate.IgnoreObjectArgument = false;
6393   Candidate.ExplicitCallArguments = Args.size();
6394 
6395   // Explicit functions are not actually candidates at all if we're not
6396   // allowing them in this context, but keep them around so we can point
6397   // to them in diagnostics.
6398   if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6399     Candidate.Viable = false;
6400     Candidate.FailureKind = ovl_fail_explicit;
6401     return;
6402   }
6403 
6404   // Functions with internal linkage are only viable in the same module unit.
6405   if (auto *MF = Function->getOwningModule()) {
6406     if (getLangOpts().CPlusPlusModules && !MF->isModuleMapModule() &&
6407         !isModuleUnitOfCurrentTU(MF)) {
6408       /// FIXME: Currently, the semantics of linkage in clang is slightly
6409       /// different from the semantics in C++ spec. In C++ spec, only names
6410       /// have linkage. So that all entities of the same should share one
6411       /// linkage. But in clang, different entities of the same could have
6412       /// different linkage.
6413       NamedDecl *ND = Function;
6414       if (auto *SpecInfo = Function->getTemplateSpecializationInfo())
6415         ND = SpecInfo->getTemplate();
6416 
6417       if (ND->getFormalLinkage() == Linkage::InternalLinkage) {
6418         Candidate.Viable = false;
6419         Candidate.FailureKind = ovl_fail_module_mismatched;
6420         return;
6421       }
6422     }
6423   }
6424 
6425   if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6426       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6427     Candidate.Viable = false;
6428     Candidate.FailureKind = ovl_non_default_multiversion_function;
6429     return;
6430   }
6431 
6432   if (Constructor) {
6433     // C++ [class.copy]p3:
6434     //   A member function template is never instantiated to perform the copy
6435     //   of a class object to an object of its class type.
6436     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6437     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6438         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6439          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6440                        ClassType))) {
6441       Candidate.Viable = false;
6442       Candidate.FailureKind = ovl_fail_illegal_constructor;
6443       return;
6444     }
6445 
6446     // C++ [over.match.funcs]p8: (proposed DR resolution)
6447     //   A constructor inherited from class type C that has a first parameter
6448     //   of type "reference to P" (including such a constructor instantiated
6449     //   from a template) is excluded from the set of candidate functions when
6450     //   constructing an object of type cv D if the argument list has exactly
6451     //   one argument and D is reference-related to P and P is reference-related
6452     //   to C.
6453     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6454     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6455         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6456       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6457       QualType C = Context.getRecordType(Constructor->getParent());
6458       QualType D = Context.getRecordType(Shadow->getParent());
6459       SourceLocation Loc = Args.front()->getExprLoc();
6460       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6461           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6462         Candidate.Viable = false;
6463         Candidate.FailureKind = ovl_fail_inhctor_slice;
6464         return;
6465       }
6466     }
6467 
6468     // Check that the constructor is capable of constructing an object in the
6469     // destination address space.
6470     if (!Qualifiers::isAddressSpaceSupersetOf(
6471             Constructor->getMethodQualifiers().getAddressSpace(),
6472             CandidateSet.getDestAS())) {
6473       Candidate.Viable = false;
6474       Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6475     }
6476   }
6477 
6478   unsigned NumParams = Proto->getNumParams();
6479 
6480   // (C++ 13.3.2p2): A candidate function having fewer than m
6481   // parameters is viable only if it has an ellipsis in its parameter
6482   // list (8.3.5).
6483   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6484       !Proto->isVariadic() &&
6485       shouldEnforceArgLimit(PartialOverloading, Function)) {
6486     Candidate.Viable = false;
6487     Candidate.FailureKind = ovl_fail_too_many_arguments;
6488     return;
6489   }
6490 
6491   // (C++ 13.3.2p2): A candidate function having more than m parameters
6492   // is viable only if the (m+1)st parameter has a default argument
6493   // (8.3.6). For the purposes of overload resolution, the
6494   // parameter list is truncated on the right, so that there are
6495   // exactly m parameters.
6496   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6497   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6498     // Not enough arguments.
6499     Candidate.Viable = false;
6500     Candidate.FailureKind = ovl_fail_too_few_arguments;
6501     return;
6502   }
6503 
6504   // (CUDA B.1): Check for invalid calls between targets.
6505   if (getLangOpts().CUDA)
6506     if (const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true))
6507       // Skip the check for callers that are implicit members, because in this
6508       // case we may not yet know what the member's target is; the target is
6509       // inferred for the member automatically, based on the bases and fields of
6510       // the class.
6511       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6512         Candidate.Viable = false;
6513         Candidate.FailureKind = ovl_fail_bad_target;
6514         return;
6515       }
6516 
6517   if (Function->getTrailingRequiresClause()) {
6518     ConstraintSatisfaction Satisfaction;
6519     if (CheckFunctionConstraints(Function, Satisfaction) ||
6520         !Satisfaction.IsSatisfied) {
6521       Candidate.Viable = false;
6522       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6523       return;
6524     }
6525   }
6526 
6527   // Determine the implicit conversion sequences for each of the
6528   // arguments.
6529   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6530     unsigned ConvIdx =
6531         PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6532     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6533       // We already formed a conversion sequence for this parameter during
6534       // template argument deduction.
6535     } else if (ArgIdx < NumParams) {
6536       // (C++ 13.3.2p3): for F to be a viable function, there shall
6537       // exist for each argument an implicit conversion sequence
6538       // (13.3.3.1) that converts that argument to the corresponding
6539       // parameter of F.
6540       QualType ParamType = Proto->getParamType(ArgIdx);
6541       Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6542           *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6543           /*InOverloadResolution=*/true,
6544           /*AllowObjCWritebackConversion=*/
6545           getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6546       if (Candidate.Conversions[ConvIdx].isBad()) {
6547         Candidate.Viable = false;
6548         Candidate.FailureKind = ovl_fail_bad_conversion;
6549         return;
6550       }
6551     } else {
6552       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6553       // argument for which there is no corresponding parameter is
6554       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6555       Candidate.Conversions[ConvIdx].setEllipsis();
6556     }
6557   }
6558 
6559   if (EnableIfAttr *FailedAttr =
6560           CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
6561     Candidate.Viable = false;
6562     Candidate.FailureKind = ovl_fail_enable_if;
6563     Candidate.DeductionFailure.Data = FailedAttr;
6564     return;
6565   }
6566 }
6567 
6568 ObjCMethodDecl *
6569 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6570                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6571   if (Methods.size() <= 1)
6572     return nullptr;
6573 
6574   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6575     bool Match = true;
6576     ObjCMethodDecl *Method = Methods[b];
6577     unsigned NumNamedArgs = Sel.getNumArgs();
6578     // Method might have more arguments than selector indicates. This is due
6579     // to addition of c-style arguments in method.
6580     if (Method->param_size() > NumNamedArgs)
6581       NumNamedArgs = Method->param_size();
6582     if (Args.size() < NumNamedArgs)
6583       continue;
6584 
6585     for (unsigned i = 0; i < NumNamedArgs; i++) {
6586       // We can't do any type-checking on a type-dependent argument.
6587       if (Args[i]->isTypeDependent()) {
6588         Match = false;
6589         break;
6590       }
6591 
6592       ParmVarDecl *param = Method->parameters()[i];
6593       Expr *argExpr = Args[i];
6594       assert(argExpr && "SelectBestMethod(): missing expression");
6595 
6596       // Strip the unbridged-cast placeholder expression off unless it's
6597       // a consumed argument.
6598       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6599           !param->hasAttr<CFConsumedAttr>())
6600         argExpr = stripARCUnbridgedCast(argExpr);
6601 
6602       // If the parameter is __unknown_anytype, move on to the next method.
6603       if (param->getType() == Context.UnknownAnyTy) {
6604         Match = false;
6605         break;
6606       }
6607 
6608       ImplicitConversionSequence ConversionState
6609         = TryCopyInitialization(*this, argExpr, param->getType(),
6610                                 /*SuppressUserConversions*/false,
6611                                 /*InOverloadResolution=*/true,
6612                                 /*AllowObjCWritebackConversion=*/
6613                                 getLangOpts().ObjCAutoRefCount,
6614                                 /*AllowExplicit*/false);
6615       // This function looks for a reasonably-exact match, so we consider
6616       // incompatible pointer conversions to be a failure here.
6617       if (ConversionState.isBad() ||
6618           (ConversionState.isStandard() &&
6619            ConversionState.Standard.Second ==
6620                ICK_Incompatible_Pointer_Conversion)) {
6621         Match = false;
6622         break;
6623       }
6624     }
6625     // Promote additional arguments to variadic methods.
6626     if (Match && Method->isVariadic()) {
6627       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6628         if (Args[i]->isTypeDependent()) {
6629           Match = false;
6630           break;
6631         }
6632         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6633                                                           nullptr);
6634         if (Arg.isInvalid()) {
6635           Match = false;
6636           break;
6637         }
6638       }
6639     } else {
6640       // Check for extra arguments to non-variadic methods.
6641       if (Args.size() != NumNamedArgs)
6642         Match = false;
6643       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6644         // Special case when selectors have no argument. In this case, select
6645         // one with the most general result type of 'id'.
6646         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6647           QualType ReturnT = Methods[b]->getReturnType();
6648           if (ReturnT->isObjCIdType())
6649             return Methods[b];
6650         }
6651       }
6652     }
6653 
6654     if (Match)
6655       return Method;
6656   }
6657   return nullptr;
6658 }
6659 
6660 static bool convertArgsForAvailabilityChecks(
6661     Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
6662     ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
6663     Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
6664   if (ThisArg) {
6665     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6666     assert(!isa<CXXConstructorDecl>(Method) &&
6667            "Shouldn't have `this` for ctors!");
6668     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6669     ExprResult R = S.PerformObjectArgumentInitialization(
6670         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6671     if (R.isInvalid())
6672       return false;
6673     ConvertedThis = R.get();
6674   } else {
6675     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6676       (void)MD;
6677       assert((MissingImplicitThis || MD->isStatic() ||
6678               isa<CXXConstructorDecl>(MD)) &&
6679              "Expected `this` for non-ctor instance methods");
6680     }
6681     ConvertedThis = nullptr;
6682   }
6683 
6684   // Ignore any variadic arguments. Converting them is pointless, since the
6685   // user can't refer to them in the function condition.
6686   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6687 
6688   // Convert the arguments.
6689   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6690     ExprResult R;
6691     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6692                                         S.Context, Function->getParamDecl(I)),
6693                                     SourceLocation(), Args[I]);
6694 
6695     if (R.isInvalid())
6696       return false;
6697 
6698     ConvertedArgs.push_back(R.get());
6699   }
6700 
6701   if (Trap.hasErrorOccurred())
6702     return false;
6703 
6704   // Push default arguments if needed.
6705   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6706     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6707       ParmVarDecl *P = Function->getParamDecl(i);
6708       if (!P->hasDefaultArg())
6709         return false;
6710       ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
6711       if (R.isInvalid())
6712         return false;
6713       ConvertedArgs.push_back(R.get());
6714     }
6715 
6716     if (Trap.hasErrorOccurred())
6717       return false;
6718   }
6719   return true;
6720 }
6721 
6722 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
6723                                   SourceLocation CallLoc,
6724                                   ArrayRef<Expr *> Args,
6725                                   bool MissingImplicitThis) {
6726   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6727   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6728     return nullptr;
6729 
6730   SFINAETrap Trap(*this);
6731   SmallVector<Expr *, 16> ConvertedArgs;
6732   // FIXME: We should look into making enable_if late-parsed.
6733   Expr *DiscardedThis;
6734   if (!convertArgsForAvailabilityChecks(
6735           *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
6736           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6737     return *EnableIfAttrs.begin();
6738 
6739   for (auto *EIA : EnableIfAttrs) {
6740     APValue Result;
6741     // FIXME: This doesn't consider value-dependent cases, because doing so is
6742     // very difficult. Ideally, we should handle them more gracefully.
6743     if (EIA->getCond()->isValueDependent() ||
6744         !EIA->getCond()->EvaluateWithSubstitution(
6745             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6746       return EIA;
6747 
6748     if (!Result.isInt() || !Result.getInt().getBoolValue())
6749       return EIA;
6750   }
6751   return nullptr;
6752 }
6753 
6754 template <typename CheckFn>
6755 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6756                                         bool ArgDependent, SourceLocation Loc,
6757                                         CheckFn &&IsSuccessful) {
6758   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6759   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6760     if (ArgDependent == DIA->getArgDependent())
6761       Attrs.push_back(DIA);
6762   }
6763 
6764   // Common case: No diagnose_if attributes, so we can quit early.
6765   if (Attrs.empty())
6766     return false;
6767 
6768   auto WarningBegin = std::stable_partition(
6769       Attrs.begin(), Attrs.end(),
6770       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6771 
6772   // Note that diagnose_if attributes are late-parsed, so they appear in the
6773   // correct order (unlike enable_if attributes).
6774   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6775                                IsSuccessful);
6776   if (ErrAttr != WarningBegin) {
6777     const DiagnoseIfAttr *DIA = *ErrAttr;
6778     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6779     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6780         << DIA->getParent() << DIA->getCond()->getSourceRange();
6781     return true;
6782   }
6783 
6784   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6785     if (IsSuccessful(DIA)) {
6786       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6787       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6788           << DIA->getParent() << DIA->getCond()->getSourceRange();
6789     }
6790 
6791   return false;
6792 }
6793 
6794 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6795                                                const Expr *ThisArg,
6796                                                ArrayRef<const Expr *> Args,
6797                                                SourceLocation Loc) {
6798   return diagnoseDiagnoseIfAttrsWith(
6799       *this, Function, /*ArgDependent=*/true, Loc,
6800       [&](const DiagnoseIfAttr *DIA) {
6801         APValue Result;
6802         // It's sane to use the same Args for any redecl of this function, since
6803         // EvaluateWithSubstitution only cares about the position of each
6804         // argument in the arg list, not the ParmVarDecl* it maps to.
6805         if (!DIA->getCond()->EvaluateWithSubstitution(
6806                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6807           return false;
6808         return Result.isInt() && Result.getInt().getBoolValue();
6809       });
6810 }
6811 
6812 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6813                                                  SourceLocation Loc) {
6814   return diagnoseDiagnoseIfAttrsWith(
6815       *this, ND, /*ArgDependent=*/false, Loc,
6816       [&](const DiagnoseIfAttr *DIA) {
6817         bool Result;
6818         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6819                Result;
6820       });
6821 }
6822 
6823 /// Add all of the function declarations in the given function set to
6824 /// the overload candidate set.
6825 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6826                                  ArrayRef<Expr *> Args,
6827                                  OverloadCandidateSet &CandidateSet,
6828                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6829                                  bool SuppressUserConversions,
6830                                  bool PartialOverloading,
6831                                  bool FirstArgumentIsBase) {
6832   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6833     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6834     ArrayRef<Expr *> FunctionArgs = Args;
6835 
6836     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6837     FunctionDecl *FD =
6838         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6839 
6840     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6841       QualType ObjectType;
6842       Expr::Classification ObjectClassification;
6843       if (Args.size() > 0) {
6844         if (Expr *E = Args[0]) {
6845           // Use the explicit base to restrict the lookup:
6846           ObjectType = E->getType();
6847           // Pointers in the object arguments are implicitly dereferenced, so we
6848           // always classify them as l-values.
6849           if (!ObjectType.isNull() && ObjectType->isPointerType())
6850             ObjectClassification = Expr::Classification::makeSimpleLValue();
6851           else
6852             ObjectClassification = E->Classify(Context);
6853         } // .. else there is an implicit base.
6854         FunctionArgs = Args.slice(1);
6855       }
6856       if (FunTmpl) {
6857         AddMethodTemplateCandidate(
6858             FunTmpl, F.getPair(),
6859             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6860             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6861             FunctionArgs, CandidateSet, SuppressUserConversions,
6862             PartialOverloading);
6863       } else {
6864         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6865                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6866                            ObjectClassification, FunctionArgs, CandidateSet,
6867                            SuppressUserConversions, PartialOverloading);
6868       }
6869     } else {
6870       // This branch handles both standalone functions and static methods.
6871 
6872       // Slice the first argument (which is the base) when we access
6873       // static method as non-static.
6874       if (Args.size() > 0 &&
6875           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6876                         !isa<CXXConstructorDecl>(FD)))) {
6877         assert(cast<CXXMethodDecl>(FD)->isStatic());
6878         FunctionArgs = Args.slice(1);
6879       }
6880       if (FunTmpl) {
6881         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6882                                      ExplicitTemplateArgs, FunctionArgs,
6883                                      CandidateSet, SuppressUserConversions,
6884                                      PartialOverloading);
6885       } else {
6886         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6887                              SuppressUserConversions, PartialOverloading);
6888       }
6889     }
6890   }
6891 }
6892 
6893 /// AddMethodCandidate - Adds a named decl (which is some kind of
6894 /// method) as a method candidate to the given overload set.
6895 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
6896                               Expr::Classification ObjectClassification,
6897                               ArrayRef<Expr *> Args,
6898                               OverloadCandidateSet &CandidateSet,
6899                               bool SuppressUserConversions,
6900                               OverloadCandidateParamOrder PO) {
6901   NamedDecl *Decl = FoundDecl.getDecl();
6902   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6903 
6904   if (isa<UsingShadowDecl>(Decl))
6905     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6906 
6907   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6908     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6909            "Expected a member function template");
6910     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6911                                /*ExplicitArgs*/ nullptr, ObjectType,
6912                                ObjectClassification, Args, CandidateSet,
6913                                SuppressUserConversions, false, PO);
6914   } else {
6915     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6916                        ObjectType, ObjectClassification, Args, CandidateSet,
6917                        SuppressUserConversions, false, None, PO);
6918   }
6919 }
6920 
6921 /// AddMethodCandidate - Adds the given C++ member function to the set
6922 /// of candidate functions, using the given function call arguments
6923 /// and the object argument (@c Object). For example, in a call
6924 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6925 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6926 /// allow user-defined conversions via constructors or conversion
6927 /// operators.
6928 void
6929 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6930                          CXXRecordDecl *ActingContext, QualType ObjectType,
6931                          Expr::Classification ObjectClassification,
6932                          ArrayRef<Expr *> Args,
6933                          OverloadCandidateSet &CandidateSet,
6934                          bool SuppressUserConversions,
6935                          bool PartialOverloading,
6936                          ConversionSequenceList EarlyConversions,
6937                          OverloadCandidateParamOrder PO) {
6938   const FunctionProtoType *Proto
6939     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6940   assert(Proto && "Methods without a prototype cannot be overloaded");
6941   assert(!isa<CXXConstructorDecl>(Method) &&
6942          "Use AddOverloadCandidate for constructors");
6943 
6944   if (!CandidateSet.isNewCandidate(Method, PO))
6945     return;
6946 
6947   // C++11 [class.copy]p23: [DR1402]
6948   //   A defaulted move assignment operator that is defined as deleted is
6949   //   ignored by overload resolution.
6950   if (Method->isDefaulted() && Method->isDeleted() &&
6951       Method->isMoveAssignmentOperator())
6952     return;
6953 
6954   // Overload resolution is always an unevaluated context.
6955   EnterExpressionEvaluationContext Unevaluated(
6956       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6957 
6958   // Add this candidate
6959   OverloadCandidate &Candidate =
6960       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6961   Candidate.FoundDecl = FoundDecl;
6962   Candidate.Function = Method;
6963   Candidate.RewriteKind =
6964       CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
6965   Candidate.IsSurrogate = false;
6966   Candidate.IgnoreObjectArgument = false;
6967   Candidate.ExplicitCallArguments = Args.size();
6968 
6969   unsigned NumParams = Proto->getNumParams();
6970 
6971   // (C++ 13.3.2p2): A candidate function having fewer than m
6972   // parameters is viable only if it has an ellipsis in its parameter
6973   // list (8.3.5).
6974   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6975       !Proto->isVariadic() &&
6976       shouldEnforceArgLimit(PartialOverloading, Method)) {
6977     Candidate.Viable = false;
6978     Candidate.FailureKind = ovl_fail_too_many_arguments;
6979     return;
6980   }
6981 
6982   // (C++ 13.3.2p2): A candidate function having more than m parameters
6983   // is viable only if the (m+1)st parameter has a default argument
6984   // (8.3.6). For the purposes of overload resolution, the
6985   // parameter list is truncated on the right, so that there are
6986   // exactly m parameters.
6987   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6988   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6989     // Not enough arguments.
6990     Candidate.Viable = false;
6991     Candidate.FailureKind = ovl_fail_too_few_arguments;
6992     return;
6993   }
6994 
6995   Candidate.Viable = true;
6996 
6997   if (Method->isStatic() || ObjectType.isNull())
6998     // The implicit object argument is ignored.
6999     Candidate.IgnoreObjectArgument = true;
7000   else {
7001     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7002     // Determine the implicit conversion sequence for the object
7003     // parameter.
7004     Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization(
7005         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7006         Method, ActingContext);
7007     if (Candidate.Conversions[ConvIdx].isBad()) {
7008       Candidate.Viable = false;
7009       Candidate.FailureKind = ovl_fail_bad_conversion;
7010       return;
7011     }
7012   }
7013 
7014   // (CUDA B.1): Check for invalid calls between targets.
7015   if (getLangOpts().CUDA)
7016     if (const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true))
7017       if (!IsAllowedCUDACall(Caller, Method)) {
7018         Candidate.Viable = false;
7019         Candidate.FailureKind = ovl_fail_bad_target;
7020         return;
7021       }
7022 
7023   if (Method->getTrailingRequiresClause()) {
7024     ConstraintSatisfaction Satisfaction;
7025     if (CheckFunctionConstraints(Method, Satisfaction) ||
7026         !Satisfaction.IsSatisfied) {
7027       Candidate.Viable = false;
7028       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7029       return;
7030     }
7031   }
7032 
7033   // Determine the implicit conversion sequences for each of the
7034   // arguments.
7035   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7036     unsigned ConvIdx =
7037         PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
7038     if (Candidate.Conversions[ConvIdx].isInitialized()) {
7039       // We already formed a conversion sequence for this parameter during
7040       // template argument deduction.
7041     } else if (ArgIdx < NumParams) {
7042       // (C++ 13.3.2p3): for F to be a viable function, there shall
7043       // exist for each argument an implicit conversion sequence
7044       // (13.3.3.1) that converts that argument to the corresponding
7045       // parameter of F.
7046       QualType ParamType = Proto->getParamType(ArgIdx);
7047       Candidate.Conversions[ConvIdx]
7048         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7049                                 SuppressUserConversions,
7050                                 /*InOverloadResolution=*/true,
7051                                 /*AllowObjCWritebackConversion=*/
7052                                   getLangOpts().ObjCAutoRefCount);
7053       if (Candidate.Conversions[ConvIdx].isBad()) {
7054         Candidate.Viable = false;
7055         Candidate.FailureKind = ovl_fail_bad_conversion;
7056         return;
7057       }
7058     } else {
7059       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7060       // argument for which there is no corresponding parameter is
7061       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7062       Candidate.Conversions[ConvIdx].setEllipsis();
7063     }
7064   }
7065 
7066   if (EnableIfAttr *FailedAttr =
7067           CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7068     Candidate.Viable = false;
7069     Candidate.FailureKind = ovl_fail_enable_if;
7070     Candidate.DeductionFailure.Data = FailedAttr;
7071     return;
7072   }
7073 
7074   if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
7075       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
7076     Candidate.Viable = false;
7077     Candidate.FailureKind = ovl_non_default_multiversion_function;
7078   }
7079 }
7080 
7081 /// Add a C++ member function template as a candidate to the candidate
7082 /// set, using template argument deduction to produce an appropriate member
7083 /// function template specialization.
7084 void Sema::AddMethodTemplateCandidate(
7085     FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7086     CXXRecordDecl *ActingContext,
7087     TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7088     Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7089     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7090     bool PartialOverloading, OverloadCandidateParamOrder PO) {
7091   if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7092     return;
7093 
7094   // C++ [over.match.funcs]p7:
7095   //   In each case where a candidate is a function template, candidate
7096   //   function template specializations are generated using template argument
7097   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
7098   //   candidate functions in the usual way.113) A given name can refer to one
7099   //   or more function templates and also to a set of overloaded non-template
7100   //   functions. In such a case, the candidate functions generated from each
7101   //   function template are combined with the set of non-template candidate
7102   //   functions.
7103   TemplateDeductionInfo Info(CandidateSet.getLocation());
7104   FunctionDecl *Specialization = nullptr;
7105   ConversionSequenceList Conversions;
7106   if (TemplateDeductionResult Result = DeduceTemplateArguments(
7107           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7108           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7109             return CheckNonDependentConversions(
7110                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7111                 SuppressUserConversions, ActingContext, ObjectType,
7112                 ObjectClassification, PO);
7113           })) {
7114     OverloadCandidate &Candidate =
7115         CandidateSet.addCandidate(Conversions.size(), Conversions);
7116     Candidate.FoundDecl = FoundDecl;
7117     Candidate.Function = MethodTmpl->getTemplatedDecl();
7118     Candidate.Viable = false;
7119     Candidate.RewriteKind =
7120       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7121     Candidate.IsSurrogate = false;
7122     Candidate.IgnoreObjectArgument =
7123         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
7124         ObjectType.isNull();
7125     Candidate.ExplicitCallArguments = Args.size();
7126     if (Result == TDK_NonDependentConversionFailure)
7127       Candidate.FailureKind = ovl_fail_bad_conversion;
7128     else {
7129       Candidate.FailureKind = ovl_fail_bad_deduction;
7130       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7131                                                             Info);
7132     }
7133     return;
7134   }
7135 
7136   // Add the function template specialization produced by template argument
7137   // deduction as a candidate.
7138   assert(Specialization && "Missing member function template specialization?");
7139   assert(isa<CXXMethodDecl>(Specialization) &&
7140          "Specialization is not a member function?");
7141   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
7142                      ActingContext, ObjectType, ObjectClassification, Args,
7143                      CandidateSet, SuppressUserConversions, PartialOverloading,
7144                      Conversions, PO);
7145 }
7146 
7147 /// Determine whether a given function template has a simple explicit specifier
7148 /// or a non-value-dependent explicit-specification that evaluates to true.
7149 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
7150   return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
7151 }
7152 
7153 /// Add a C++ function template specialization as a candidate
7154 /// in the candidate set, using template argument deduction to produce
7155 /// an appropriate function template specialization.
7156 void Sema::AddTemplateOverloadCandidate(
7157     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7158     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7159     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7160     bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7161     OverloadCandidateParamOrder PO) {
7162   if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
7163     return;
7164 
7165   // If the function template has a non-dependent explicit specification,
7166   // exclude it now if appropriate; we are not permitted to perform deduction
7167   // and substitution in this case.
7168   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7169     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7170     Candidate.FoundDecl = FoundDecl;
7171     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7172     Candidate.Viable = false;
7173     Candidate.FailureKind = ovl_fail_explicit;
7174     return;
7175   }
7176 
7177   // C++ [over.match.funcs]p7:
7178   //   In each case where a candidate is a function template, candidate
7179   //   function template specializations are generated using template argument
7180   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
7181   //   candidate functions in the usual way.113) A given name can refer to one
7182   //   or more function templates and also to a set of overloaded non-template
7183   //   functions. In such a case, the candidate functions generated from each
7184   //   function template are combined with the set of non-template candidate
7185   //   functions.
7186   TemplateDeductionInfo Info(CandidateSet.getLocation());
7187   FunctionDecl *Specialization = nullptr;
7188   ConversionSequenceList Conversions;
7189   if (TemplateDeductionResult Result = DeduceTemplateArguments(
7190           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7191           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7192             return CheckNonDependentConversions(
7193                 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7194                 SuppressUserConversions, nullptr, QualType(), {}, PO);
7195           })) {
7196     OverloadCandidate &Candidate =
7197         CandidateSet.addCandidate(Conversions.size(), Conversions);
7198     Candidate.FoundDecl = FoundDecl;
7199     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7200     Candidate.Viable = false;
7201     Candidate.RewriteKind =
7202       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7203     Candidate.IsSurrogate = false;
7204     Candidate.IsADLCandidate = IsADLCandidate;
7205     // Ignore the object argument if there is one, since we don't have an object
7206     // type.
7207     Candidate.IgnoreObjectArgument =
7208         isa<CXXMethodDecl>(Candidate.Function) &&
7209         !isa<CXXConstructorDecl>(Candidate.Function);
7210     Candidate.ExplicitCallArguments = Args.size();
7211     if (Result == TDK_NonDependentConversionFailure)
7212       Candidate.FailureKind = ovl_fail_bad_conversion;
7213     else {
7214       Candidate.FailureKind = ovl_fail_bad_deduction;
7215       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7216                                                             Info);
7217     }
7218     return;
7219   }
7220 
7221   // Add the function template specialization produced by template argument
7222   // deduction as a candidate.
7223   assert(Specialization && "Missing function template specialization?");
7224   AddOverloadCandidate(
7225       Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7226       PartialOverloading, AllowExplicit,
7227       /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO);
7228 }
7229 
7230 /// Check that implicit conversion sequences can be formed for each argument
7231 /// whose corresponding parameter has a non-dependent type, per DR1391's
7232 /// [temp.deduct.call]p10.
7233 bool Sema::CheckNonDependentConversions(
7234     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7235     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7236     ConversionSequenceList &Conversions, bool SuppressUserConversions,
7237     CXXRecordDecl *ActingContext, QualType ObjectType,
7238     Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7239   // FIXME: The cases in which we allow explicit conversions for constructor
7240   // arguments never consider calling a constructor template. It's not clear
7241   // that is correct.
7242   const bool AllowExplicit = false;
7243 
7244   auto *FD = FunctionTemplate->getTemplatedDecl();
7245   auto *Method = dyn_cast<CXXMethodDecl>(FD);
7246   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7247   unsigned ThisConversions = HasThisConversion ? 1 : 0;
7248 
7249   Conversions =
7250       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7251 
7252   // Overload resolution is always an unevaluated context.
7253   EnterExpressionEvaluationContext Unevaluated(
7254       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7255 
7256   // For a method call, check the 'this' conversion here too. DR1391 doesn't
7257   // require that, but this check should never result in a hard error, and
7258   // overload resolution is permitted to sidestep instantiations.
7259   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7260       !ObjectType.isNull()) {
7261     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7262     Conversions[ConvIdx] = TryObjectArgumentInitialization(
7263         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7264         Method, ActingContext);
7265     if (Conversions[ConvIdx].isBad())
7266       return true;
7267   }
7268 
7269   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
7270        ++I) {
7271     QualType ParamType = ParamTypes[I];
7272     if (!ParamType->isDependentType()) {
7273       unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
7274                              ? 0
7275                              : (ThisConversions + I);
7276       Conversions[ConvIdx]
7277         = TryCopyInitialization(*this, Args[I], ParamType,
7278                                 SuppressUserConversions,
7279                                 /*InOverloadResolution=*/true,
7280                                 /*AllowObjCWritebackConversion=*/
7281                                   getLangOpts().ObjCAutoRefCount,
7282                                 AllowExplicit);
7283       if (Conversions[ConvIdx].isBad())
7284         return true;
7285     }
7286   }
7287 
7288   return false;
7289 }
7290 
7291 /// Determine whether this is an allowable conversion from the result
7292 /// of an explicit conversion operator to the expected type, per C++
7293 /// [over.match.conv]p1 and [over.match.ref]p1.
7294 ///
7295 /// \param ConvType The return type of the conversion function.
7296 ///
7297 /// \param ToType The type we are converting to.
7298 ///
7299 /// \param AllowObjCPointerConversion Allow a conversion from one
7300 /// Objective-C pointer to another.
7301 ///
7302 /// \returns true if the conversion is allowable, false otherwise.
7303 static bool isAllowableExplicitConversion(Sema &S,
7304                                           QualType ConvType, QualType ToType,
7305                                           bool AllowObjCPointerConversion) {
7306   QualType ToNonRefType = ToType.getNonReferenceType();
7307 
7308   // Easy case: the types are the same.
7309   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7310     return true;
7311 
7312   // Allow qualification conversions.
7313   bool ObjCLifetimeConversion;
7314   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7315                                   ObjCLifetimeConversion))
7316     return true;
7317 
7318   // If we're not allowed to consider Objective-C pointer conversions,
7319   // we're done.
7320   if (!AllowObjCPointerConversion)
7321     return false;
7322 
7323   // Is this an Objective-C pointer conversion?
7324   bool IncompatibleObjC = false;
7325   QualType ConvertedType;
7326   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7327                                    IncompatibleObjC);
7328 }
7329 
7330 /// AddConversionCandidate - Add a C++ conversion function as a
7331 /// candidate in the candidate set (C++ [over.match.conv],
7332 /// C++ [over.match.copy]). From is the expression we're converting from,
7333 /// and ToType is the type that we're eventually trying to convert to
7334 /// (which may or may not be the same type as the type that the
7335 /// conversion function produces).
7336 void Sema::AddConversionCandidate(
7337     CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7338     CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7339     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7340     bool AllowExplicit, bool AllowResultConversion) {
7341   assert(!Conversion->getDescribedFunctionTemplate() &&
7342          "Conversion function templates use AddTemplateConversionCandidate");
7343   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7344   if (!CandidateSet.isNewCandidate(Conversion))
7345     return;
7346 
7347   // If the conversion function has an undeduced return type, trigger its
7348   // deduction now.
7349   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7350     if (DeduceReturnType(Conversion, From->getExprLoc()))
7351       return;
7352     ConvType = Conversion->getConversionType().getNonReferenceType();
7353   }
7354 
7355   // If we don't allow any conversion of the result type, ignore conversion
7356   // functions that don't convert to exactly (possibly cv-qualified) T.
7357   if (!AllowResultConversion &&
7358       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7359     return;
7360 
7361   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7362   // operator is only a candidate if its return type is the target type or
7363   // can be converted to the target type with a qualification conversion.
7364   //
7365   // FIXME: Include such functions in the candidate list and explain why we
7366   // can't select them.
7367   if (Conversion->isExplicit() &&
7368       !isAllowableExplicitConversion(*this, ConvType, ToType,
7369                                      AllowObjCConversionOnExplicit))
7370     return;
7371 
7372   // Overload resolution is always an unevaluated context.
7373   EnterExpressionEvaluationContext Unevaluated(
7374       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7375 
7376   // Add this candidate
7377   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7378   Candidate.FoundDecl = FoundDecl;
7379   Candidate.Function = Conversion;
7380   Candidate.IsSurrogate = false;
7381   Candidate.IgnoreObjectArgument = false;
7382   Candidate.FinalConversion.setAsIdentityConversion();
7383   Candidate.FinalConversion.setFromType(ConvType);
7384   Candidate.FinalConversion.setAllToTypes(ToType);
7385   Candidate.Viable = true;
7386   Candidate.ExplicitCallArguments = 1;
7387 
7388   // Explicit functions are not actually candidates at all if we're not
7389   // allowing them in this context, but keep them around so we can point
7390   // to them in diagnostics.
7391   if (!AllowExplicit && Conversion->isExplicit()) {
7392     Candidate.Viable = false;
7393     Candidate.FailureKind = ovl_fail_explicit;
7394     return;
7395   }
7396 
7397   // C++ [over.match.funcs]p4:
7398   //   For conversion functions, the function is considered to be a member of
7399   //   the class of the implicit implied object argument for the purpose of
7400   //   defining the type of the implicit object parameter.
7401   //
7402   // Determine the implicit conversion sequence for the implicit
7403   // object parameter.
7404   QualType ImplicitParamType = From->getType();
7405   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7406     ImplicitParamType = FromPtrType->getPointeeType();
7407   CXXRecordDecl *ConversionContext
7408     = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
7409 
7410   Candidate.Conversions[0] = TryObjectArgumentInitialization(
7411       *this, CandidateSet.getLocation(), From->getType(),
7412       From->Classify(Context), Conversion, ConversionContext);
7413 
7414   if (Candidate.Conversions[0].isBad()) {
7415     Candidate.Viable = false;
7416     Candidate.FailureKind = ovl_fail_bad_conversion;
7417     return;
7418   }
7419 
7420   if (Conversion->getTrailingRequiresClause()) {
7421     ConstraintSatisfaction Satisfaction;
7422     if (CheckFunctionConstraints(Conversion, Satisfaction) ||
7423         !Satisfaction.IsSatisfied) {
7424       Candidate.Viable = false;
7425       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7426       return;
7427     }
7428   }
7429 
7430   // We won't go through a user-defined type conversion function to convert a
7431   // derived to base as such conversions are given Conversion Rank. They only
7432   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7433   QualType FromCanon
7434     = Context.getCanonicalType(From->getType().getUnqualifiedType());
7435   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7436   if (FromCanon == ToCanon ||
7437       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7438     Candidate.Viable = false;
7439     Candidate.FailureKind = ovl_fail_trivial_conversion;
7440     return;
7441   }
7442 
7443   // To determine what the conversion from the result of calling the
7444   // conversion function to the type we're eventually trying to
7445   // convert to (ToType), we need to synthesize a call to the
7446   // conversion function and attempt copy initialization from it. This
7447   // makes sure that we get the right semantics with respect to
7448   // lvalues/rvalues and the type. Fortunately, we can allocate this
7449   // call on the stack and we don't need its arguments to be
7450   // well-formed.
7451   DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7452                             VK_LValue, From->getBeginLoc());
7453   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7454                                 Context.getPointerType(Conversion->getType()),
7455                                 CK_FunctionToPointerDecay, &ConversionRef,
7456                                 VK_PRValue, FPOptionsOverride());
7457 
7458   QualType ConversionType = Conversion->getConversionType();
7459   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7460     Candidate.Viable = false;
7461     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7462     return;
7463   }
7464 
7465   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7466 
7467   // Note that it is safe to allocate CallExpr on the stack here because
7468   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7469   // allocator).
7470   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7471 
7472   alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7473   CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7474       Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7475 
7476   ImplicitConversionSequence ICS =
7477       TryCopyInitialization(*this, TheTemporaryCall, ToType,
7478                             /*SuppressUserConversions=*/true,
7479                             /*InOverloadResolution=*/false,
7480                             /*AllowObjCWritebackConversion=*/false);
7481 
7482   switch (ICS.getKind()) {
7483   case ImplicitConversionSequence::StandardConversion:
7484     Candidate.FinalConversion = ICS.Standard;
7485 
7486     // C++ [over.ics.user]p3:
7487     //   If the user-defined conversion is specified by a specialization of a
7488     //   conversion function template, the second standard conversion sequence
7489     //   shall have exact match rank.
7490     if (Conversion->getPrimaryTemplate() &&
7491         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7492       Candidate.Viable = false;
7493       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7494       return;
7495     }
7496 
7497     // C++0x [dcl.init.ref]p5:
7498     //    In the second case, if the reference is an rvalue reference and
7499     //    the second standard conversion sequence of the user-defined
7500     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7501     //    program is ill-formed.
7502     if (ToType->isRValueReferenceType() &&
7503         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7504       Candidate.Viable = false;
7505       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7506       return;
7507     }
7508     break;
7509 
7510   case ImplicitConversionSequence::BadConversion:
7511     Candidate.Viable = false;
7512     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7513     return;
7514 
7515   default:
7516     llvm_unreachable(
7517            "Can only end up with a standard conversion sequence or failure");
7518   }
7519 
7520   if (EnableIfAttr *FailedAttr =
7521           CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7522     Candidate.Viable = false;
7523     Candidate.FailureKind = ovl_fail_enable_if;
7524     Candidate.DeductionFailure.Data = FailedAttr;
7525     return;
7526   }
7527 
7528   if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7529       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7530     Candidate.Viable = false;
7531     Candidate.FailureKind = ovl_non_default_multiversion_function;
7532   }
7533 }
7534 
7535 /// Adds a conversion function template specialization
7536 /// candidate to the overload set, using template argument deduction
7537 /// to deduce the template arguments of the conversion function
7538 /// template from the type that we are converting to (C++
7539 /// [temp.deduct.conv]).
7540 void Sema::AddTemplateConversionCandidate(
7541     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7542     CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7543     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7544     bool AllowExplicit, bool AllowResultConversion) {
7545   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7546          "Only conversion function templates permitted here");
7547 
7548   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7549     return;
7550 
7551   // If the function template has a non-dependent explicit specification,
7552   // exclude it now if appropriate; we are not permitted to perform deduction
7553   // and substitution in this case.
7554   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7555     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7556     Candidate.FoundDecl = FoundDecl;
7557     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7558     Candidate.Viable = false;
7559     Candidate.FailureKind = ovl_fail_explicit;
7560     return;
7561   }
7562 
7563   TemplateDeductionInfo Info(CandidateSet.getLocation());
7564   CXXConversionDecl *Specialization = nullptr;
7565   if (TemplateDeductionResult Result
7566         = DeduceTemplateArguments(FunctionTemplate, ToType,
7567                                   Specialization, Info)) {
7568     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7569     Candidate.FoundDecl = FoundDecl;
7570     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7571     Candidate.Viable = false;
7572     Candidate.FailureKind = ovl_fail_bad_deduction;
7573     Candidate.IsSurrogate = false;
7574     Candidate.IgnoreObjectArgument = false;
7575     Candidate.ExplicitCallArguments = 1;
7576     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7577                                                           Info);
7578     return;
7579   }
7580 
7581   // Add the conversion function template specialization produced by
7582   // template argument deduction as a candidate.
7583   assert(Specialization && "Missing function template specialization?");
7584   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7585                          CandidateSet, AllowObjCConversionOnExplicit,
7586                          AllowExplicit, AllowResultConversion);
7587 }
7588 
7589 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7590 /// converts the given @c Object to a function pointer via the
7591 /// conversion function @c Conversion, and then attempts to call it
7592 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7593 /// the type of function that we'll eventually be calling.
7594 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7595                                  DeclAccessPair FoundDecl,
7596                                  CXXRecordDecl *ActingContext,
7597                                  const FunctionProtoType *Proto,
7598                                  Expr *Object,
7599                                  ArrayRef<Expr *> Args,
7600                                  OverloadCandidateSet& CandidateSet) {
7601   if (!CandidateSet.isNewCandidate(Conversion))
7602     return;
7603 
7604   // Overload resolution is always an unevaluated context.
7605   EnterExpressionEvaluationContext Unevaluated(
7606       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7607 
7608   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7609   Candidate.FoundDecl = FoundDecl;
7610   Candidate.Function = nullptr;
7611   Candidate.Surrogate = Conversion;
7612   Candidate.Viable = true;
7613   Candidate.IsSurrogate = true;
7614   Candidate.IgnoreObjectArgument = false;
7615   Candidate.ExplicitCallArguments = Args.size();
7616 
7617   // Determine the implicit conversion sequence for the implicit
7618   // object parameter.
7619   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7620       *this, CandidateSet.getLocation(), Object->getType(),
7621       Object->Classify(Context), Conversion, ActingContext);
7622   if (ObjectInit.isBad()) {
7623     Candidate.Viable = false;
7624     Candidate.FailureKind = ovl_fail_bad_conversion;
7625     Candidate.Conversions[0] = ObjectInit;
7626     return;
7627   }
7628 
7629   // The first conversion is actually a user-defined conversion whose
7630   // first conversion is ObjectInit's standard conversion (which is
7631   // effectively a reference binding). Record it as such.
7632   Candidate.Conversions[0].setUserDefined();
7633   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7634   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7635   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7636   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7637   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7638   Candidate.Conversions[0].UserDefined.After
7639     = Candidate.Conversions[0].UserDefined.Before;
7640   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7641 
7642   // Find the
7643   unsigned NumParams = Proto->getNumParams();
7644 
7645   // (C++ 13.3.2p2): A candidate function having fewer than m
7646   // parameters is viable only if it has an ellipsis in its parameter
7647   // list (8.3.5).
7648   if (Args.size() > NumParams && !Proto->isVariadic()) {
7649     Candidate.Viable = false;
7650     Candidate.FailureKind = ovl_fail_too_many_arguments;
7651     return;
7652   }
7653 
7654   // Function types don't have any default arguments, so just check if
7655   // we have enough arguments.
7656   if (Args.size() < NumParams) {
7657     // Not enough arguments.
7658     Candidate.Viable = false;
7659     Candidate.FailureKind = ovl_fail_too_few_arguments;
7660     return;
7661   }
7662 
7663   // Determine the implicit conversion sequences for each of the
7664   // arguments.
7665   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7666     if (ArgIdx < NumParams) {
7667       // (C++ 13.3.2p3): for F to be a viable function, there shall
7668       // exist for each argument an implicit conversion sequence
7669       // (13.3.3.1) that converts that argument to the corresponding
7670       // parameter of F.
7671       QualType ParamType = Proto->getParamType(ArgIdx);
7672       Candidate.Conversions[ArgIdx + 1]
7673         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7674                                 /*SuppressUserConversions=*/false,
7675                                 /*InOverloadResolution=*/false,
7676                                 /*AllowObjCWritebackConversion=*/
7677                                   getLangOpts().ObjCAutoRefCount);
7678       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7679         Candidate.Viable = false;
7680         Candidate.FailureKind = ovl_fail_bad_conversion;
7681         return;
7682       }
7683     } else {
7684       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7685       // argument for which there is no corresponding parameter is
7686       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7687       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7688     }
7689   }
7690 
7691   if (EnableIfAttr *FailedAttr =
7692           CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7693     Candidate.Viable = false;
7694     Candidate.FailureKind = ovl_fail_enable_if;
7695     Candidate.DeductionFailure.Data = FailedAttr;
7696     return;
7697   }
7698 }
7699 
7700 /// Add all of the non-member operator function declarations in the given
7701 /// function set to the overload candidate set.
7702 void Sema::AddNonMemberOperatorCandidates(
7703     const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
7704     OverloadCandidateSet &CandidateSet,
7705     TemplateArgumentListInfo *ExplicitTemplateArgs) {
7706   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7707     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7708     ArrayRef<Expr *> FunctionArgs = Args;
7709 
7710     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7711     FunctionDecl *FD =
7712         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7713 
7714     // Don't consider rewritten functions if we're not rewriting.
7715     if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
7716       continue;
7717 
7718     assert(!isa<CXXMethodDecl>(FD) &&
7719            "unqualified operator lookup found a member function");
7720 
7721     if (FunTmpl) {
7722       AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
7723                                    FunctionArgs, CandidateSet);
7724       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7725         AddTemplateOverloadCandidate(
7726             FunTmpl, F.getPair(), ExplicitTemplateArgs,
7727             {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
7728             true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
7729     } else {
7730       if (ExplicitTemplateArgs)
7731         continue;
7732       AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
7733       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7734         AddOverloadCandidate(FD, F.getPair(),
7735                              {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
7736                              false, false, true, false, ADLCallKind::NotADL,
7737                              None, OverloadCandidateParamOrder::Reversed);
7738     }
7739   }
7740 }
7741 
7742 /// Add overload candidates for overloaded operators that are
7743 /// member functions.
7744 ///
7745 /// Add the overloaded operator candidates that are member functions
7746 /// for the operator Op that was used in an operator expression such
7747 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7748 /// CandidateSet will store the added overload candidates. (C++
7749 /// [over.match.oper]).
7750 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7751                                        SourceLocation OpLoc,
7752                                        ArrayRef<Expr *> Args,
7753                                        OverloadCandidateSet &CandidateSet,
7754                                        OverloadCandidateParamOrder PO) {
7755   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7756 
7757   // C++ [over.match.oper]p3:
7758   //   For a unary operator @ with an operand of a type whose
7759   //   cv-unqualified version is T1, and for a binary operator @ with
7760   //   a left operand of a type whose cv-unqualified version is T1 and
7761   //   a right operand of a type whose cv-unqualified version is T2,
7762   //   three sets of candidate functions, designated member
7763   //   candidates, non-member candidates and built-in candidates, are
7764   //   constructed as follows:
7765   QualType T1 = Args[0]->getType();
7766 
7767   //     -- If T1 is a complete class type or a class currently being
7768   //        defined, the set of member candidates is the result of the
7769   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7770   //        the set of member candidates is empty.
7771   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7772     // Complete the type if it can be completed.
7773     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7774       return;
7775     // If the type is neither complete nor being defined, bail out now.
7776     if (!T1Rec->getDecl()->getDefinition())
7777       return;
7778 
7779     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7780     LookupQualifiedName(Operators, T1Rec->getDecl());
7781     Operators.suppressDiagnostics();
7782 
7783     for (LookupResult::iterator Oper = Operators.begin(),
7784                              OperEnd = Operators.end();
7785          Oper != OperEnd;
7786          ++Oper)
7787       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7788                          Args[0]->Classify(Context), Args.slice(1),
7789                          CandidateSet, /*SuppressUserConversion=*/false, PO);
7790   }
7791 }
7792 
7793 /// AddBuiltinCandidate - Add a candidate for a built-in
7794 /// operator. ResultTy and ParamTys are the result and parameter types
7795 /// of the built-in candidate, respectively. Args and NumArgs are the
7796 /// arguments being passed to the candidate. IsAssignmentOperator
7797 /// should be true when this built-in candidate is an assignment
7798 /// operator. NumContextualBoolArguments is the number of arguments
7799 /// (at the beginning of the argument list) that will be contextually
7800 /// converted to bool.
7801 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7802                                OverloadCandidateSet& CandidateSet,
7803                                bool IsAssignmentOperator,
7804                                unsigned NumContextualBoolArguments) {
7805   // Overload resolution is always an unevaluated context.
7806   EnterExpressionEvaluationContext Unevaluated(
7807       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7808 
7809   // Add this candidate
7810   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7811   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7812   Candidate.Function = nullptr;
7813   Candidate.IsSurrogate = false;
7814   Candidate.IgnoreObjectArgument = false;
7815   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7816 
7817   // Determine the implicit conversion sequences for each of the
7818   // arguments.
7819   Candidate.Viable = true;
7820   Candidate.ExplicitCallArguments = Args.size();
7821   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7822     // C++ [over.match.oper]p4:
7823     //   For the built-in assignment operators, conversions of the
7824     //   left operand are restricted as follows:
7825     //     -- no temporaries are introduced to hold the left operand, and
7826     //     -- no user-defined conversions are applied to the left
7827     //        operand to achieve a type match with the left-most
7828     //        parameter of a built-in candidate.
7829     //
7830     // We block these conversions by turning off user-defined
7831     // conversions, since that is the only way that initialization of
7832     // a reference to a non-class type can occur from something that
7833     // is not of the same type.
7834     if (ArgIdx < NumContextualBoolArguments) {
7835       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7836              "Contextual conversion to bool requires bool type");
7837       Candidate.Conversions[ArgIdx]
7838         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7839     } else {
7840       Candidate.Conversions[ArgIdx]
7841         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7842                                 ArgIdx == 0 && IsAssignmentOperator,
7843                                 /*InOverloadResolution=*/false,
7844                                 /*AllowObjCWritebackConversion=*/
7845                                   getLangOpts().ObjCAutoRefCount);
7846     }
7847     if (Candidate.Conversions[ArgIdx].isBad()) {
7848       Candidate.Viable = false;
7849       Candidate.FailureKind = ovl_fail_bad_conversion;
7850       break;
7851     }
7852   }
7853 }
7854 
7855 namespace {
7856 
7857 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7858 /// candidate operator functions for built-in operators (C++
7859 /// [over.built]). The types are separated into pointer types and
7860 /// enumeration types.
7861 class BuiltinCandidateTypeSet  {
7862   /// TypeSet - A set of types.
7863   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7864                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7865 
7866   /// PointerTypes - The set of pointer types that will be used in the
7867   /// built-in candidates.
7868   TypeSet PointerTypes;
7869 
7870   /// MemberPointerTypes - The set of member pointer types that will be
7871   /// used in the built-in candidates.
7872   TypeSet MemberPointerTypes;
7873 
7874   /// EnumerationTypes - The set of enumeration types that will be
7875   /// used in the built-in candidates.
7876   TypeSet EnumerationTypes;
7877 
7878   /// The set of vector types that will be used in the built-in
7879   /// candidates.
7880   TypeSet VectorTypes;
7881 
7882   /// The set of matrix types that will be used in the built-in
7883   /// candidates.
7884   TypeSet MatrixTypes;
7885 
7886   /// A flag indicating non-record types are viable candidates
7887   bool HasNonRecordTypes;
7888 
7889   /// A flag indicating whether either arithmetic or enumeration types
7890   /// were present in the candidate set.
7891   bool HasArithmeticOrEnumeralTypes;
7892 
7893   /// A flag indicating whether the nullptr type was present in the
7894   /// candidate set.
7895   bool HasNullPtrType;
7896 
7897   /// Sema - The semantic analysis instance where we are building the
7898   /// candidate type set.
7899   Sema &SemaRef;
7900 
7901   /// Context - The AST context in which we will build the type sets.
7902   ASTContext &Context;
7903 
7904   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7905                                                const Qualifiers &VisibleQuals);
7906   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7907 
7908 public:
7909   /// iterator - Iterates through the types that are part of the set.
7910   typedef TypeSet::iterator iterator;
7911 
7912   BuiltinCandidateTypeSet(Sema &SemaRef)
7913     : HasNonRecordTypes(false),
7914       HasArithmeticOrEnumeralTypes(false),
7915       HasNullPtrType(false),
7916       SemaRef(SemaRef),
7917       Context(SemaRef.Context) { }
7918 
7919   void AddTypesConvertedFrom(QualType Ty,
7920                              SourceLocation Loc,
7921                              bool AllowUserConversions,
7922                              bool AllowExplicitConversions,
7923                              const Qualifiers &VisibleTypeConversionsQuals);
7924 
7925   llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
7926   llvm::iterator_range<iterator> member_pointer_types() {
7927     return MemberPointerTypes;
7928   }
7929   llvm::iterator_range<iterator> enumeration_types() {
7930     return EnumerationTypes;
7931   }
7932   llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
7933   llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
7934 
7935   bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
7936   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7937   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7938   bool hasNullPtrType() const { return HasNullPtrType; }
7939 };
7940 
7941 } // end anonymous namespace
7942 
7943 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7944 /// the set of pointer types along with any more-qualified variants of
7945 /// that type. For example, if @p Ty is "int const *", this routine
7946 /// will add "int const *", "int const volatile *", "int const
7947 /// restrict *", and "int const volatile restrict *" to the set of
7948 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7949 /// false otherwise.
7950 ///
7951 /// FIXME: what to do about extended qualifiers?
7952 bool
7953 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7954                                              const Qualifiers &VisibleQuals) {
7955 
7956   // Insert this type.
7957   if (!PointerTypes.insert(Ty))
7958     return false;
7959 
7960   QualType PointeeTy;
7961   const PointerType *PointerTy = Ty->getAs<PointerType>();
7962   bool buildObjCPtr = false;
7963   if (!PointerTy) {
7964     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7965     PointeeTy = PTy->getPointeeType();
7966     buildObjCPtr = true;
7967   } else {
7968     PointeeTy = PointerTy->getPointeeType();
7969   }
7970 
7971   // Don't add qualified variants of arrays. For one, they're not allowed
7972   // (the qualifier would sink to the element type), and for another, the
7973   // only overload situation where it matters is subscript or pointer +- int,
7974   // and those shouldn't have qualifier variants anyway.
7975   if (PointeeTy->isArrayType())
7976     return true;
7977 
7978   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7979   bool hasVolatile = VisibleQuals.hasVolatile();
7980   bool hasRestrict = VisibleQuals.hasRestrict();
7981 
7982   // Iterate through all strict supersets of BaseCVR.
7983   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7984     if ((CVR | BaseCVR) != CVR) continue;
7985     // Skip over volatile if no volatile found anywhere in the types.
7986     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7987 
7988     // Skip over restrict if no restrict found anywhere in the types, or if
7989     // the type cannot be restrict-qualified.
7990     if ((CVR & Qualifiers::Restrict) &&
7991         (!hasRestrict ||
7992          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7993       continue;
7994 
7995     // Build qualified pointee type.
7996     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7997 
7998     // Build qualified pointer type.
7999     QualType QPointerTy;
8000     if (!buildObjCPtr)
8001       QPointerTy = Context.getPointerType(QPointeeTy);
8002     else
8003       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
8004 
8005     // Insert qualified pointer type.
8006     PointerTypes.insert(QPointerTy);
8007   }
8008 
8009   return true;
8010 }
8011 
8012 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8013 /// to the set of pointer types along with any more-qualified variants of
8014 /// that type. For example, if @p Ty is "int const *", this routine
8015 /// will add "int const *", "int const volatile *", "int const
8016 /// restrict *", and "int const volatile restrict *" to the set of
8017 /// pointer types. Returns true if the add of @p Ty itself succeeded,
8018 /// false otherwise.
8019 ///
8020 /// FIXME: what to do about extended qualifiers?
8021 bool
8022 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8023     QualType Ty) {
8024   // Insert this type.
8025   if (!MemberPointerTypes.insert(Ty))
8026     return false;
8027 
8028   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8029   assert(PointerTy && "type was not a member pointer type!");
8030 
8031   QualType PointeeTy = PointerTy->getPointeeType();
8032   // Don't add qualified variants of arrays. For one, they're not allowed
8033   // (the qualifier would sink to the element type), and for another, the
8034   // only overload situation where it matters is subscript or pointer +- int,
8035   // and those shouldn't have qualifier variants anyway.
8036   if (PointeeTy->isArrayType())
8037     return true;
8038   const Type *ClassTy = PointerTy->getClass();
8039 
8040   // Iterate through all strict supersets of the pointee type's CVR
8041   // qualifiers.
8042   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8043   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8044     if ((CVR | BaseCVR) != CVR) continue;
8045 
8046     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8047     MemberPointerTypes.insert(
8048       Context.getMemberPointerType(QPointeeTy, ClassTy));
8049   }
8050 
8051   return true;
8052 }
8053 
8054 /// AddTypesConvertedFrom - Add each of the types to which the type @p
8055 /// Ty can be implicit converted to the given set of @p Types. We're
8056 /// primarily interested in pointer types and enumeration types. We also
8057 /// take member pointer types, for the conditional operator.
8058 /// AllowUserConversions is true if we should look at the conversion
8059 /// functions of a class type, and AllowExplicitConversions if we
8060 /// should also include the explicit conversion functions of a class
8061 /// type.
8062 void
8063 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
8064                                                SourceLocation Loc,
8065                                                bool AllowUserConversions,
8066                                                bool AllowExplicitConversions,
8067                                                const Qualifiers &VisibleQuals) {
8068   // Only deal with canonical types.
8069   Ty = Context.getCanonicalType(Ty);
8070 
8071   // Look through reference types; they aren't part of the type of an
8072   // expression for the purposes of conversions.
8073   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
8074     Ty = RefTy->getPointeeType();
8075 
8076   // If we're dealing with an array type, decay to the pointer.
8077   if (Ty->isArrayType())
8078     Ty = SemaRef.Context.getArrayDecayedType(Ty);
8079 
8080   // Otherwise, we don't care about qualifiers on the type.
8081   Ty = Ty.getLocalUnqualifiedType();
8082 
8083   // Flag if we ever add a non-record type.
8084   const RecordType *TyRec = Ty->getAs<RecordType>();
8085   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
8086 
8087   // Flag if we encounter an arithmetic type.
8088   HasArithmeticOrEnumeralTypes =
8089     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
8090 
8091   if (Ty->isObjCIdType() || Ty->isObjCClassType())
8092     PointerTypes.insert(Ty);
8093   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
8094     // Insert our type, and its more-qualified variants, into the set
8095     // of types.
8096     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
8097       return;
8098   } else if (Ty->isMemberPointerType()) {
8099     // Member pointers are far easier, since the pointee can't be converted.
8100     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
8101       return;
8102   } else if (Ty->isEnumeralType()) {
8103     HasArithmeticOrEnumeralTypes = true;
8104     EnumerationTypes.insert(Ty);
8105   } else if (Ty->isVectorType()) {
8106     // We treat vector types as arithmetic types in many contexts as an
8107     // extension.
8108     HasArithmeticOrEnumeralTypes = true;
8109     VectorTypes.insert(Ty);
8110   } else if (Ty->isMatrixType()) {
8111     // Similar to vector types, we treat vector types as arithmetic types in
8112     // many contexts as an extension.
8113     HasArithmeticOrEnumeralTypes = true;
8114     MatrixTypes.insert(Ty);
8115   } else if (Ty->isNullPtrType()) {
8116     HasNullPtrType = true;
8117   } else if (AllowUserConversions && TyRec) {
8118     // No conversion functions in incomplete types.
8119     if (!SemaRef.isCompleteType(Loc, Ty))
8120       return;
8121 
8122     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8123     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8124       if (isa<UsingShadowDecl>(D))
8125         D = cast<UsingShadowDecl>(D)->getTargetDecl();
8126 
8127       // Skip conversion function templates; they don't tell us anything
8128       // about which builtin types we can convert to.
8129       if (isa<FunctionTemplateDecl>(D))
8130         continue;
8131 
8132       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
8133       if (AllowExplicitConversions || !Conv->isExplicit()) {
8134         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
8135                               VisibleQuals);
8136       }
8137     }
8138   }
8139 }
8140 /// Helper function for adjusting address spaces for the pointer or reference
8141 /// operands of builtin operators depending on the argument.
8142 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
8143                                                         Expr *Arg) {
8144   return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
8145 }
8146 
8147 /// Helper function for AddBuiltinOperatorCandidates() that adds
8148 /// the volatile- and non-volatile-qualified assignment operators for the
8149 /// given type to the candidate set.
8150 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
8151                                                    QualType T,
8152                                                    ArrayRef<Expr *> Args,
8153                                     OverloadCandidateSet &CandidateSet) {
8154   QualType ParamTypes[2];
8155 
8156   // T& operator=(T&, T)
8157   ParamTypes[0] = S.Context.getLValueReferenceType(
8158       AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
8159   ParamTypes[1] = T;
8160   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8161                         /*IsAssignmentOperator=*/true);
8162 
8163   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
8164     // volatile T& operator=(volatile T&, T)
8165     ParamTypes[0] = S.Context.getLValueReferenceType(
8166         AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
8167                                                 Args[0]));
8168     ParamTypes[1] = T;
8169     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8170                           /*IsAssignmentOperator=*/true);
8171   }
8172 }
8173 
8174 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8175 /// if any, found in visible type conversion functions found in ArgExpr's type.
8176 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8177     Qualifiers VRQuals;
8178     const RecordType *TyRec;
8179     if (const MemberPointerType *RHSMPType =
8180         ArgExpr->getType()->getAs<MemberPointerType>())
8181       TyRec = RHSMPType->getClass()->getAs<RecordType>();
8182     else
8183       TyRec = ArgExpr->getType()->getAs<RecordType>();
8184     if (!TyRec) {
8185       // Just to be safe, assume the worst case.
8186       VRQuals.addVolatile();
8187       VRQuals.addRestrict();
8188       return VRQuals;
8189     }
8190 
8191     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8192     if (!ClassDecl->hasDefinition())
8193       return VRQuals;
8194 
8195     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8196       if (isa<UsingShadowDecl>(D))
8197         D = cast<UsingShadowDecl>(D)->getTargetDecl();
8198       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8199         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8200         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8201           CanTy = ResTypeRef->getPointeeType();
8202         // Need to go down the pointer/mempointer chain and add qualifiers
8203         // as see them.
8204         bool done = false;
8205         while (!done) {
8206           if (CanTy.isRestrictQualified())
8207             VRQuals.addRestrict();
8208           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8209             CanTy = ResTypePtr->getPointeeType();
8210           else if (const MemberPointerType *ResTypeMPtr =
8211                 CanTy->getAs<MemberPointerType>())
8212             CanTy = ResTypeMPtr->getPointeeType();
8213           else
8214             done = true;
8215           if (CanTy.isVolatileQualified())
8216             VRQuals.addVolatile();
8217           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8218             return VRQuals;
8219         }
8220       }
8221     }
8222     return VRQuals;
8223 }
8224 
8225 // Note: We're currently only handling qualifiers that are meaningful for the
8226 // LHS of compound assignment overloading.
8227 static void forAllQualifierCombinationsImpl(
8228     QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
8229     llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8230   // _Atomic
8231   if (Available.hasAtomic()) {
8232     Available.removeAtomic();
8233     forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
8234     forAllQualifierCombinationsImpl(Available, Applied, Callback);
8235     return;
8236   }
8237 
8238   // volatile
8239   if (Available.hasVolatile()) {
8240     Available.removeVolatile();
8241     assert(!Applied.hasVolatile());
8242     forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
8243                                     Callback);
8244     forAllQualifierCombinationsImpl(Available, Applied, Callback);
8245     return;
8246   }
8247 
8248   Callback(Applied);
8249 }
8250 
8251 static void forAllQualifierCombinations(
8252     QualifiersAndAtomic Quals,
8253     llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8254   return forAllQualifierCombinationsImpl(Quals, QualifiersAndAtomic(),
8255                                          Callback);
8256 }
8257 
8258 static QualType makeQualifiedLValueReferenceType(QualType Base,
8259                                                  QualifiersAndAtomic Quals,
8260                                                  Sema &S) {
8261   if (Quals.hasAtomic())
8262     Base = S.Context.getAtomicType(Base);
8263   if (Quals.hasVolatile())
8264     Base = S.Context.getVolatileType(Base);
8265   return S.Context.getLValueReferenceType(Base);
8266 }
8267 
8268 namespace {
8269 
8270 /// Helper class to manage the addition of builtin operator overload
8271 /// candidates. It provides shared state and utility methods used throughout
8272 /// the process, as well as a helper method to add each group of builtin
8273 /// operator overloads from the standard to a candidate set.
8274 class BuiltinOperatorOverloadBuilder {
8275   // Common instance state available to all overload candidate addition methods.
8276   Sema &S;
8277   ArrayRef<Expr *> Args;
8278   QualifiersAndAtomic VisibleTypeConversionsQuals;
8279   bool HasArithmeticOrEnumeralCandidateType;
8280   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8281   OverloadCandidateSet &CandidateSet;
8282 
8283   static constexpr int ArithmeticTypesCap = 24;
8284   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8285 
8286   // Define some indices used to iterate over the arithmetic types in
8287   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
8288   // types are that preserved by promotion (C++ [over.built]p2).
8289   unsigned FirstIntegralType,
8290            LastIntegralType;
8291   unsigned FirstPromotedIntegralType,
8292            LastPromotedIntegralType;
8293   unsigned FirstPromotedArithmeticType,
8294            LastPromotedArithmeticType;
8295   unsigned NumArithmeticTypes;
8296 
8297   void InitArithmeticTypes() {
8298     // Start of promoted types.
8299     FirstPromotedArithmeticType = 0;
8300     ArithmeticTypes.push_back(S.Context.FloatTy);
8301     ArithmeticTypes.push_back(S.Context.DoubleTy);
8302     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8303     if (S.Context.getTargetInfo().hasFloat128Type())
8304       ArithmeticTypes.push_back(S.Context.Float128Ty);
8305     if (S.Context.getTargetInfo().hasIbm128Type())
8306       ArithmeticTypes.push_back(S.Context.Ibm128Ty);
8307 
8308     // Start of integral types.
8309     FirstIntegralType = ArithmeticTypes.size();
8310     FirstPromotedIntegralType = ArithmeticTypes.size();
8311     ArithmeticTypes.push_back(S.Context.IntTy);
8312     ArithmeticTypes.push_back(S.Context.LongTy);
8313     ArithmeticTypes.push_back(S.Context.LongLongTy);
8314     if (S.Context.getTargetInfo().hasInt128Type() ||
8315         (S.Context.getAuxTargetInfo() &&
8316          S.Context.getAuxTargetInfo()->hasInt128Type()))
8317       ArithmeticTypes.push_back(S.Context.Int128Ty);
8318     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8319     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8320     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8321     if (S.Context.getTargetInfo().hasInt128Type() ||
8322         (S.Context.getAuxTargetInfo() &&
8323          S.Context.getAuxTargetInfo()->hasInt128Type()))
8324       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8325     LastPromotedIntegralType = ArithmeticTypes.size();
8326     LastPromotedArithmeticType = ArithmeticTypes.size();
8327     // End of promoted types.
8328 
8329     ArithmeticTypes.push_back(S.Context.BoolTy);
8330     ArithmeticTypes.push_back(S.Context.CharTy);
8331     ArithmeticTypes.push_back(S.Context.WCharTy);
8332     if (S.Context.getLangOpts().Char8)
8333       ArithmeticTypes.push_back(S.Context.Char8Ty);
8334     ArithmeticTypes.push_back(S.Context.Char16Ty);
8335     ArithmeticTypes.push_back(S.Context.Char32Ty);
8336     ArithmeticTypes.push_back(S.Context.SignedCharTy);
8337     ArithmeticTypes.push_back(S.Context.ShortTy);
8338     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8339     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8340     LastIntegralType = ArithmeticTypes.size();
8341     NumArithmeticTypes = ArithmeticTypes.size();
8342     // End of integral types.
8343     // FIXME: What about complex? What about half?
8344 
8345     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
8346            "Enough inline storage for all arithmetic types.");
8347   }
8348 
8349   /// Helper method to factor out the common pattern of adding overloads
8350   /// for '++' and '--' builtin operators.
8351   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8352                                            bool HasVolatile,
8353                                            bool HasRestrict) {
8354     QualType ParamTypes[2] = {
8355       S.Context.getLValueReferenceType(CandidateTy),
8356       S.Context.IntTy
8357     };
8358 
8359     // Non-volatile version.
8360     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8361 
8362     // Use a heuristic to reduce number of builtin candidates in the set:
8363     // add volatile version only if there are conversions to a volatile type.
8364     if (HasVolatile) {
8365       ParamTypes[0] =
8366         S.Context.getLValueReferenceType(
8367           S.Context.getVolatileType(CandidateTy));
8368       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8369     }
8370 
8371     // Add restrict version only if there are conversions to a restrict type
8372     // and our candidate type is a non-restrict-qualified pointer.
8373     if (HasRestrict && CandidateTy->isAnyPointerType() &&
8374         !CandidateTy.isRestrictQualified()) {
8375       ParamTypes[0]
8376         = S.Context.getLValueReferenceType(
8377             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8378       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8379 
8380       if (HasVolatile) {
8381         ParamTypes[0]
8382           = S.Context.getLValueReferenceType(
8383               S.Context.getCVRQualifiedType(CandidateTy,
8384                                             (Qualifiers::Volatile |
8385                                              Qualifiers::Restrict)));
8386         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8387       }
8388     }
8389 
8390   }
8391 
8392   /// Helper to add an overload candidate for a binary builtin with types \p L
8393   /// and \p R.
8394   void AddCandidate(QualType L, QualType R) {
8395     QualType LandR[2] = {L, R};
8396     S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8397   }
8398 
8399 public:
8400   BuiltinOperatorOverloadBuilder(
8401     Sema &S, ArrayRef<Expr *> Args,
8402     QualifiersAndAtomic VisibleTypeConversionsQuals,
8403     bool HasArithmeticOrEnumeralCandidateType,
8404     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8405     OverloadCandidateSet &CandidateSet)
8406     : S(S), Args(Args),
8407       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8408       HasArithmeticOrEnumeralCandidateType(
8409         HasArithmeticOrEnumeralCandidateType),
8410       CandidateTypes(CandidateTypes),
8411       CandidateSet(CandidateSet) {
8412 
8413     InitArithmeticTypes();
8414   }
8415 
8416   // Increment is deprecated for bool since C++17.
8417   //
8418   // C++ [over.built]p3:
8419   //
8420   //   For every pair (T, VQ), where T is an arithmetic type other
8421   //   than bool, and VQ is either volatile or empty, there exist
8422   //   candidate operator functions of the form
8423   //
8424   //       VQ T&      operator++(VQ T&);
8425   //       T          operator++(VQ T&, int);
8426   //
8427   // C++ [over.built]p4:
8428   //
8429   //   For every pair (T, VQ), where T is an arithmetic type other
8430   //   than bool, and VQ is either volatile or empty, there exist
8431   //   candidate operator functions of the form
8432   //
8433   //       VQ T&      operator--(VQ T&);
8434   //       T          operator--(VQ T&, int);
8435   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8436     if (!HasArithmeticOrEnumeralCandidateType)
8437       return;
8438 
8439     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8440       const auto TypeOfT = ArithmeticTypes[Arith];
8441       if (TypeOfT == S.Context.BoolTy) {
8442         if (Op == OO_MinusMinus)
8443           continue;
8444         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8445           continue;
8446       }
8447       addPlusPlusMinusMinusStyleOverloads(
8448         TypeOfT,
8449         VisibleTypeConversionsQuals.hasVolatile(),
8450         VisibleTypeConversionsQuals.hasRestrict());
8451     }
8452   }
8453 
8454   // C++ [over.built]p5:
8455   //
8456   //   For every pair (T, VQ), where T is a cv-qualified or
8457   //   cv-unqualified object type, and VQ is either volatile or
8458   //   empty, there exist candidate operator functions of the form
8459   //
8460   //       T*VQ&      operator++(T*VQ&);
8461   //       T*VQ&      operator--(T*VQ&);
8462   //       T*         operator++(T*VQ&, int);
8463   //       T*         operator--(T*VQ&, int);
8464   void addPlusPlusMinusMinusPointerOverloads() {
8465     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
8466       // Skip pointer types that aren't pointers to object types.
8467       if (!PtrTy->getPointeeType()->isObjectType())
8468         continue;
8469 
8470       addPlusPlusMinusMinusStyleOverloads(
8471           PtrTy,
8472           (!PtrTy.isVolatileQualified() &&
8473            VisibleTypeConversionsQuals.hasVolatile()),
8474           (!PtrTy.isRestrictQualified() &&
8475            VisibleTypeConversionsQuals.hasRestrict()));
8476     }
8477   }
8478 
8479   // C++ [over.built]p6:
8480   //   For every cv-qualified or cv-unqualified object type T, there
8481   //   exist candidate operator functions of the form
8482   //
8483   //       T&         operator*(T*);
8484   //
8485   // C++ [over.built]p7:
8486   //   For every function type T that does not have cv-qualifiers or a
8487   //   ref-qualifier, there exist candidate operator functions of the form
8488   //       T&         operator*(T*);
8489   void addUnaryStarPointerOverloads() {
8490     for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
8491       QualType PointeeTy = ParamTy->getPointeeType();
8492       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8493         continue;
8494 
8495       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8496         if (Proto->getMethodQuals() || Proto->getRefQualifier())
8497           continue;
8498 
8499       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8500     }
8501   }
8502 
8503   // C++ [over.built]p9:
8504   //  For every promoted arithmetic type T, there exist candidate
8505   //  operator functions of the form
8506   //
8507   //       T         operator+(T);
8508   //       T         operator-(T);
8509   void addUnaryPlusOrMinusArithmeticOverloads() {
8510     if (!HasArithmeticOrEnumeralCandidateType)
8511       return;
8512 
8513     for (unsigned Arith = FirstPromotedArithmeticType;
8514          Arith < LastPromotedArithmeticType; ++Arith) {
8515       QualType ArithTy = ArithmeticTypes[Arith];
8516       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8517     }
8518 
8519     // Extension: We also add these operators for vector types.
8520     for (QualType VecTy : CandidateTypes[0].vector_types())
8521       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8522   }
8523 
8524   // C++ [over.built]p8:
8525   //   For every type T, there exist candidate operator functions of
8526   //   the form
8527   //
8528   //       T*         operator+(T*);
8529   void addUnaryPlusPointerOverloads() {
8530     for (QualType ParamTy : CandidateTypes[0].pointer_types())
8531       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8532   }
8533 
8534   // C++ [over.built]p10:
8535   //   For every promoted integral type T, there exist candidate
8536   //   operator functions of the form
8537   //
8538   //        T         operator~(T);
8539   void addUnaryTildePromotedIntegralOverloads() {
8540     if (!HasArithmeticOrEnumeralCandidateType)
8541       return;
8542 
8543     for (unsigned Int = FirstPromotedIntegralType;
8544          Int < LastPromotedIntegralType; ++Int) {
8545       QualType IntTy = ArithmeticTypes[Int];
8546       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8547     }
8548 
8549     // Extension: We also add this operator for vector types.
8550     for (QualType VecTy : CandidateTypes[0].vector_types())
8551       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8552   }
8553 
8554   // C++ [over.match.oper]p16:
8555   //   For every pointer to member type T or type std::nullptr_t, there
8556   //   exist candidate operator functions of the form
8557   //
8558   //        bool operator==(T,T);
8559   //        bool operator!=(T,T);
8560   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8561     /// Set of (canonical) types that we've already handled.
8562     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8563 
8564     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8565       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
8566         // Don't add the same builtin candidate twice.
8567         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
8568           continue;
8569 
8570         QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
8571         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8572       }
8573 
8574       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8575         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8576         if (AddedTypes.insert(NullPtrTy).second) {
8577           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8578           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8579         }
8580       }
8581     }
8582   }
8583 
8584   // C++ [over.built]p15:
8585   //
8586   //   For every T, where T is an enumeration type or a pointer type,
8587   //   there exist candidate operator functions of the form
8588   //
8589   //        bool       operator<(T, T);
8590   //        bool       operator>(T, T);
8591   //        bool       operator<=(T, T);
8592   //        bool       operator>=(T, T);
8593   //        bool       operator==(T, T);
8594   //        bool       operator!=(T, T);
8595   //           R       operator<=>(T, T)
8596   void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
8597     // C++ [over.match.oper]p3:
8598     //   [...]the built-in candidates include all of the candidate operator
8599     //   functions defined in 13.6 that, compared to the given operator, [...]
8600     //   do not have the same parameter-type-list as any non-template non-member
8601     //   candidate.
8602     //
8603     // Note that in practice, this only affects enumeration types because there
8604     // aren't any built-in candidates of record type, and a user-defined operator
8605     // must have an operand of record or enumeration type. Also, the only other
8606     // overloaded operator with enumeration arguments, operator=,
8607     // cannot be overloaded for enumeration types, so this is the only place
8608     // where we must suppress candidates like this.
8609     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8610       UserDefinedBinaryOperators;
8611 
8612     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8613       if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
8614         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8615                                          CEnd = CandidateSet.end();
8616              C != CEnd; ++C) {
8617           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8618             continue;
8619 
8620           if (C->Function->isFunctionTemplateSpecialization())
8621             continue;
8622 
8623           // We interpret "same parameter-type-list" as applying to the
8624           // "synthesized candidate, with the order of the two parameters
8625           // reversed", not to the original function.
8626           bool Reversed = C->isReversed();
8627           QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
8628                                         ->getType()
8629                                         .getUnqualifiedType();
8630           QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
8631                                          ->getType()
8632                                          .getUnqualifiedType();
8633 
8634           // Skip if either parameter isn't of enumeral type.
8635           if (!FirstParamType->isEnumeralType() ||
8636               !SecondParamType->isEnumeralType())
8637             continue;
8638 
8639           // Add this operator to the set of known user-defined operators.
8640           UserDefinedBinaryOperators.insert(
8641             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8642                            S.Context.getCanonicalType(SecondParamType)));
8643         }
8644       }
8645     }
8646 
8647     /// Set of (canonical) types that we've already handled.
8648     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8649 
8650     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8651       for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
8652         // Don't add the same builtin candidate twice.
8653         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8654           continue;
8655         if (IsSpaceship && PtrTy->isFunctionPointerType())
8656           continue;
8657 
8658         QualType ParamTypes[2] = {PtrTy, PtrTy};
8659         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8660       }
8661       for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
8662         CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
8663 
8664         // Don't add the same builtin candidate twice, or if a user defined
8665         // candidate exists.
8666         if (!AddedTypes.insert(CanonType).second ||
8667             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8668                                                             CanonType)))
8669           continue;
8670         QualType ParamTypes[2] = {EnumTy, EnumTy};
8671         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8672       }
8673     }
8674   }
8675 
8676   // C++ [over.built]p13:
8677   //
8678   //   For every cv-qualified or cv-unqualified object type T
8679   //   there exist candidate operator functions of the form
8680   //
8681   //      T*         operator+(T*, ptrdiff_t);
8682   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8683   //      T*         operator-(T*, ptrdiff_t);
8684   //      T*         operator+(ptrdiff_t, T*);
8685   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8686   //
8687   // C++ [over.built]p14:
8688   //
8689   //   For every T, where T is a pointer to object type, there
8690   //   exist candidate operator functions of the form
8691   //
8692   //      ptrdiff_t  operator-(T, T);
8693   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8694     /// Set of (canonical) types that we've already handled.
8695     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8696 
8697     for (int Arg = 0; Arg < 2; ++Arg) {
8698       QualType AsymmetricParamTypes[2] = {
8699         S.Context.getPointerDiffType(),
8700         S.Context.getPointerDiffType(),
8701       };
8702       for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
8703         QualType PointeeTy = PtrTy->getPointeeType();
8704         if (!PointeeTy->isObjectType())
8705           continue;
8706 
8707         AsymmetricParamTypes[Arg] = PtrTy;
8708         if (Arg == 0 || Op == OO_Plus) {
8709           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8710           // T* operator+(ptrdiff_t, T*);
8711           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8712         }
8713         if (Op == OO_Minus) {
8714           // ptrdiff_t operator-(T, T);
8715           if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8716             continue;
8717 
8718           QualType ParamTypes[2] = {PtrTy, PtrTy};
8719           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8720         }
8721       }
8722     }
8723   }
8724 
8725   // C++ [over.built]p12:
8726   //
8727   //   For every pair of promoted arithmetic types L and R, there
8728   //   exist candidate operator functions of the form
8729   //
8730   //        LR         operator*(L, R);
8731   //        LR         operator/(L, R);
8732   //        LR         operator+(L, R);
8733   //        LR         operator-(L, R);
8734   //        bool       operator<(L, R);
8735   //        bool       operator>(L, R);
8736   //        bool       operator<=(L, R);
8737   //        bool       operator>=(L, R);
8738   //        bool       operator==(L, R);
8739   //        bool       operator!=(L, R);
8740   //
8741   //   where LR is the result of the usual arithmetic conversions
8742   //   between types L and R.
8743   //
8744   // C++ [over.built]p24:
8745   //
8746   //   For every pair of promoted arithmetic types L and R, there exist
8747   //   candidate operator functions of the form
8748   //
8749   //        LR       operator?(bool, L, R);
8750   //
8751   //   where LR is the result of the usual arithmetic conversions
8752   //   between types L and R.
8753   // Our candidates ignore the first parameter.
8754   void addGenericBinaryArithmeticOverloads() {
8755     if (!HasArithmeticOrEnumeralCandidateType)
8756       return;
8757 
8758     for (unsigned Left = FirstPromotedArithmeticType;
8759          Left < LastPromotedArithmeticType; ++Left) {
8760       for (unsigned Right = FirstPromotedArithmeticType;
8761            Right < LastPromotedArithmeticType; ++Right) {
8762         QualType LandR[2] = { ArithmeticTypes[Left],
8763                               ArithmeticTypes[Right] };
8764         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8765       }
8766     }
8767 
8768     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8769     // conditional operator for vector types.
8770     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8771       for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
8772         QualType LandR[2] = {Vec1Ty, Vec2Ty};
8773         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8774       }
8775   }
8776 
8777   /// Add binary operator overloads for each candidate matrix type M1, M2:
8778   ///  * (M1, M1) -> M1
8779   ///  * (M1, M1.getElementType()) -> M1
8780   ///  * (M2.getElementType(), M2) -> M2
8781   ///  * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
8782   void addMatrixBinaryArithmeticOverloads() {
8783     if (!HasArithmeticOrEnumeralCandidateType)
8784       return;
8785 
8786     for (QualType M1 : CandidateTypes[0].matrix_types()) {
8787       AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
8788       AddCandidate(M1, M1);
8789     }
8790 
8791     for (QualType M2 : CandidateTypes[1].matrix_types()) {
8792       AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
8793       if (!CandidateTypes[0].containsMatrixType(M2))
8794         AddCandidate(M2, M2);
8795     }
8796   }
8797 
8798   // C++2a [over.built]p14:
8799   //
8800   //   For every integral type T there exists a candidate operator function
8801   //   of the form
8802   //
8803   //        std::strong_ordering operator<=>(T, T)
8804   //
8805   // C++2a [over.built]p15:
8806   //
8807   //   For every pair of floating-point types L and R, there exists a candidate
8808   //   operator function of the form
8809   //
8810   //       std::partial_ordering operator<=>(L, R);
8811   //
8812   // FIXME: The current specification for integral types doesn't play nice with
8813   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8814   // comparisons. Under the current spec this can lead to ambiguity during
8815   // overload resolution. For example:
8816   //
8817   //   enum A : int {a};
8818   //   auto x = (a <=> (long)42);
8819   //
8820   //   error: call is ambiguous for arguments 'A' and 'long'.
8821   //   note: candidate operator<=>(int, int)
8822   //   note: candidate operator<=>(long, long)
8823   //
8824   // To avoid this error, this function deviates from the specification and adds
8825   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8826   // arithmetic types (the same as the generic relational overloads).
8827   //
8828   // For now this function acts as a placeholder.
8829   void addThreeWayArithmeticOverloads() {
8830     addGenericBinaryArithmeticOverloads();
8831   }
8832 
8833   // C++ [over.built]p17:
8834   //
8835   //   For every pair of promoted integral types L and R, there
8836   //   exist candidate operator functions of the form
8837   //
8838   //      LR         operator%(L, R);
8839   //      LR         operator&(L, R);
8840   //      LR         operator^(L, R);
8841   //      LR         operator|(L, R);
8842   //      L          operator<<(L, R);
8843   //      L          operator>>(L, R);
8844   //
8845   //   where LR is the result of the usual arithmetic conversions
8846   //   between types L and R.
8847   void addBinaryBitwiseArithmeticOverloads() {
8848     if (!HasArithmeticOrEnumeralCandidateType)
8849       return;
8850 
8851     for (unsigned Left = FirstPromotedIntegralType;
8852          Left < LastPromotedIntegralType; ++Left) {
8853       for (unsigned Right = FirstPromotedIntegralType;
8854            Right < LastPromotedIntegralType; ++Right) {
8855         QualType LandR[2] = { ArithmeticTypes[Left],
8856                               ArithmeticTypes[Right] };
8857         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8858       }
8859     }
8860   }
8861 
8862   // C++ [over.built]p20:
8863   //
8864   //   For every pair (T, VQ), where T is an enumeration or
8865   //   pointer to member type and VQ is either volatile or
8866   //   empty, there exist candidate operator functions of the form
8867   //
8868   //        VQ T&      operator=(VQ T&, T);
8869   void addAssignmentMemberPointerOrEnumeralOverloads() {
8870     /// Set of (canonical) types that we've already handled.
8871     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8872 
8873     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8874       for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
8875         if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
8876           continue;
8877 
8878         AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
8879       }
8880 
8881       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
8882         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
8883           continue;
8884 
8885         AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
8886       }
8887     }
8888   }
8889 
8890   // C++ [over.built]p19:
8891   //
8892   //   For every pair (T, VQ), where T is any type and VQ is either
8893   //   volatile or empty, there exist candidate operator functions
8894   //   of the form
8895   //
8896   //        T*VQ&      operator=(T*VQ&, T*);
8897   //
8898   // C++ [over.built]p21:
8899   //
8900   //   For every pair (T, VQ), where T is a cv-qualified or
8901   //   cv-unqualified object type and VQ is either volatile or
8902   //   empty, there exist candidate operator functions of the form
8903   //
8904   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8905   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8906   void addAssignmentPointerOverloads(bool isEqualOp) {
8907     /// Set of (canonical) types that we've already handled.
8908     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8909 
8910     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
8911       // If this is operator=, keep track of the builtin candidates we added.
8912       if (isEqualOp)
8913         AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
8914       else if (!PtrTy->getPointeeType()->isObjectType())
8915         continue;
8916 
8917       // non-volatile version
8918       QualType ParamTypes[2] = {
8919           S.Context.getLValueReferenceType(PtrTy),
8920           isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
8921       };
8922       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8923                             /*IsAssignmentOperator=*/ isEqualOp);
8924 
8925       bool NeedVolatile = !PtrTy.isVolatileQualified() &&
8926                           VisibleTypeConversionsQuals.hasVolatile();
8927       if (NeedVolatile) {
8928         // volatile version
8929         ParamTypes[0] =
8930             S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy));
8931         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8932                               /*IsAssignmentOperator=*/isEqualOp);
8933       }
8934 
8935       if (!PtrTy.isRestrictQualified() &&
8936           VisibleTypeConversionsQuals.hasRestrict()) {
8937         // restrict version
8938         ParamTypes[0] =
8939             S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy));
8940         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8941                               /*IsAssignmentOperator=*/isEqualOp);
8942 
8943         if (NeedVolatile) {
8944           // volatile restrict version
8945           ParamTypes[0] =
8946               S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
8947                   PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
8948           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8949                                 /*IsAssignmentOperator=*/isEqualOp);
8950         }
8951       }
8952     }
8953 
8954     if (isEqualOp) {
8955       for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
8956         // Make sure we don't add the same candidate twice.
8957         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8958           continue;
8959 
8960         QualType ParamTypes[2] = {
8961             S.Context.getLValueReferenceType(PtrTy),
8962             PtrTy,
8963         };
8964 
8965         // non-volatile version
8966         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8967                               /*IsAssignmentOperator=*/true);
8968 
8969         bool NeedVolatile = !PtrTy.isVolatileQualified() &&
8970                             VisibleTypeConversionsQuals.hasVolatile();
8971         if (NeedVolatile) {
8972           // volatile version
8973           ParamTypes[0] = S.Context.getLValueReferenceType(
8974               S.Context.getVolatileType(PtrTy));
8975           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8976                                 /*IsAssignmentOperator=*/true);
8977         }
8978 
8979         if (!PtrTy.isRestrictQualified() &&
8980             VisibleTypeConversionsQuals.hasRestrict()) {
8981           // restrict version
8982           ParamTypes[0] = S.Context.getLValueReferenceType(
8983               S.Context.getRestrictType(PtrTy));
8984           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8985                                 /*IsAssignmentOperator=*/true);
8986 
8987           if (NeedVolatile) {
8988             // volatile restrict version
8989             ParamTypes[0] =
8990                 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
8991                     PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
8992             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8993                                   /*IsAssignmentOperator=*/true);
8994           }
8995         }
8996       }
8997     }
8998   }
8999 
9000   // C++ [over.built]p18:
9001   //
9002   //   For every triple (L, VQ, R), where L is an arithmetic type,
9003   //   VQ is either volatile or empty, and R is a promoted
9004   //   arithmetic type, there exist candidate operator functions of
9005   //   the form
9006   //
9007   //        VQ L&      operator=(VQ L&, R);
9008   //        VQ L&      operator*=(VQ L&, R);
9009   //        VQ L&      operator/=(VQ L&, R);
9010   //        VQ L&      operator+=(VQ L&, R);
9011   //        VQ L&      operator-=(VQ L&, R);
9012   void addAssignmentArithmeticOverloads(bool isEqualOp) {
9013     if (!HasArithmeticOrEnumeralCandidateType)
9014       return;
9015 
9016     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
9017       for (unsigned Right = FirstPromotedArithmeticType;
9018            Right < LastPromotedArithmeticType; ++Right) {
9019         QualType ParamTypes[2];
9020         ParamTypes[1] = ArithmeticTypes[Right];
9021         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
9022             S, ArithmeticTypes[Left], Args[0]);
9023 
9024         forAllQualifierCombinations(
9025             VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9026               ParamTypes[0] =
9027                   makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9028               S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9029                                     /*IsAssignmentOperator=*/isEqualOp);
9030             });
9031       }
9032     }
9033 
9034     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
9035     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9036       for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
9037         QualType ParamTypes[2];
9038         ParamTypes[1] = Vec2Ty;
9039         // Add this built-in operator as a candidate (VQ is empty).
9040         ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
9041         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9042                               /*IsAssignmentOperator=*/isEqualOp);
9043 
9044         // Add this built-in operator as a candidate (VQ is 'volatile').
9045         if (VisibleTypeConversionsQuals.hasVolatile()) {
9046           ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
9047           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
9048           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9049                                 /*IsAssignmentOperator=*/isEqualOp);
9050         }
9051       }
9052   }
9053 
9054   // C++ [over.built]p22:
9055   //
9056   //   For every triple (L, VQ, R), where L is an integral type, VQ
9057   //   is either volatile or empty, and R is a promoted integral
9058   //   type, there exist candidate operator functions of the form
9059   //
9060   //        VQ L&       operator%=(VQ L&, R);
9061   //        VQ L&       operator<<=(VQ L&, R);
9062   //        VQ L&       operator>>=(VQ L&, R);
9063   //        VQ L&       operator&=(VQ L&, R);
9064   //        VQ L&       operator^=(VQ L&, R);
9065   //        VQ L&       operator|=(VQ L&, R);
9066   void addAssignmentIntegralOverloads() {
9067     if (!HasArithmeticOrEnumeralCandidateType)
9068       return;
9069 
9070     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
9071       for (unsigned Right = FirstPromotedIntegralType;
9072            Right < LastPromotedIntegralType; ++Right) {
9073         QualType ParamTypes[2];
9074         ParamTypes[1] = ArithmeticTypes[Right];
9075         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
9076             S, ArithmeticTypes[Left], Args[0]);
9077 
9078         forAllQualifierCombinations(
9079             VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9080               ParamTypes[0] =
9081                   makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9082               S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9083             });
9084       }
9085     }
9086   }
9087 
9088   // C++ [over.operator]p23:
9089   //
9090   //   There also exist candidate operator functions of the form
9091   //
9092   //        bool        operator!(bool);
9093   //        bool        operator&&(bool, bool);
9094   //        bool        operator||(bool, bool);
9095   void addExclaimOverload() {
9096     QualType ParamTy = S.Context.BoolTy;
9097     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
9098                           /*IsAssignmentOperator=*/false,
9099                           /*NumContextualBoolArguments=*/1);
9100   }
9101   void addAmpAmpOrPipePipeOverload() {
9102     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
9103     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9104                           /*IsAssignmentOperator=*/false,
9105                           /*NumContextualBoolArguments=*/2);
9106   }
9107 
9108   // C++ [over.built]p13:
9109   //
9110   //   For every cv-qualified or cv-unqualified object type T there
9111   //   exist candidate operator functions of the form
9112   //
9113   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
9114   //        T&         operator[](T*, ptrdiff_t);
9115   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
9116   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
9117   //        T&         operator[](ptrdiff_t, T*);
9118   void addSubscriptOverloads() {
9119     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9120       QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
9121       QualType PointeeType = PtrTy->getPointeeType();
9122       if (!PointeeType->isObjectType())
9123         continue;
9124 
9125       // T& operator[](T*, ptrdiff_t)
9126       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9127     }
9128 
9129     for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9130       QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
9131       QualType PointeeType = PtrTy->getPointeeType();
9132       if (!PointeeType->isObjectType())
9133         continue;
9134 
9135       // T& operator[](ptrdiff_t, T*)
9136       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9137     }
9138   }
9139 
9140   // C++ [over.built]p11:
9141   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9142   //    C1 is the same type as C2 or is a derived class of C2, T is an object
9143   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9144   //    there exist candidate operator functions of the form
9145   //
9146   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9147   //
9148   //    where CV12 is the union of CV1 and CV2.
9149   void addArrowStarOverloads() {
9150     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9151       QualType C1Ty = PtrTy;
9152       QualType C1;
9153       QualifierCollector Q1;
9154       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
9155       if (!isa<RecordType>(C1))
9156         continue;
9157       // heuristic to reduce number of builtin candidates in the set.
9158       // Add volatile/restrict version only if there are conversions to a
9159       // volatile/restrict type.
9160       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9161         continue;
9162       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9163         continue;
9164       for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
9165         const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
9166         QualType C2 = QualType(mptr->getClass(), 0);
9167         C2 = C2.getUnqualifiedType();
9168         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9169           break;
9170         QualType ParamTypes[2] = {PtrTy, MemPtrTy};
9171         // build CV12 T&
9172         QualType T = mptr->getPointeeType();
9173         if (!VisibleTypeConversionsQuals.hasVolatile() &&
9174             T.isVolatileQualified())
9175           continue;
9176         if (!VisibleTypeConversionsQuals.hasRestrict() &&
9177             T.isRestrictQualified())
9178           continue;
9179         T = Q1.apply(S.Context, T);
9180         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9181       }
9182     }
9183   }
9184 
9185   // Note that we don't consider the first argument, since it has been
9186   // contextually converted to bool long ago. The candidates below are
9187   // therefore added as binary.
9188   //
9189   // C++ [over.built]p25:
9190   //   For every type T, where T is a pointer, pointer-to-member, or scoped
9191   //   enumeration type, there exist candidate operator functions of the form
9192   //
9193   //        T        operator?(bool, T, T);
9194   //
9195   void addConditionalOperatorOverloads() {
9196     /// Set of (canonical) types that we've already handled.
9197     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9198 
9199     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9200       for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9201         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9202           continue;
9203 
9204         QualType ParamTypes[2] = {PtrTy, PtrTy};
9205         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9206       }
9207 
9208       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9209         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9210           continue;
9211 
9212         QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9213         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9214       }
9215 
9216       if (S.getLangOpts().CPlusPlus11) {
9217         for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9218           if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
9219             continue;
9220 
9221           if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9222             continue;
9223 
9224           QualType ParamTypes[2] = {EnumTy, EnumTy};
9225           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9226         }
9227       }
9228     }
9229   }
9230 };
9231 
9232 } // end anonymous namespace
9233 
9234 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
9235 /// operator overloads to the candidate set (C++ [over.built]), based
9236 /// on the operator @p Op and the arguments given. For example, if the
9237 /// operator is a binary '+', this routine might add "int
9238 /// operator+(int, int)" to cover integer addition.
9239 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9240                                         SourceLocation OpLoc,
9241                                         ArrayRef<Expr *> Args,
9242                                         OverloadCandidateSet &CandidateSet) {
9243   // Find all of the types that the arguments can convert to, but only
9244   // if the operator we're looking at has built-in operator candidates
9245   // that make use of these types. Also record whether we encounter non-record
9246   // candidate types or either arithmetic or enumeral candidate types.
9247   QualifiersAndAtomic VisibleTypeConversionsQuals;
9248   VisibleTypeConversionsQuals.addConst();
9249   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9250     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9251     if (Args[ArgIdx]->getType()->isAtomicType())
9252       VisibleTypeConversionsQuals.addAtomic();
9253   }
9254 
9255   bool HasNonRecordCandidateType = false;
9256   bool HasArithmeticOrEnumeralCandidateType = false;
9257   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9258   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9259     CandidateTypes.emplace_back(*this);
9260     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9261                                                  OpLoc,
9262                                                  true,
9263                                                  (Op == OO_Exclaim ||
9264                                                   Op == OO_AmpAmp ||
9265                                                   Op == OO_PipePipe),
9266                                                  VisibleTypeConversionsQuals);
9267     HasNonRecordCandidateType = HasNonRecordCandidateType ||
9268         CandidateTypes[ArgIdx].hasNonRecordTypes();
9269     HasArithmeticOrEnumeralCandidateType =
9270         HasArithmeticOrEnumeralCandidateType ||
9271         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9272   }
9273 
9274   // Exit early when no non-record types have been added to the candidate set
9275   // for any of the arguments to the operator.
9276   //
9277   // We can't exit early for !, ||, or &&, since there we have always have
9278   // 'bool' overloads.
9279   if (!HasNonRecordCandidateType &&
9280       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9281     return;
9282 
9283   // Setup an object to manage the common state for building overloads.
9284   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9285                                            VisibleTypeConversionsQuals,
9286                                            HasArithmeticOrEnumeralCandidateType,
9287                                            CandidateTypes, CandidateSet);
9288 
9289   // Dispatch over the operation to add in only those overloads which apply.
9290   switch (Op) {
9291   case OO_None:
9292   case NUM_OVERLOADED_OPERATORS:
9293     llvm_unreachable("Expected an overloaded operator");
9294 
9295   case OO_New:
9296   case OO_Delete:
9297   case OO_Array_New:
9298   case OO_Array_Delete:
9299   case OO_Call:
9300     llvm_unreachable(
9301                     "Special operators don't use AddBuiltinOperatorCandidates");
9302 
9303   case OO_Comma:
9304   case OO_Arrow:
9305   case OO_Coawait:
9306     // C++ [over.match.oper]p3:
9307     //   -- For the operator ',', the unary operator '&', the
9308     //      operator '->', or the operator 'co_await', the
9309     //      built-in candidates set is empty.
9310     break;
9311 
9312   case OO_Plus: // '+' is either unary or binary
9313     if (Args.size() == 1)
9314       OpBuilder.addUnaryPlusPointerOverloads();
9315     LLVM_FALLTHROUGH;
9316 
9317   case OO_Minus: // '-' is either unary or binary
9318     if (Args.size() == 1) {
9319       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9320     } else {
9321       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9322       OpBuilder.addGenericBinaryArithmeticOverloads();
9323       OpBuilder.addMatrixBinaryArithmeticOverloads();
9324     }
9325     break;
9326 
9327   case OO_Star: // '*' is either unary or binary
9328     if (Args.size() == 1)
9329       OpBuilder.addUnaryStarPointerOverloads();
9330     else {
9331       OpBuilder.addGenericBinaryArithmeticOverloads();
9332       OpBuilder.addMatrixBinaryArithmeticOverloads();
9333     }
9334     break;
9335 
9336   case OO_Slash:
9337     OpBuilder.addGenericBinaryArithmeticOverloads();
9338     break;
9339 
9340   case OO_PlusPlus:
9341   case OO_MinusMinus:
9342     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9343     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9344     break;
9345 
9346   case OO_EqualEqual:
9347   case OO_ExclaimEqual:
9348     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9349     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9350     OpBuilder.addGenericBinaryArithmeticOverloads();
9351     break;
9352 
9353   case OO_Less:
9354   case OO_Greater:
9355   case OO_LessEqual:
9356   case OO_GreaterEqual:
9357     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9358     OpBuilder.addGenericBinaryArithmeticOverloads();
9359     break;
9360 
9361   case OO_Spaceship:
9362     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
9363     OpBuilder.addThreeWayArithmeticOverloads();
9364     break;
9365 
9366   case OO_Percent:
9367   case OO_Caret:
9368   case OO_Pipe:
9369   case OO_LessLess:
9370   case OO_GreaterGreater:
9371     OpBuilder.addBinaryBitwiseArithmeticOverloads();
9372     break;
9373 
9374   case OO_Amp: // '&' is either unary or binary
9375     if (Args.size() == 1)
9376       // C++ [over.match.oper]p3:
9377       //   -- For the operator ',', the unary operator '&', or the
9378       //      operator '->', the built-in candidates set is empty.
9379       break;
9380 
9381     OpBuilder.addBinaryBitwiseArithmeticOverloads();
9382     break;
9383 
9384   case OO_Tilde:
9385     OpBuilder.addUnaryTildePromotedIntegralOverloads();
9386     break;
9387 
9388   case OO_Equal:
9389     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9390     LLVM_FALLTHROUGH;
9391 
9392   case OO_PlusEqual:
9393   case OO_MinusEqual:
9394     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9395     LLVM_FALLTHROUGH;
9396 
9397   case OO_StarEqual:
9398   case OO_SlashEqual:
9399     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9400     break;
9401 
9402   case OO_PercentEqual:
9403   case OO_LessLessEqual:
9404   case OO_GreaterGreaterEqual:
9405   case OO_AmpEqual:
9406   case OO_CaretEqual:
9407   case OO_PipeEqual:
9408     OpBuilder.addAssignmentIntegralOverloads();
9409     break;
9410 
9411   case OO_Exclaim:
9412     OpBuilder.addExclaimOverload();
9413     break;
9414 
9415   case OO_AmpAmp:
9416   case OO_PipePipe:
9417     OpBuilder.addAmpAmpOrPipePipeOverload();
9418     break;
9419 
9420   case OO_Subscript:
9421     if (Args.size() == 2)
9422       OpBuilder.addSubscriptOverloads();
9423     break;
9424 
9425   case OO_ArrowStar:
9426     OpBuilder.addArrowStarOverloads();
9427     break;
9428 
9429   case OO_Conditional:
9430     OpBuilder.addConditionalOperatorOverloads();
9431     OpBuilder.addGenericBinaryArithmeticOverloads();
9432     break;
9433   }
9434 }
9435 
9436 /// Add function candidates found via argument-dependent lookup
9437 /// to the set of overloading candidates.
9438 ///
9439 /// This routine performs argument-dependent name lookup based on the
9440 /// given function name (which may also be an operator name) and adds
9441 /// all of the overload candidates found by ADL to the overload
9442 /// candidate set (C++ [basic.lookup.argdep]).
9443 void
9444 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9445                                            SourceLocation Loc,
9446                                            ArrayRef<Expr *> Args,
9447                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
9448                                            OverloadCandidateSet& CandidateSet,
9449                                            bool PartialOverloading) {
9450   ADLResult Fns;
9451 
9452   // FIXME: This approach for uniquing ADL results (and removing
9453   // redundant candidates from the set) relies on pointer-equality,
9454   // which means we need to key off the canonical decl.  However,
9455   // always going back to the canonical decl might not get us the
9456   // right set of default arguments.  What default arguments are
9457   // we supposed to consider on ADL candidates, anyway?
9458 
9459   // FIXME: Pass in the explicit template arguments?
9460   ArgumentDependentLookup(Name, Loc, Args, Fns);
9461 
9462   // Erase all of the candidates we already knew about.
9463   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9464                                    CandEnd = CandidateSet.end();
9465        Cand != CandEnd; ++Cand)
9466     if (Cand->Function) {
9467       Fns.erase(Cand->Function);
9468       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9469         Fns.erase(FunTmpl);
9470     }
9471 
9472   // For each of the ADL candidates we found, add it to the overload
9473   // set.
9474   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9475     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9476 
9477     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9478       if (ExplicitTemplateArgs)
9479         continue;
9480 
9481       AddOverloadCandidate(
9482           FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
9483           PartialOverloading, /*AllowExplicit=*/true,
9484           /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
9485       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) {
9486         AddOverloadCandidate(
9487             FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
9488             /*SuppressUserConversions=*/false, PartialOverloading,
9489             /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
9490             ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed);
9491       }
9492     } else {
9493       auto *FTD = cast<FunctionTemplateDecl>(*I);
9494       AddTemplateOverloadCandidate(
9495           FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
9496           /*SuppressUserConversions=*/false, PartialOverloading,
9497           /*AllowExplicit=*/true, ADLCallKind::UsesADL);
9498       if (CandidateSet.getRewriteInfo().shouldAddReversed(
9499               Context, FTD->getTemplatedDecl())) {
9500         AddTemplateOverloadCandidate(
9501             FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
9502             CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
9503             /*AllowExplicit=*/true, ADLCallKind::UsesADL,
9504             OverloadCandidateParamOrder::Reversed);
9505       }
9506     }
9507   }
9508 }
9509 
9510 namespace {
9511 enum class Comparison { Equal, Better, Worse };
9512 }
9513 
9514 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9515 /// overload resolution.
9516 ///
9517 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9518 /// Cand1's first N enable_if attributes have precisely the same conditions as
9519 /// Cand2's first N enable_if attributes (where N = the number of enable_if
9520 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9521 ///
9522 /// Note that you can have a pair of candidates such that Cand1's enable_if
9523 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9524 /// worse than Cand1's.
9525 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9526                                        const FunctionDecl *Cand2) {
9527   // Common case: One (or both) decls don't have enable_if attrs.
9528   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9529   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9530   if (!Cand1Attr || !Cand2Attr) {
9531     if (Cand1Attr == Cand2Attr)
9532       return Comparison::Equal;
9533     return Cand1Attr ? Comparison::Better : Comparison::Worse;
9534   }
9535 
9536   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9537   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9538 
9539   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9540   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9541     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9542     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9543 
9544     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9545     // has fewer enable_if attributes than Cand2, and vice versa.
9546     if (!Cand1A)
9547       return Comparison::Worse;
9548     if (!Cand2A)
9549       return Comparison::Better;
9550 
9551     Cand1ID.clear();
9552     Cand2ID.clear();
9553 
9554     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9555     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9556     if (Cand1ID != Cand2ID)
9557       return Comparison::Worse;
9558   }
9559 
9560   return Comparison::Equal;
9561 }
9562 
9563 static Comparison
9564 isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9565                               const OverloadCandidate &Cand2) {
9566   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9567       !Cand2.Function->isMultiVersion())
9568     return Comparison::Equal;
9569 
9570   // If both are invalid, they are equal. If one of them is invalid, the other
9571   // is better.
9572   if (Cand1.Function->isInvalidDecl()) {
9573     if (Cand2.Function->isInvalidDecl())
9574       return Comparison::Equal;
9575     return Comparison::Worse;
9576   }
9577   if (Cand2.Function->isInvalidDecl())
9578     return Comparison::Better;
9579 
9580   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9581   // cpu_dispatch, else arbitrarily based on the identifiers.
9582   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9583   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9584   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9585   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9586 
9587   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9588     return Comparison::Equal;
9589 
9590   if (Cand1CPUDisp && !Cand2CPUDisp)
9591     return Comparison::Better;
9592   if (Cand2CPUDisp && !Cand1CPUDisp)
9593     return Comparison::Worse;
9594 
9595   if (Cand1CPUSpec && Cand2CPUSpec) {
9596     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9597       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
9598                  ? Comparison::Better
9599                  : Comparison::Worse;
9600 
9601     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9602         FirstDiff = std::mismatch(
9603             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9604             Cand2CPUSpec->cpus_begin(),
9605             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9606               return LHS->getName() == RHS->getName();
9607             });
9608 
9609     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9610            "Two different cpu-specific versions should not have the same "
9611            "identifier list, otherwise they'd be the same decl!");
9612     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
9613                ? Comparison::Better
9614                : Comparison::Worse;
9615   }
9616   llvm_unreachable("No way to get here unless both had cpu_dispatch");
9617 }
9618 
9619 /// Compute the type of the implicit object parameter for the given function,
9620 /// if any. Returns None if there is no implicit object parameter, and a null
9621 /// QualType if there is a 'matches anything' implicit object parameter.
9622 static Optional<QualType> getImplicitObjectParamType(ASTContext &Context,
9623                                                      const FunctionDecl *F) {
9624   if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
9625     return llvm::None;
9626 
9627   auto *M = cast<CXXMethodDecl>(F);
9628   // Static member functions' object parameters match all types.
9629   if (M->isStatic())
9630     return QualType();
9631 
9632   QualType T = M->getThisObjectType();
9633   if (M->getRefQualifier() == RQ_RValue)
9634     return Context.getRValueReferenceType(T);
9635   return Context.getLValueReferenceType(T);
9636 }
9637 
9638 static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1,
9639                                    const FunctionDecl *F2, unsigned NumParams) {
9640   if (declaresSameEntity(F1, F2))
9641     return true;
9642 
9643   auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
9644     if (First) {
9645       if (Optional<QualType> T = getImplicitObjectParamType(Context, F))
9646         return *T;
9647     }
9648     assert(I < F->getNumParams());
9649     return F->getParamDecl(I++)->getType();
9650   };
9651 
9652   unsigned I1 = 0, I2 = 0;
9653   for (unsigned I = 0; I != NumParams; ++I) {
9654     QualType T1 = NextParam(F1, I1, I == 0);
9655     QualType T2 = NextParam(F2, I2, I == 0);
9656     assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
9657     if (!Context.hasSameUnqualifiedType(T1, T2))
9658       return false;
9659   }
9660   return true;
9661 }
9662 
9663 /// We're allowed to use constraints partial ordering only if the candidates
9664 /// have the same parameter types:
9665 /// [temp.func.order]p6.2.2 [...] or if the function parameters that
9666 /// positionally correspond between the two templates are not of the same type,
9667 /// neither template is more specialized than the other.
9668 /// [over.match.best]p2.6
9669 /// F1 and F2 are non-template functions with the same parameter-type-lists,
9670 /// and F1 is more constrained than F2 [...]
9671 static bool canCompareFunctionConstraints(Sema &S,
9672                                           const OverloadCandidate &Cand1,
9673                                           const OverloadCandidate &Cand2) {
9674   // FIXME: Per P2113R0 we also need to compare the template parameter lists
9675   // when comparing template functions.
9676   if (Cand1.Function && Cand2.Function && Cand1.Function->hasPrototype() &&
9677       Cand2.Function->hasPrototype()) {
9678     auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType());
9679     auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType());
9680     if (PT1->getNumParams() == PT2->getNumParams() &&
9681         PT1->isVariadic() == PT2->isVariadic() &&
9682         S.FunctionParamTypesAreEqual(PT1, PT2, nullptr,
9683                                      Cand1.isReversed() ^ Cand2.isReversed()))
9684       return true;
9685   }
9686   return false;
9687 }
9688 
9689 /// isBetterOverloadCandidate - Determines whether the first overload
9690 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9691 bool clang::isBetterOverloadCandidate(
9692     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9693     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9694   // Define viable functions to be better candidates than non-viable
9695   // functions.
9696   if (!Cand2.Viable)
9697     return Cand1.Viable;
9698   else if (!Cand1.Viable)
9699     return false;
9700 
9701   // [CUDA] A function with 'never' preference is marked not viable, therefore
9702   // is never shown up here. The worst preference shown up here is 'wrong side',
9703   // e.g. an H function called by a HD function in device compilation. This is
9704   // valid AST as long as the HD function is not emitted, e.g. it is an inline
9705   // function which is called only by an H function. A deferred diagnostic will
9706   // be triggered if it is emitted. However a wrong-sided function is still
9707   // a viable candidate here.
9708   //
9709   // If Cand1 can be emitted and Cand2 cannot be emitted in the current
9710   // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
9711   // can be emitted, Cand1 is not better than Cand2. This rule should have
9712   // precedence over other rules.
9713   //
9714   // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
9715   // other rules should be used to determine which is better. This is because
9716   // host/device based overloading resolution is mostly for determining
9717   // viability of a function. If two functions are both viable, other factors
9718   // should take precedence in preference, e.g. the standard-defined preferences
9719   // like argument conversion ranks or enable_if partial-ordering. The
9720   // preference for pass-object-size parameters is probably most similar to a
9721   // type-based-overloading decision and so should take priority.
9722   //
9723   // If other rules cannot determine which is better, CUDA preference will be
9724   // used again to determine which is better.
9725   //
9726   // TODO: Currently IdentifyCUDAPreference does not return correct values
9727   // for functions called in global variable initializers due to missing
9728   // correct context about device/host. Therefore we can only enforce this
9729   // rule when there is a caller. We should enforce this rule for functions
9730   // in global variable initializers once proper context is added.
9731   //
9732   // TODO: We can only enable the hostness based overloading resolution when
9733   // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
9734   // overloading resolution diagnostics.
9735   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
9736       S.getLangOpts().GPUExcludeWrongSideOverloads) {
9737     if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
9738       bool IsCallerImplicitHD = Sema::isCUDAImplicitHostDeviceFunction(Caller);
9739       bool IsCand1ImplicitHD =
9740           Sema::isCUDAImplicitHostDeviceFunction(Cand1.Function);
9741       bool IsCand2ImplicitHD =
9742           Sema::isCUDAImplicitHostDeviceFunction(Cand2.Function);
9743       auto P1 = S.IdentifyCUDAPreference(Caller, Cand1.Function);
9744       auto P2 = S.IdentifyCUDAPreference(Caller, Cand2.Function);
9745       assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never);
9746       // The implicit HD function may be a function in a system header which
9747       // is forced by pragma. In device compilation, if we prefer HD candidates
9748       // over wrong-sided candidates, overloading resolution may change, which
9749       // may result in non-deferrable diagnostics. As a workaround, we let
9750       // implicit HD candidates take equal preference as wrong-sided candidates.
9751       // This will preserve the overloading resolution.
9752       // TODO: We still need special handling of implicit HD functions since
9753       // they may incur other diagnostics to be deferred. We should make all
9754       // host/device related diagnostics deferrable and remove special handling
9755       // of implicit HD functions.
9756       auto EmitThreshold =
9757           (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
9758            (IsCand1ImplicitHD || IsCand2ImplicitHD))
9759               ? Sema::CFP_Never
9760               : Sema::CFP_WrongSide;
9761       auto Cand1Emittable = P1 > EmitThreshold;
9762       auto Cand2Emittable = P2 > EmitThreshold;
9763       if (Cand1Emittable && !Cand2Emittable)
9764         return true;
9765       if (!Cand1Emittable && Cand2Emittable)
9766         return false;
9767     }
9768   }
9769 
9770   // C++ [over.match.best]p1:
9771   //
9772   //   -- if F is a static member function, ICS1(F) is defined such
9773   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9774   //      any function G, and, symmetrically, ICS1(G) is neither
9775   //      better nor worse than ICS1(F).
9776   unsigned StartArg = 0;
9777   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9778     StartArg = 1;
9779 
9780   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9781     // We don't allow incompatible pointer conversions in C++.
9782     if (!S.getLangOpts().CPlusPlus)
9783       return ICS.isStandard() &&
9784              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9785 
9786     // The only ill-formed conversion we allow in C++ is the string literal to
9787     // char* conversion, which is only considered ill-formed after C++11.
9788     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9789            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9790   };
9791 
9792   // Define functions that don't require ill-formed conversions for a given
9793   // argument to be better candidates than functions that do.
9794   unsigned NumArgs = Cand1.Conversions.size();
9795   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9796   bool HasBetterConversion = false;
9797   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9798     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9799     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9800     if (Cand1Bad != Cand2Bad) {
9801       if (Cand1Bad)
9802         return false;
9803       HasBetterConversion = true;
9804     }
9805   }
9806 
9807   if (HasBetterConversion)
9808     return true;
9809 
9810   // C++ [over.match.best]p1:
9811   //   A viable function F1 is defined to be a better function than another
9812   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9813   //   conversion sequence than ICSi(F2), and then...
9814   bool HasWorseConversion = false;
9815   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9816     switch (CompareImplicitConversionSequences(S, Loc,
9817                                                Cand1.Conversions[ArgIdx],
9818                                                Cand2.Conversions[ArgIdx])) {
9819     case ImplicitConversionSequence::Better:
9820       // Cand1 has a better conversion sequence.
9821       HasBetterConversion = true;
9822       break;
9823 
9824     case ImplicitConversionSequence::Worse:
9825       if (Cand1.Function && Cand2.Function &&
9826           Cand1.isReversed() != Cand2.isReversed() &&
9827           haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function,
9828                                  NumArgs)) {
9829         // Work around large-scale breakage caused by considering reversed
9830         // forms of operator== in C++20:
9831         //
9832         // When comparing a function against a reversed function with the same
9833         // parameter types, if we have a better conversion for one argument and
9834         // a worse conversion for the other, the implicit conversion sequences
9835         // are treated as being equally good.
9836         //
9837         // This prevents a comparison function from being considered ambiguous
9838         // with a reversed form that is written in the same way.
9839         //
9840         // We diagnose this as an extension from CreateOverloadedBinOp.
9841         HasWorseConversion = true;
9842         break;
9843       }
9844 
9845       // Cand1 can't be better than Cand2.
9846       return false;
9847 
9848     case ImplicitConversionSequence::Indistinguishable:
9849       // Do nothing.
9850       break;
9851     }
9852   }
9853 
9854   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9855   //       ICSj(F2), or, if not that,
9856   if (HasBetterConversion && !HasWorseConversion)
9857     return true;
9858 
9859   //   -- the context is an initialization by user-defined conversion
9860   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9861   //      from the return type of F1 to the destination type (i.e.,
9862   //      the type of the entity being initialized) is a better
9863   //      conversion sequence than the standard conversion sequence
9864   //      from the return type of F2 to the destination type.
9865   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9866       Cand1.Function && Cand2.Function &&
9867       isa<CXXConversionDecl>(Cand1.Function) &&
9868       isa<CXXConversionDecl>(Cand2.Function)) {
9869     // First check whether we prefer one of the conversion functions over the
9870     // other. This only distinguishes the results in non-standard, extension
9871     // cases such as the conversion from a lambda closure type to a function
9872     // pointer or block.
9873     ImplicitConversionSequence::CompareKind Result =
9874         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9875     if (Result == ImplicitConversionSequence::Indistinguishable)
9876       Result = CompareStandardConversionSequences(S, Loc,
9877                                                   Cand1.FinalConversion,
9878                                                   Cand2.FinalConversion);
9879 
9880     if (Result != ImplicitConversionSequence::Indistinguishable)
9881       return Result == ImplicitConversionSequence::Better;
9882 
9883     // FIXME: Compare kind of reference binding if conversion functions
9884     // convert to a reference type used in direct reference binding, per
9885     // C++14 [over.match.best]p1 section 2 bullet 3.
9886   }
9887 
9888   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9889   // as combined with the resolution to CWG issue 243.
9890   //
9891   // When the context is initialization by constructor ([over.match.ctor] or
9892   // either phase of [over.match.list]), a constructor is preferred over
9893   // a conversion function.
9894   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9895       Cand1.Function && Cand2.Function &&
9896       isa<CXXConstructorDecl>(Cand1.Function) !=
9897           isa<CXXConstructorDecl>(Cand2.Function))
9898     return isa<CXXConstructorDecl>(Cand1.Function);
9899 
9900   //    -- F1 is a non-template function and F2 is a function template
9901   //       specialization, or, if not that,
9902   bool Cand1IsSpecialization = Cand1.Function &&
9903                                Cand1.Function->getPrimaryTemplate();
9904   bool Cand2IsSpecialization = Cand2.Function &&
9905                                Cand2.Function->getPrimaryTemplate();
9906   if (Cand1IsSpecialization != Cand2IsSpecialization)
9907     return Cand2IsSpecialization;
9908 
9909   //   -- F1 and F2 are function template specializations, and the function
9910   //      template for F1 is more specialized than the template for F2
9911   //      according to the partial ordering rules described in 14.5.5.2, or,
9912   //      if not that,
9913   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9914     if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
9915             Cand1.Function->getPrimaryTemplate(),
9916             Cand2.Function->getPrimaryTemplate(), Loc,
9917             isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
9918                                                    : TPOC_Call,
9919             Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments,
9920             Cand1.isReversed() ^ Cand2.isReversed(),
9921             canCompareFunctionConstraints(S, Cand1, Cand2)))
9922       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9923   }
9924 
9925   //   -— F1 and F2 are non-template functions with the same
9926   //      parameter-type-lists, and F1 is more constrained than F2 [...],
9927   if (!Cand1IsSpecialization && !Cand2IsSpecialization &&
9928       canCompareFunctionConstraints(S, Cand1, Cand2)) {
9929     Expr *RC1 = Cand1.Function->getTrailingRequiresClause();
9930     Expr *RC2 = Cand2.Function->getTrailingRequiresClause();
9931     if (RC1 && RC2) {
9932       bool AtLeastAsConstrained1, AtLeastAsConstrained2;
9933       if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function, {RC2},
9934                                    AtLeastAsConstrained1) ||
9935           S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function, {RC1},
9936                                    AtLeastAsConstrained2))
9937         return false;
9938       if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
9939         return AtLeastAsConstrained1;
9940     } else if (RC1 || RC2) {
9941       return RC1 != nullptr;
9942     }
9943   }
9944 
9945   //   -- F1 is a constructor for a class D, F2 is a constructor for a base
9946   //      class B of D, and for all arguments the corresponding parameters of
9947   //      F1 and F2 have the same type.
9948   // FIXME: Implement the "all parameters have the same type" check.
9949   bool Cand1IsInherited =
9950       isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9951   bool Cand2IsInherited =
9952       isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9953   if (Cand1IsInherited != Cand2IsInherited)
9954     return Cand2IsInherited;
9955   else if (Cand1IsInherited) {
9956     assert(Cand2IsInherited);
9957     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9958     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9959     if (Cand1Class->isDerivedFrom(Cand2Class))
9960       return true;
9961     if (Cand2Class->isDerivedFrom(Cand1Class))
9962       return false;
9963     // Inherited from sibling base classes: still ambiguous.
9964   }
9965 
9966   //   -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
9967   //   -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
9968   //      with reversed order of parameters and F1 is not
9969   //
9970   // We rank reversed + different operator as worse than just reversed, but
9971   // that comparison can never happen, because we only consider reversing for
9972   // the maximally-rewritten operator (== or <=>).
9973   if (Cand1.RewriteKind != Cand2.RewriteKind)
9974     return Cand1.RewriteKind < Cand2.RewriteKind;
9975 
9976   // Check C++17 tie-breakers for deduction guides.
9977   {
9978     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9979     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9980     if (Guide1 && Guide2) {
9981       //  -- F1 is generated from a deduction-guide and F2 is not
9982       if (Guide1->isImplicit() != Guide2->isImplicit())
9983         return Guide2->isImplicit();
9984 
9985       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9986       if (Guide1->isCopyDeductionCandidate())
9987         return true;
9988     }
9989   }
9990 
9991   // Check for enable_if value-based overload resolution.
9992   if (Cand1.Function && Cand2.Function) {
9993     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9994     if (Cmp != Comparison::Equal)
9995       return Cmp == Comparison::Better;
9996   }
9997 
9998   bool HasPS1 = Cand1.Function != nullptr &&
9999                 functionHasPassObjectSizeParams(Cand1.Function);
10000   bool HasPS2 = Cand2.Function != nullptr &&
10001                 functionHasPassObjectSizeParams(Cand2.Function);
10002   if (HasPS1 != HasPS2 && HasPS1)
10003     return true;
10004 
10005   auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
10006   if (MV == Comparison::Better)
10007     return true;
10008   if (MV == Comparison::Worse)
10009     return false;
10010 
10011   // If other rules cannot determine which is better, CUDA preference is used
10012   // to determine which is better.
10013   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
10014     FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10015     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
10016            S.IdentifyCUDAPreference(Caller, Cand2.Function);
10017   }
10018 
10019   // General member function overloading is handled above, so this only handles
10020   // constructors with address spaces.
10021   // This only handles address spaces since C++ has no other
10022   // qualifier that can be used with constructors.
10023   const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
10024   const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
10025   if (CD1 && CD2) {
10026     LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
10027     LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
10028     if (AS1 != AS2) {
10029       if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
10030         return true;
10031       if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
10032         return false;
10033     }
10034   }
10035 
10036   return false;
10037 }
10038 
10039 /// Determine whether two declarations are "equivalent" for the purposes of
10040 /// name lookup and overload resolution. This applies when the same internal/no
10041 /// linkage entity is defined by two modules (probably by textually including
10042 /// the same header). In such a case, we don't consider the declarations to
10043 /// declare the same entity, but we also don't want lookups with both
10044 /// declarations visible to be ambiguous in some cases (this happens when using
10045 /// a modularized libstdc++).
10046 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
10047                                                   const NamedDecl *B) {
10048   auto *VA = dyn_cast_or_null<ValueDecl>(A);
10049   auto *VB = dyn_cast_or_null<ValueDecl>(B);
10050   if (!VA || !VB)
10051     return false;
10052 
10053   // The declarations must be declaring the same name as an internal linkage
10054   // entity in different modules.
10055   if (!VA->getDeclContext()->getRedeclContext()->Equals(
10056           VB->getDeclContext()->getRedeclContext()) ||
10057       getOwningModule(VA) == getOwningModule(VB) ||
10058       VA->isExternallyVisible() || VB->isExternallyVisible())
10059     return false;
10060 
10061   // Check that the declarations appear to be equivalent.
10062   //
10063   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
10064   // For constants and functions, we should check the initializer or body is
10065   // the same. For non-constant variables, we shouldn't allow it at all.
10066   if (Context.hasSameType(VA->getType(), VB->getType()))
10067     return true;
10068 
10069   // Enum constants within unnamed enumerations will have different types, but
10070   // may still be similar enough to be interchangeable for our purposes.
10071   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
10072     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
10073       // Only handle anonymous enums. If the enumerations were named and
10074       // equivalent, they would have been merged to the same type.
10075       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
10076       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
10077       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
10078           !Context.hasSameType(EnumA->getIntegerType(),
10079                                EnumB->getIntegerType()))
10080         return false;
10081       // Allow this only if the value is the same for both enumerators.
10082       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
10083     }
10084   }
10085 
10086   // Nothing else is sufficiently similar.
10087   return false;
10088 }
10089 
10090 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
10091     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
10092   assert(D && "Unknown declaration");
10093   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
10094 
10095   Module *M = getOwningModule(D);
10096   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
10097       << !M << (M ? M->getFullModuleName() : "");
10098 
10099   for (auto *E : Equiv) {
10100     Module *M = getOwningModule(E);
10101     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
10102         << !M << (M ? M->getFullModuleName() : "");
10103   }
10104 }
10105 
10106 /// Computes the best viable function (C++ 13.3.3)
10107 /// within an overload candidate set.
10108 ///
10109 /// \param Loc The location of the function name (or operator symbol) for
10110 /// which overload resolution occurs.
10111 ///
10112 /// \param Best If overload resolution was successful or found a deleted
10113 /// function, \p Best points to the candidate function found.
10114 ///
10115 /// \returns The result of overload resolution.
10116 OverloadingResult
10117 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
10118                                          iterator &Best) {
10119   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
10120   std::transform(begin(), end(), std::back_inserter(Candidates),
10121                  [](OverloadCandidate &Cand) { return &Cand; });
10122 
10123   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
10124   // are accepted by both clang and NVCC. However, during a particular
10125   // compilation mode only one call variant is viable. We need to
10126   // exclude non-viable overload candidates from consideration based
10127   // only on their host/device attributes. Specifically, if one
10128   // candidate call is WrongSide and the other is SameSide, we ignore
10129   // the WrongSide candidate.
10130   // We only need to remove wrong-sided candidates here if
10131   // -fgpu-exclude-wrong-side-overloads is off. When
10132   // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
10133   // uniformly in isBetterOverloadCandidate.
10134   if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) {
10135     const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10136     bool ContainsSameSideCandidate =
10137         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
10138           // Check viable function only.
10139           return Cand->Viable && Cand->Function &&
10140                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
10141                      Sema::CFP_SameSide;
10142         });
10143     if (ContainsSameSideCandidate) {
10144       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
10145         // Check viable function only to avoid unnecessary data copying/moving.
10146         return Cand->Viable && Cand->Function &&
10147                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
10148                    Sema::CFP_WrongSide;
10149       };
10150       llvm::erase_if(Candidates, IsWrongSideCandidate);
10151     }
10152   }
10153 
10154   // Find the best viable function.
10155   Best = end();
10156   for (auto *Cand : Candidates) {
10157     Cand->Best = false;
10158     if (Cand->Viable)
10159       if (Best == end() ||
10160           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
10161         Best = Cand;
10162   }
10163 
10164   // If we didn't find any viable functions, abort.
10165   if (Best == end())
10166     return OR_No_Viable_Function;
10167 
10168   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
10169 
10170   llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
10171   PendingBest.push_back(&*Best);
10172   Best->Best = true;
10173 
10174   // Make sure that this function is better than every other viable
10175   // function. If not, we have an ambiguity.
10176   while (!PendingBest.empty()) {
10177     auto *Curr = PendingBest.pop_back_val();
10178     for (auto *Cand : Candidates) {
10179       if (Cand->Viable && !Cand->Best &&
10180           !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
10181         PendingBest.push_back(Cand);
10182         Cand->Best = true;
10183 
10184         if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
10185                                                      Curr->Function))
10186           EquivalentCands.push_back(Cand->Function);
10187         else
10188           Best = end();
10189       }
10190     }
10191   }
10192 
10193   // If we found more than one best candidate, this is ambiguous.
10194   if (Best == end())
10195     return OR_Ambiguous;
10196 
10197   // Best is the best viable function.
10198   if (Best->Function && Best->Function->isDeleted())
10199     return OR_Deleted;
10200 
10201   if (!EquivalentCands.empty())
10202     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
10203                                                     EquivalentCands);
10204 
10205   return OR_Success;
10206 }
10207 
10208 namespace {
10209 
10210 enum OverloadCandidateKind {
10211   oc_function,
10212   oc_method,
10213   oc_reversed_binary_operator,
10214   oc_constructor,
10215   oc_implicit_default_constructor,
10216   oc_implicit_copy_constructor,
10217   oc_implicit_move_constructor,
10218   oc_implicit_copy_assignment,
10219   oc_implicit_move_assignment,
10220   oc_implicit_equality_comparison,
10221   oc_inherited_constructor
10222 };
10223 
10224 enum OverloadCandidateSelect {
10225   ocs_non_template,
10226   ocs_template,
10227   ocs_described_template,
10228 };
10229 
10230 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
10231 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
10232                           OverloadCandidateRewriteKind CRK,
10233                           std::string &Description) {
10234 
10235   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
10236   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
10237     isTemplate = true;
10238     Description = S.getTemplateArgumentBindingsText(
10239         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
10240   }
10241 
10242   OverloadCandidateSelect Select = [&]() {
10243     if (!Description.empty())
10244       return ocs_described_template;
10245     return isTemplate ? ocs_template : ocs_non_template;
10246   }();
10247 
10248   OverloadCandidateKind Kind = [&]() {
10249     if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
10250       return oc_implicit_equality_comparison;
10251 
10252     if (CRK & CRK_Reversed)
10253       return oc_reversed_binary_operator;
10254 
10255     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
10256       if (!Ctor->isImplicit()) {
10257         if (isa<ConstructorUsingShadowDecl>(Found))
10258           return oc_inherited_constructor;
10259         else
10260           return oc_constructor;
10261       }
10262 
10263       if (Ctor->isDefaultConstructor())
10264         return oc_implicit_default_constructor;
10265 
10266       if (Ctor->isMoveConstructor())
10267         return oc_implicit_move_constructor;
10268 
10269       assert(Ctor->isCopyConstructor() &&
10270              "unexpected sort of implicit constructor");
10271       return oc_implicit_copy_constructor;
10272     }
10273 
10274     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
10275       // This actually gets spelled 'candidate function' for now, but
10276       // it doesn't hurt to split it out.
10277       if (!Meth->isImplicit())
10278         return oc_method;
10279 
10280       if (Meth->isMoveAssignmentOperator())
10281         return oc_implicit_move_assignment;
10282 
10283       if (Meth->isCopyAssignmentOperator())
10284         return oc_implicit_copy_assignment;
10285 
10286       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
10287       return oc_method;
10288     }
10289 
10290     return oc_function;
10291   }();
10292 
10293   return std::make_pair(Kind, Select);
10294 }
10295 
10296 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
10297   // FIXME: It'd be nice to only emit a note once per using-decl per overload
10298   // set.
10299   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
10300     S.Diag(FoundDecl->getLocation(),
10301            diag::note_ovl_candidate_inherited_constructor)
10302       << Shadow->getNominatedBaseClass();
10303 }
10304 
10305 } // end anonymous namespace
10306 
10307 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
10308                                     const FunctionDecl *FD) {
10309   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
10310     bool AlwaysTrue;
10311     if (EnableIf->getCond()->isValueDependent() ||
10312         !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
10313       return false;
10314     if (!AlwaysTrue)
10315       return false;
10316   }
10317   return true;
10318 }
10319 
10320 /// Returns true if we can take the address of the function.
10321 ///
10322 /// \param Complain - If true, we'll emit a diagnostic
10323 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
10324 ///   we in overload resolution?
10325 /// \param Loc - The location of the statement we're complaining about. Ignored
10326 ///   if we're not complaining, or if we're in overload resolution.
10327 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
10328                                               bool Complain,
10329                                               bool InOverloadResolution,
10330                                               SourceLocation Loc) {
10331   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
10332     if (Complain) {
10333       if (InOverloadResolution)
10334         S.Diag(FD->getBeginLoc(),
10335                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
10336       else
10337         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
10338     }
10339     return false;
10340   }
10341 
10342   if (FD->getTrailingRequiresClause()) {
10343     ConstraintSatisfaction Satisfaction;
10344     if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
10345       return false;
10346     if (!Satisfaction.IsSatisfied) {
10347       if (Complain) {
10348         if (InOverloadResolution) {
10349           SmallString<128> TemplateArgString;
10350           if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
10351             TemplateArgString += " ";
10352             TemplateArgString += S.getTemplateArgumentBindingsText(
10353                 FunTmpl->getTemplateParameters(),
10354                 *FD->getTemplateSpecializationArgs());
10355           }
10356 
10357           S.Diag(FD->getBeginLoc(),
10358                  diag::note_ovl_candidate_unsatisfied_constraints)
10359               << TemplateArgString;
10360         } else
10361           S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
10362               << FD;
10363         S.DiagnoseUnsatisfiedConstraint(Satisfaction);
10364       }
10365       return false;
10366     }
10367   }
10368 
10369   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
10370     return P->hasAttr<PassObjectSizeAttr>();
10371   });
10372   if (I == FD->param_end())
10373     return true;
10374 
10375   if (Complain) {
10376     // Add one to ParamNo because it's user-facing
10377     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
10378     if (InOverloadResolution)
10379       S.Diag(FD->getLocation(),
10380              diag::note_ovl_candidate_has_pass_object_size_params)
10381           << ParamNo;
10382     else
10383       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
10384           << FD << ParamNo;
10385   }
10386   return false;
10387 }
10388 
10389 static bool checkAddressOfCandidateIsAvailable(Sema &S,
10390                                                const FunctionDecl *FD) {
10391   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
10392                                            /*InOverloadResolution=*/true,
10393                                            /*Loc=*/SourceLocation());
10394 }
10395 
10396 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10397                                              bool Complain,
10398                                              SourceLocation Loc) {
10399   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
10400                                              /*InOverloadResolution=*/false,
10401                                              Loc);
10402 }
10403 
10404 // Don't print candidates other than the one that matches the calling
10405 // convention of the call operator, since that is guaranteed to exist.
10406 static bool shouldSkipNotingLambdaConversionDecl(FunctionDecl *Fn) {
10407   const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
10408 
10409   if (!ConvD)
10410     return false;
10411   const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
10412   if (!RD->isLambda())
10413     return false;
10414 
10415   CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
10416   CallingConv CallOpCC =
10417       CallOp->getType()->castAs<FunctionType>()->getCallConv();
10418   QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
10419   CallingConv ConvToCC =
10420       ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
10421 
10422   return ConvToCC != CallOpCC;
10423 }
10424 
10425 // Notes the location of an overload candidate.
10426 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
10427                                  OverloadCandidateRewriteKind RewriteKind,
10428                                  QualType DestType, bool TakingAddress) {
10429   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
10430     return;
10431   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
10432       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
10433     return;
10434   if (shouldSkipNotingLambdaConversionDecl(Fn))
10435     return;
10436 
10437   std::string FnDesc;
10438   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
10439       ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
10440   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
10441                          << (unsigned)KSPair.first << (unsigned)KSPair.second
10442                          << Fn << FnDesc;
10443 
10444   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
10445   Diag(Fn->getLocation(), PD);
10446   MaybeEmitInheritedConstructorNote(*this, Found);
10447 }
10448 
10449 static void
10450 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
10451   // Perhaps the ambiguity was caused by two atomic constraints that are
10452   // 'identical' but not equivalent:
10453   //
10454   // void foo() requires (sizeof(T) > 4) { } // #1
10455   // void foo() requires (sizeof(T) > 4) && T::value { } // #2
10456   //
10457   // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
10458   // #2 to subsume #1, but these constraint are not considered equivalent
10459   // according to the subsumption rules because they are not the same
10460   // source-level construct. This behavior is quite confusing and we should try
10461   // to help the user figure out what happened.
10462 
10463   SmallVector<const Expr *, 3> FirstAC, SecondAC;
10464   FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
10465   for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10466     if (!I->Function)
10467       continue;
10468     SmallVector<const Expr *, 3> AC;
10469     if (auto *Template = I->Function->getPrimaryTemplate())
10470       Template->getAssociatedConstraints(AC);
10471     else
10472       I->Function->getAssociatedConstraints(AC);
10473     if (AC.empty())
10474       continue;
10475     if (FirstCand == nullptr) {
10476       FirstCand = I->Function;
10477       FirstAC = AC;
10478     } else if (SecondCand == nullptr) {
10479       SecondCand = I->Function;
10480       SecondAC = AC;
10481     } else {
10482       // We have more than one pair of constrained functions - this check is
10483       // expensive and we'd rather not try to diagnose it.
10484       return;
10485     }
10486   }
10487   if (!SecondCand)
10488     return;
10489   // The diagnostic can only happen if there are associated constraints on
10490   // both sides (there needs to be some identical atomic constraint).
10491   if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
10492                                                       SecondCand, SecondAC))
10493     // Just show the user one diagnostic, they'll probably figure it out
10494     // from here.
10495     return;
10496 }
10497 
10498 // Notes the location of all overload candidates designated through
10499 // OverloadedExpr
10500 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
10501                                      bool TakingAddress) {
10502   assert(OverloadedExpr->getType() == Context.OverloadTy);
10503 
10504   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
10505   OverloadExpr *OvlExpr = Ovl.Expression;
10506 
10507   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10508                             IEnd = OvlExpr->decls_end();
10509        I != IEnd; ++I) {
10510     if (FunctionTemplateDecl *FunTmpl =
10511                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
10512       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
10513                             TakingAddress);
10514     } else if (FunctionDecl *Fun
10515                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
10516       NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
10517     }
10518   }
10519 }
10520 
10521 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
10522 /// "lead" diagnostic; it will be given two arguments, the source and
10523 /// target types of the conversion.
10524 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
10525                                  Sema &S,
10526                                  SourceLocation CaretLoc,
10527                                  const PartialDiagnostic &PDiag) const {
10528   S.Diag(CaretLoc, PDiag)
10529     << Ambiguous.getFromType() << Ambiguous.getToType();
10530   unsigned CandsShown = 0;
10531   AmbiguousConversionSequence::const_iterator I, E;
10532   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
10533     if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
10534       break;
10535     ++CandsShown;
10536     S.NoteOverloadCandidate(I->first, I->second);
10537   }
10538   S.Diags.overloadCandidatesShown(CandsShown);
10539   if (I != E)
10540     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
10541 }
10542 
10543 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
10544                                   unsigned I, bool TakingCandidateAddress) {
10545   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
10546   assert(Conv.isBad());
10547   assert(Cand->Function && "for now, candidate must be a function");
10548   FunctionDecl *Fn = Cand->Function;
10549 
10550   // There's a conversion slot for the object argument if this is a
10551   // non-constructor method.  Note that 'I' corresponds the
10552   // conversion-slot index.
10553   bool isObjectArgument = false;
10554   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
10555     if (I == 0)
10556       isObjectArgument = true;
10557     else
10558       I--;
10559   }
10560 
10561   std::string FnDesc;
10562   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10563       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
10564                                 FnDesc);
10565 
10566   Expr *FromExpr = Conv.Bad.FromExpr;
10567   QualType FromTy = Conv.Bad.getFromType();
10568   QualType ToTy = Conv.Bad.getToType();
10569 
10570   if (FromTy == S.Context.OverloadTy) {
10571     assert(FromExpr && "overload set argument came from implicit argument?");
10572     Expr *E = FromExpr->IgnoreParens();
10573     if (isa<UnaryOperator>(E))
10574       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
10575     DeclarationName Name = cast<OverloadExpr>(E)->getName();
10576 
10577     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
10578         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10579         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
10580         << Name << I + 1;
10581     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10582     return;
10583   }
10584 
10585   // Do some hand-waving analysis to see if the non-viability is due
10586   // to a qualifier mismatch.
10587   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
10588   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
10589   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
10590     CToTy = RT->getPointeeType();
10591   else {
10592     // TODO: detect and diagnose the full richness of const mismatches.
10593     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
10594       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
10595         CFromTy = FromPT->getPointeeType();
10596         CToTy = ToPT->getPointeeType();
10597       }
10598   }
10599 
10600   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
10601       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
10602     Qualifiers FromQs = CFromTy.getQualifiers();
10603     Qualifiers ToQs = CToTy.getQualifiers();
10604 
10605     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
10606       if (isObjectArgument)
10607         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
10608             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10609             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10610             << FromQs.getAddressSpace() << ToQs.getAddressSpace();
10611       else
10612         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
10613             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10614             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10615             << FromQs.getAddressSpace() << ToQs.getAddressSpace()
10616             << ToTy->isReferenceType() << I + 1;
10617       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10618       return;
10619     }
10620 
10621     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10622       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
10623           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10624           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10625           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
10626           << (unsigned)isObjectArgument << I + 1;
10627       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10628       return;
10629     }
10630 
10631     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
10632       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
10633           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10634           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10635           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
10636           << (unsigned)isObjectArgument << I + 1;
10637       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10638       return;
10639     }
10640 
10641     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
10642       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
10643           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10644           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10645           << FromQs.hasUnaligned() << I + 1;
10646       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10647       return;
10648     }
10649 
10650     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
10651     assert(CVR && "expected qualifiers mismatch");
10652 
10653     if (isObjectArgument) {
10654       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
10655           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10656           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10657           << (CVR - 1);
10658     } else {
10659       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
10660           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10661           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10662           << (CVR - 1) << I + 1;
10663     }
10664     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10665     return;
10666   }
10667 
10668   if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
10669       Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
10670     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
10671         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10672         << (unsigned)isObjectArgument << I + 1
10673         << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
10674         << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
10675     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10676     return;
10677   }
10678 
10679   // Special diagnostic for failure to convert an initializer list, since
10680   // telling the user that it has type void is not useful.
10681   if (FromExpr && isa<InitListExpr>(FromExpr)) {
10682     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
10683         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10684         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10685         << ToTy << (unsigned)isObjectArgument << I + 1
10686         << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1
10687             : Conv.Bad.Kind == BadConversionSequence::too_many_initializers
10688                 ? 2
10689                 : 0);
10690     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10691     return;
10692   }
10693 
10694   // Diagnose references or pointers to incomplete types differently,
10695   // since it's far from impossible that the incompleteness triggered
10696   // the failure.
10697   QualType TempFromTy = FromTy.getNonReferenceType();
10698   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
10699     TempFromTy = PTy->getPointeeType();
10700   if (TempFromTy->isIncompleteType()) {
10701     // Emit the generic diagnostic and, optionally, add the hints to it.
10702     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
10703         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10704         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10705         << ToTy << (unsigned)isObjectArgument << I + 1
10706         << (unsigned)(Cand->Fix.Kind);
10707 
10708     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10709     return;
10710   }
10711 
10712   // Diagnose base -> derived pointer conversions.
10713   unsigned BaseToDerivedConversion = 0;
10714   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
10715     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
10716       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10717                                                FromPtrTy->getPointeeType()) &&
10718           !FromPtrTy->getPointeeType()->isIncompleteType() &&
10719           !ToPtrTy->getPointeeType()->isIncompleteType() &&
10720           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
10721                           FromPtrTy->getPointeeType()))
10722         BaseToDerivedConversion = 1;
10723     }
10724   } else if (const ObjCObjectPointerType *FromPtrTy
10725                                     = FromTy->getAs<ObjCObjectPointerType>()) {
10726     if (const ObjCObjectPointerType *ToPtrTy
10727                                         = ToTy->getAs<ObjCObjectPointerType>())
10728       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
10729         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
10730           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10731                                                 FromPtrTy->getPointeeType()) &&
10732               FromIface->isSuperClassOf(ToIface))
10733             BaseToDerivedConversion = 2;
10734   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
10735     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
10736         !FromTy->isIncompleteType() &&
10737         !ToRefTy->getPointeeType()->isIncompleteType() &&
10738         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
10739       BaseToDerivedConversion = 3;
10740     }
10741   }
10742 
10743   if (BaseToDerivedConversion) {
10744     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
10745         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10746         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10747         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
10748     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10749     return;
10750   }
10751 
10752   if (isa<ObjCObjectPointerType>(CFromTy) &&
10753       isa<PointerType>(CToTy)) {
10754       Qualifiers FromQs = CFromTy.getQualifiers();
10755       Qualifiers ToQs = CToTy.getQualifiers();
10756       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10757         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
10758             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10759             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10760             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
10761         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10762         return;
10763       }
10764   }
10765 
10766   if (TakingCandidateAddress &&
10767       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
10768     return;
10769 
10770   // Emit the generic diagnostic and, optionally, add the hints to it.
10771   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
10772   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10773         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10774         << ToTy << (unsigned)isObjectArgument << I + 1
10775         << (unsigned)(Cand->Fix.Kind);
10776 
10777   // If we can fix the conversion, suggest the FixIts.
10778   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
10779        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
10780     FDiag << *HI;
10781   S.Diag(Fn->getLocation(), FDiag);
10782 
10783   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10784 }
10785 
10786 /// Additional arity mismatch diagnosis specific to a function overload
10787 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
10788 /// over a candidate in any candidate set.
10789 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
10790                                unsigned NumArgs) {
10791   FunctionDecl *Fn = Cand->Function;
10792   unsigned MinParams = Fn->getMinRequiredArguments();
10793 
10794   // With invalid overloaded operators, it's possible that we think we
10795   // have an arity mismatch when in fact it looks like we have the
10796   // right number of arguments, because only overloaded operators have
10797   // the weird behavior of overloading member and non-member functions.
10798   // Just don't report anything.
10799   if (Fn->isInvalidDecl() &&
10800       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
10801     return true;
10802 
10803   if (NumArgs < MinParams) {
10804     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
10805            (Cand->FailureKind == ovl_fail_bad_deduction &&
10806             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
10807   } else {
10808     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
10809            (Cand->FailureKind == ovl_fail_bad_deduction &&
10810             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
10811   }
10812 
10813   return false;
10814 }
10815 
10816 /// General arity mismatch diagnosis over a candidate in a candidate set.
10817 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
10818                                   unsigned NumFormalArgs) {
10819   assert(isa<FunctionDecl>(D) &&
10820       "The templated declaration should at least be a function"
10821       " when diagnosing bad template argument deduction due to too many"
10822       " or too few arguments");
10823 
10824   FunctionDecl *Fn = cast<FunctionDecl>(D);
10825 
10826   // TODO: treat calls to a missing default constructor as a special case
10827   const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
10828   unsigned MinParams = Fn->getMinRequiredArguments();
10829 
10830   // at least / at most / exactly
10831   unsigned mode, modeCount;
10832   if (NumFormalArgs < MinParams) {
10833     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
10834         FnTy->isTemplateVariadic())
10835       mode = 0; // "at least"
10836     else
10837       mode = 2; // "exactly"
10838     modeCount = MinParams;
10839   } else {
10840     if (MinParams != FnTy->getNumParams())
10841       mode = 1; // "at most"
10842     else
10843       mode = 2; // "exactly"
10844     modeCount = FnTy->getNumParams();
10845   }
10846 
10847   std::string Description;
10848   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10849       ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
10850 
10851   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10852     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10853         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10854         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
10855   else
10856     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
10857         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10858         << Description << mode << modeCount << NumFormalArgs;
10859 
10860   MaybeEmitInheritedConstructorNote(S, Found);
10861 }
10862 
10863 /// Arity mismatch diagnosis specific to a function overload candidate.
10864 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
10865                                   unsigned NumFormalArgs) {
10866   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
10867     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10868 }
10869 
10870 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10871   if (TemplateDecl *TD = Templated->getDescribedTemplate())
10872     return TD;
10873   llvm_unreachable("Unsupported: Getting the described template declaration"
10874                    " for bad deduction diagnosis");
10875 }
10876 
10877 /// Diagnose a failed template-argument deduction.
10878 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10879                                  DeductionFailureInfo &DeductionFailure,
10880                                  unsigned NumArgs,
10881                                  bool TakingCandidateAddress) {
10882   TemplateParameter Param = DeductionFailure.getTemplateParameter();
10883   NamedDecl *ParamD;
10884   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10885   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10886   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10887   switch (DeductionFailure.Result) {
10888   case Sema::TDK_Success:
10889     llvm_unreachable("TDK_success while diagnosing bad deduction");
10890 
10891   case Sema::TDK_Incomplete: {
10892     assert(ParamD && "no parameter found for incomplete deduction result");
10893     S.Diag(Templated->getLocation(),
10894            diag::note_ovl_candidate_incomplete_deduction)
10895         << ParamD->getDeclName();
10896     MaybeEmitInheritedConstructorNote(S, Found);
10897     return;
10898   }
10899 
10900   case Sema::TDK_IncompletePack: {
10901     assert(ParamD && "no parameter found for incomplete deduction result");
10902     S.Diag(Templated->getLocation(),
10903            diag::note_ovl_candidate_incomplete_deduction_pack)
10904         << ParamD->getDeclName()
10905         << (DeductionFailure.getFirstArg()->pack_size() + 1)
10906         << *DeductionFailure.getFirstArg();
10907     MaybeEmitInheritedConstructorNote(S, Found);
10908     return;
10909   }
10910 
10911   case Sema::TDK_Underqualified: {
10912     assert(ParamD && "no parameter found for bad qualifiers deduction result");
10913     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10914 
10915     QualType Param = DeductionFailure.getFirstArg()->getAsType();
10916 
10917     // Param will have been canonicalized, but it should just be a
10918     // qualified version of ParamD, so move the qualifiers to that.
10919     QualifierCollector Qs;
10920     Qs.strip(Param);
10921     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10922     assert(S.Context.hasSameType(Param, NonCanonParam));
10923 
10924     // Arg has also been canonicalized, but there's nothing we can do
10925     // about that.  It also doesn't matter as much, because it won't
10926     // have any template parameters in it (because deduction isn't
10927     // done on dependent types).
10928     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10929 
10930     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10931         << ParamD->getDeclName() << Arg << NonCanonParam;
10932     MaybeEmitInheritedConstructorNote(S, Found);
10933     return;
10934   }
10935 
10936   case Sema::TDK_Inconsistent: {
10937     assert(ParamD && "no parameter found for inconsistent deduction result");
10938     int which = 0;
10939     if (isa<TemplateTypeParmDecl>(ParamD))
10940       which = 0;
10941     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10942       // Deduction might have failed because we deduced arguments of two
10943       // different types for a non-type template parameter.
10944       // FIXME: Use a different TDK value for this.
10945       QualType T1 =
10946           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10947       QualType T2 =
10948           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10949       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10950         S.Diag(Templated->getLocation(),
10951                diag::note_ovl_candidate_inconsistent_deduction_types)
10952           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10953           << *DeductionFailure.getSecondArg() << T2;
10954         MaybeEmitInheritedConstructorNote(S, Found);
10955         return;
10956       }
10957 
10958       which = 1;
10959     } else {
10960       which = 2;
10961     }
10962 
10963     // Tweak the diagnostic if the problem is that we deduced packs of
10964     // different arities. We'll print the actual packs anyway in case that
10965     // includes additional useful information.
10966     if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
10967         DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
10968         DeductionFailure.getFirstArg()->pack_size() !=
10969             DeductionFailure.getSecondArg()->pack_size()) {
10970       which = 3;
10971     }
10972 
10973     S.Diag(Templated->getLocation(),
10974            diag::note_ovl_candidate_inconsistent_deduction)
10975         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10976         << *DeductionFailure.getSecondArg();
10977     MaybeEmitInheritedConstructorNote(S, Found);
10978     return;
10979   }
10980 
10981   case Sema::TDK_InvalidExplicitArguments:
10982     assert(ParamD && "no parameter found for invalid explicit arguments");
10983     if (ParamD->getDeclName())
10984       S.Diag(Templated->getLocation(),
10985              diag::note_ovl_candidate_explicit_arg_mismatch_named)
10986           << ParamD->getDeclName();
10987     else {
10988       int index = 0;
10989       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10990         index = TTP->getIndex();
10991       else if (NonTypeTemplateParmDecl *NTTP
10992                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10993         index = NTTP->getIndex();
10994       else
10995         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10996       S.Diag(Templated->getLocation(),
10997              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10998           << (index + 1);
10999     }
11000     MaybeEmitInheritedConstructorNote(S, Found);
11001     return;
11002 
11003   case Sema::TDK_ConstraintsNotSatisfied: {
11004     // Format the template argument list into the argument string.
11005     SmallString<128> TemplateArgString;
11006     TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
11007     TemplateArgString = " ";
11008     TemplateArgString += S.getTemplateArgumentBindingsText(
11009         getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11010     if (TemplateArgString.size() == 1)
11011       TemplateArgString.clear();
11012     S.Diag(Templated->getLocation(),
11013            diag::note_ovl_candidate_unsatisfied_constraints)
11014         << TemplateArgString;
11015 
11016     S.DiagnoseUnsatisfiedConstraint(
11017         static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
11018     return;
11019   }
11020   case Sema::TDK_TooManyArguments:
11021   case Sema::TDK_TooFewArguments:
11022     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
11023     return;
11024 
11025   case Sema::TDK_InstantiationDepth:
11026     S.Diag(Templated->getLocation(),
11027            diag::note_ovl_candidate_instantiation_depth);
11028     MaybeEmitInheritedConstructorNote(S, Found);
11029     return;
11030 
11031   case Sema::TDK_SubstitutionFailure: {
11032     // Format the template argument list into the argument string.
11033     SmallString<128> TemplateArgString;
11034     if (TemplateArgumentList *Args =
11035             DeductionFailure.getTemplateArgumentList()) {
11036       TemplateArgString = " ";
11037       TemplateArgString += S.getTemplateArgumentBindingsText(
11038           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11039       if (TemplateArgString.size() == 1)
11040         TemplateArgString.clear();
11041     }
11042 
11043     // If this candidate was disabled by enable_if, say so.
11044     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
11045     if (PDiag && PDiag->second.getDiagID() ==
11046           diag::err_typename_nested_not_found_enable_if) {
11047       // FIXME: Use the source range of the condition, and the fully-qualified
11048       //        name of the enable_if template. These are both present in PDiag.
11049       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
11050         << "'enable_if'" << TemplateArgString;
11051       return;
11052     }
11053 
11054     // We found a specific requirement that disabled the enable_if.
11055     if (PDiag && PDiag->second.getDiagID() ==
11056         diag::err_typename_nested_not_found_requirement) {
11057       S.Diag(Templated->getLocation(),
11058              diag::note_ovl_candidate_disabled_by_requirement)
11059         << PDiag->second.getStringArg(0) << TemplateArgString;
11060       return;
11061     }
11062 
11063     // Format the SFINAE diagnostic into the argument string.
11064     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
11065     //        formatted message in another diagnostic.
11066     SmallString<128> SFINAEArgString;
11067     SourceRange R;
11068     if (PDiag) {
11069       SFINAEArgString = ": ";
11070       R = SourceRange(PDiag->first, PDiag->first);
11071       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
11072     }
11073 
11074     S.Diag(Templated->getLocation(),
11075            diag::note_ovl_candidate_substitution_failure)
11076         << TemplateArgString << SFINAEArgString << R;
11077     MaybeEmitInheritedConstructorNote(S, Found);
11078     return;
11079   }
11080 
11081   case Sema::TDK_DeducedMismatch:
11082   case Sema::TDK_DeducedMismatchNested: {
11083     // Format the template argument list into the argument string.
11084     SmallString<128> TemplateArgString;
11085     if (TemplateArgumentList *Args =
11086             DeductionFailure.getTemplateArgumentList()) {
11087       TemplateArgString = " ";
11088       TemplateArgString += S.getTemplateArgumentBindingsText(
11089           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11090       if (TemplateArgString.size() == 1)
11091         TemplateArgString.clear();
11092     }
11093 
11094     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
11095         << (*DeductionFailure.getCallArgIndex() + 1)
11096         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
11097         << TemplateArgString
11098         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
11099     break;
11100   }
11101 
11102   case Sema::TDK_NonDeducedMismatch: {
11103     // FIXME: Provide a source location to indicate what we couldn't match.
11104     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
11105     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
11106     if (FirstTA.getKind() == TemplateArgument::Template &&
11107         SecondTA.getKind() == TemplateArgument::Template) {
11108       TemplateName FirstTN = FirstTA.getAsTemplate();
11109       TemplateName SecondTN = SecondTA.getAsTemplate();
11110       if (FirstTN.getKind() == TemplateName::Template &&
11111           SecondTN.getKind() == TemplateName::Template) {
11112         if (FirstTN.getAsTemplateDecl()->getName() ==
11113             SecondTN.getAsTemplateDecl()->getName()) {
11114           // FIXME: This fixes a bad diagnostic where both templates are named
11115           // the same.  This particular case is a bit difficult since:
11116           // 1) It is passed as a string to the diagnostic printer.
11117           // 2) The diagnostic printer only attempts to find a better
11118           //    name for types, not decls.
11119           // Ideally, this should folded into the diagnostic printer.
11120           S.Diag(Templated->getLocation(),
11121                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
11122               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
11123           return;
11124         }
11125       }
11126     }
11127 
11128     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
11129         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
11130       return;
11131 
11132     // FIXME: For generic lambda parameters, check if the function is a lambda
11133     // call operator, and if so, emit a prettier and more informative
11134     // diagnostic that mentions 'auto' and lambda in addition to
11135     // (or instead of?) the canonical template type parameters.
11136     S.Diag(Templated->getLocation(),
11137            diag::note_ovl_candidate_non_deduced_mismatch)
11138         << FirstTA << SecondTA;
11139     return;
11140   }
11141   // TODO: diagnose these individually, then kill off
11142   // note_ovl_candidate_bad_deduction, which is uselessly vague.
11143   case Sema::TDK_MiscellaneousDeductionFailure:
11144     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
11145     MaybeEmitInheritedConstructorNote(S, Found);
11146     return;
11147   case Sema::TDK_CUDATargetMismatch:
11148     S.Diag(Templated->getLocation(),
11149            diag::note_cuda_ovl_candidate_target_mismatch);
11150     return;
11151   }
11152 }
11153 
11154 /// Diagnose a failed template-argument deduction, for function calls.
11155 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
11156                                  unsigned NumArgs,
11157                                  bool TakingCandidateAddress) {
11158   unsigned TDK = Cand->DeductionFailure.Result;
11159   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
11160     if (CheckArityMismatch(S, Cand, NumArgs))
11161       return;
11162   }
11163   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
11164                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
11165 }
11166 
11167 /// CUDA: diagnose an invalid call across targets.
11168 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
11169   FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11170   FunctionDecl *Callee = Cand->Function;
11171 
11172   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
11173                            CalleeTarget = S.IdentifyCUDATarget(Callee);
11174 
11175   std::string FnDesc;
11176   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11177       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
11178                                 Cand->getRewriteKind(), FnDesc);
11179 
11180   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
11181       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11182       << FnDesc /* Ignored */
11183       << CalleeTarget << CallerTarget;
11184 
11185   // This could be an implicit constructor for which we could not infer the
11186   // target due to a collsion. Diagnose that case.
11187   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
11188   if (Meth != nullptr && Meth->isImplicit()) {
11189     CXXRecordDecl *ParentClass = Meth->getParent();
11190     Sema::CXXSpecialMember CSM;
11191 
11192     switch (FnKindPair.first) {
11193     default:
11194       return;
11195     case oc_implicit_default_constructor:
11196       CSM = Sema::CXXDefaultConstructor;
11197       break;
11198     case oc_implicit_copy_constructor:
11199       CSM = Sema::CXXCopyConstructor;
11200       break;
11201     case oc_implicit_move_constructor:
11202       CSM = Sema::CXXMoveConstructor;
11203       break;
11204     case oc_implicit_copy_assignment:
11205       CSM = Sema::CXXCopyAssignment;
11206       break;
11207     case oc_implicit_move_assignment:
11208       CSM = Sema::CXXMoveAssignment;
11209       break;
11210     };
11211 
11212     bool ConstRHS = false;
11213     if (Meth->getNumParams()) {
11214       if (const ReferenceType *RT =
11215               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
11216         ConstRHS = RT->getPointeeType().isConstQualified();
11217       }
11218     }
11219 
11220     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
11221                                               /* ConstRHS */ ConstRHS,
11222                                               /* Diagnose */ true);
11223   }
11224 }
11225 
11226 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
11227   FunctionDecl *Callee = Cand->Function;
11228   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
11229 
11230   S.Diag(Callee->getLocation(),
11231          diag::note_ovl_candidate_disabled_by_function_cond_attr)
11232       << Attr->getCond()->getSourceRange() << Attr->getMessage();
11233 }
11234 
11235 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
11236   ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function);
11237   assert(ES.isExplicit() && "not an explicit candidate");
11238 
11239   unsigned Kind;
11240   switch (Cand->Function->getDeclKind()) {
11241   case Decl::Kind::CXXConstructor:
11242     Kind = 0;
11243     break;
11244   case Decl::Kind::CXXConversion:
11245     Kind = 1;
11246     break;
11247   case Decl::Kind::CXXDeductionGuide:
11248     Kind = Cand->Function->isImplicit() ? 0 : 2;
11249     break;
11250   default:
11251     llvm_unreachable("invalid Decl");
11252   }
11253 
11254   // Note the location of the first (in-class) declaration; a redeclaration
11255   // (particularly an out-of-class definition) will typically lack the
11256   // 'explicit' specifier.
11257   // FIXME: This is probably a good thing to do for all 'candidate' notes.
11258   FunctionDecl *First = Cand->Function->getFirstDecl();
11259   if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
11260     First = Pattern->getFirstDecl();
11261 
11262   S.Diag(First->getLocation(),
11263          diag::note_ovl_candidate_explicit)
11264       << Kind << (ES.getExpr() ? 1 : 0)
11265       << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
11266 }
11267 
11268 /// Generates a 'note' diagnostic for an overload candidate.  We've
11269 /// already generated a primary error at the call site.
11270 ///
11271 /// It really does need to be a single diagnostic with its caret
11272 /// pointed at the candidate declaration.  Yes, this creates some
11273 /// major challenges of technical writing.  Yes, this makes pointing
11274 /// out problems with specific arguments quite awkward.  It's still
11275 /// better than generating twenty screens of text for every failed
11276 /// overload.
11277 ///
11278 /// It would be great to be able to express per-candidate problems
11279 /// more richly for those diagnostic clients that cared, but we'd
11280 /// still have to be just as careful with the default diagnostics.
11281 /// \param CtorDestAS Addr space of object being constructed (for ctor
11282 /// candidates only).
11283 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
11284                                   unsigned NumArgs,
11285                                   bool TakingCandidateAddress,
11286                                   LangAS CtorDestAS = LangAS::Default) {
11287   FunctionDecl *Fn = Cand->Function;
11288   if (shouldSkipNotingLambdaConversionDecl(Fn))
11289     return;
11290 
11291   // There is no physical candidate declaration to point to for OpenCL builtins.
11292   // Except for failed conversions, the notes are identical for each candidate,
11293   // so do not generate such notes.
11294   if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
11295       Cand->FailureKind != ovl_fail_bad_conversion)
11296     return;
11297 
11298   // Note deleted candidates, but only if they're viable.
11299   if (Cand->Viable) {
11300     if (Fn->isDeleted()) {
11301       std::string FnDesc;
11302       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11303           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11304                                     Cand->getRewriteKind(), FnDesc);
11305 
11306       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
11307           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11308           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
11309       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11310       return;
11311     }
11312 
11313     // We don't really have anything else to say about viable candidates.
11314     S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11315     return;
11316   }
11317 
11318   switch (Cand->FailureKind) {
11319   case ovl_fail_too_many_arguments:
11320   case ovl_fail_too_few_arguments:
11321     return DiagnoseArityMismatch(S, Cand, NumArgs);
11322 
11323   case ovl_fail_bad_deduction:
11324     return DiagnoseBadDeduction(S, Cand, NumArgs,
11325                                 TakingCandidateAddress);
11326 
11327   case ovl_fail_illegal_constructor: {
11328     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
11329       << (Fn->getPrimaryTemplate() ? 1 : 0);
11330     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11331     return;
11332   }
11333 
11334   case ovl_fail_object_addrspace_mismatch: {
11335     Qualifiers QualsForPrinting;
11336     QualsForPrinting.setAddressSpace(CtorDestAS);
11337     S.Diag(Fn->getLocation(),
11338            diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
11339         << QualsForPrinting;
11340     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11341     return;
11342   }
11343 
11344   case ovl_fail_trivial_conversion:
11345   case ovl_fail_bad_final_conversion:
11346   case ovl_fail_final_conversion_not_exact:
11347     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11348 
11349   case ovl_fail_bad_conversion: {
11350     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
11351     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
11352       if (Cand->Conversions[I].isBad())
11353         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
11354 
11355     // FIXME: this currently happens when we're called from SemaInit
11356     // when user-conversion overload fails.  Figure out how to handle
11357     // those conditions and diagnose them well.
11358     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11359   }
11360 
11361   case ovl_fail_bad_target:
11362     return DiagnoseBadTarget(S, Cand);
11363 
11364   case ovl_fail_enable_if:
11365     return DiagnoseFailedEnableIfAttr(S, Cand);
11366 
11367   case ovl_fail_explicit:
11368     return DiagnoseFailedExplicitSpec(S, Cand);
11369 
11370   case ovl_fail_inhctor_slice:
11371     // It's generally not interesting to note copy/move constructors here.
11372     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
11373       return;
11374     S.Diag(Fn->getLocation(),
11375            diag::note_ovl_candidate_inherited_constructor_slice)
11376       << (Fn->getPrimaryTemplate() ? 1 : 0)
11377       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
11378     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11379     return;
11380 
11381   case ovl_fail_addr_not_available: {
11382     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
11383     (void)Available;
11384     assert(!Available);
11385     break;
11386   }
11387   case ovl_non_default_multiversion_function:
11388     // Do nothing, these should simply be ignored.
11389     break;
11390 
11391   case ovl_fail_constraints_not_satisfied: {
11392     std::string FnDesc;
11393     std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11394         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11395                                   Cand->getRewriteKind(), FnDesc);
11396 
11397     S.Diag(Fn->getLocation(),
11398            diag::note_ovl_candidate_constraints_not_satisfied)
11399         << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11400         << FnDesc /* Ignored */;
11401     ConstraintSatisfaction Satisfaction;
11402     if (S.CheckFunctionConstraints(Fn, Satisfaction))
11403       break;
11404     S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11405   }
11406   }
11407 }
11408 
11409 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
11410   if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate))
11411     return;
11412 
11413   // Desugar the type of the surrogate down to a function type,
11414   // retaining as many typedefs as possible while still showing
11415   // the function type (and, therefore, its parameter types).
11416   QualType FnType = Cand->Surrogate->getConversionType();
11417   bool isLValueReference = false;
11418   bool isRValueReference = false;
11419   bool isPointer = false;
11420   if (const LValueReferenceType *FnTypeRef =
11421         FnType->getAs<LValueReferenceType>()) {
11422     FnType = FnTypeRef->getPointeeType();
11423     isLValueReference = true;
11424   } else if (const RValueReferenceType *FnTypeRef =
11425                FnType->getAs<RValueReferenceType>()) {
11426     FnType = FnTypeRef->getPointeeType();
11427     isRValueReference = true;
11428   }
11429   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
11430     FnType = FnTypePtr->getPointeeType();
11431     isPointer = true;
11432   }
11433   // Desugar down to a function type.
11434   FnType = QualType(FnType->getAs<FunctionType>(), 0);
11435   // Reconstruct the pointer/reference as appropriate.
11436   if (isPointer) FnType = S.Context.getPointerType(FnType);
11437   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
11438   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
11439 
11440   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
11441     << FnType;
11442 }
11443 
11444 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
11445                                          SourceLocation OpLoc,
11446                                          OverloadCandidate *Cand) {
11447   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
11448   std::string TypeStr("operator");
11449   TypeStr += Opc;
11450   TypeStr += "(";
11451   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
11452   if (Cand->Conversions.size() == 1) {
11453     TypeStr += ")";
11454     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11455   } else {
11456     TypeStr += ", ";
11457     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
11458     TypeStr += ")";
11459     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11460   }
11461 }
11462 
11463 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
11464                                          OverloadCandidate *Cand) {
11465   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
11466     if (ICS.isBad()) break; // all meaningless after first invalid
11467     if (!ICS.isAmbiguous()) continue;
11468 
11469     ICS.DiagnoseAmbiguousConversion(
11470         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
11471   }
11472 }
11473 
11474 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
11475   if (Cand->Function)
11476     return Cand->Function->getLocation();
11477   if (Cand->IsSurrogate)
11478     return Cand->Surrogate->getLocation();
11479   return SourceLocation();
11480 }
11481 
11482 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
11483   switch ((Sema::TemplateDeductionResult)DFI.Result) {
11484   case Sema::TDK_Success:
11485   case Sema::TDK_NonDependentConversionFailure:
11486     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
11487 
11488   case Sema::TDK_Invalid:
11489   case Sema::TDK_Incomplete:
11490   case Sema::TDK_IncompletePack:
11491     return 1;
11492 
11493   case Sema::TDK_Underqualified:
11494   case Sema::TDK_Inconsistent:
11495     return 2;
11496 
11497   case Sema::TDK_SubstitutionFailure:
11498   case Sema::TDK_DeducedMismatch:
11499   case Sema::TDK_ConstraintsNotSatisfied:
11500   case Sema::TDK_DeducedMismatchNested:
11501   case Sema::TDK_NonDeducedMismatch:
11502   case Sema::TDK_MiscellaneousDeductionFailure:
11503   case Sema::TDK_CUDATargetMismatch:
11504     return 3;
11505 
11506   case Sema::TDK_InstantiationDepth:
11507     return 4;
11508 
11509   case Sema::TDK_InvalidExplicitArguments:
11510     return 5;
11511 
11512   case Sema::TDK_TooManyArguments:
11513   case Sema::TDK_TooFewArguments:
11514     return 6;
11515   }
11516   llvm_unreachable("Unhandled deduction result");
11517 }
11518 
11519 namespace {
11520 struct CompareOverloadCandidatesForDisplay {
11521   Sema &S;
11522   SourceLocation Loc;
11523   size_t NumArgs;
11524   OverloadCandidateSet::CandidateSetKind CSK;
11525 
11526   CompareOverloadCandidatesForDisplay(
11527       Sema &S, SourceLocation Loc, size_t NArgs,
11528       OverloadCandidateSet::CandidateSetKind CSK)
11529       : S(S), NumArgs(NArgs), CSK(CSK) {}
11530 
11531   OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
11532     // If there are too many or too few arguments, that's the high-order bit we
11533     // want to sort by, even if the immediate failure kind was something else.
11534     if (C->FailureKind == ovl_fail_too_many_arguments ||
11535         C->FailureKind == ovl_fail_too_few_arguments)
11536       return static_cast<OverloadFailureKind>(C->FailureKind);
11537 
11538     if (C->Function) {
11539       if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
11540         return ovl_fail_too_many_arguments;
11541       if (NumArgs < C->Function->getMinRequiredArguments())
11542         return ovl_fail_too_few_arguments;
11543     }
11544 
11545     return static_cast<OverloadFailureKind>(C->FailureKind);
11546   }
11547 
11548   bool operator()(const OverloadCandidate *L,
11549                   const OverloadCandidate *R) {
11550     // Fast-path this check.
11551     if (L == R) return false;
11552 
11553     // Order first by viability.
11554     if (L->Viable) {
11555       if (!R->Viable) return true;
11556 
11557       // TODO: introduce a tri-valued comparison for overload
11558       // candidates.  Would be more worthwhile if we had a sort
11559       // that could exploit it.
11560       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
11561         return true;
11562       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
11563         return false;
11564     } else if (R->Viable)
11565       return false;
11566 
11567     assert(L->Viable == R->Viable);
11568 
11569     // Criteria by which we can sort non-viable candidates:
11570     if (!L->Viable) {
11571       OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
11572       OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
11573 
11574       // 1. Arity mismatches come after other candidates.
11575       if (LFailureKind == ovl_fail_too_many_arguments ||
11576           LFailureKind == ovl_fail_too_few_arguments) {
11577         if (RFailureKind == ovl_fail_too_many_arguments ||
11578             RFailureKind == ovl_fail_too_few_arguments) {
11579           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
11580           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
11581           if (LDist == RDist) {
11582             if (LFailureKind == RFailureKind)
11583               // Sort non-surrogates before surrogates.
11584               return !L->IsSurrogate && R->IsSurrogate;
11585             // Sort candidates requiring fewer parameters than there were
11586             // arguments given after candidates requiring more parameters
11587             // than there were arguments given.
11588             return LFailureKind == ovl_fail_too_many_arguments;
11589           }
11590           return LDist < RDist;
11591         }
11592         return false;
11593       }
11594       if (RFailureKind == ovl_fail_too_many_arguments ||
11595           RFailureKind == ovl_fail_too_few_arguments)
11596         return true;
11597 
11598       // 2. Bad conversions come first and are ordered by the number
11599       // of bad conversions and quality of good conversions.
11600       if (LFailureKind == ovl_fail_bad_conversion) {
11601         if (RFailureKind != ovl_fail_bad_conversion)
11602           return true;
11603 
11604         // The conversion that can be fixed with a smaller number of changes,
11605         // comes first.
11606         unsigned numLFixes = L->Fix.NumConversionsFixed;
11607         unsigned numRFixes = R->Fix.NumConversionsFixed;
11608         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
11609         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
11610         if (numLFixes != numRFixes) {
11611           return numLFixes < numRFixes;
11612         }
11613 
11614         // If there's any ordering between the defined conversions...
11615         // FIXME: this might not be transitive.
11616         assert(L->Conversions.size() == R->Conversions.size());
11617 
11618         int leftBetter = 0;
11619         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
11620         for (unsigned E = L->Conversions.size(); I != E; ++I) {
11621           switch (CompareImplicitConversionSequences(S, Loc,
11622                                                      L->Conversions[I],
11623                                                      R->Conversions[I])) {
11624           case ImplicitConversionSequence::Better:
11625             leftBetter++;
11626             break;
11627 
11628           case ImplicitConversionSequence::Worse:
11629             leftBetter--;
11630             break;
11631 
11632           case ImplicitConversionSequence::Indistinguishable:
11633             break;
11634           }
11635         }
11636         if (leftBetter > 0) return true;
11637         if (leftBetter < 0) return false;
11638 
11639       } else if (RFailureKind == ovl_fail_bad_conversion)
11640         return false;
11641 
11642       if (LFailureKind == ovl_fail_bad_deduction) {
11643         if (RFailureKind != ovl_fail_bad_deduction)
11644           return true;
11645 
11646         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11647           return RankDeductionFailure(L->DeductionFailure)
11648                < RankDeductionFailure(R->DeductionFailure);
11649       } else if (RFailureKind == ovl_fail_bad_deduction)
11650         return false;
11651 
11652       // TODO: others?
11653     }
11654 
11655     // Sort everything else by location.
11656     SourceLocation LLoc = GetLocationForCandidate(L);
11657     SourceLocation RLoc = GetLocationForCandidate(R);
11658 
11659     // Put candidates without locations (e.g. builtins) at the end.
11660     if (LLoc.isInvalid()) return false;
11661     if (RLoc.isInvalid()) return true;
11662 
11663     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11664   }
11665 };
11666 }
11667 
11668 /// CompleteNonViableCandidate - Normally, overload resolution only
11669 /// computes up to the first bad conversion. Produces the FixIt set if
11670 /// possible.
11671 static void
11672 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
11673                            ArrayRef<Expr *> Args,
11674                            OverloadCandidateSet::CandidateSetKind CSK) {
11675   assert(!Cand->Viable);
11676 
11677   // Don't do anything on failures other than bad conversion.
11678   if (Cand->FailureKind != ovl_fail_bad_conversion)
11679     return;
11680 
11681   // We only want the FixIts if all the arguments can be corrected.
11682   bool Unfixable = false;
11683   // Use a implicit copy initialization to check conversion fixes.
11684   Cand->Fix.setConversionChecker(TryCopyInitialization);
11685 
11686   // Attempt to fix the bad conversion.
11687   unsigned ConvCount = Cand->Conversions.size();
11688   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
11689        ++ConvIdx) {
11690     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
11691     if (Cand->Conversions[ConvIdx].isInitialized() &&
11692         Cand->Conversions[ConvIdx].isBad()) {
11693       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11694       break;
11695     }
11696   }
11697 
11698   // FIXME: this should probably be preserved from the overload
11699   // operation somehow.
11700   bool SuppressUserConversions = false;
11701 
11702   unsigned ConvIdx = 0;
11703   unsigned ArgIdx = 0;
11704   ArrayRef<QualType> ParamTypes;
11705   bool Reversed = Cand->isReversed();
11706 
11707   if (Cand->IsSurrogate) {
11708     QualType ConvType
11709       = Cand->Surrogate->getConversionType().getNonReferenceType();
11710     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11711       ConvType = ConvPtrType->getPointeeType();
11712     ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
11713     // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11714     ConvIdx = 1;
11715   } else if (Cand->Function) {
11716     ParamTypes =
11717         Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
11718     if (isa<CXXMethodDecl>(Cand->Function) &&
11719         !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
11720       // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11721       ConvIdx = 1;
11722       if (CSK == OverloadCandidateSet::CSK_Operator &&
11723           Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
11724           Cand->Function->getDeclName().getCXXOverloadedOperator() !=
11725               OO_Subscript)
11726         // Argument 0 is 'this', which doesn't have a corresponding parameter.
11727         ArgIdx = 1;
11728     }
11729   } else {
11730     // Builtin operator.
11731     assert(ConvCount <= 3);
11732     ParamTypes = Cand->BuiltinParamTypes;
11733   }
11734 
11735   // Fill in the rest of the conversions.
11736   for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
11737        ConvIdx != ConvCount;
11738        ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
11739     assert(ArgIdx < Args.size() && "no argument for this arg conversion");
11740     if (Cand->Conversions[ConvIdx].isInitialized()) {
11741       // We've already checked this conversion.
11742     } else if (ParamIdx < ParamTypes.size()) {
11743       if (ParamTypes[ParamIdx]->isDependentType())
11744         Cand->Conversions[ConvIdx].setAsIdentityConversion(
11745             Args[ArgIdx]->getType());
11746       else {
11747         Cand->Conversions[ConvIdx] =
11748             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
11749                                   SuppressUserConversions,
11750                                   /*InOverloadResolution=*/true,
11751                                   /*AllowObjCWritebackConversion=*/
11752                                   S.getLangOpts().ObjCAutoRefCount);
11753         // Store the FixIt in the candidate if it exists.
11754         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
11755           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11756       }
11757     } else
11758       Cand->Conversions[ConvIdx].setEllipsis();
11759   }
11760 }
11761 
11762 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
11763     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11764     SourceLocation OpLoc,
11765     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11766   // Sort the candidates by viability and position.  Sorting directly would
11767   // be prohibitive, so we make a set of pointers and sort those.
11768   SmallVector<OverloadCandidate*, 32> Cands;
11769   if (OCD == OCD_AllCandidates) Cands.reserve(size());
11770   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11771     if (!Filter(*Cand))
11772       continue;
11773     switch (OCD) {
11774     case OCD_AllCandidates:
11775       if (!Cand->Viable) {
11776         if (!Cand->Function && !Cand->IsSurrogate) {
11777           // This a non-viable builtin candidate.  We do not, in general,
11778           // want to list every possible builtin candidate.
11779           continue;
11780         }
11781         CompleteNonViableCandidate(S, Cand, Args, Kind);
11782       }
11783       break;
11784 
11785     case OCD_ViableCandidates:
11786       if (!Cand->Viable)
11787         continue;
11788       break;
11789 
11790     case OCD_AmbiguousCandidates:
11791       if (!Cand->Best)
11792         continue;
11793       break;
11794     }
11795 
11796     Cands.push_back(Cand);
11797   }
11798 
11799   llvm::stable_sort(
11800       Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
11801 
11802   return Cands;
11803 }
11804 
11805 bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
11806                                             SourceLocation OpLoc) {
11807   bool DeferHint = false;
11808   if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
11809     // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
11810     // host device candidates.
11811     auto WrongSidedCands =
11812         CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
11813           return (Cand.Viable == false &&
11814                   Cand.FailureKind == ovl_fail_bad_target) ||
11815                  (Cand.Function &&
11816                   Cand.Function->template hasAttr<CUDAHostAttr>() &&
11817                   Cand.Function->template hasAttr<CUDADeviceAttr>());
11818         });
11819     DeferHint = !WrongSidedCands.empty();
11820   }
11821   return DeferHint;
11822 }
11823 
11824 /// When overload resolution fails, prints diagnostic messages containing the
11825 /// candidates in the candidate set.
11826 void OverloadCandidateSet::NoteCandidates(
11827     PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
11828     ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
11829     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11830 
11831   auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
11832 
11833   S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
11834 
11835   NoteCandidates(S, Args, Cands, Opc, OpLoc);
11836 
11837   if (OCD == OCD_AmbiguousCandidates)
11838     MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
11839 }
11840 
11841 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
11842                                           ArrayRef<OverloadCandidate *> Cands,
11843                                           StringRef Opc, SourceLocation OpLoc) {
11844   bool ReportedAmbiguousConversions = false;
11845 
11846   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11847   unsigned CandsShown = 0;
11848   auto I = Cands.begin(), E = Cands.end();
11849   for (; I != E; ++I) {
11850     OverloadCandidate *Cand = *I;
11851 
11852     if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
11853         ShowOverloads == Ovl_Best) {
11854       break;
11855     }
11856     ++CandsShown;
11857 
11858     if (Cand->Function)
11859       NoteFunctionCandidate(S, Cand, Args.size(),
11860                             /*TakingCandidateAddress=*/false, DestAS);
11861     else if (Cand->IsSurrogate)
11862       NoteSurrogateCandidate(S, Cand);
11863     else {
11864       assert(Cand->Viable &&
11865              "Non-viable built-in candidates are not added to Cands.");
11866       // Generally we only see ambiguities including viable builtin
11867       // operators if overload resolution got screwed up by an
11868       // ambiguous user-defined conversion.
11869       //
11870       // FIXME: It's quite possible for different conversions to see
11871       // different ambiguities, though.
11872       if (!ReportedAmbiguousConversions) {
11873         NoteAmbiguousUserConversions(S, OpLoc, Cand);
11874         ReportedAmbiguousConversions = true;
11875       }
11876 
11877       // If this is a viable builtin, print it.
11878       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
11879     }
11880   }
11881 
11882   // Inform S.Diags that we've shown an overload set with N elements.  This may
11883   // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
11884   S.Diags.overloadCandidatesShown(CandsShown);
11885 
11886   if (I != E)
11887     S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
11888            shouldDeferDiags(S, Args, OpLoc))
11889         << int(E - I);
11890 }
11891 
11892 static SourceLocation
11893 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
11894   return Cand->Specialization ? Cand->Specialization->getLocation()
11895                               : SourceLocation();
11896 }
11897 
11898 namespace {
11899 struct CompareTemplateSpecCandidatesForDisplay {
11900   Sema &S;
11901   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
11902 
11903   bool operator()(const TemplateSpecCandidate *L,
11904                   const TemplateSpecCandidate *R) {
11905     // Fast-path this check.
11906     if (L == R)
11907       return false;
11908 
11909     // Assuming that both candidates are not matches...
11910 
11911     // Sort by the ranking of deduction failures.
11912     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11913       return RankDeductionFailure(L->DeductionFailure) <
11914              RankDeductionFailure(R->DeductionFailure);
11915 
11916     // Sort everything else by location.
11917     SourceLocation LLoc = GetLocationForCandidate(L);
11918     SourceLocation RLoc = GetLocationForCandidate(R);
11919 
11920     // Put candidates without locations (e.g. builtins) at the end.
11921     if (LLoc.isInvalid())
11922       return false;
11923     if (RLoc.isInvalid())
11924       return true;
11925 
11926     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11927   }
11928 };
11929 }
11930 
11931 /// Diagnose a template argument deduction failure.
11932 /// We are treating these failures as overload failures due to bad
11933 /// deductions.
11934 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
11935                                                  bool ForTakingAddress) {
11936   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
11937                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
11938 }
11939 
11940 void TemplateSpecCandidateSet::destroyCandidates() {
11941   for (iterator i = begin(), e = end(); i != e; ++i) {
11942     i->DeductionFailure.Destroy();
11943   }
11944 }
11945 
11946 void TemplateSpecCandidateSet::clear() {
11947   destroyCandidates();
11948   Candidates.clear();
11949 }
11950 
11951 /// NoteCandidates - When no template specialization match is found, prints
11952 /// diagnostic messages containing the non-matching specializations that form
11953 /// the candidate set.
11954 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
11955 /// OCD == OCD_AllCandidates and Cand->Viable == false.
11956 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
11957   // Sort the candidates by position (assuming no candidate is a match).
11958   // Sorting directly would be prohibitive, so we make a set of pointers
11959   // and sort those.
11960   SmallVector<TemplateSpecCandidate *, 32> Cands;
11961   Cands.reserve(size());
11962   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11963     if (Cand->Specialization)
11964       Cands.push_back(Cand);
11965     // Otherwise, this is a non-matching builtin candidate.  We do not,
11966     // in general, want to list every possible builtin candidate.
11967   }
11968 
11969   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
11970 
11971   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
11972   // for generalization purposes (?).
11973   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11974 
11975   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
11976   unsigned CandsShown = 0;
11977   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11978     TemplateSpecCandidate *Cand = *I;
11979 
11980     // Set an arbitrary limit on the number of candidates we'll spam
11981     // the user with.  FIXME: This limit should depend on details of the
11982     // candidate list.
11983     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
11984       break;
11985     ++CandsShown;
11986 
11987     assert(Cand->Specialization &&
11988            "Non-matching built-in candidates are not added to Cands.");
11989     Cand->NoteDeductionFailure(S, ForTakingAddress);
11990   }
11991 
11992   if (I != E)
11993     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
11994 }
11995 
11996 // [PossiblyAFunctionType]  -->   [Return]
11997 // NonFunctionType --> NonFunctionType
11998 // R (A) --> R(A)
11999 // R (*)(A) --> R (A)
12000 // R (&)(A) --> R (A)
12001 // R (S::*)(A) --> R (A)
12002 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
12003   QualType Ret = PossiblyAFunctionType;
12004   if (const PointerType *ToTypePtr =
12005     PossiblyAFunctionType->getAs<PointerType>())
12006     Ret = ToTypePtr->getPointeeType();
12007   else if (const ReferenceType *ToTypeRef =
12008     PossiblyAFunctionType->getAs<ReferenceType>())
12009     Ret = ToTypeRef->getPointeeType();
12010   else if (const MemberPointerType *MemTypePtr =
12011     PossiblyAFunctionType->getAs<MemberPointerType>())
12012     Ret = MemTypePtr->getPointeeType();
12013   Ret =
12014     Context.getCanonicalType(Ret).getUnqualifiedType();
12015   return Ret;
12016 }
12017 
12018 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
12019                                  bool Complain = true) {
12020   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
12021       S.DeduceReturnType(FD, Loc, Complain))
12022     return true;
12023 
12024   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
12025   if (S.getLangOpts().CPlusPlus17 &&
12026       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
12027       !S.ResolveExceptionSpec(Loc, FPT))
12028     return true;
12029 
12030   return false;
12031 }
12032 
12033 namespace {
12034 // A helper class to help with address of function resolution
12035 // - allows us to avoid passing around all those ugly parameters
12036 class AddressOfFunctionResolver {
12037   Sema& S;
12038   Expr* SourceExpr;
12039   const QualType& TargetType;
12040   QualType TargetFunctionType; // Extracted function type from target type
12041 
12042   bool Complain;
12043   //DeclAccessPair& ResultFunctionAccessPair;
12044   ASTContext& Context;
12045 
12046   bool TargetTypeIsNonStaticMemberFunction;
12047   bool FoundNonTemplateFunction;
12048   bool StaticMemberFunctionFromBoundPointer;
12049   bool HasComplained;
12050 
12051   OverloadExpr::FindResult OvlExprInfo;
12052   OverloadExpr *OvlExpr;
12053   TemplateArgumentListInfo OvlExplicitTemplateArgs;
12054   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
12055   TemplateSpecCandidateSet FailedCandidates;
12056 
12057 public:
12058   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
12059                             const QualType &TargetType, bool Complain)
12060       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
12061         Complain(Complain), Context(S.getASTContext()),
12062         TargetTypeIsNonStaticMemberFunction(
12063             !!TargetType->getAs<MemberPointerType>()),
12064         FoundNonTemplateFunction(false),
12065         StaticMemberFunctionFromBoundPointer(false),
12066         HasComplained(false),
12067         OvlExprInfo(OverloadExpr::find(SourceExpr)),
12068         OvlExpr(OvlExprInfo.Expression),
12069         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
12070     ExtractUnqualifiedFunctionTypeFromTargetType();
12071 
12072     if (TargetFunctionType->isFunctionType()) {
12073       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
12074         if (!UME->isImplicitAccess() &&
12075             !S.ResolveSingleFunctionTemplateSpecialization(UME))
12076           StaticMemberFunctionFromBoundPointer = true;
12077     } else if (OvlExpr->hasExplicitTemplateArgs()) {
12078       DeclAccessPair dap;
12079       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
12080               OvlExpr, false, &dap)) {
12081         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
12082           if (!Method->isStatic()) {
12083             // If the target type is a non-function type and the function found
12084             // is a non-static member function, pretend as if that was the
12085             // target, it's the only possible type to end up with.
12086             TargetTypeIsNonStaticMemberFunction = true;
12087 
12088             // And skip adding the function if its not in the proper form.
12089             // We'll diagnose this due to an empty set of functions.
12090             if (!OvlExprInfo.HasFormOfMemberPointer)
12091               return;
12092           }
12093 
12094         Matches.push_back(std::make_pair(dap, Fn));
12095       }
12096       return;
12097     }
12098 
12099     if (OvlExpr->hasExplicitTemplateArgs())
12100       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
12101 
12102     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
12103       // C++ [over.over]p4:
12104       //   If more than one function is selected, [...]
12105       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
12106         if (FoundNonTemplateFunction)
12107           EliminateAllTemplateMatches();
12108         else
12109           EliminateAllExceptMostSpecializedTemplate();
12110       }
12111     }
12112 
12113     if (S.getLangOpts().CUDA && Matches.size() > 1)
12114       EliminateSuboptimalCudaMatches();
12115   }
12116 
12117   bool hasComplained() const { return HasComplained; }
12118 
12119 private:
12120   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
12121     QualType Discard;
12122     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
12123            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
12124   }
12125 
12126   /// \return true if A is considered a better overload candidate for the
12127   /// desired type than B.
12128   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
12129     // If A doesn't have exactly the correct type, we don't want to classify it
12130     // as "better" than anything else. This way, the user is required to
12131     // disambiguate for us if there are multiple candidates and no exact match.
12132     return candidateHasExactlyCorrectType(A) &&
12133            (!candidateHasExactlyCorrectType(B) ||
12134             compareEnableIfAttrs(S, A, B) == Comparison::Better);
12135   }
12136 
12137   /// \return true if we were able to eliminate all but one overload candidate,
12138   /// false otherwise.
12139   bool eliminiateSuboptimalOverloadCandidates() {
12140     // Same algorithm as overload resolution -- one pass to pick the "best",
12141     // another pass to be sure that nothing is better than the best.
12142     auto Best = Matches.begin();
12143     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
12144       if (isBetterCandidate(I->second, Best->second))
12145         Best = I;
12146 
12147     const FunctionDecl *BestFn = Best->second;
12148     auto IsBestOrInferiorToBest = [this, BestFn](
12149         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
12150       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
12151     };
12152 
12153     // Note: We explicitly leave Matches unmodified if there isn't a clear best
12154     // option, so we can potentially give the user a better error
12155     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
12156       return false;
12157     Matches[0] = *Best;
12158     Matches.resize(1);
12159     return true;
12160   }
12161 
12162   bool isTargetTypeAFunction() const {
12163     return TargetFunctionType->isFunctionType();
12164   }
12165 
12166   // [ToType]     [Return]
12167 
12168   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
12169   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
12170   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
12171   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
12172     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
12173   }
12174 
12175   // return true if any matching specializations were found
12176   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
12177                                    const DeclAccessPair& CurAccessFunPair) {
12178     if (CXXMethodDecl *Method
12179               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
12180       // Skip non-static function templates when converting to pointer, and
12181       // static when converting to member pointer.
12182       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
12183         return false;
12184     }
12185     else if (TargetTypeIsNonStaticMemberFunction)
12186       return false;
12187 
12188     // C++ [over.over]p2:
12189     //   If the name is a function template, template argument deduction is
12190     //   done (14.8.2.2), and if the argument deduction succeeds, the
12191     //   resulting template argument list is used to generate a single
12192     //   function template specialization, which is added to the set of
12193     //   overloaded functions considered.
12194     FunctionDecl *Specialization = nullptr;
12195     TemplateDeductionInfo Info(FailedCandidates.getLocation());
12196     if (Sema::TemplateDeductionResult Result
12197           = S.DeduceTemplateArguments(FunctionTemplate,
12198                                       &OvlExplicitTemplateArgs,
12199                                       TargetFunctionType, Specialization,
12200                                       Info, /*IsAddressOfFunction*/true)) {
12201       // Make a note of the failed deduction for diagnostics.
12202       FailedCandidates.addCandidate()
12203           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
12204                MakeDeductionFailureInfo(Context, Result, Info));
12205       return false;
12206     }
12207 
12208     // Template argument deduction ensures that we have an exact match or
12209     // compatible pointer-to-function arguments that would be adjusted by ICS.
12210     // This function template specicalization works.
12211     assert(S.isSameOrCompatibleFunctionType(
12212               Context.getCanonicalType(Specialization->getType()),
12213               Context.getCanonicalType(TargetFunctionType)));
12214 
12215     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
12216       return false;
12217 
12218     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
12219     return true;
12220   }
12221 
12222   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
12223                                       const DeclAccessPair& CurAccessFunPair) {
12224     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12225       // Skip non-static functions when converting to pointer, and static
12226       // when converting to member pointer.
12227       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
12228         return false;
12229     }
12230     else if (TargetTypeIsNonStaticMemberFunction)
12231       return false;
12232 
12233     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
12234       if (S.getLangOpts().CUDA)
12235         if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true))
12236           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
12237             return false;
12238       if (FunDecl->isMultiVersion()) {
12239         const auto *TA = FunDecl->getAttr<TargetAttr>();
12240         if (TA && !TA->isDefaultVersion())
12241           return false;
12242       }
12243 
12244       // If any candidate has a placeholder return type, trigger its deduction
12245       // now.
12246       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
12247                                Complain)) {
12248         HasComplained |= Complain;
12249         return false;
12250       }
12251 
12252       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
12253         return false;
12254 
12255       // If we're in C, we need to support types that aren't exactly identical.
12256       if (!S.getLangOpts().CPlusPlus ||
12257           candidateHasExactlyCorrectType(FunDecl)) {
12258         Matches.push_back(std::make_pair(
12259             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
12260         FoundNonTemplateFunction = true;
12261         return true;
12262       }
12263     }
12264 
12265     return false;
12266   }
12267 
12268   bool FindAllFunctionsThatMatchTargetTypeExactly() {
12269     bool Ret = false;
12270 
12271     // If the overload expression doesn't have the form of a pointer to
12272     // member, don't try to convert it to a pointer-to-member type.
12273     if (IsInvalidFormOfPointerToMemberFunction())
12274       return false;
12275 
12276     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12277                                E = OvlExpr->decls_end();
12278          I != E; ++I) {
12279       // Look through any using declarations to find the underlying function.
12280       NamedDecl *Fn = (*I)->getUnderlyingDecl();
12281 
12282       // C++ [over.over]p3:
12283       //   Non-member functions and static member functions match
12284       //   targets of type "pointer-to-function" or "reference-to-function."
12285       //   Nonstatic member functions match targets of
12286       //   type "pointer-to-member-function."
12287       // Note that according to DR 247, the containing class does not matter.
12288       if (FunctionTemplateDecl *FunctionTemplate
12289                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
12290         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
12291           Ret = true;
12292       }
12293       // If we have explicit template arguments supplied, skip non-templates.
12294       else if (!OvlExpr->hasExplicitTemplateArgs() &&
12295                AddMatchingNonTemplateFunction(Fn, I.getPair()))
12296         Ret = true;
12297     }
12298     assert(Ret || Matches.empty());
12299     return Ret;
12300   }
12301 
12302   void EliminateAllExceptMostSpecializedTemplate() {
12303     //   [...] and any given function template specialization F1 is
12304     //   eliminated if the set contains a second function template
12305     //   specialization whose function template is more specialized
12306     //   than the function template of F1 according to the partial
12307     //   ordering rules of 14.5.5.2.
12308 
12309     // The algorithm specified above is quadratic. We instead use a
12310     // two-pass algorithm (similar to the one used to identify the
12311     // best viable function in an overload set) that identifies the
12312     // best function template (if it exists).
12313 
12314     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
12315     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
12316       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
12317 
12318     // TODO: It looks like FailedCandidates does not serve much purpose
12319     // here, since the no_viable diagnostic has index 0.
12320     UnresolvedSetIterator Result = S.getMostSpecialized(
12321         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
12322         SourceExpr->getBeginLoc(), S.PDiag(),
12323         S.PDiag(diag::err_addr_ovl_ambiguous)
12324             << Matches[0].second->getDeclName(),
12325         S.PDiag(diag::note_ovl_candidate)
12326             << (unsigned)oc_function << (unsigned)ocs_described_template,
12327         Complain, TargetFunctionType);
12328 
12329     if (Result != MatchesCopy.end()) {
12330       // Make it the first and only element
12331       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
12332       Matches[0].second = cast<FunctionDecl>(*Result);
12333       Matches.resize(1);
12334     } else
12335       HasComplained |= Complain;
12336   }
12337 
12338   void EliminateAllTemplateMatches() {
12339     //   [...] any function template specializations in the set are
12340     //   eliminated if the set also contains a non-template function, [...]
12341     for (unsigned I = 0, N = Matches.size(); I != N; ) {
12342       if (Matches[I].second->getPrimaryTemplate() == nullptr)
12343         ++I;
12344       else {
12345         Matches[I] = Matches[--N];
12346         Matches.resize(N);
12347       }
12348     }
12349   }
12350 
12351   void EliminateSuboptimalCudaMatches() {
12352     S.EraseUnwantedCUDAMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
12353                                Matches);
12354   }
12355 
12356 public:
12357   void ComplainNoMatchesFound() const {
12358     assert(Matches.empty());
12359     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
12360         << OvlExpr->getName() << TargetFunctionType
12361         << OvlExpr->getSourceRange();
12362     if (FailedCandidates.empty())
12363       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12364                                   /*TakingAddress=*/true);
12365     else {
12366       // We have some deduction failure messages. Use them to diagnose
12367       // the function templates, and diagnose the non-template candidates
12368       // normally.
12369       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12370                                  IEnd = OvlExpr->decls_end();
12371            I != IEnd; ++I)
12372         if (FunctionDecl *Fun =
12373                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
12374           if (!functionHasPassObjectSizeParams(Fun))
12375             S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
12376                                     /*TakingAddress=*/true);
12377       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
12378     }
12379   }
12380 
12381   bool IsInvalidFormOfPointerToMemberFunction() const {
12382     return TargetTypeIsNonStaticMemberFunction &&
12383       !OvlExprInfo.HasFormOfMemberPointer;
12384   }
12385 
12386   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
12387       // TODO: Should we condition this on whether any functions might
12388       // have matched, or is it more appropriate to do that in callers?
12389       // TODO: a fixit wouldn't hurt.
12390       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
12391         << TargetType << OvlExpr->getSourceRange();
12392   }
12393 
12394   bool IsStaticMemberFunctionFromBoundPointer() const {
12395     return StaticMemberFunctionFromBoundPointer;
12396   }
12397 
12398   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
12399     S.Diag(OvlExpr->getBeginLoc(),
12400            diag::err_invalid_form_pointer_member_function)
12401         << OvlExpr->getSourceRange();
12402   }
12403 
12404   void ComplainOfInvalidConversion() const {
12405     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
12406         << OvlExpr->getName() << TargetType;
12407   }
12408 
12409   void ComplainMultipleMatchesFound() const {
12410     assert(Matches.size() > 1);
12411     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
12412         << OvlExpr->getName() << OvlExpr->getSourceRange();
12413     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12414                                 /*TakingAddress=*/true);
12415   }
12416 
12417   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
12418 
12419   int getNumMatches() const { return Matches.size(); }
12420 
12421   FunctionDecl* getMatchingFunctionDecl() const {
12422     if (Matches.size() != 1) return nullptr;
12423     return Matches[0].second;
12424   }
12425 
12426   const DeclAccessPair* getMatchingFunctionAccessPair() const {
12427     if (Matches.size() != 1) return nullptr;
12428     return &Matches[0].first;
12429   }
12430 };
12431 }
12432 
12433 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
12434 /// an overloaded function (C++ [over.over]), where @p From is an
12435 /// expression with overloaded function type and @p ToType is the type
12436 /// we're trying to resolve to. For example:
12437 ///
12438 /// @code
12439 /// int f(double);
12440 /// int f(int);
12441 ///
12442 /// int (*pfd)(double) = f; // selects f(double)
12443 /// @endcode
12444 ///
12445 /// This routine returns the resulting FunctionDecl if it could be
12446 /// resolved, and NULL otherwise. When @p Complain is true, this
12447 /// routine will emit diagnostics if there is an error.
12448 FunctionDecl *
12449 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
12450                                          QualType TargetType,
12451                                          bool Complain,
12452                                          DeclAccessPair &FoundResult,
12453                                          bool *pHadMultipleCandidates) {
12454   assert(AddressOfExpr->getType() == Context.OverloadTy);
12455 
12456   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
12457                                      Complain);
12458   int NumMatches = Resolver.getNumMatches();
12459   FunctionDecl *Fn = nullptr;
12460   bool ShouldComplain = Complain && !Resolver.hasComplained();
12461   if (NumMatches == 0 && ShouldComplain) {
12462     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
12463       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
12464     else
12465       Resolver.ComplainNoMatchesFound();
12466   }
12467   else if (NumMatches > 1 && ShouldComplain)
12468     Resolver.ComplainMultipleMatchesFound();
12469   else if (NumMatches == 1) {
12470     Fn = Resolver.getMatchingFunctionDecl();
12471     assert(Fn);
12472     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
12473       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
12474     FoundResult = *Resolver.getMatchingFunctionAccessPair();
12475     if (Complain) {
12476       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
12477         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
12478       else
12479         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
12480     }
12481   }
12482 
12483   if (pHadMultipleCandidates)
12484     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
12485   return Fn;
12486 }
12487 
12488 /// Given an expression that refers to an overloaded function, try to
12489 /// resolve that function to a single function that can have its address taken.
12490 /// This will modify `Pair` iff it returns non-null.
12491 ///
12492 /// This routine can only succeed if from all of the candidates in the overload
12493 /// set for SrcExpr that can have their addresses taken, there is one candidate
12494 /// that is more constrained than the rest.
12495 FunctionDecl *
12496 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
12497   OverloadExpr::FindResult R = OverloadExpr::find(E);
12498   OverloadExpr *Ovl = R.Expression;
12499   bool IsResultAmbiguous = false;
12500   FunctionDecl *Result = nullptr;
12501   DeclAccessPair DAP;
12502   SmallVector<FunctionDecl *, 2> AmbiguousDecls;
12503 
12504   auto CheckMoreConstrained =
12505       [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> {
12506         SmallVector<const Expr *, 1> AC1, AC2;
12507         FD1->getAssociatedConstraints(AC1);
12508         FD2->getAssociatedConstraints(AC2);
12509         bool AtLeastAsConstrained1, AtLeastAsConstrained2;
12510         if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
12511           return None;
12512         if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
12513           return None;
12514         if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
12515           return None;
12516         return AtLeastAsConstrained1;
12517       };
12518 
12519   // Don't use the AddressOfResolver because we're specifically looking for
12520   // cases where we have one overload candidate that lacks
12521   // enable_if/pass_object_size/...
12522   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
12523     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
12524     if (!FD)
12525       return nullptr;
12526 
12527     if (!checkAddressOfFunctionIsAvailable(FD))
12528       continue;
12529 
12530     // We have more than one result - see if it is more constrained than the
12531     // previous one.
12532     if (Result) {
12533       Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD,
12534                                                                         Result);
12535       if (!MoreConstrainedThanPrevious) {
12536         IsResultAmbiguous = true;
12537         AmbiguousDecls.push_back(FD);
12538         continue;
12539       }
12540       if (!*MoreConstrainedThanPrevious)
12541         continue;
12542       // FD is more constrained - replace Result with it.
12543     }
12544     IsResultAmbiguous = false;
12545     DAP = I.getPair();
12546     Result = FD;
12547   }
12548 
12549   if (IsResultAmbiguous)
12550     return nullptr;
12551 
12552   if (Result) {
12553     SmallVector<const Expr *, 1> ResultAC;
12554     // We skipped over some ambiguous declarations which might be ambiguous with
12555     // the selected result.
12556     for (FunctionDecl *Skipped : AmbiguousDecls)
12557       if (!CheckMoreConstrained(Skipped, Result))
12558         return nullptr;
12559     Pair = DAP;
12560   }
12561   return Result;
12562 }
12563 
12564 /// Given an overloaded function, tries to turn it into a non-overloaded
12565 /// function reference using resolveAddressOfSingleOverloadCandidate. This
12566 /// will perform access checks, diagnose the use of the resultant decl, and, if
12567 /// requested, potentially perform a function-to-pointer decay.
12568 ///
12569 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
12570 /// Otherwise, returns true. This may emit diagnostics and return true.
12571 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
12572     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
12573   Expr *E = SrcExpr.get();
12574   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
12575 
12576   DeclAccessPair DAP;
12577   FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
12578   if (!Found || Found->isCPUDispatchMultiVersion() ||
12579       Found->isCPUSpecificMultiVersion())
12580     return false;
12581 
12582   // Emitting multiple diagnostics for a function that is both inaccessible and
12583   // unavailable is consistent with our behavior elsewhere. So, always check
12584   // for both.
12585   DiagnoseUseOfDecl(Found, E->getExprLoc());
12586   CheckAddressOfMemberAccess(E, DAP);
12587   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
12588   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
12589     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
12590   else
12591     SrcExpr = Fixed;
12592   return true;
12593 }
12594 
12595 /// Given an expression that refers to an overloaded function, try to
12596 /// resolve that overloaded function expression down to a single function.
12597 ///
12598 /// This routine can only resolve template-ids that refer to a single function
12599 /// template, where that template-id refers to a single template whose template
12600 /// arguments are either provided by the template-id or have defaults,
12601 /// as described in C++0x [temp.arg.explicit]p3.
12602 ///
12603 /// If no template-ids are found, no diagnostics are emitted and NULL is
12604 /// returned.
12605 FunctionDecl *
12606 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
12607                                                   bool Complain,
12608                                                   DeclAccessPair *FoundResult) {
12609   // C++ [over.over]p1:
12610   //   [...] [Note: any redundant set of parentheses surrounding the
12611   //   overloaded function name is ignored (5.1). ]
12612   // C++ [over.over]p1:
12613   //   [...] The overloaded function name can be preceded by the &
12614   //   operator.
12615 
12616   // If we didn't actually find any template-ids, we're done.
12617   if (!ovl->hasExplicitTemplateArgs())
12618     return nullptr;
12619 
12620   TemplateArgumentListInfo ExplicitTemplateArgs;
12621   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
12622   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
12623 
12624   // Look through all of the overloaded functions, searching for one
12625   // whose type matches exactly.
12626   FunctionDecl *Matched = nullptr;
12627   for (UnresolvedSetIterator I = ovl->decls_begin(),
12628          E = ovl->decls_end(); I != E; ++I) {
12629     // C++0x [temp.arg.explicit]p3:
12630     //   [...] In contexts where deduction is done and fails, or in contexts
12631     //   where deduction is not done, if a template argument list is
12632     //   specified and it, along with any default template arguments,
12633     //   identifies a single function template specialization, then the
12634     //   template-id is an lvalue for the function template specialization.
12635     FunctionTemplateDecl *FunctionTemplate
12636       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
12637 
12638     // C++ [over.over]p2:
12639     //   If the name is a function template, template argument deduction is
12640     //   done (14.8.2.2), and if the argument deduction succeeds, the
12641     //   resulting template argument list is used to generate a single
12642     //   function template specialization, which is added to the set of
12643     //   overloaded functions considered.
12644     FunctionDecl *Specialization = nullptr;
12645     TemplateDeductionInfo Info(FailedCandidates.getLocation());
12646     if (TemplateDeductionResult Result
12647           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
12648                                     Specialization, Info,
12649                                     /*IsAddressOfFunction*/true)) {
12650       // Make a note of the failed deduction for diagnostics.
12651       // TODO: Actually use the failed-deduction info?
12652       FailedCandidates.addCandidate()
12653           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
12654                MakeDeductionFailureInfo(Context, Result, Info));
12655       continue;
12656     }
12657 
12658     assert(Specialization && "no specialization and no error?");
12659 
12660     // Multiple matches; we can't resolve to a single declaration.
12661     if (Matched) {
12662       if (Complain) {
12663         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
12664           << ovl->getName();
12665         NoteAllOverloadCandidates(ovl);
12666       }
12667       return nullptr;
12668     }
12669 
12670     Matched = Specialization;
12671     if (FoundResult) *FoundResult = I.getPair();
12672   }
12673 
12674   if (Matched &&
12675       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
12676     return nullptr;
12677 
12678   return Matched;
12679 }
12680 
12681 // Resolve and fix an overloaded expression that can be resolved
12682 // because it identifies a single function template specialization.
12683 //
12684 // Last three arguments should only be supplied if Complain = true
12685 //
12686 // Return true if it was logically possible to so resolve the
12687 // expression, regardless of whether or not it succeeded.  Always
12688 // returns true if 'complain' is set.
12689 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
12690                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
12691                       bool complain, SourceRange OpRangeForComplaining,
12692                                            QualType DestTypeForComplaining,
12693                                             unsigned DiagIDForComplaining) {
12694   assert(SrcExpr.get()->getType() == Context.OverloadTy);
12695 
12696   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
12697 
12698   DeclAccessPair found;
12699   ExprResult SingleFunctionExpression;
12700   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
12701                            ovl.Expression, /*complain*/ false, &found)) {
12702     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
12703       SrcExpr = ExprError();
12704       return true;
12705     }
12706 
12707     // It is only correct to resolve to an instance method if we're
12708     // resolving a form that's permitted to be a pointer to member.
12709     // Otherwise we'll end up making a bound member expression, which
12710     // is illegal in all the contexts we resolve like this.
12711     if (!ovl.HasFormOfMemberPointer &&
12712         isa<CXXMethodDecl>(fn) &&
12713         cast<CXXMethodDecl>(fn)->isInstance()) {
12714       if (!complain) return false;
12715 
12716       Diag(ovl.Expression->getExprLoc(),
12717            diag::err_bound_member_function)
12718         << 0 << ovl.Expression->getSourceRange();
12719 
12720       // TODO: I believe we only end up here if there's a mix of
12721       // static and non-static candidates (otherwise the expression
12722       // would have 'bound member' type, not 'overload' type).
12723       // Ideally we would note which candidate was chosen and why
12724       // the static candidates were rejected.
12725       SrcExpr = ExprError();
12726       return true;
12727     }
12728 
12729     // Fix the expression to refer to 'fn'.
12730     SingleFunctionExpression =
12731         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
12732 
12733     // If desired, do function-to-pointer decay.
12734     if (doFunctionPointerConverion) {
12735       SingleFunctionExpression =
12736         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
12737       if (SingleFunctionExpression.isInvalid()) {
12738         SrcExpr = ExprError();
12739         return true;
12740       }
12741     }
12742   }
12743 
12744   if (!SingleFunctionExpression.isUsable()) {
12745     if (complain) {
12746       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
12747         << ovl.Expression->getName()
12748         << DestTypeForComplaining
12749         << OpRangeForComplaining
12750         << ovl.Expression->getQualifierLoc().getSourceRange();
12751       NoteAllOverloadCandidates(SrcExpr.get());
12752 
12753       SrcExpr = ExprError();
12754       return true;
12755     }
12756 
12757     return false;
12758   }
12759 
12760   SrcExpr = SingleFunctionExpression;
12761   return true;
12762 }
12763 
12764 /// Add a single candidate to the overload set.
12765 static void AddOverloadedCallCandidate(Sema &S,
12766                                        DeclAccessPair FoundDecl,
12767                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
12768                                        ArrayRef<Expr *> Args,
12769                                        OverloadCandidateSet &CandidateSet,
12770                                        bool PartialOverloading,
12771                                        bool KnownValid) {
12772   NamedDecl *Callee = FoundDecl.getDecl();
12773   if (isa<UsingShadowDecl>(Callee))
12774     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
12775 
12776   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
12777     if (ExplicitTemplateArgs) {
12778       assert(!KnownValid && "Explicit template arguments?");
12779       return;
12780     }
12781     // Prevent ill-formed function decls to be added as overload candidates.
12782     if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
12783       return;
12784 
12785     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
12786                            /*SuppressUserConversions=*/false,
12787                            PartialOverloading);
12788     return;
12789   }
12790 
12791   if (FunctionTemplateDecl *FuncTemplate
12792       = dyn_cast<FunctionTemplateDecl>(Callee)) {
12793     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
12794                                    ExplicitTemplateArgs, Args, CandidateSet,
12795                                    /*SuppressUserConversions=*/false,
12796                                    PartialOverloading);
12797     return;
12798   }
12799 
12800   assert(!KnownValid && "unhandled case in overloaded call candidate");
12801 }
12802 
12803 /// Add the overload candidates named by callee and/or found by argument
12804 /// dependent lookup to the given overload set.
12805 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
12806                                        ArrayRef<Expr *> Args,
12807                                        OverloadCandidateSet &CandidateSet,
12808                                        bool PartialOverloading) {
12809 
12810 #ifndef NDEBUG
12811   // Verify that ArgumentDependentLookup is consistent with the rules
12812   // in C++0x [basic.lookup.argdep]p3:
12813   //
12814   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
12815   //   and let Y be the lookup set produced by argument dependent
12816   //   lookup (defined as follows). If X contains
12817   //
12818   //     -- a declaration of a class member, or
12819   //
12820   //     -- a block-scope function declaration that is not a
12821   //        using-declaration, or
12822   //
12823   //     -- a declaration that is neither a function or a function
12824   //        template
12825   //
12826   //   then Y is empty.
12827 
12828   if (ULE->requiresADL()) {
12829     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12830            E = ULE->decls_end(); I != E; ++I) {
12831       assert(!(*I)->getDeclContext()->isRecord());
12832       assert(isa<UsingShadowDecl>(*I) ||
12833              !(*I)->getDeclContext()->isFunctionOrMethod());
12834       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
12835     }
12836   }
12837 #endif
12838 
12839   // It would be nice to avoid this copy.
12840   TemplateArgumentListInfo TABuffer;
12841   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12842   if (ULE->hasExplicitTemplateArgs()) {
12843     ULE->copyTemplateArgumentsInto(TABuffer);
12844     ExplicitTemplateArgs = &TABuffer;
12845   }
12846 
12847   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12848          E = ULE->decls_end(); I != E; ++I)
12849     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12850                                CandidateSet, PartialOverloading,
12851                                /*KnownValid*/ true);
12852 
12853   if (ULE->requiresADL())
12854     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
12855                                          Args, ExplicitTemplateArgs,
12856                                          CandidateSet, PartialOverloading);
12857 }
12858 
12859 /// Add the call candidates from the given set of lookup results to the given
12860 /// overload set. Non-function lookup results are ignored.
12861 void Sema::AddOverloadedCallCandidates(
12862     LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
12863     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
12864   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12865     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12866                                CandidateSet, false, /*KnownValid*/ false);
12867 }
12868 
12869 /// Determine whether a declaration with the specified name could be moved into
12870 /// a different namespace.
12871 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
12872   switch (Name.getCXXOverloadedOperator()) {
12873   case OO_New: case OO_Array_New:
12874   case OO_Delete: case OO_Array_Delete:
12875     return false;
12876 
12877   default:
12878     return true;
12879   }
12880 }
12881 
12882 /// Attempt to recover from an ill-formed use of a non-dependent name in a
12883 /// template, where the non-dependent name was declared after the template
12884 /// was defined. This is common in code written for a compilers which do not
12885 /// correctly implement two-stage name lookup.
12886 ///
12887 /// Returns true if a viable candidate was found and a diagnostic was issued.
12888 static bool DiagnoseTwoPhaseLookup(
12889     Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
12890     LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
12891     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
12892     CXXRecordDecl **FoundInClass = nullptr) {
12893   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
12894     return false;
12895 
12896   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
12897     if (DC->isTransparentContext())
12898       continue;
12899 
12900     SemaRef.LookupQualifiedName(R, DC);
12901 
12902     if (!R.empty()) {
12903       R.suppressDiagnostics();
12904 
12905       OverloadCandidateSet Candidates(FnLoc, CSK);
12906       SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
12907                                           Candidates);
12908 
12909       OverloadCandidateSet::iterator Best;
12910       OverloadingResult OR =
12911           Candidates.BestViableFunction(SemaRef, FnLoc, Best);
12912 
12913       if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
12914         // We either found non-function declarations or a best viable function
12915         // at class scope. A class-scope lookup result disables ADL. Don't
12916         // look past this, but let the caller know that we found something that
12917         // either is, or might be, usable in this class.
12918         if (FoundInClass) {
12919           *FoundInClass = RD;
12920           if (OR == OR_Success) {
12921             R.clear();
12922             R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
12923             R.resolveKind();
12924           }
12925         }
12926         return false;
12927       }
12928 
12929       if (OR != OR_Success) {
12930         // There wasn't a unique best function or function template.
12931         return false;
12932       }
12933 
12934       // Find the namespaces where ADL would have looked, and suggest
12935       // declaring the function there instead.
12936       Sema::AssociatedNamespaceSet AssociatedNamespaces;
12937       Sema::AssociatedClassSet AssociatedClasses;
12938       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
12939                                                  AssociatedNamespaces,
12940                                                  AssociatedClasses);
12941       Sema::AssociatedNamespaceSet SuggestedNamespaces;
12942       if (canBeDeclaredInNamespace(R.getLookupName())) {
12943         DeclContext *Std = SemaRef.getStdNamespace();
12944         for (Sema::AssociatedNamespaceSet::iterator
12945                it = AssociatedNamespaces.begin(),
12946                end = AssociatedNamespaces.end(); it != end; ++it) {
12947           // Never suggest declaring a function within namespace 'std'.
12948           if (Std && Std->Encloses(*it))
12949             continue;
12950 
12951           // Never suggest declaring a function within a namespace with a
12952           // reserved name, like __gnu_cxx.
12953           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
12954           if (NS &&
12955               NS->getQualifiedNameAsString().find("__") != std::string::npos)
12956             continue;
12957 
12958           SuggestedNamespaces.insert(*it);
12959         }
12960       }
12961 
12962       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
12963         << R.getLookupName();
12964       if (SuggestedNamespaces.empty()) {
12965         SemaRef.Diag(Best->Function->getLocation(),
12966                      diag::note_not_found_by_two_phase_lookup)
12967           << R.getLookupName() << 0;
12968       } else if (SuggestedNamespaces.size() == 1) {
12969         SemaRef.Diag(Best->Function->getLocation(),
12970                      diag::note_not_found_by_two_phase_lookup)
12971           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
12972       } else {
12973         // FIXME: It would be useful to list the associated namespaces here,
12974         // but the diagnostics infrastructure doesn't provide a way to produce
12975         // a localized representation of a list of items.
12976         SemaRef.Diag(Best->Function->getLocation(),
12977                      diag::note_not_found_by_two_phase_lookup)
12978           << R.getLookupName() << 2;
12979       }
12980 
12981       // Try to recover by calling this function.
12982       return true;
12983     }
12984 
12985     R.clear();
12986   }
12987 
12988   return false;
12989 }
12990 
12991 /// Attempt to recover from ill-formed use of a non-dependent operator in a
12992 /// template, where the non-dependent operator was declared after the template
12993 /// was defined.
12994 ///
12995 /// Returns true if a viable candidate was found and a diagnostic was issued.
12996 static bool
12997 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
12998                                SourceLocation OpLoc,
12999                                ArrayRef<Expr *> Args) {
13000   DeclarationName OpName =
13001     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
13002   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
13003   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
13004                                 OverloadCandidateSet::CSK_Operator,
13005                                 /*ExplicitTemplateArgs=*/nullptr, Args);
13006 }
13007 
13008 namespace {
13009 class BuildRecoveryCallExprRAII {
13010   Sema &SemaRef;
13011 public:
13012   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
13013     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
13014     SemaRef.IsBuildingRecoveryCallExpr = true;
13015   }
13016 
13017   ~BuildRecoveryCallExprRAII() {
13018     SemaRef.IsBuildingRecoveryCallExpr = false;
13019   }
13020 };
13021 
13022 }
13023 
13024 /// Attempts to recover from a call where no functions were found.
13025 ///
13026 /// This function will do one of three things:
13027 ///  * Diagnose, recover, and return a recovery expression.
13028 ///  * Diagnose, fail to recover, and return ExprError().
13029 ///  * Do not diagnose, do not recover, and return ExprResult(). The caller is
13030 ///    expected to diagnose as appropriate.
13031 static ExprResult
13032 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
13033                       UnresolvedLookupExpr *ULE,
13034                       SourceLocation LParenLoc,
13035                       MutableArrayRef<Expr *> Args,
13036                       SourceLocation RParenLoc,
13037                       bool EmptyLookup, bool AllowTypoCorrection) {
13038   // Do not try to recover if it is already building a recovery call.
13039   // This stops infinite loops for template instantiations like
13040   //
13041   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
13042   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
13043   if (SemaRef.IsBuildingRecoveryCallExpr)
13044     return ExprResult();
13045   BuildRecoveryCallExprRAII RCE(SemaRef);
13046 
13047   CXXScopeSpec SS;
13048   SS.Adopt(ULE->getQualifierLoc());
13049   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
13050 
13051   TemplateArgumentListInfo TABuffer;
13052   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13053   if (ULE->hasExplicitTemplateArgs()) {
13054     ULE->copyTemplateArgumentsInto(TABuffer);
13055     ExplicitTemplateArgs = &TABuffer;
13056   }
13057 
13058   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
13059                  Sema::LookupOrdinaryName);
13060   CXXRecordDecl *FoundInClass = nullptr;
13061   if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
13062                              OverloadCandidateSet::CSK_Normal,
13063                              ExplicitTemplateArgs, Args, &FoundInClass)) {
13064     // OK, diagnosed a two-phase lookup issue.
13065   } else if (EmptyLookup) {
13066     // Try to recover from an empty lookup with typo correction.
13067     R.clear();
13068     NoTypoCorrectionCCC NoTypoValidator{};
13069     FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
13070                                                 ExplicitTemplateArgs != nullptr,
13071                                                 dyn_cast<MemberExpr>(Fn));
13072     CorrectionCandidateCallback &Validator =
13073         AllowTypoCorrection
13074             ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
13075             : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
13076     if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
13077                                     Args))
13078       return ExprError();
13079   } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
13080     // We found a usable declaration of the name in a dependent base of some
13081     // enclosing class.
13082     // FIXME: We should also explain why the candidates found by name lookup
13083     // were not viable.
13084     if (SemaRef.DiagnoseDependentMemberLookup(R))
13085       return ExprError();
13086   } else {
13087     // We had viable candidates and couldn't recover; let the caller diagnose
13088     // this.
13089     return ExprResult();
13090   }
13091 
13092   // If we get here, we should have issued a diagnostic and formed a recovery
13093   // lookup result.
13094   assert(!R.empty() && "lookup results empty despite recovery");
13095 
13096   // If recovery created an ambiguity, just bail out.
13097   if (R.isAmbiguous()) {
13098     R.suppressDiagnostics();
13099     return ExprError();
13100   }
13101 
13102   // Build an implicit member call if appropriate.  Just drop the
13103   // casts and such from the call, we don't really care.
13104   ExprResult NewFn = ExprError();
13105   if ((*R.begin())->isCXXClassMember())
13106     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
13107                                                     ExplicitTemplateArgs, S);
13108   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
13109     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
13110                                         ExplicitTemplateArgs);
13111   else
13112     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
13113 
13114   if (NewFn.isInvalid())
13115     return ExprError();
13116 
13117   // This shouldn't cause an infinite loop because we're giving it
13118   // an expression with viable lookup results, which should never
13119   // end up here.
13120   return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
13121                                MultiExprArg(Args.data(), Args.size()),
13122                                RParenLoc);
13123 }
13124 
13125 /// Constructs and populates an OverloadedCandidateSet from
13126 /// the given function.
13127 /// \returns true when an the ExprResult output parameter has been set.
13128 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
13129                                   UnresolvedLookupExpr *ULE,
13130                                   MultiExprArg Args,
13131                                   SourceLocation RParenLoc,
13132                                   OverloadCandidateSet *CandidateSet,
13133                                   ExprResult *Result) {
13134 #ifndef NDEBUG
13135   if (ULE->requiresADL()) {
13136     // To do ADL, we must have found an unqualified name.
13137     assert(!ULE->getQualifier() && "qualified name with ADL");
13138 
13139     // We don't perform ADL for implicit declarations of builtins.
13140     // Verify that this was correctly set up.
13141     FunctionDecl *F;
13142     if (ULE->decls_begin() != ULE->decls_end() &&
13143         ULE->decls_begin() + 1 == ULE->decls_end() &&
13144         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
13145         F->getBuiltinID() && F->isImplicit())
13146       llvm_unreachable("performing ADL for builtin");
13147 
13148     // We don't perform ADL in C.
13149     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
13150   }
13151 #endif
13152 
13153   UnbridgedCastsSet UnbridgedCasts;
13154   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
13155     *Result = ExprError();
13156     return true;
13157   }
13158 
13159   // Add the functions denoted by the callee to the set of candidate
13160   // functions, including those from argument-dependent lookup.
13161   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
13162 
13163   if (getLangOpts().MSVCCompat &&
13164       CurContext->isDependentContext() && !isSFINAEContext() &&
13165       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
13166 
13167     OverloadCandidateSet::iterator Best;
13168     if (CandidateSet->empty() ||
13169         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
13170             OR_No_Viable_Function) {
13171       // In Microsoft mode, if we are inside a template class member function
13172       // then create a type dependent CallExpr. The goal is to postpone name
13173       // lookup to instantiation time to be able to search into type dependent
13174       // base classes.
13175       CallExpr *CE =
13176           CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
13177                            RParenLoc, CurFPFeatureOverrides());
13178       CE->markDependentForPostponedNameLookup();
13179       *Result = CE;
13180       return true;
13181     }
13182   }
13183 
13184   if (CandidateSet->empty())
13185     return false;
13186 
13187   UnbridgedCasts.restore();
13188   return false;
13189 }
13190 
13191 // Guess at what the return type for an unresolvable overload should be.
13192 static QualType chooseRecoveryType(OverloadCandidateSet &CS,
13193                                    OverloadCandidateSet::iterator *Best) {
13194   llvm::Optional<QualType> Result;
13195   // Adjust Type after seeing a candidate.
13196   auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
13197     if (!Candidate.Function)
13198       return;
13199     if (Candidate.Function->isInvalidDecl())
13200       return;
13201     QualType T = Candidate.Function->getReturnType();
13202     if (T.isNull())
13203       return;
13204     if (!Result)
13205       Result = T;
13206     else if (Result != T)
13207       Result = QualType();
13208   };
13209 
13210   // Look for an unambiguous type from a progressively larger subset.
13211   // e.g. if types disagree, but all *viable* overloads return int, choose int.
13212   //
13213   // First, consider only the best candidate.
13214   if (Best && *Best != CS.end())
13215     ConsiderCandidate(**Best);
13216   // Next, consider only viable candidates.
13217   if (!Result)
13218     for (const auto &C : CS)
13219       if (C.Viable)
13220         ConsiderCandidate(C);
13221   // Finally, consider all candidates.
13222   if (!Result)
13223     for (const auto &C : CS)
13224       ConsiderCandidate(C);
13225 
13226   if (!Result)
13227     return QualType();
13228   auto Value = *Result;
13229   if (Value.isNull() || Value->isUndeducedType())
13230     return QualType();
13231   return Value;
13232 }
13233 
13234 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
13235 /// the completed call expression. If overload resolution fails, emits
13236 /// diagnostics and returns ExprError()
13237 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
13238                                            UnresolvedLookupExpr *ULE,
13239                                            SourceLocation LParenLoc,
13240                                            MultiExprArg Args,
13241                                            SourceLocation RParenLoc,
13242                                            Expr *ExecConfig,
13243                                            OverloadCandidateSet *CandidateSet,
13244                                            OverloadCandidateSet::iterator *Best,
13245                                            OverloadingResult OverloadResult,
13246                                            bool AllowTypoCorrection) {
13247   switch (OverloadResult) {
13248   case OR_Success: {
13249     FunctionDecl *FDecl = (*Best)->Function;
13250     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
13251     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
13252       return ExprError();
13253     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13254     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
13255                                          ExecConfig, /*IsExecConfig=*/false,
13256                                          (*Best)->IsADLCandidate);
13257   }
13258 
13259   case OR_No_Viable_Function: {
13260     // Try to recover by looking for viable functions which the user might
13261     // have meant to call.
13262     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
13263                                                 Args, RParenLoc,
13264                                                 CandidateSet->empty(),
13265                                                 AllowTypoCorrection);
13266     if (Recovery.isInvalid() || Recovery.isUsable())
13267       return Recovery;
13268 
13269     // If the user passes in a function that we can't take the address of, we
13270     // generally end up emitting really bad error messages. Here, we attempt to
13271     // emit better ones.
13272     for (const Expr *Arg : Args) {
13273       if (!Arg->getType()->isFunctionType())
13274         continue;
13275       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
13276         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13277         if (FD &&
13278             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13279                                                        Arg->getExprLoc()))
13280           return ExprError();
13281       }
13282     }
13283 
13284     CandidateSet->NoteCandidates(
13285         PartialDiagnosticAt(
13286             Fn->getBeginLoc(),
13287             SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
13288                 << ULE->getName() << Fn->getSourceRange()),
13289         SemaRef, OCD_AllCandidates, Args);
13290     break;
13291   }
13292 
13293   case OR_Ambiguous:
13294     CandidateSet->NoteCandidates(
13295         PartialDiagnosticAt(Fn->getBeginLoc(),
13296                             SemaRef.PDiag(diag::err_ovl_ambiguous_call)
13297                                 << ULE->getName() << Fn->getSourceRange()),
13298         SemaRef, OCD_AmbiguousCandidates, Args);
13299     break;
13300 
13301   case OR_Deleted: {
13302     CandidateSet->NoteCandidates(
13303         PartialDiagnosticAt(Fn->getBeginLoc(),
13304                             SemaRef.PDiag(diag::err_ovl_deleted_call)
13305                                 << ULE->getName() << Fn->getSourceRange()),
13306         SemaRef, OCD_AllCandidates, Args);
13307 
13308     // We emitted an error for the unavailable/deleted function call but keep
13309     // the call in the AST.
13310     FunctionDecl *FDecl = (*Best)->Function;
13311     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13312     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
13313                                          ExecConfig, /*IsExecConfig=*/false,
13314                                          (*Best)->IsADLCandidate);
13315   }
13316   }
13317 
13318   // Overload resolution failed, try to recover.
13319   SmallVector<Expr *, 8> SubExprs = {Fn};
13320   SubExprs.append(Args.begin(), Args.end());
13321   return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
13322                                     chooseRecoveryType(*CandidateSet, Best));
13323 }
13324 
13325 static void markUnaddressableCandidatesUnviable(Sema &S,
13326                                                 OverloadCandidateSet &CS) {
13327   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
13328     if (I->Viable &&
13329         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
13330       I->Viable = false;
13331       I->FailureKind = ovl_fail_addr_not_available;
13332     }
13333   }
13334 }
13335 
13336 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
13337 /// (which eventually refers to the declaration Func) and the call
13338 /// arguments Args/NumArgs, attempt to resolve the function call down
13339 /// to a specific function. If overload resolution succeeds, returns
13340 /// the call expression produced by overload resolution.
13341 /// Otherwise, emits diagnostics and returns ExprError.
13342 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
13343                                          UnresolvedLookupExpr *ULE,
13344                                          SourceLocation LParenLoc,
13345                                          MultiExprArg Args,
13346                                          SourceLocation RParenLoc,
13347                                          Expr *ExecConfig,
13348                                          bool AllowTypoCorrection,
13349                                          bool CalleesAddressIsTaken) {
13350   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
13351                                     OverloadCandidateSet::CSK_Normal);
13352   ExprResult result;
13353 
13354   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
13355                              &result))
13356     return result;
13357 
13358   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
13359   // functions that aren't addressible are considered unviable.
13360   if (CalleesAddressIsTaken)
13361     markUnaddressableCandidatesUnviable(*this, CandidateSet);
13362 
13363   OverloadCandidateSet::iterator Best;
13364   OverloadingResult OverloadResult =
13365       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
13366 
13367   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
13368                                   ExecConfig, &CandidateSet, &Best,
13369                                   OverloadResult, AllowTypoCorrection);
13370 }
13371 
13372 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
13373   return Functions.size() > 1 ||
13374          (Functions.size() == 1 &&
13375           isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl()));
13376 }
13377 
13378 ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
13379                                             NestedNameSpecifierLoc NNSLoc,
13380                                             DeclarationNameInfo DNI,
13381                                             const UnresolvedSetImpl &Fns,
13382                                             bool PerformADL) {
13383   return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI,
13384                                       PerformADL, IsOverloaded(Fns),
13385                                       Fns.begin(), Fns.end());
13386 }
13387 
13388 /// Create a unary operation that may resolve to an overloaded
13389 /// operator.
13390 ///
13391 /// \param OpLoc The location of the operator itself (e.g., '*').
13392 ///
13393 /// \param Opc The UnaryOperatorKind that describes this operator.
13394 ///
13395 /// \param Fns The set of non-member functions that will be
13396 /// considered by overload resolution. The caller needs to build this
13397 /// set based on the context using, e.g.,
13398 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13399 /// set should not contain any member functions; those will be added
13400 /// by CreateOverloadedUnaryOp().
13401 ///
13402 /// \param Input The input argument.
13403 ExprResult
13404 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
13405                               const UnresolvedSetImpl &Fns,
13406                               Expr *Input, bool PerformADL) {
13407   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
13408   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
13409   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13410   // TODO: provide better source location info.
13411   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13412 
13413   if (checkPlaceholderForOverload(*this, Input))
13414     return ExprError();
13415 
13416   Expr *Args[2] = { Input, nullptr };
13417   unsigned NumArgs = 1;
13418 
13419   // For post-increment and post-decrement, add the implicit '0' as
13420   // the second argument, so that we know this is a post-increment or
13421   // post-decrement.
13422   if (Opc == UO_PostInc || Opc == UO_PostDec) {
13423     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13424     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
13425                                      SourceLocation());
13426     NumArgs = 2;
13427   }
13428 
13429   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
13430 
13431   if (Input->isTypeDependent()) {
13432     if (Fns.empty())
13433       return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy,
13434                                    VK_PRValue, OK_Ordinary, OpLoc, false,
13435                                    CurFPFeatureOverrides());
13436 
13437     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13438     ExprResult Fn = CreateUnresolvedLookupExpr(
13439         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
13440     if (Fn.isInvalid())
13441       return ExprError();
13442     return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
13443                                        Context.DependentTy, VK_PRValue, OpLoc,
13444                                        CurFPFeatureOverrides());
13445   }
13446 
13447   // Build an empty overload set.
13448   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
13449 
13450   // Add the candidates from the given function set.
13451   AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
13452 
13453   // Add operator candidates that are member functions.
13454   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13455 
13456   // Add candidates from ADL.
13457   if (PerformADL) {
13458     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
13459                                          /*ExplicitTemplateArgs*/nullptr,
13460                                          CandidateSet);
13461   }
13462 
13463   // Add builtin operator candidates.
13464   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13465 
13466   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13467 
13468   // Perform overload resolution.
13469   OverloadCandidateSet::iterator Best;
13470   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13471   case OR_Success: {
13472     // We found a built-in operator or an overloaded operator.
13473     FunctionDecl *FnDecl = Best->Function;
13474 
13475     if (FnDecl) {
13476       Expr *Base = nullptr;
13477       // We matched an overloaded operator. Build a call to that
13478       // operator.
13479 
13480       // Convert the arguments.
13481       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13482         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
13483 
13484         ExprResult InputRes =
13485           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
13486                                               Best->FoundDecl, Method);
13487         if (InputRes.isInvalid())
13488           return ExprError();
13489         Base = Input = InputRes.get();
13490       } else {
13491         // Convert the arguments.
13492         ExprResult InputInit
13493           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13494                                                       Context,
13495                                                       FnDecl->getParamDecl(0)),
13496                                       SourceLocation(),
13497                                       Input);
13498         if (InputInit.isInvalid())
13499           return ExprError();
13500         Input = InputInit.get();
13501       }
13502 
13503       // Build the actual expression node.
13504       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
13505                                                 Base, HadMultipleCandidates,
13506                                                 OpLoc);
13507       if (FnExpr.isInvalid())
13508         return ExprError();
13509 
13510       // Determine the result type.
13511       QualType ResultTy = FnDecl->getReturnType();
13512       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13513       ResultTy = ResultTy.getNonLValueExprType(Context);
13514 
13515       Args[0] = Input;
13516       CallExpr *TheCall = CXXOperatorCallExpr::Create(
13517           Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
13518           CurFPFeatureOverrides(), Best->IsADLCandidate);
13519 
13520       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
13521         return ExprError();
13522 
13523       if (CheckFunctionCall(FnDecl, TheCall,
13524                             FnDecl->getType()->castAs<FunctionProtoType>()))
13525         return ExprError();
13526       return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
13527     } else {
13528       // We matched a built-in operator. Convert the arguments, then
13529       // break out so that we will build the appropriate built-in
13530       // operator node.
13531       ExprResult InputRes = PerformImplicitConversion(
13532           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
13533           CCK_ForBuiltinOverloadedOp);
13534       if (InputRes.isInvalid())
13535         return ExprError();
13536       Input = InputRes.get();
13537       break;
13538     }
13539   }
13540 
13541   case OR_No_Viable_Function:
13542     // This is an erroneous use of an operator which can be overloaded by
13543     // a non-member function. Check for non-member operators which were
13544     // defined too late to be candidates.
13545     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
13546       // FIXME: Recover by calling the found function.
13547       return ExprError();
13548 
13549     // No viable function; fall through to handling this as a
13550     // built-in operator, which will produce an error message for us.
13551     break;
13552 
13553   case OR_Ambiguous:
13554     CandidateSet.NoteCandidates(
13555         PartialDiagnosticAt(OpLoc,
13556                             PDiag(diag::err_ovl_ambiguous_oper_unary)
13557                                 << UnaryOperator::getOpcodeStr(Opc)
13558                                 << Input->getType() << Input->getSourceRange()),
13559         *this, OCD_AmbiguousCandidates, ArgsArray,
13560         UnaryOperator::getOpcodeStr(Opc), OpLoc);
13561     return ExprError();
13562 
13563   case OR_Deleted:
13564     CandidateSet.NoteCandidates(
13565         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
13566                                        << UnaryOperator::getOpcodeStr(Opc)
13567                                        << Input->getSourceRange()),
13568         *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
13569         OpLoc);
13570     return ExprError();
13571   }
13572 
13573   // Either we found no viable overloaded operator or we matched a
13574   // built-in operator. In either case, fall through to trying to
13575   // build a built-in operation.
13576   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13577 }
13578 
13579 /// Perform lookup for an overloaded binary operator.
13580 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
13581                                  OverloadedOperatorKind Op,
13582                                  const UnresolvedSetImpl &Fns,
13583                                  ArrayRef<Expr *> Args, bool PerformADL) {
13584   SourceLocation OpLoc = CandidateSet.getLocation();
13585 
13586   OverloadedOperatorKind ExtraOp =
13587       CandidateSet.getRewriteInfo().AllowRewrittenCandidates
13588           ? getRewrittenOverloadedOperator(Op)
13589           : OO_None;
13590 
13591   // Add the candidates from the given function set. This also adds the
13592   // rewritten candidates using these functions if necessary.
13593   AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
13594 
13595   // Add operator candidates that are member functions.
13596   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13597   if (CandidateSet.getRewriteInfo().shouldAddReversed(Op))
13598     AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
13599                                 OverloadCandidateParamOrder::Reversed);
13600 
13601   // In C++20, also add any rewritten member candidates.
13602   if (ExtraOp) {
13603     AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
13604     if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp))
13605       AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
13606                                   CandidateSet,
13607                                   OverloadCandidateParamOrder::Reversed);
13608   }
13609 
13610   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
13611   // performed for an assignment operator (nor for operator[] nor operator->,
13612   // which don't get here).
13613   if (Op != OO_Equal && PerformADL) {
13614     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13615     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
13616                                          /*ExplicitTemplateArgs*/ nullptr,
13617                                          CandidateSet);
13618     if (ExtraOp) {
13619       DeclarationName ExtraOpName =
13620           Context.DeclarationNames.getCXXOperatorName(ExtraOp);
13621       AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
13622                                            /*ExplicitTemplateArgs*/ nullptr,
13623                                            CandidateSet);
13624     }
13625   }
13626 
13627   // Add builtin operator candidates.
13628   //
13629   // FIXME: We don't add any rewritten candidates here. This is strictly
13630   // incorrect; a builtin candidate could be hidden by a non-viable candidate,
13631   // resulting in our selecting a rewritten builtin candidate. For example:
13632   //
13633   //   enum class E { e };
13634   //   bool operator!=(E, E) requires false;
13635   //   bool k = E::e != E::e;
13636   //
13637   // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
13638   // it seems unreasonable to consider rewritten builtin candidates. A core
13639   // issue has been filed proposing to removed this requirement.
13640   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13641 }
13642 
13643 /// Create a binary operation that may resolve to an overloaded
13644 /// operator.
13645 ///
13646 /// \param OpLoc The location of the operator itself (e.g., '+').
13647 ///
13648 /// \param Opc The BinaryOperatorKind that describes this operator.
13649 ///
13650 /// \param Fns The set of non-member functions that will be
13651 /// considered by overload resolution. The caller needs to build this
13652 /// set based on the context using, e.g.,
13653 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13654 /// set should not contain any member functions; those will be added
13655 /// by CreateOverloadedBinOp().
13656 ///
13657 /// \param LHS Left-hand argument.
13658 /// \param RHS Right-hand argument.
13659 /// \param PerformADL Whether to consider operator candidates found by ADL.
13660 /// \param AllowRewrittenCandidates Whether to consider candidates found by
13661 ///        C++20 operator rewrites.
13662 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
13663 ///        the function in question. Such a function is never a candidate in
13664 ///        our overload resolution. This also enables synthesizing a three-way
13665 ///        comparison from < and == as described in C++20 [class.spaceship]p1.
13666 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
13667                                        BinaryOperatorKind Opc,
13668                                        const UnresolvedSetImpl &Fns, Expr *LHS,
13669                                        Expr *RHS, bool PerformADL,
13670                                        bool AllowRewrittenCandidates,
13671                                        FunctionDecl *DefaultedFn) {
13672   Expr *Args[2] = { LHS, RHS };
13673   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
13674 
13675   if (!getLangOpts().CPlusPlus20)
13676     AllowRewrittenCandidates = false;
13677 
13678   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
13679 
13680   // If either side is type-dependent, create an appropriate dependent
13681   // expression.
13682   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13683     if (Fns.empty()) {
13684       // If there are no functions to store, just build a dependent
13685       // BinaryOperator or CompoundAssignment.
13686       if (BinaryOperator::isCompoundAssignmentOp(Opc))
13687         return CompoundAssignOperator::Create(
13688             Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
13689             OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
13690             Context.DependentTy);
13691       return BinaryOperator::Create(
13692           Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
13693           OK_Ordinary, OpLoc, CurFPFeatureOverrides());
13694     }
13695 
13696     // FIXME: save results of ADL from here?
13697     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13698     // TODO: provide better source location info in DNLoc component.
13699     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13700     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13701     ExprResult Fn = CreateUnresolvedLookupExpr(
13702         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
13703     if (Fn.isInvalid())
13704       return ExprError();
13705     return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
13706                                        Context.DependentTy, VK_PRValue, OpLoc,
13707                                        CurFPFeatureOverrides());
13708   }
13709 
13710   // Always do placeholder-like conversions on the RHS.
13711   if (checkPlaceholderForOverload(*this, Args[1]))
13712     return ExprError();
13713 
13714   // Do placeholder-like conversion on the LHS; note that we should
13715   // not get here with a PseudoObject LHS.
13716   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
13717   if (checkPlaceholderForOverload(*this, Args[0]))
13718     return ExprError();
13719 
13720   // If this is the assignment operator, we only perform overload resolution
13721   // if the left-hand side is a class or enumeration type. This is actually
13722   // a hack. The standard requires that we do overload resolution between the
13723   // various built-in candidates, but as DR507 points out, this can lead to
13724   // problems. So we do it this way, which pretty much follows what GCC does.
13725   // Note that we go the traditional code path for compound assignment forms.
13726   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
13727     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13728 
13729   // If this is the .* operator, which is not overloadable, just
13730   // create a built-in binary operator.
13731   if (Opc == BO_PtrMemD)
13732     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13733 
13734   // Build the overload set.
13735   OverloadCandidateSet CandidateSet(
13736       OpLoc, OverloadCandidateSet::CSK_Operator,
13737       OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates));
13738   if (DefaultedFn)
13739     CandidateSet.exclude(DefaultedFn);
13740   LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
13741 
13742   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13743 
13744   // Perform overload resolution.
13745   OverloadCandidateSet::iterator Best;
13746   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13747     case OR_Success: {
13748       // We found a built-in operator or an overloaded operator.
13749       FunctionDecl *FnDecl = Best->Function;
13750 
13751       bool IsReversed = Best->isReversed();
13752       if (IsReversed)
13753         std::swap(Args[0], Args[1]);
13754 
13755       if (FnDecl) {
13756         Expr *Base = nullptr;
13757         // We matched an overloaded operator. Build a call to that
13758         // operator.
13759 
13760         OverloadedOperatorKind ChosenOp =
13761             FnDecl->getDeclName().getCXXOverloadedOperator();
13762 
13763         // C++2a [over.match.oper]p9:
13764         //   If a rewritten operator== candidate is selected by overload
13765         //   resolution for an operator@, its return type shall be cv bool
13766         if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
13767             !FnDecl->getReturnType()->isBooleanType()) {
13768           bool IsExtension =
13769               FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
13770           Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
13771                                   : diag::err_ovl_rewrite_equalequal_not_bool)
13772               << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
13773               << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13774           Diag(FnDecl->getLocation(), diag::note_declared_at);
13775           if (!IsExtension)
13776             return ExprError();
13777         }
13778 
13779         if (AllowRewrittenCandidates && !IsReversed &&
13780             CandidateSet.getRewriteInfo().isReversible()) {
13781           // We could have reversed this operator, but didn't. Check if some
13782           // reversed form was a viable candidate, and if so, if it had a
13783           // better conversion for either parameter. If so, this call is
13784           // formally ambiguous, and allowing it is an extension.
13785           llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
13786           for (OverloadCandidate &Cand : CandidateSet) {
13787             if (Cand.Viable && Cand.Function && Cand.isReversed() &&
13788                 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) {
13789               for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
13790                 if (CompareImplicitConversionSequences(
13791                         *this, OpLoc, Cand.Conversions[ArgIdx],
13792                         Best->Conversions[ArgIdx]) ==
13793                     ImplicitConversionSequence::Better) {
13794                   AmbiguousWith.push_back(Cand.Function);
13795                   break;
13796                 }
13797               }
13798             }
13799           }
13800 
13801           if (!AmbiguousWith.empty()) {
13802             bool AmbiguousWithSelf =
13803                 AmbiguousWith.size() == 1 &&
13804                 declaresSameEntity(AmbiguousWith.front(), FnDecl);
13805             Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
13806                 << BinaryOperator::getOpcodeStr(Opc)
13807                 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
13808                 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13809             if (AmbiguousWithSelf) {
13810               Diag(FnDecl->getLocation(),
13811                    diag::note_ovl_ambiguous_oper_binary_reversed_self);
13812             } else {
13813               Diag(FnDecl->getLocation(),
13814                    diag::note_ovl_ambiguous_oper_binary_selected_candidate);
13815               for (auto *F : AmbiguousWith)
13816                 Diag(F->getLocation(),
13817                      diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
13818             }
13819           }
13820         }
13821 
13822         // Convert the arguments.
13823         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13824           // Best->Access is only meaningful for class members.
13825           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
13826 
13827           ExprResult Arg1 =
13828             PerformCopyInitialization(
13829               InitializedEntity::InitializeParameter(Context,
13830                                                      FnDecl->getParamDecl(0)),
13831               SourceLocation(), Args[1]);
13832           if (Arg1.isInvalid())
13833             return ExprError();
13834 
13835           ExprResult Arg0 =
13836             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13837                                                 Best->FoundDecl, Method);
13838           if (Arg0.isInvalid())
13839             return ExprError();
13840           Base = Args[0] = Arg0.getAs<Expr>();
13841           Args[1] = RHS = Arg1.getAs<Expr>();
13842         } else {
13843           // Convert the arguments.
13844           ExprResult Arg0 = PerformCopyInitialization(
13845             InitializedEntity::InitializeParameter(Context,
13846                                                    FnDecl->getParamDecl(0)),
13847             SourceLocation(), Args[0]);
13848           if (Arg0.isInvalid())
13849             return ExprError();
13850 
13851           ExprResult Arg1 =
13852             PerformCopyInitialization(
13853               InitializedEntity::InitializeParameter(Context,
13854                                                      FnDecl->getParamDecl(1)),
13855               SourceLocation(), Args[1]);
13856           if (Arg1.isInvalid())
13857             return ExprError();
13858           Args[0] = LHS = Arg0.getAs<Expr>();
13859           Args[1] = RHS = Arg1.getAs<Expr>();
13860         }
13861 
13862         // Build the actual expression node.
13863         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13864                                                   Best->FoundDecl, Base,
13865                                                   HadMultipleCandidates, OpLoc);
13866         if (FnExpr.isInvalid())
13867           return ExprError();
13868 
13869         // Determine the result type.
13870         QualType ResultTy = FnDecl->getReturnType();
13871         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13872         ResultTy = ResultTy.getNonLValueExprType(Context);
13873 
13874         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13875             Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
13876             CurFPFeatureOverrides(), Best->IsADLCandidate);
13877 
13878         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
13879                                 FnDecl))
13880           return ExprError();
13881 
13882         ArrayRef<const Expr *> ArgsArray(Args, 2);
13883         const Expr *ImplicitThis = nullptr;
13884         // Cut off the implicit 'this'.
13885         if (isa<CXXMethodDecl>(FnDecl)) {
13886           ImplicitThis = ArgsArray[0];
13887           ArgsArray = ArgsArray.slice(1);
13888         }
13889 
13890         // Check for a self move.
13891         if (Op == OO_Equal)
13892           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
13893 
13894         if (ImplicitThis) {
13895           QualType ThisType = Context.getPointerType(ImplicitThis->getType());
13896           QualType ThisTypeFromDecl = Context.getPointerType(
13897               cast<CXXMethodDecl>(FnDecl)->getThisObjectType());
13898 
13899           CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
13900                             ThisTypeFromDecl);
13901         }
13902 
13903         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
13904                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
13905                   VariadicDoesNotApply);
13906 
13907         ExprResult R = MaybeBindToTemporary(TheCall);
13908         if (R.isInvalid())
13909           return ExprError();
13910 
13911         R = CheckForImmediateInvocation(R, FnDecl);
13912         if (R.isInvalid())
13913           return ExprError();
13914 
13915         // For a rewritten candidate, we've already reversed the arguments
13916         // if needed. Perform the rest of the rewrite now.
13917         if ((Best->RewriteKind & CRK_DifferentOperator) ||
13918             (Op == OO_Spaceship && IsReversed)) {
13919           if (Op == OO_ExclaimEqual) {
13920             assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
13921             R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
13922           } else {
13923             assert(ChosenOp == OO_Spaceship && "unexpected operator name");
13924             llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13925             Expr *ZeroLiteral =
13926                 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
13927 
13928             Sema::CodeSynthesisContext Ctx;
13929             Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
13930             Ctx.Entity = FnDecl;
13931             pushCodeSynthesisContext(Ctx);
13932 
13933             R = CreateOverloadedBinOp(
13934                 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
13935                 IsReversed ? R.get() : ZeroLiteral, PerformADL,
13936                 /*AllowRewrittenCandidates=*/false);
13937 
13938             popCodeSynthesisContext();
13939           }
13940           if (R.isInvalid())
13941             return ExprError();
13942         } else {
13943           assert(ChosenOp == Op && "unexpected operator name");
13944         }
13945 
13946         // Make a note in the AST if we did any rewriting.
13947         if (Best->RewriteKind != CRK_None)
13948           R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
13949 
13950         return R;
13951       } else {
13952         // We matched a built-in operator. Convert the arguments, then
13953         // break out so that we will build the appropriate built-in
13954         // operator node.
13955         ExprResult ArgsRes0 = PerformImplicitConversion(
13956             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13957             AA_Passing, CCK_ForBuiltinOverloadedOp);
13958         if (ArgsRes0.isInvalid())
13959           return ExprError();
13960         Args[0] = ArgsRes0.get();
13961 
13962         ExprResult ArgsRes1 = PerformImplicitConversion(
13963             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13964             AA_Passing, CCK_ForBuiltinOverloadedOp);
13965         if (ArgsRes1.isInvalid())
13966           return ExprError();
13967         Args[1] = ArgsRes1.get();
13968         break;
13969       }
13970     }
13971 
13972     case OR_No_Viable_Function: {
13973       // C++ [over.match.oper]p9:
13974       //   If the operator is the operator , [...] and there are no
13975       //   viable functions, then the operator is assumed to be the
13976       //   built-in operator and interpreted according to clause 5.
13977       if (Opc == BO_Comma)
13978         break;
13979 
13980       // When defaulting an 'operator<=>', we can try to synthesize a three-way
13981       // compare result using '==' and '<'.
13982       if (DefaultedFn && Opc == BO_Cmp) {
13983         ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
13984                                                           Args[1], DefaultedFn);
13985         if (E.isInvalid() || E.isUsable())
13986           return E;
13987       }
13988 
13989       // For class as left operand for assignment or compound assignment
13990       // operator do not fall through to handling in built-in, but report that
13991       // no overloaded assignment operator found
13992       ExprResult Result = ExprError();
13993       StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
13994       auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
13995                                                    Args, OpLoc);
13996       DeferDiagsRAII DDR(*this,
13997                          CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
13998       if (Args[0]->getType()->isRecordType() &&
13999           Opc >= BO_Assign && Opc <= BO_OrAssign) {
14000         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
14001              << BinaryOperator::getOpcodeStr(Opc)
14002              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14003         if (Args[0]->getType()->isIncompleteType()) {
14004           Diag(OpLoc, diag::note_assign_lhs_incomplete)
14005             << Args[0]->getType()
14006             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14007         }
14008       } else {
14009         // This is an erroneous use of an operator which can be overloaded by
14010         // a non-member function. Check for non-member operators which were
14011         // defined too late to be candidates.
14012         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
14013           // FIXME: Recover by calling the found function.
14014           return ExprError();
14015 
14016         // No viable function; try to create a built-in operation, which will
14017         // produce an error. Then, show the non-viable candidates.
14018         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14019       }
14020       assert(Result.isInvalid() &&
14021              "C++ binary operator overloading is missing candidates!");
14022       CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
14023       return Result;
14024     }
14025 
14026     case OR_Ambiguous:
14027       CandidateSet.NoteCandidates(
14028           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
14029                                          << BinaryOperator::getOpcodeStr(Opc)
14030                                          << Args[0]->getType()
14031                                          << Args[1]->getType()
14032                                          << Args[0]->getSourceRange()
14033                                          << Args[1]->getSourceRange()),
14034           *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
14035           OpLoc);
14036       return ExprError();
14037 
14038     case OR_Deleted:
14039       if (isImplicitlyDeleted(Best->Function)) {
14040         FunctionDecl *DeletedFD = Best->Function;
14041         DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
14042         if (DFK.isSpecialMember()) {
14043           Diag(OpLoc, diag::err_ovl_deleted_special_oper)
14044             << Args[0]->getType() << DFK.asSpecialMember();
14045         } else {
14046           assert(DFK.isComparison());
14047           Diag(OpLoc, diag::err_ovl_deleted_comparison)
14048             << Args[0]->getType() << DeletedFD;
14049         }
14050 
14051         // The user probably meant to call this special member. Just
14052         // explain why it's deleted.
14053         NoteDeletedFunction(DeletedFD);
14054         return ExprError();
14055       }
14056       CandidateSet.NoteCandidates(
14057           PartialDiagnosticAt(
14058               OpLoc, PDiag(diag::err_ovl_deleted_oper)
14059                          << getOperatorSpelling(Best->Function->getDeclName()
14060                                                     .getCXXOverloadedOperator())
14061                          << Args[0]->getSourceRange()
14062                          << Args[1]->getSourceRange()),
14063           *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
14064           OpLoc);
14065       return ExprError();
14066   }
14067 
14068   // We matched a built-in operator; build it.
14069   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14070 }
14071 
14072 ExprResult Sema::BuildSynthesizedThreeWayComparison(
14073     SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
14074     FunctionDecl *DefaultedFn) {
14075   const ComparisonCategoryInfo *Info =
14076       Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
14077   // If we're not producing a known comparison category type, we can't
14078   // synthesize a three-way comparison. Let the caller diagnose this.
14079   if (!Info)
14080     return ExprResult((Expr*)nullptr);
14081 
14082   // If we ever want to perform this synthesis more generally, we will need to
14083   // apply the temporary materialization conversion to the operands.
14084   assert(LHS->isGLValue() && RHS->isGLValue() &&
14085          "cannot use prvalue expressions more than once");
14086   Expr *OrigLHS = LHS;
14087   Expr *OrigRHS = RHS;
14088 
14089   // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
14090   // each of them multiple times below.
14091   LHS = new (Context)
14092       OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
14093                       LHS->getObjectKind(), LHS);
14094   RHS = new (Context)
14095       OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
14096                       RHS->getObjectKind(), RHS);
14097 
14098   ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
14099                                         DefaultedFn);
14100   if (Eq.isInvalid())
14101     return ExprError();
14102 
14103   ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
14104                                           true, DefaultedFn);
14105   if (Less.isInvalid())
14106     return ExprError();
14107 
14108   ExprResult Greater;
14109   if (Info->isPartial()) {
14110     Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
14111                                     DefaultedFn);
14112     if (Greater.isInvalid())
14113       return ExprError();
14114   }
14115 
14116   // Form the list of comparisons we're going to perform.
14117   struct Comparison {
14118     ExprResult Cmp;
14119     ComparisonCategoryResult Result;
14120   } Comparisons[4] =
14121   { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
14122                           : ComparisonCategoryResult::Equivalent},
14123     {Less, ComparisonCategoryResult::Less},
14124     {Greater, ComparisonCategoryResult::Greater},
14125     {ExprResult(), ComparisonCategoryResult::Unordered},
14126   };
14127 
14128   int I = Info->isPartial() ? 3 : 2;
14129 
14130   // Combine the comparisons with suitable conditional expressions.
14131   ExprResult Result;
14132   for (; I >= 0; --I) {
14133     // Build a reference to the comparison category constant.
14134     auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
14135     // FIXME: Missing a constant for a comparison category. Diagnose this?
14136     if (!VI)
14137       return ExprResult((Expr*)nullptr);
14138     ExprResult ThisResult =
14139         BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
14140     if (ThisResult.isInvalid())
14141       return ExprError();
14142 
14143     // Build a conditional unless this is the final case.
14144     if (Result.get()) {
14145       Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
14146                                   ThisResult.get(), Result.get());
14147       if (Result.isInvalid())
14148         return ExprError();
14149     } else {
14150       Result = ThisResult;
14151     }
14152   }
14153 
14154   // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
14155   // bind the OpaqueValueExprs before they're (repeatedly) used.
14156   Expr *SyntacticForm = BinaryOperator::Create(
14157       Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
14158       Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
14159       CurFPFeatureOverrides());
14160   Expr *SemanticForm[] = {LHS, RHS, Result.get()};
14161   return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
14162 }
14163 
14164 static bool PrepareArgumentsForCallToObjectOfClassType(
14165     Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
14166     MultiExprArg Args, SourceLocation LParenLoc) {
14167 
14168   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14169   unsigned NumParams = Proto->getNumParams();
14170   unsigned NumArgsSlots =
14171       MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
14172   // Build the full argument list for the method call (the implicit object
14173   // parameter is placed at the beginning of the list).
14174   MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
14175   bool IsError = false;
14176   // Initialize the implicit object parameter.
14177   // Check the argument types.
14178   for (unsigned i = 0; i != NumParams; i++) {
14179     Expr *Arg;
14180     if (i < Args.size()) {
14181       Arg = Args[i];
14182       ExprResult InputInit =
14183           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
14184                                           S.Context, Method->getParamDecl(i)),
14185                                       SourceLocation(), Arg);
14186       IsError |= InputInit.isInvalid();
14187       Arg = InputInit.getAs<Expr>();
14188     } else {
14189       ExprResult DefArg =
14190           S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14191       if (DefArg.isInvalid()) {
14192         IsError = true;
14193         break;
14194       }
14195       Arg = DefArg.getAs<Expr>();
14196     }
14197 
14198     MethodArgs.push_back(Arg);
14199   }
14200   return IsError;
14201 }
14202 
14203 ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
14204                                                     SourceLocation RLoc,
14205                                                     Expr *Base,
14206                                                     MultiExprArg ArgExpr) {
14207   SmallVector<Expr *, 2> Args;
14208   Args.push_back(Base);
14209   for (auto e : ArgExpr) {
14210     Args.push_back(e);
14211   }
14212   DeclarationName OpName =
14213       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
14214 
14215   SourceRange Range = ArgExpr.empty()
14216                           ? SourceRange{}
14217                           : SourceRange(ArgExpr.front()->getBeginLoc(),
14218                                         ArgExpr.back()->getEndLoc());
14219 
14220   // If either side is type-dependent, create an appropriate dependent
14221   // expression.
14222   if (Expr::hasAnyTypeDependentArguments(Args)) {
14223 
14224     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14225     // CHECKME: no 'operator' keyword?
14226     DeclarationNameInfo OpNameInfo(OpName, LLoc);
14227     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
14228     ExprResult Fn = CreateUnresolvedLookupExpr(
14229         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
14230     if (Fn.isInvalid())
14231       return ExprError();
14232     // Can't add any actual overloads yet
14233 
14234     return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
14235                                        Context.DependentTy, VK_PRValue, RLoc,
14236                                        CurFPFeatureOverrides());
14237   }
14238 
14239   // Handle placeholders
14240   UnbridgedCastsSet UnbridgedCasts;
14241   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14242     return ExprError();
14243   }
14244   // Build an empty overload set.
14245   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
14246 
14247   // Subscript can only be overloaded as a member function.
14248 
14249   // Add operator candidates that are member functions.
14250   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
14251 
14252   // Add builtin operator candidates.
14253   if (Args.size() == 2)
14254     AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
14255 
14256   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14257 
14258   // Perform overload resolution.
14259   OverloadCandidateSet::iterator Best;
14260   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
14261     case OR_Success: {
14262       // We found a built-in operator or an overloaded operator.
14263       FunctionDecl *FnDecl = Best->Function;
14264 
14265       if (FnDecl) {
14266         // We matched an overloaded operator. Build a call to that
14267         // operator.
14268 
14269         CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
14270 
14271         // Convert the arguments.
14272         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
14273         SmallVector<Expr *, 2> MethodArgs;
14274         ExprResult Arg0 = PerformObjectArgumentInitialization(
14275             Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14276         if (Arg0.isInvalid())
14277           return ExprError();
14278 
14279         MethodArgs.push_back(Arg0.get());
14280         bool IsError = PrepareArgumentsForCallToObjectOfClassType(
14281             *this, MethodArgs, Method, ArgExpr, LLoc);
14282         if (IsError)
14283           return ExprError();
14284 
14285         // Build the actual expression node.
14286         DeclarationNameInfo OpLocInfo(OpName, LLoc);
14287         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
14288         ExprResult FnExpr = CreateFunctionRefExpr(
14289             *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
14290             OpLocInfo.getLoc(), OpLocInfo.getInfo());
14291         if (FnExpr.isInvalid())
14292           return ExprError();
14293 
14294         // Determine the result type
14295         QualType ResultTy = FnDecl->getReturnType();
14296         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14297         ResultTy = ResultTy.getNonLValueExprType(Context);
14298 
14299         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14300             Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
14301             CurFPFeatureOverrides());
14302         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
14303           return ExprError();
14304 
14305         if (CheckFunctionCall(Method, TheCall,
14306                               Method->getType()->castAs<FunctionProtoType>()))
14307           return ExprError();
14308 
14309         return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14310                                            FnDecl);
14311       } else {
14312         // We matched a built-in operator. Convert the arguments, then
14313         // break out so that we will build the appropriate built-in
14314         // operator node.
14315         ExprResult ArgsRes0 = PerformImplicitConversion(
14316             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
14317             AA_Passing, CCK_ForBuiltinOverloadedOp);
14318         if (ArgsRes0.isInvalid())
14319           return ExprError();
14320         Args[0] = ArgsRes0.get();
14321 
14322         ExprResult ArgsRes1 = PerformImplicitConversion(
14323             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
14324             AA_Passing, CCK_ForBuiltinOverloadedOp);
14325         if (ArgsRes1.isInvalid())
14326           return ExprError();
14327         Args[1] = ArgsRes1.get();
14328 
14329         break;
14330       }
14331     }
14332 
14333     case OR_No_Viable_Function: {
14334       PartialDiagnostic PD =
14335           CandidateSet.empty()
14336               ? (PDiag(diag::err_ovl_no_oper)
14337                  << Args[0]->getType() << /*subscript*/ 0
14338                  << Args[0]->getSourceRange() << Range)
14339               : (PDiag(diag::err_ovl_no_viable_subscript)
14340                  << Args[0]->getType() << Args[0]->getSourceRange() << Range);
14341       CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
14342                                   OCD_AllCandidates, ArgExpr, "[]", LLoc);
14343       return ExprError();
14344     }
14345 
14346     case OR_Ambiguous:
14347       if (Args.size() == 2) {
14348         CandidateSet.NoteCandidates(
14349             PartialDiagnosticAt(
14350                 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
14351                           << "[]" << Args[0]->getType() << Args[1]->getType()
14352                           << Args[0]->getSourceRange() << Range),
14353             *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
14354       } else {
14355         CandidateSet.NoteCandidates(
14356             PartialDiagnosticAt(LLoc,
14357                                 PDiag(diag::err_ovl_ambiguous_subscript_call)
14358                                     << Args[0]->getType()
14359                                     << Args[0]->getSourceRange() << Range),
14360             *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
14361       }
14362       return ExprError();
14363 
14364     case OR_Deleted:
14365       CandidateSet.NoteCandidates(
14366           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
14367                                         << "[]" << Args[0]->getSourceRange()
14368                                         << Range),
14369           *this, OCD_AllCandidates, Args, "[]", LLoc);
14370       return ExprError();
14371     }
14372 
14373   // We matched a built-in operator; build it.
14374   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
14375 }
14376 
14377 /// BuildCallToMemberFunction - Build a call to a member
14378 /// function. MemExpr is the expression that refers to the member
14379 /// function (and includes the object parameter), Args/NumArgs are the
14380 /// arguments to the function call (not including the object
14381 /// parameter). The caller needs to validate that the member
14382 /// expression refers to a non-static member function or an overloaded
14383 /// member function.
14384 ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
14385                                            SourceLocation LParenLoc,
14386                                            MultiExprArg Args,
14387                                            SourceLocation RParenLoc,
14388                                            Expr *ExecConfig, bool IsExecConfig,
14389                                            bool AllowRecovery) {
14390   assert(MemExprE->getType() == Context.BoundMemberTy ||
14391          MemExprE->getType() == Context.OverloadTy);
14392 
14393   // Dig out the member expression. This holds both the object
14394   // argument and the member function we're referring to.
14395   Expr *NakedMemExpr = MemExprE->IgnoreParens();
14396 
14397   // Determine whether this is a call to a pointer-to-member function.
14398   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
14399     assert(op->getType() == Context.BoundMemberTy);
14400     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
14401 
14402     QualType fnType =
14403       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
14404 
14405     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
14406     QualType resultType = proto->getCallResultType(Context);
14407     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
14408 
14409     // Check that the object type isn't more qualified than the
14410     // member function we're calling.
14411     Qualifiers funcQuals = proto->getMethodQuals();
14412 
14413     QualType objectType = op->getLHS()->getType();
14414     if (op->getOpcode() == BO_PtrMemI)
14415       objectType = objectType->castAs<PointerType>()->getPointeeType();
14416     Qualifiers objectQuals = objectType.getQualifiers();
14417 
14418     Qualifiers difference = objectQuals - funcQuals;
14419     difference.removeObjCGCAttr();
14420     difference.removeAddressSpace();
14421     if (difference) {
14422       std::string qualsString = difference.getAsString();
14423       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
14424         << fnType.getUnqualifiedType()
14425         << qualsString
14426         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
14427     }
14428 
14429     CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
14430         Context, MemExprE, Args, resultType, valueKind, RParenLoc,
14431         CurFPFeatureOverrides(), proto->getNumParams());
14432 
14433     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
14434                             call, nullptr))
14435       return ExprError();
14436 
14437     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
14438       return ExprError();
14439 
14440     if (CheckOtherCall(call, proto))
14441       return ExprError();
14442 
14443     return MaybeBindToTemporary(call);
14444   }
14445 
14446   // We only try to build a recovery expr at this level if we can preserve
14447   // the return type, otherwise we return ExprError() and let the caller
14448   // recover.
14449   auto BuildRecoveryExpr = [&](QualType Type) {
14450     if (!AllowRecovery)
14451       return ExprError();
14452     std::vector<Expr *> SubExprs = {MemExprE};
14453     llvm::append_range(SubExprs, Args);
14454     return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
14455                               Type);
14456   };
14457   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
14458     return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
14459                             RParenLoc, CurFPFeatureOverrides());
14460 
14461   UnbridgedCastsSet UnbridgedCasts;
14462   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14463     return ExprError();
14464 
14465   MemberExpr *MemExpr;
14466   CXXMethodDecl *Method = nullptr;
14467   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
14468   NestedNameSpecifier *Qualifier = nullptr;
14469   if (isa<MemberExpr>(NakedMemExpr)) {
14470     MemExpr = cast<MemberExpr>(NakedMemExpr);
14471     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
14472     FoundDecl = MemExpr->getFoundDecl();
14473     Qualifier = MemExpr->getQualifier();
14474     UnbridgedCasts.restore();
14475   } else {
14476     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
14477     Qualifier = UnresExpr->getQualifier();
14478 
14479     QualType ObjectType = UnresExpr->getBaseType();
14480     Expr::Classification ObjectClassification
14481       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
14482                             : UnresExpr->getBase()->Classify(Context);
14483 
14484     // Add overload candidates
14485     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
14486                                       OverloadCandidateSet::CSK_Normal);
14487 
14488     // FIXME: avoid copy.
14489     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14490     if (UnresExpr->hasExplicitTemplateArgs()) {
14491       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14492       TemplateArgs = &TemplateArgsBuffer;
14493     }
14494 
14495     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
14496            E = UnresExpr->decls_end(); I != E; ++I) {
14497 
14498       NamedDecl *Func = *I;
14499       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
14500       if (isa<UsingShadowDecl>(Func))
14501         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
14502 
14503 
14504       // Microsoft supports direct constructor calls.
14505       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
14506         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
14507                              CandidateSet,
14508                              /*SuppressUserConversions*/ false);
14509       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
14510         // If explicit template arguments were provided, we can't call a
14511         // non-template member function.
14512         if (TemplateArgs)
14513           continue;
14514 
14515         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
14516                            ObjectClassification, Args, CandidateSet,
14517                            /*SuppressUserConversions=*/false);
14518       } else {
14519         AddMethodTemplateCandidate(
14520             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
14521             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
14522             /*SuppressUserConversions=*/false);
14523       }
14524     }
14525 
14526     DeclarationName DeclName = UnresExpr->getMemberName();
14527 
14528     UnbridgedCasts.restore();
14529 
14530     OverloadCandidateSet::iterator Best;
14531     bool Succeeded = false;
14532     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
14533                                             Best)) {
14534     case OR_Success:
14535       Method = cast<CXXMethodDecl>(Best->Function);
14536       FoundDecl = Best->FoundDecl;
14537       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
14538       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
14539         break;
14540       // If FoundDecl is different from Method (such as if one is a template
14541       // and the other a specialization), make sure DiagnoseUseOfDecl is
14542       // called on both.
14543       // FIXME: This would be more comprehensively addressed by modifying
14544       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
14545       // being used.
14546       if (Method != FoundDecl.getDecl() &&
14547                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
14548         break;
14549       Succeeded = true;
14550       break;
14551 
14552     case OR_No_Viable_Function:
14553       CandidateSet.NoteCandidates(
14554           PartialDiagnosticAt(
14555               UnresExpr->getMemberLoc(),
14556               PDiag(diag::err_ovl_no_viable_member_function_in_call)
14557                   << DeclName << MemExprE->getSourceRange()),
14558           *this, OCD_AllCandidates, Args);
14559       break;
14560     case OR_Ambiguous:
14561       CandidateSet.NoteCandidates(
14562           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14563                               PDiag(diag::err_ovl_ambiguous_member_call)
14564                                   << DeclName << MemExprE->getSourceRange()),
14565           *this, OCD_AmbiguousCandidates, Args);
14566       break;
14567     case OR_Deleted:
14568       CandidateSet.NoteCandidates(
14569           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14570                               PDiag(diag::err_ovl_deleted_member_call)
14571                                   << DeclName << MemExprE->getSourceRange()),
14572           *this, OCD_AllCandidates, Args);
14573       break;
14574     }
14575     // Overload resolution fails, try to recover.
14576     if (!Succeeded)
14577       return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
14578 
14579     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
14580 
14581     // If overload resolution picked a static member, build a
14582     // non-member call based on that function.
14583     if (Method->isStatic()) {
14584       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
14585                                    ExecConfig, IsExecConfig);
14586     }
14587 
14588     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
14589   }
14590 
14591   QualType ResultType = Method->getReturnType();
14592   ExprValueKind VK = Expr::getValueKindForType(ResultType);
14593   ResultType = ResultType.getNonLValueExprType(Context);
14594 
14595   assert(Method && "Member call to something that isn't a method?");
14596   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14597   CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create(
14598       Context, MemExprE, Args, ResultType, VK, RParenLoc,
14599       CurFPFeatureOverrides(), Proto->getNumParams());
14600 
14601   // Check for a valid return type.
14602   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
14603                           TheCall, Method))
14604     return BuildRecoveryExpr(ResultType);
14605 
14606   // Convert the object argument (for a non-static member function call).
14607   // We only need to do this if there was actually an overload; otherwise
14608   // it was done at lookup.
14609   if (!Method->isStatic()) {
14610     ExprResult ObjectArg =
14611       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
14612                                           FoundDecl, Method);
14613     if (ObjectArg.isInvalid())
14614       return ExprError();
14615     MemExpr->setBase(ObjectArg.get());
14616   }
14617 
14618   // Convert the rest of the arguments
14619   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
14620                               RParenLoc))
14621     return BuildRecoveryExpr(ResultType);
14622 
14623   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14624 
14625   if (CheckFunctionCall(Method, TheCall, Proto))
14626     return ExprError();
14627 
14628   // In the case the method to call was not selected by the overloading
14629   // resolution process, we still need to handle the enable_if attribute. Do
14630   // that here, so it will not hide previous -- and more relevant -- errors.
14631   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
14632     if (const EnableIfAttr *Attr =
14633             CheckEnableIf(Method, LParenLoc, Args, true)) {
14634       Diag(MemE->getMemberLoc(),
14635            diag::err_ovl_no_viable_member_function_in_call)
14636           << Method << Method->getSourceRange();
14637       Diag(Method->getLocation(),
14638            diag::note_ovl_candidate_disabled_by_function_cond_attr)
14639           << Attr->getCond()->getSourceRange() << Attr->getMessage();
14640       return ExprError();
14641     }
14642   }
14643 
14644   if ((isa<CXXConstructorDecl>(CurContext) ||
14645        isa<CXXDestructorDecl>(CurContext)) &&
14646       TheCall->getMethodDecl()->isPure()) {
14647     const CXXMethodDecl *MD = TheCall->getMethodDecl();
14648 
14649     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
14650         MemExpr->performsVirtualDispatch(getLangOpts())) {
14651       Diag(MemExpr->getBeginLoc(),
14652            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
14653           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
14654           << MD->getParent();
14655 
14656       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
14657       if (getLangOpts().AppleKext)
14658         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
14659             << MD->getParent() << MD->getDeclName();
14660     }
14661   }
14662 
14663   if (CXXDestructorDecl *DD =
14664           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
14665     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
14666     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
14667     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
14668                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
14669                          MemExpr->getMemberLoc());
14670   }
14671 
14672   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14673                                      TheCall->getMethodDecl());
14674 }
14675 
14676 /// BuildCallToObjectOfClassType - Build a call to an object of class
14677 /// type (C++ [over.call.object]), which can end up invoking an
14678 /// overloaded function call operator (@c operator()) or performing a
14679 /// user-defined conversion on the object argument.
14680 ExprResult
14681 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
14682                                    SourceLocation LParenLoc,
14683                                    MultiExprArg Args,
14684                                    SourceLocation RParenLoc) {
14685   if (checkPlaceholderForOverload(*this, Obj))
14686     return ExprError();
14687   ExprResult Object = Obj;
14688 
14689   UnbridgedCastsSet UnbridgedCasts;
14690   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14691     return ExprError();
14692 
14693   assert(Object.get()->getType()->isRecordType() &&
14694          "Requires object type argument");
14695 
14696   // C++ [over.call.object]p1:
14697   //  If the primary-expression E in the function call syntax
14698   //  evaluates to a class object of type "cv T", then the set of
14699   //  candidate functions includes at least the function call
14700   //  operators of T. The function call operators of T are obtained by
14701   //  ordinary lookup of the name operator() in the context of
14702   //  (E).operator().
14703   OverloadCandidateSet CandidateSet(LParenLoc,
14704                                     OverloadCandidateSet::CSK_Operator);
14705   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
14706 
14707   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
14708                           diag::err_incomplete_object_call, Object.get()))
14709     return true;
14710 
14711   const auto *Record = Object.get()->getType()->castAs<RecordType>();
14712   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
14713   LookupQualifiedName(R, Record->getDecl());
14714   R.suppressDiagnostics();
14715 
14716   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14717        Oper != OperEnd; ++Oper) {
14718     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
14719                        Object.get()->Classify(Context), Args, CandidateSet,
14720                        /*SuppressUserConversion=*/false);
14721   }
14722 
14723   // C++ [over.call.object]p2:
14724   //   In addition, for each (non-explicit in C++0x) conversion function
14725   //   declared in T of the form
14726   //
14727   //        operator conversion-type-id () cv-qualifier;
14728   //
14729   //   where cv-qualifier is the same cv-qualification as, or a
14730   //   greater cv-qualification than, cv, and where conversion-type-id
14731   //   denotes the type "pointer to function of (P1,...,Pn) returning
14732   //   R", or the type "reference to pointer to function of
14733   //   (P1,...,Pn) returning R", or the type "reference to function
14734   //   of (P1,...,Pn) returning R", a surrogate call function [...]
14735   //   is also considered as a candidate function. Similarly,
14736   //   surrogate call functions are added to the set of candidate
14737   //   functions for each conversion function declared in an
14738   //   accessible base class provided the function is not hidden
14739   //   within T by another intervening declaration.
14740   const auto &Conversions =
14741       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
14742   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
14743     NamedDecl *D = *I;
14744     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
14745     if (isa<UsingShadowDecl>(D))
14746       D = cast<UsingShadowDecl>(D)->getTargetDecl();
14747 
14748     // Skip over templated conversion functions; they aren't
14749     // surrogates.
14750     if (isa<FunctionTemplateDecl>(D))
14751       continue;
14752 
14753     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
14754     if (!Conv->isExplicit()) {
14755       // Strip the reference type (if any) and then the pointer type (if
14756       // any) to get down to what might be a function type.
14757       QualType ConvType = Conv->getConversionType().getNonReferenceType();
14758       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
14759         ConvType = ConvPtrType->getPointeeType();
14760 
14761       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
14762       {
14763         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
14764                               Object.get(), Args, CandidateSet);
14765       }
14766     }
14767   }
14768 
14769   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14770 
14771   // Perform overload resolution.
14772   OverloadCandidateSet::iterator Best;
14773   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
14774                                           Best)) {
14775   case OR_Success:
14776     // Overload resolution succeeded; we'll build the appropriate call
14777     // below.
14778     break;
14779 
14780   case OR_No_Viable_Function: {
14781     PartialDiagnostic PD =
14782         CandidateSet.empty()
14783             ? (PDiag(diag::err_ovl_no_oper)
14784                << Object.get()->getType() << /*call*/ 1
14785                << Object.get()->getSourceRange())
14786             : (PDiag(diag::err_ovl_no_viable_object_call)
14787                << Object.get()->getType() << Object.get()->getSourceRange());
14788     CandidateSet.NoteCandidates(
14789         PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
14790         OCD_AllCandidates, Args);
14791     break;
14792   }
14793   case OR_Ambiguous:
14794     CandidateSet.NoteCandidates(
14795         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14796                             PDiag(diag::err_ovl_ambiguous_object_call)
14797                                 << Object.get()->getType()
14798                                 << Object.get()->getSourceRange()),
14799         *this, OCD_AmbiguousCandidates, Args);
14800     break;
14801 
14802   case OR_Deleted:
14803     CandidateSet.NoteCandidates(
14804         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14805                             PDiag(diag::err_ovl_deleted_object_call)
14806                                 << Object.get()->getType()
14807                                 << Object.get()->getSourceRange()),
14808         *this, OCD_AllCandidates, Args);
14809     break;
14810   }
14811 
14812   if (Best == CandidateSet.end())
14813     return true;
14814 
14815   UnbridgedCasts.restore();
14816 
14817   if (Best->Function == nullptr) {
14818     // Since there is no function declaration, this is one of the
14819     // surrogate candidates. Dig out the conversion function.
14820     CXXConversionDecl *Conv
14821       = cast<CXXConversionDecl>(
14822                          Best->Conversions[0].UserDefined.ConversionFunction);
14823 
14824     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
14825                               Best->FoundDecl);
14826     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
14827       return ExprError();
14828     assert(Conv == Best->FoundDecl.getDecl() &&
14829              "Found Decl & conversion-to-functionptr should be same, right?!");
14830     // We selected one of the surrogate functions that converts the
14831     // object parameter to a function pointer. Perform the conversion
14832     // on the object argument, then let BuildCallExpr finish the job.
14833 
14834     // Create an implicit member expr to refer to the conversion operator.
14835     // and then call it.
14836     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
14837                                              Conv, HadMultipleCandidates);
14838     if (Call.isInvalid())
14839       return ExprError();
14840     // Record usage of conversion in an implicit cast.
14841     Call = ImplicitCastExpr::Create(
14842         Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
14843         nullptr, VK_PRValue, CurFPFeatureOverrides());
14844 
14845     return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
14846   }
14847 
14848   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
14849 
14850   // We found an overloaded operator(). Build a CXXOperatorCallExpr
14851   // that calls this method, using Object for the implicit object
14852   // parameter and passing along the remaining arguments.
14853   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14854 
14855   // An error diagnostic has already been printed when parsing the declaration.
14856   if (Method->isInvalidDecl())
14857     return ExprError();
14858 
14859   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14860   unsigned NumParams = Proto->getNumParams();
14861 
14862   DeclarationNameInfo OpLocInfo(
14863                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
14864   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
14865   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14866                                            Obj, HadMultipleCandidates,
14867                                            OpLocInfo.getLoc(),
14868                                            OpLocInfo.getInfo());
14869   if (NewFn.isInvalid())
14870     return true;
14871 
14872   SmallVector<Expr *, 8> MethodArgs;
14873   MethodArgs.reserve(NumParams + 1);
14874 
14875   bool IsError = false;
14876 
14877   // Initialize the implicit object parameter.
14878   ExprResult ObjRes =
14879     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
14880                                         Best->FoundDecl, Method);
14881   if (ObjRes.isInvalid())
14882     IsError = true;
14883   else
14884     Object = ObjRes;
14885   MethodArgs.push_back(Object.get());
14886 
14887   IsError |= PrepareArgumentsForCallToObjectOfClassType(
14888       *this, MethodArgs, Method, Args, LParenLoc);
14889 
14890   // If this is a variadic call, handle args passed through "...".
14891   if (Proto->isVariadic()) {
14892     // Promote the arguments (C99 6.5.2.2p7).
14893     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
14894       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
14895                                                         nullptr);
14896       IsError |= Arg.isInvalid();
14897       MethodArgs.push_back(Arg.get());
14898     }
14899   }
14900 
14901   if (IsError)
14902     return true;
14903 
14904   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14905 
14906   // Once we've built TheCall, all of the expressions are properly owned.
14907   QualType ResultTy = Method->getReturnType();
14908   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14909   ResultTy = ResultTy.getNonLValueExprType(Context);
14910 
14911   CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14912       Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
14913       CurFPFeatureOverrides());
14914 
14915   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
14916     return true;
14917 
14918   if (CheckFunctionCall(Method, TheCall, Proto))
14919     return true;
14920 
14921   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
14922 }
14923 
14924 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
14925 ///  (if one exists), where @c Base is an expression of class type and
14926 /// @c Member is the name of the member we're trying to find.
14927 ExprResult
14928 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
14929                                bool *NoArrowOperatorFound) {
14930   assert(Base->getType()->isRecordType() &&
14931          "left-hand side must have class type");
14932 
14933   if (checkPlaceholderForOverload(*this, Base))
14934     return ExprError();
14935 
14936   SourceLocation Loc = Base->getExprLoc();
14937 
14938   // C++ [over.ref]p1:
14939   //
14940   //   [...] An expression x->m is interpreted as (x.operator->())->m
14941   //   for a class object x of type T if T::operator->() exists and if
14942   //   the operator is selected as the best match function by the
14943   //   overload resolution mechanism (13.3).
14944   DeclarationName OpName =
14945     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
14946   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
14947 
14948   if (RequireCompleteType(Loc, Base->getType(),
14949                           diag::err_typecheck_incomplete_tag, Base))
14950     return ExprError();
14951 
14952   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
14953   LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
14954   R.suppressDiagnostics();
14955 
14956   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14957        Oper != OperEnd; ++Oper) {
14958     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
14959                        None, CandidateSet, /*SuppressUserConversion=*/false);
14960   }
14961 
14962   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14963 
14964   // Perform overload resolution.
14965   OverloadCandidateSet::iterator Best;
14966   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14967   case OR_Success:
14968     // Overload resolution succeeded; we'll build the call below.
14969     break;
14970 
14971   case OR_No_Viable_Function: {
14972     auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
14973     if (CandidateSet.empty()) {
14974       QualType BaseType = Base->getType();
14975       if (NoArrowOperatorFound) {
14976         // Report this specific error to the caller instead of emitting a
14977         // diagnostic, as requested.
14978         *NoArrowOperatorFound = true;
14979         return ExprError();
14980       }
14981       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
14982         << BaseType << Base->getSourceRange();
14983       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
14984         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
14985           << FixItHint::CreateReplacement(OpLoc, ".");
14986       }
14987     } else
14988       Diag(OpLoc, diag::err_ovl_no_viable_oper)
14989         << "operator->" << Base->getSourceRange();
14990     CandidateSet.NoteCandidates(*this, Base, Cands);
14991     return ExprError();
14992   }
14993   case OR_Ambiguous:
14994     CandidateSet.NoteCandidates(
14995         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
14996                                        << "->" << Base->getType()
14997                                        << Base->getSourceRange()),
14998         *this, OCD_AmbiguousCandidates, Base);
14999     return ExprError();
15000 
15001   case OR_Deleted:
15002     CandidateSet.NoteCandidates(
15003         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15004                                        << "->" << Base->getSourceRange()),
15005         *this, OCD_AllCandidates, Base);
15006     return ExprError();
15007   }
15008 
15009   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
15010 
15011   // Convert the object parameter.
15012   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
15013   ExprResult BaseResult =
15014     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
15015                                         Best->FoundDecl, Method);
15016   if (BaseResult.isInvalid())
15017     return ExprError();
15018   Base = BaseResult.get();
15019 
15020   // Build the operator call.
15021   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
15022                                             Base, HadMultipleCandidates, OpLoc);
15023   if (FnExpr.isInvalid())
15024     return ExprError();
15025 
15026   QualType ResultTy = Method->getReturnType();
15027   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15028   ResultTy = ResultTy.getNonLValueExprType(Context);
15029   CXXOperatorCallExpr *TheCall =
15030       CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
15031                                   ResultTy, VK, OpLoc, CurFPFeatureOverrides());
15032 
15033   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
15034     return ExprError();
15035 
15036   if (CheckFunctionCall(Method, TheCall,
15037                         Method->getType()->castAs<FunctionProtoType>()))
15038     return ExprError();
15039 
15040   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
15041 }
15042 
15043 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
15044 /// a literal operator described by the provided lookup results.
15045 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
15046                                           DeclarationNameInfo &SuffixInfo,
15047                                           ArrayRef<Expr*> Args,
15048                                           SourceLocation LitEndLoc,
15049                                        TemplateArgumentListInfo *TemplateArgs) {
15050   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
15051 
15052   OverloadCandidateSet CandidateSet(UDSuffixLoc,
15053                                     OverloadCandidateSet::CSK_Normal);
15054   AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
15055                                  TemplateArgs);
15056 
15057   bool HadMultipleCandidates = (CandidateSet.size() > 1);
15058 
15059   // Perform overload resolution. This will usually be trivial, but might need
15060   // to perform substitutions for a literal operator template.
15061   OverloadCandidateSet::iterator Best;
15062   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
15063   case OR_Success:
15064   case OR_Deleted:
15065     break;
15066 
15067   case OR_No_Viable_Function:
15068     CandidateSet.NoteCandidates(
15069         PartialDiagnosticAt(UDSuffixLoc,
15070                             PDiag(diag::err_ovl_no_viable_function_in_call)
15071                                 << R.getLookupName()),
15072         *this, OCD_AllCandidates, Args);
15073     return ExprError();
15074 
15075   case OR_Ambiguous:
15076     CandidateSet.NoteCandidates(
15077         PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
15078                                                 << R.getLookupName()),
15079         *this, OCD_AmbiguousCandidates, Args);
15080     return ExprError();
15081   }
15082 
15083   FunctionDecl *FD = Best->Function;
15084   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
15085                                         nullptr, HadMultipleCandidates,
15086                                         SuffixInfo.getLoc(),
15087                                         SuffixInfo.getInfo());
15088   if (Fn.isInvalid())
15089     return true;
15090 
15091   // Check the argument types. This should almost always be a no-op, except
15092   // that array-to-pointer decay is applied to string literals.
15093   Expr *ConvArgs[2];
15094   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
15095     ExprResult InputInit = PerformCopyInitialization(
15096       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
15097       SourceLocation(), Args[ArgIdx]);
15098     if (InputInit.isInvalid())
15099       return true;
15100     ConvArgs[ArgIdx] = InputInit.get();
15101   }
15102 
15103   QualType ResultTy = FD->getReturnType();
15104   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15105   ResultTy = ResultTy.getNonLValueExprType(Context);
15106 
15107   UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
15108       Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
15109       VK, LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
15110 
15111   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
15112     return ExprError();
15113 
15114   if (CheckFunctionCall(FD, UDL, nullptr))
15115     return ExprError();
15116 
15117   return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
15118 }
15119 
15120 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
15121 /// given LookupResult is non-empty, it is assumed to describe a member which
15122 /// will be invoked. Otherwise, the function will be found via argument
15123 /// dependent lookup.
15124 /// CallExpr is set to a valid expression and FRS_Success returned on success,
15125 /// otherwise CallExpr is set to ExprError() and some non-success value
15126 /// is returned.
15127 Sema::ForRangeStatus
15128 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
15129                                 SourceLocation RangeLoc,
15130                                 const DeclarationNameInfo &NameInfo,
15131                                 LookupResult &MemberLookup,
15132                                 OverloadCandidateSet *CandidateSet,
15133                                 Expr *Range, ExprResult *CallExpr) {
15134   Scope *S = nullptr;
15135 
15136   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
15137   if (!MemberLookup.empty()) {
15138     ExprResult MemberRef =
15139         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
15140                                  /*IsPtr=*/false, CXXScopeSpec(),
15141                                  /*TemplateKWLoc=*/SourceLocation(),
15142                                  /*FirstQualifierInScope=*/nullptr,
15143                                  MemberLookup,
15144                                  /*TemplateArgs=*/nullptr, S);
15145     if (MemberRef.isInvalid()) {
15146       *CallExpr = ExprError();
15147       return FRS_DiagnosticIssued;
15148     }
15149     *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
15150     if (CallExpr->isInvalid()) {
15151       *CallExpr = ExprError();
15152       return FRS_DiagnosticIssued;
15153     }
15154   } else {
15155     ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
15156                                                 NestedNameSpecifierLoc(),
15157                                                 NameInfo, UnresolvedSet<0>());
15158     if (FnR.isInvalid())
15159       return FRS_DiagnosticIssued;
15160     UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
15161 
15162     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
15163                                                     CandidateSet, CallExpr);
15164     if (CandidateSet->empty() || CandidateSetError) {
15165       *CallExpr = ExprError();
15166       return FRS_NoViableFunction;
15167     }
15168     OverloadCandidateSet::iterator Best;
15169     OverloadingResult OverloadResult =
15170         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
15171 
15172     if (OverloadResult == OR_No_Viable_Function) {
15173       *CallExpr = ExprError();
15174       return FRS_NoViableFunction;
15175     }
15176     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
15177                                          Loc, nullptr, CandidateSet, &Best,
15178                                          OverloadResult,
15179                                          /*AllowTypoCorrection=*/false);
15180     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
15181       *CallExpr = ExprError();
15182       return FRS_DiagnosticIssued;
15183     }
15184   }
15185   return FRS_Success;
15186 }
15187 
15188 
15189 /// FixOverloadedFunctionReference - E is an expression that refers to
15190 /// a C++ overloaded function (possibly with some parentheses and
15191 /// perhaps a '&' around it). We have resolved the overloaded function
15192 /// to the function declaration Fn, so patch up the expression E to
15193 /// refer (possibly indirectly) to Fn. Returns the new expr.
15194 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
15195                                            FunctionDecl *Fn) {
15196   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
15197     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
15198                                                    Found, Fn);
15199     if (SubExpr == PE->getSubExpr())
15200       return PE;
15201 
15202     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
15203   }
15204 
15205   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
15206     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
15207                                                    Found, Fn);
15208     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
15209                                SubExpr->getType()) &&
15210            "Implicit cast type cannot be determined from overload");
15211     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
15212     if (SubExpr == ICE->getSubExpr())
15213       return ICE;
15214 
15215     return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
15216                                     SubExpr, nullptr, ICE->getValueKind(),
15217                                     CurFPFeatureOverrides());
15218   }
15219 
15220   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
15221     if (!GSE->isResultDependent()) {
15222       Expr *SubExpr =
15223           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
15224       if (SubExpr == GSE->getResultExpr())
15225         return GSE;
15226 
15227       // Replace the resulting type information before rebuilding the generic
15228       // selection expression.
15229       ArrayRef<Expr *> A = GSE->getAssocExprs();
15230       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
15231       unsigned ResultIdx = GSE->getResultIndex();
15232       AssocExprs[ResultIdx] = SubExpr;
15233 
15234       return GenericSelectionExpr::Create(
15235           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
15236           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
15237           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
15238           ResultIdx);
15239     }
15240     // Rather than fall through to the unreachable, return the original generic
15241     // selection expression.
15242     return GSE;
15243   }
15244 
15245   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
15246     assert(UnOp->getOpcode() == UO_AddrOf &&
15247            "Can only take the address of an overloaded function");
15248     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
15249       if (Method->isStatic()) {
15250         // Do nothing: static member functions aren't any different
15251         // from non-member functions.
15252       } else {
15253         // Fix the subexpression, which really has to be an
15254         // UnresolvedLookupExpr holding an overloaded member function
15255         // or template.
15256         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
15257                                                        Found, Fn);
15258         if (SubExpr == UnOp->getSubExpr())
15259           return UnOp;
15260 
15261         assert(isa<DeclRefExpr>(SubExpr)
15262                && "fixed to something other than a decl ref");
15263         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
15264                && "fixed to a member ref with no nested name qualifier");
15265 
15266         // We have taken the address of a pointer to member
15267         // function. Perform the computation here so that we get the
15268         // appropriate pointer to member type.
15269         QualType ClassType
15270           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
15271         QualType MemPtrType
15272           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
15273         // Under the MS ABI, lock down the inheritance model now.
15274         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15275           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
15276 
15277         return UnaryOperator::Create(
15278             Context, SubExpr, UO_AddrOf, MemPtrType, VK_PRValue, OK_Ordinary,
15279             UnOp->getOperatorLoc(), false, CurFPFeatureOverrides());
15280       }
15281     }
15282     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
15283                                                    Found, Fn);
15284     if (SubExpr == UnOp->getSubExpr())
15285       return UnOp;
15286 
15287     // FIXME: This can't currently fail, but in principle it could.
15288     return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf, SubExpr)
15289         .get();
15290   }
15291 
15292   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15293     // FIXME: avoid copy.
15294     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15295     if (ULE->hasExplicitTemplateArgs()) {
15296       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
15297       TemplateArgs = &TemplateArgsBuffer;
15298     }
15299 
15300     QualType Type = Fn->getType();
15301     ExprValueKind ValueKind = getLangOpts().CPlusPlus ? VK_LValue : VK_PRValue;
15302 
15303     // FIXME: Duplicated from BuildDeclarationNameExpr.
15304     if (unsigned BID = Fn->getBuiltinID()) {
15305       if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
15306         Type = Context.BuiltinFnTy;
15307         ValueKind = VK_PRValue;
15308       }
15309     }
15310 
15311     DeclRefExpr *DRE = BuildDeclRefExpr(
15312         Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
15313         Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
15314     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
15315     return DRE;
15316   }
15317 
15318   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
15319     // FIXME: avoid copy.
15320     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15321     if (MemExpr->hasExplicitTemplateArgs()) {
15322       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
15323       TemplateArgs = &TemplateArgsBuffer;
15324     }
15325 
15326     Expr *Base;
15327 
15328     // If we're filling in a static method where we used to have an
15329     // implicit member access, rewrite to a simple decl ref.
15330     if (MemExpr->isImplicitAccess()) {
15331       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
15332         DeclRefExpr *DRE = BuildDeclRefExpr(
15333             Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
15334             MemExpr->getQualifierLoc(), Found.getDecl(),
15335             MemExpr->getTemplateKeywordLoc(), TemplateArgs);
15336         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
15337         return DRE;
15338       } else {
15339         SourceLocation Loc = MemExpr->getMemberLoc();
15340         if (MemExpr->getQualifier())
15341           Loc = MemExpr->getQualifierLoc().getBeginLoc();
15342         Base =
15343             BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
15344       }
15345     } else
15346       Base = MemExpr->getBase();
15347 
15348     ExprValueKind valueKind;
15349     QualType type;
15350     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
15351       valueKind = VK_LValue;
15352       type = Fn->getType();
15353     } else {
15354       valueKind = VK_PRValue;
15355       type = Context.BoundMemberTy;
15356     }
15357 
15358     return BuildMemberExpr(
15359         Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
15360         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
15361         /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
15362         type, valueKind, OK_Ordinary, TemplateArgs);
15363   }
15364 
15365   llvm_unreachable("Invalid reference to overloaded function");
15366 }
15367 
15368 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
15369                                                 DeclAccessPair Found,
15370                                                 FunctionDecl *Fn) {
15371   return FixOverloadedFunctionReference(E.get(), Found, Fn);
15372 }
15373 
15374 bool clang::shouldEnforceArgLimit(bool PartialOverloading,
15375                                   FunctionDecl *Function) {
15376   if (!PartialOverloading || !Function)
15377     return true;
15378   if (Function->isVariadic())
15379     return false;
15380   if (const auto *Proto =
15381           dyn_cast<FunctionProtoType>(Function->getFunctionType()))
15382     if (Proto->isTemplateVariadic())
15383       return false;
15384   if (auto *Pattern = Function->getTemplateInstantiationPattern())
15385     if (const auto *Proto =
15386             dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
15387       if (Proto->isTemplateVariadic())
15388         return false;
15389   return true;
15390 }
15391