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
53 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
54                       const Expr *Base, bool HadMultipleCandidates,
55                       SourceLocation Loc = SourceLocation(),
56                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
57   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
58     return ExprError();
59   // If FoundDecl is different from Fn (such as if one is a template
60   // and the other a specialization), make sure DiagnoseUseOfDecl is
61   // called on both.
62   // FIXME: This would be more comprehensively addressed by modifying
63   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
64   // being used.
65   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
66     return ExprError();
67   DeclRefExpr *DRE = new (S.Context)
68       DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
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_OCL_Scalar_Widening,
141     ICR_Complex_Real_Conversion,
142     ICR_Conversion,
143     ICR_Conversion,
144     ICR_Writeback_Conversion,
145     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
146                      // it was omitted by the patch that added
147                      // ICK_Zero_Event_Conversion
148     ICR_C_Conversion,
149     ICR_C_Conversion_Extension
150   };
151   return Rank[(int)Kind];
152 }
153 
154 /// GetImplicitConversionName - Return the name of this kind of
155 /// implicit conversion.
156 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
157   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
158     "No conversion",
159     "Lvalue-to-rvalue",
160     "Array-to-pointer",
161     "Function-to-pointer",
162     "Function pointer conversion",
163     "Qualification",
164     "Integral promotion",
165     "Floating point promotion",
166     "Complex promotion",
167     "Integral conversion",
168     "Floating conversion",
169     "Complex conversion",
170     "Floating-integral conversion",
171     "Pointer conversion",
172     "Pointer-to-member conversion",
173     "Boolean conversion",
174     "Compatible-types conversion",
175     "Derived-to-base conversion",
176     "Vector conversion",
177     "Vector splat",
178     "Complex-real conversion",
179     "Block Pointer conversion",
180     "Transparent Union Conversion",
181     "Writeback conversion",
182     "OpenCL Zero Event Conversion",
183     "C specific type conversion",
184     "Incompatible pointer conversion"
185   };
186   return Name[Kind];
187 }
188 
189 /// StandardConversionSequence - Set the standard conversion
190 /// sequence to the identity conversion.
191 void StandardConversionSequence::setAsIdentityConversion() {
192   First = ICK_Identity;
193   Second = ICK_Identity;
194   Third = ICK_Identity;
195   DeprecatedStringLiteralToCharPtr = false;
196   QualificationIncludesObjCLifetime = false;
197   ReferenceBinding = false;
198   DirectBinding = false;
199   IsLvalueReference = true;
200   BindsToFunctionLvalue = false;
201   BindsToRvalue = false;
202   BindsImplicitObjectArgumentWithoutRefQualifier = false;
203   ObjCLifetimeConversionBinding = false;
204   CopyConstructor = nullptr;
205 }
206 
207 /// getRank - Retrieve the rank of this standard conversion sequence
208 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
209 /// implicit conversions.
210 ImplicitConversionRank StandardConversionSequence::getRank() const {
211   ImplicitConversionRank Rank = ICR_Exact_Match;
212   if  (GetConversionRank(First) > Rank)
213     Rank = GetConversionRank(First);
214   if  (GetConversionRank(Second) > Rank)
215     Rank = GetConversionRank(Second);
216   if  (GetConversionRank(Third) > Rank)
217     Rank = GetConversionRank(Third);
218   return Rank;
219 }
220 
221 /// isPointerConversionToBool - Determines whether this conversion is
222 /// a conversion of a pointer or pointer-to-member to bool. This is
223 /// used as part of the ranking of standard conversion sequences
224 /// (C++ 13.3.3.2p4).
225 bool StandardConversionSequence::isPointerConversionToBool() const {
226   // Note that FromType has not necessarily been transformed by the
227   // array-to-pointer or function-to-pointer implicit conversions, so
228   // check for their presence as well as checking whether FromType is
229   // a pointer.
230   if (getToType(1)->isBooleanType() &&
231       (getFromType()->isPointerType() ||
232        getFromType()->isMemberPointerType() ||
233        getFromType()->isObjCObjectPointerType() ||
234        getFromType()->isBlockPointerType() ||
235        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
236     return true;
237 
238   return false;
239 }
240 
241 /// isPointerConversionToVoidPointer - Determines whether this
242 /// conversion is a conversion of a pointer to a void pointer. This is
243 /// used as part of the ranking of standard conversion sequences (C++
244 /// 13.3.3.2p4).
245 bool
246 StandardConversionSequence::
247 isPointerConversionToVoidPointer(ASTContext& Context) const {
248   QualType FromType = getFromType();
249   QualType ToType = getToType(1);
250 
251   // Note that FromType has not necessarily been transformed by the
252   // array-to-pointer implicit conversion, so check for its presence
253   // and redo the conversion to get a pointer.
254   if (First == ICK_Array_To_Pointer)
255     FromType = Context.getArrayDecayedType(FromType);
256 
257   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
258     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
259       return ToPtrType->getPointeeType()->isVoidType();
260 
261   return false;
262 }
263 
264 /// Skip any implicit casts which could be either part of a narrowing conversion
265 /// or after one in an implicit conversion.
266 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
267                                              const Expr *Converted) {
268   // We can have cleanups wrapping the converted expression; these need to be
269   // preserved so that destructors run if necessary.
270   if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
271     Expr *Inner =
272         const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
273     return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
274                                     EWC->getObjects());
275   }
276 
277   while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
278     switch (ICE->getCastKind()) {
279     case CK_NoOp:
280     case CK_IntegralCast:
281     case CK_IntegralToBoolean:
282     case CK_IntegralToFloating:
283     case CK_BooleanToSignedIntegral:
284     case CK_FloatingToIntegral:
285     case CK_FloatingToBoolean:
286     case CK_FloatingCast:
287       Converted = ICE->getSubExpr();
288       continue;
289 
290     default:
291       return Converted;
292     }
293   }
294 
295   return Converted;
296 }
297 
298 /// Check if this standard conversion sequence represents a narrowing
299 /// conversion, according to C++11 [dcl.init.list]p7.
300 ///
301 /// \param Ctx  The AST context.
302 /// \param Converted  The result of applying this standard conversion sequence.
303 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
304 ///        value of the expression prior to the narrowing conversion.
305 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
306 ///        type of the expression prior to the narrowing conversion.
307 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
308 ///        from floating point types to integral types should be ignored.
309 NarrowingKind StandardConversionSequence::getNarrowingKind(
310     ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
311     QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
312   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
313 
314   // C++11 [dcl.init.list]p7:
315   //   A narrowing conversion is an implicit conversion ...
316   QualType FromType = getToType(0);
317   QualType ToType = getToType(1);
318 
319   // A conversion to an enumeration type is narrowing if the conversion to
320   // the underlying type is narrowing. This only arises for expressions of
321   // the form 'Enum{init}'.
322   if (auto *ET = ToType->getAs<EnumType>())
323     ToType = ET->getDecl()->getIntegerType();
324 
325   switch (Second) {
326   // 'bool' is an integral type; dispatch to the right place to handle it.
327   case ICK_Boolean_Conversion:
328     if (FromType->isRealFloatingType())
329       goto FloatingIntegralConversion;
330     if (FromType->isIntegralOrUnscopedEnumerationType())
331       goto IntegralConversion;
332     // -- from a pointer type or pointer-to-member type to bool, or
333     return NK_Type_Narrowing;
334 
335   // -- from a floating-point type to an integer type, or
336   //
337   // -- from an integer type or unscoped enumeration type to a floating-point
338   //    type, except where the source is a constant expression and the actual
339   //    value after conversion will fit into the target type and will produce
340   //    the original value when converted back to the original type, or
341   case ICK_Floating_Integral:
342   FloatingIntegralConversion:
343     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
344       return NK_Type_Narrowing;
345     } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
346                ToType->isRealFloatingType()) {
347       if (IgnoreFloatToIntegralConversion)
348         return NK_Not_Narrowing;
349       llvm::APSInt IntConstantValue;
350       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
351       assert(Initializer && "Unknown conversion expression");
352 
353       // If it's value-dependent, we can't tell whether it's narrowing.
354       if (Initializer->isValueDependent())
355         return NK_Dependent_Narrowing;
356 
357       if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
358         // Convert the integer to the floating type.
359         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
360         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
361                                 llvm::APFloat::rmNearestTiesToEven);
362         // And back.
363         llvm::APSInt ConvertedValue = IntConstantValue;
364         bool ignored;
365         Result.convertToInteger(ConvertedValue,
366                                 llvm::APFloat::rmTowardZero, &ignored);
367         // If the resulting value is different, this was a narrowing conversion.
368         if (IntConstantValue != ConvertedValue) {
369           ConstantValue = APValue(IntConstantValue);
370           ConstantType = Initializer->getType();
371           return NK_Constant_Narrowing;
372         }
373       } else {
374         // Variables are always narrowings.
375         return NK_Variable_Narrowing;
376       }
377     }
378     return NK_Not_Narrowing;
379 
380   // -- from long double to double or float, or from double to float, except
381   //    where the source is a constant expression and the actual value after
382   //    conversion is within the range of values that can be represented (even
383   //    if it cannot be represented exactly), or
384   case ICK_Floating_Conversion:
385     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
386         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
387       // FromType is larger than ToType.
388       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
389 
390       // If it's value-dependent, we can't tell whether it's narrowing.
391       if (Initializer->isValueDependent())
392         return NK_Dependent_Narrowing;
393 
394       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
395         // Constant!
396         assert(ConstantValue.isFloat());
397         llvm::APFloat FloatVal = ConstantValue.getFloat();
398         // Convert the source value into the target type.
399         bool ignored;
400         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
401           Ctx.getFloatTypeSemantics(ToType),
402           llvm::APFloat::rmNearestTiesToEven, &ignored);
403         // If there was no overflow, the source value is within the range of
404         // values that can be represented.
405         if (ConvertStatus & llvm::APFloat::opOverflow) {
406           ConstantType = Initializer->getType();
407           return NK_Constant_Narrowing;
408         }
409       } else {
410         return NK_Variable_Narrowing;
411       }
412     }
413     return NK_Not_Narrowing;
414 
415   // -- from an integer type or unscoped enumeration type to an integer type
416   //    that cannot represent all the values of the original type, except where
417   //    the source is a constant expression and the actual value after
418   //    conversion will fit into the target type and will produce the original
419   //    value when converted back to the original type.
420   case ICK_Integral_Conversion:
421   IntegralConversion: {
422     assert(FromType->isIntegralOrUnscopedEnumerationType());
423     assert(ToType->isIntegralOrUnscopedEnumerationType());
424     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
425     const unsigned FromWidth = Ctx.getIntWidth(FromType);
426     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
427     const unsigned ToWidth = Ctx.getIntWidth(ToType);
428 
429     if (FromWidth > ToWidth ||
430         (FromWidth == ToWidth && FromSigned != ToSigned) ||
431         (FromSigned && !ToSigned)) {
432       // Not all values of FromType can be represented in ToType.
433       llvm::APSInt InitializerValue;
434       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
435 
436       // If it's value-dependent, we can't tell whether it's narrowing.
437       if (Initializer->isValueDependent())
438         return NK_Dependent_Narrowing;
439 
440       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
441         // Such conversions on variables are always narrowing.
442         return NK_Variable_Narrowing;
443       }
444       bool Narrowing = false;
445       if (FromWidth < ToWidth) {
446         // Negative -> unsigned is narrowing. Otherwise, more bits is never
447         // narrowing.
448         if (InitializerValue.isSigned() && InitializerValue.isNegative())
449           Narrowing = true;
450       } else {
451         // Add a bit to the InitializerValue so we don't have to worry about
452         // signed vs. unsigned comparisons.
453         InitializerValue = InitializerValue.extend(
454           InitializerValue.getBitWidth() + 1);
455         // Convert the initializer to and from the target width and signed-ness.
456         llvm::APSInt ConvertedValue = InitializerValue;
457         ConvertedValue = ConvertedValue.trunc(ToWidth);
458         ConvertedValue.setIsSigned(ToSigned);
459         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
460         ConvertedValue.setIsSigned(InitializerValue.isSigned());
461         // If the result is different, this was a narrowing conversion.
462         if (ConvertedValue != InitializerValue)
463           Narrowing = true;
464       }
465       if (Narrowing) {
466         ConstantType = Initializer->getType();
467         ConstantValue = APValue(InitializerValue);
468         return NK_Constant_Narrowing;
469       }
470     }
471     return NK_Not_Narrowing;
472   }
473 
474   default:
475     // Other kinds of conversions are not narrowings.
476     return NK_Not_Narrowing;
477   }
478 }
479 
480 /// dump - Print this standard conversion sequence to standard
481 /// error. Useful for debugging overloading issues.
482 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
483   raw_ostream &OS = llvm::errs();
484   bool PrintedSomething = false;
485   if (First != ICK_Identity) {
486     OS << GetImplicitConversionName(First);
487     PrintedSomething = true;
488   }
489 
490   if (Second != ICK_Identity) {
491     if (PrintedSomething) {
492       OS << " -> ";
493     }
494     OS << GetImplicitConversionName(Second);
495 
496     if (CopyConstructor) {
497       OS << " (by copy constructor)";
498     } else if (DirectBinding) {
499       OS << " (direct reference binding)";
500     } else if (ReferenceBinding) {
501       OS << " (reference binding)";
502     }
503     PrintedSomething = true;
504   }
505 
506   if (Third != ICK_Identity) {
507     if (PrintedSomething) {
508       OS << " -> ";
509     }
510     OS << GetImplicitConversionName(Third);
511     PrintedSomething = true;
512   }
513 
514   if (!PrintedSomething) {
515     OS << "No conversions required";
516   }
517 }
518 
519 /// dump - Print this user-defined conversion sequence to standard
520 /// error. Useful for debugging overloading issues.
521 void UserDefinedConversionSequence::dump() const {
522   raw_ostream &OS = llvm::errs();
523   if (Before.First || Before.Second || Before.Third) {
524     Before.dump();
525     OS << " -> ";
526   }
527   if (ConversionFunction)
528     OS << '\'' << *ConversionFunction << '\'';
529   else
530     OS << "aggregate initialization";
531   if (After.First || After.Second || After.Third) {
532     OS << " -> ";
533     After.dump();
534   }
535 }
536 
537 /// dump - Print this implicit conversion sequence to standard
538 /// error. Useful for debugging overloading issues.
539 void ImplicitConversionSequence::dump() const {
540   raw_ostream &OS = llvm::errs();
541   if (isStdInitializerListElement())
542     OS << "Worst std::initializer_list element conversion: ";
543   switch (ConversionKind) {
544   case StandardConversion:
545     OS << "Standard conversion: ";
546     Standard.dump();
547     break;
548   case UserDefinedConversion:
549     OS << "User-defined conversion: ";
550     UserDefined.dump();
551     break;
552   case EllipsisConversion:
553     OS << "Ellipsis conversion";
554     break;
555   case AmbiguousConversion:
556     OS << "Ambiguous conversion";
557     break;
558   case BadConversion:
559     OS << "Bad conversion";
560     break;
561   }
562 
563   OS << "\n";
564 }
565 
566 void AmbiguousConversionSequence::construct() {
567   new (&conversions()) ConversionSet();
568 }
569 
570 void AmbiguousConversionSequence::destruct() {
571   conversions().~ConversionSet();
572 }
573 
574 void
575 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
576   FromTypePtr = O.FromTypePtr;
577   ToTypePtr = O.ToTypePtr;
578   new (&conversions()) ConversionSet(O.conversions());
579 }
580 
581 namespace {
582   // Structure used by DeductionFailureInfo to store
583   // template argument information.
584   struct DFIArguments {
585     TemplateArgument FirstArg;
586     TemplateArgument SecondArg;
587   };
588   // Structure used by DeductionFailureInfo to store
589   // template parameter and template argument information.
590   struct DFIParamWithArguments : DFIArguments {
591     TemplateParameter Param;
592   };
593   // Structure used by DeductionFailureInfo to store template argument
594   // information and the index of the problematic call argument.
595   struct DFIDeducedMismatchArgs : DFIArguments {
596     TemplateArgumentList *TemplateArgs;
597     unsigned CallArgIndex;
598   };
599   // Structure used by DeductionFailureInfo to store information about
600   // unsatisfied constraints.
601   struct CNSInfo {
602     TemplateArgumentList *TemplateArgs;
603     ConstraintSatisfaction Satisfaction;
604   };
605 }
606 
607 /// Convert from Sema's representation of template deduction information
608 /// to the form used in overload-candidate information.
609 DeductionFailureInfo
610 clang::MakeDeductionFailureInfo(ASTContext &Context,
611                                 Sema::TemplateDeductionResult TDK,
612                                 TemplateDeductionInfo &Info) {
613   DeductionFailureInfo Result;
614   Result.Result = static_cast<unsigned>(TDK);
615   Result.HasDiagnostic = false;
616   switch (TDK) {
617   case Sema::TDK_Invalid:
618   case Sema::TDK_InstantiationDepth:
619   case Sema::TDK_TooManyArguments:
620   case Sema::TDK_TooFewArguments:
621   case Sema::TDK_MiscellaneousDeductionFailure:
622   case Sema::TDK_CUDATargetMismatch:
623     Result.Data = nullptr;
624     break;
625 
626   case Sema::TDK_Incomplete:
627   case Sema::TDK_InvalidExplicitArguments:
628     Result.Data = Info.Param.getOpaqueValue();
629     break;
630 
631   case Sema::TDK_DeducedMismatch:
632   case Sema::TDK_DeducedMismatchNested: {
633     // FIXME: Should allocate from normal heap so that we can free this later.
634     auto *Saved = new (Context) DFIDeducedMismatchArgs;
635     Saved->FirstArg = Info.FirstArg;
636     Saved->SecondArg = Info.SecondArg;
637     Saved->TemplateArgs = Info.take();
638     Saved->CallArgIndex = Info.CallArgIndex;
639     Result.Data = Saved;
640     break;
641   }
642 
643   case Sema::TDK_NonDeducedMismatch: {
644     // FIXME: Should allocate from normal heap so that we can free this later.
645     DFIArguments *Saved = new (Context) DFIArguments;
646     Saved->FirstArg = Info.FirstArg;
647     Saved->SecondArg = Info.SecondArg;
648     Result.Data = Saved;
649     break;
650   }
651 
652   case Sema::TDK_IncompletePack:
653     // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
654   case Sema::TDK_Inconsistent:
655   case Sema::TDK_Underqualified: {
656     // FIXME: Should allocate from normal heap so that we can free this later.
657     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
658     Saved->Param = Info.Param;
659     Saved->FirstArg = Info.FirstArg;
660     Saved->SecondArg = Info.SecondArg;
661     Result.Data = Saved;
662     break;
663   }
664 
665   case Sema::TDK_SubstitutionFailure:
666     Result.Data = Info.take();
667     if (Info.hasSFINAEDiagnostic()) {
668       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
669           SourceLocation(), PartialDiagnostic::NullDiagnostic());
670       Info.takeSFINAEDiagnostic(*Diag);
671       Result.HasDiagnostic = true;
672     }
673     break;
674 
675   case Sema::TDK_ConstraintsNotSatisfied: {
676     CNSInfo *Saved = new (Context) CNSInfo;
677     Saved->TemplateArgs = Info.take();
678     Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
679     Result.Data = Saved;
680     break;
681   }
682 
683   case Sema::TDK_Success:
684   case Sema::TDK_NonDependentConversionFailure:
685     llvm_unreachable("not a deduction failure");
686   }
687 
688   return Result;
689 }
690 
691 void DeductionFailureInfo::Destroy() {
692   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
693   case Sema::TDK_Success:
694   case Sema::TDK_Invalid:
695   case Sema::TDK_InstantiationDepth:
696   case Sema::TDK_Incomplete:
697   case Sema::TDK_TooManyArguments:
698   case Sema::TDK_TooFewArguments:
699   case Sema::TDK_InvalidExplicitArguments:
700   case Sema::TDK_CUDATargetMismatch:
701   case Sema::TDK_NonDependentConversionFailure:
702     break;
703 
704   case Sema::TDK_IncompletePack:
705   case Sema::TDK_Inconsistent:
706   case Sema::TDK_Underqualified:
707   case Sema::TDK_DeducedMismatch:
708   case Sema::TDK_DeducedMismatchNested:
709   case Sema::TDK_NonDeducedMismatch:
710     // FIXME: Destroy the data?
711     Data = nullptr;
712     break;
713 
714   case Sema::TDK_SubstitutionFailure:
715     // FIXME: Destroy the template argument list?
716     Data = nullptr;
717     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
718       Diag->~PartialDiagnosticAt();
719       HasDiagnostic = false;
720     }
721     break;
722 
723   case Sema::TDK_ConstraintsNotSatisfied:
724     // FIXME: Destroy the template argument list?
725     Data = nullptr;
726     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
727       Diag->~PartialDiagnosticAt();
728       HasDiagnostic = false;
729     }
730     break;
731 
732   // Unhandled
733   case Sema::TDK_MiscellaneousDeductionFailure:
734     break;
735   }
736 }
737 
738 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
739   if (HasDiagnostic)
740     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
741   return nullptr;
742 }
743 
744 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
745   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
746   case Sema::TDK_Success:
747   case Sema::TDK_Invalid:
748   case Sema::TDK_InstantiationDepth:
749   case Sema::TDK_TooManyArguments:
750   case Sema::TDK_TooFewArguments:
751   case Sema::TDK_SubstitutionFailure:
752   case Sema::TDK_DeducedMismatch:
753   case Sema::TDK_DeducedMismatchNested:
754   case Sema::TDK_NonDeducedMismatch:
755   case Sema::TDK_CUDATargetMismatch:
756   case Sema::TDK_NonDependentConversionFailure:
757   case Sema::TDK_ConstraintsNotSatisfied:
758     return TemplateParameter();
759 
760   case Sema::TDK_Incomplete:
761   case Sema::TDK_InvalidExplicitArguments:
762     return TemplateParameter::getFromOpaqueValue(Data);
763 
764   case Sema::TDK_IncompletePack:
765   case Sema::TDK_Inconsistent:
766   case Sema::TDK_Underqualified:
767     return static_cast<DFIParamWithArguments*>(Data)->Param;
768 
769   // Unhandled
770   case Sema::TDK_MiscellaneousDeductionFailure:
771     break;
772   }
773 
774   return TemplateParameter();
775 }
776 
777 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
778   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
779   case Sema::TDK_Success:
780   case Sema::TDK_Invalid:
781   case Sema::TDK_InstantiationDepth:
782   case Sema::TDK_TooManyArguments:
783   case Sema::TDK_TooFewArguments:
784   case Sema::TDK_Incomplete:
785   case Sema::TDK_IncompletePack:
786   case Sema::TDK_InvalidExplicitArguments:
787   case Sema::TDK_Inconsistent:
788   case Sema::TDK_Underqualified:
789   case Sema::TDK_NonDeducedMismatch:
790   case Sema::TDK_CUDATargetMismatch:
791   case Sema::TDK_NonDependentConversionFailure:
792     return nullptr;
793 
794   case Sema::TDK_DeducedMismatch:
795   case Sema::TDK_DeducedMismatchNested:
796     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
797 
798   case Sema::TDK_SubstitutionFailure:
799     return static_cast<TemplateArgumentList*>(Data);
800 
801   case Sema::TDK_ConstraintsNotSatisfied:
802     return static_cast<CNSInfo*>(Data)->TemplateArgs;
803 
804   // Unhandled
805   case Sema::TDK_MiscellaneousDeductionFailure:
806     break;
807   }
808 
809   return nullptr;
810 }
811 
812 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
813   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
814   case Sema::TDK_Success:
815   case Sema::TDK_Invalid:
816   case Sema::TDK_InstantiationDepth:
817   case Sema::TDK_Incomplete:
818   case Sema::TDK_TooManyArguments:
819   case Sema::TDK_TooFewArguments:
820   case Sema::TDK_InvalidExplicitArguments:
821   case Sema::TDK_SubstitutionFailure:
822   case Sema::TDK_CUDATargetMismatch:
823   case Sema::TDK_NonDependentConversionFailure:
824   case Sema::TDK_ConstraintsNotSatisfied:
825     return nullptr;
826 
827   case Sema::TDK_IncompletePack:
828   case Sema::TDK_Inconsistent:
829   case Sema::TDK_Underqualified:
830   case Sema::TDK_DeducedMismatch:
831   case Sema::TDK_DeducedMismatchNested:
832   case Sema::TDK_NonDeducedMismatch:
833     return &static_cast<DFIArguments*>(Data)->FirstArg;
834 
835   // Unhandled
836   case Sema::TDK_MiscellaneousDeductionFailure:
837     break;
838   }
839 
840   return nullptr;
841 }
842 
843 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
844   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
845   case Sema::TDK_Success:
846   case Sema::TDK_Invalid:
847   case Sema::TDK_InstantiationDepth:
848   case Sema::TDK_Incomplete:
849   case Sema::TDK_IncompletePack:
850   case Sema::TDK_TooManyArguments:
851   case Sema::TDK_TooFewArguments:
852   case Sema::TDK_InvalidExplicitArguments:
853   case Sema::TDK_SubstitutionFailure:
854   case Sema::TDK_CUDATargetMismatch:
855   case Sema::TDK_NonDependentConversionFailure:
856   case Sema::TDK_ConstraintsNotSatisfied:
857     return nullptr;
858 
859   case Sema::TDK_Inconsistent:
860   case Sema::TDK_Underqualified:
861   case Sema::TDK_DeducedMismatch:
862   case Sema::TDK_DeducedMismatchNested:
863   case Sema::TDK_NonDeducedMismatch:
864     return &static_cast<DFIArguments*>(Data)->SecondArg;
865 
866   // Unhandled
867   case Sema::TDK_MiscellaneousDeductionFailure:
868     break;
869   }
870 
871   return nullptr;
872 }
873 
874 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
875   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
876   case Sema::TDK_DeducedMismatch:
877   case Sema::TDK_DeducedMismatchNested:
878     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
879 
880   default:
881     return llvm::None;
882   }
883 }
884 
885 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
886     OverloadedOperatorKind Op) {
887   if (!AllowRewrittenCandidates)
888     return false;
889   return Op == OO_EqualEqual || Op == OO_Spaceship;
890 }
891 
892 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
893     ASTContext &Ctx, const FunctionDecl *FD) {
894   if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator()))
895     return false;
896   // Don't bother adding a reversed candidate that can never be a better
897   // match than the non-reversed version.
898   return FD->getNumParams() != 2 ||
899          !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
900                                      FD->getParamDecl(1)->getType()) ||
901          FD->hasAttr<EnableIfAttr>();
902 }
903 
904 void OverloadCandidateSet::destroyCandidates() {
905   for (iterator i = begin(), e = end(); i != e; ++i) {
906     for (auto &C : i->Conversions)
907       C.~ImplicitConversionSequence();
908     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
909       i->DeductionFailure.Destroy();
910   }
911 }
912 
913 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
914   destroyCandidates();
915   SlabAllocator.Reset();
916   NumInlineBytesUsed = 0;
917   Candidates.clear();
918   Functions.clear();
919   Kind = CSK;
920 }
921 
922 namespace {
923   class UnbridgedCastsSet {
924     struct Entry {
925       Expr **Addr;
926       Expr *Saved;
927     };
928     SmallVector<Entry, 2> Entries;
929 
930   public:
931     void save(Sema &S, Expr *&E) {
932       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
933       Entry entry = { &E, E };
934       Entries.push_back(entry);
935       E = S.stripARCUnbridgedCast(E);
936     }
937 
938     void restore() {
939       for (SmallVectorImpl<Entry>::iterator
940              i = Entries.begin(), e = Entries.end(); i != e; ++i)
941         *i->Addr = i->Saved;
942     }
943   };
944 }
945 
946 /// checkPlaceholderForOverload - Do any interesting placeholder-like
947 /// preprocessing on the given expression.
948 ///
949 /// \param unbridgedCasts a collection to which to add unbridged casts;
950 ///   without this, they will be immediately diagnosed as errors
951 ///
952 /// Return true on unrecoverable error.
953 static bool
954 checkPlaceholderForOverload(Sema &S, Expr *&E,
955                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
956   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
957     // We can't handle overloaded expressions here because overload
958     // resolution might reasonably tweak them.
959     if (placeholder->getKind() == BuiltinType::Overload) return false;
960 
961     // If the context potentially accepts unbridged ARC casts, strip
962     // the unbridged cast and add it to the collection for later restoration.
963     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
964         unbridgedCasts) {
965       unbridgedCasts->save(S, E);
966       return false;
967     }
968 
969     // Go ahead and check everything else.
970     ExprResult result = S.CheckPlaceholderExpr(E);
971     if (result.isInvalid())
972       return true;
973 
974     E = result.get();
975     return false;
976   }
977 
978   // Nothing to do.
979   return false;
980 }
981 
982 /// checkArgPlaceholdersForOverload - Check a set of call operands for
983 /// placeholders.
984 static bool checkArgPlaceholdersForOverload(Sema &S,
985                                             MultiExprArg Args,
986                                             UnbridgedCastsSet &unbridged) {
987   for (unsigned i = 0, e = Args.size(); i != e; ++i)
988     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
989       return true;
990 
991   return false;
992 }
993 
994 /// Determine whether the given New declaration is an overload of the
995 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
996 /// New and Old cannot be overloaded, e.g., if New has the same signature as
997 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
998 /// functions (or function templates) at all. When it does return Ovl_Match or
999 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1000 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1001 /// declaration.
1002 ///
1003 /// Example: Given the following input:
1004 ///
1005 ///   void f(int, float); // #1
1006 ///   void f(int, int); // #2
1007 ///   int f(int, int); // #3
1008 ///
1009 /// When we process #1, there is no previous declaration of "f", so IsOverload
1010 /// will not be used.
1011 ///
1012 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1013 /// the parameter types, we see that #1 and #2 are overloaded (since they have
1014 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1015 /// unchanged.
1016 ///
1017 /// When we process #3, Old is an overload set containing #1 and #2. We compare
1018 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1019 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1020 /// functions are not part of the signature), IsOverload returns Ovl_Match and
1021 /// MatchedDecl will be set to point to the FunctionDecl for #2.
1022 ///
1023 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1024 /// by a using declaration. The rules for whether to hide shadow declarations
1025 /// ignore some properties which otherwise figure into a function template's
1026 /// signature.
1027 Sema::OverloadKind
1028 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1029                     NamedDecl *&Match, bool NewIsUsingDecl) {
1030   for (LookupResult::iterator I = Old.begin(), E = Old.end();
1031          I != E; ++I) {
1032     NamedDecl *OldD = *I;
1033 
1034     bool OldIsUsingDecl = false;
1035     if (isa<UsingShadowDecl>(OldD)) {
1036       OldIsUsingDecl = true;
1037 
1038       // We can always introduce two using declarations into the same
1039       // context, even if they have identical signatures.
1040       if (NewIsUsingDecl) continue;
1041 
1042       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1043     }
1044 
1045     // A using-declaration does not conflict with another declaration
1046     // if one of them is hidden.
1047     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1048       continue;
1049 
1050     // If either declaration was introduced by a using declaration,
1051     // we'll need to use slightly different rules for matching.
1052     // Essentially, these rules are the normal rules, except that
1053     // function templates hide function templates with different
1054     // return types or template parameter lists.
1055     bool UseMemberUsingDeclRules =
1056       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1057       !New->getFriendObjectKind();
1058 
1059     if (FunctionDecl *OldF = OldD->getAsFunction()) {
1060       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1061         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1062           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1063           continue;
1064         }
1065 
1066         if (!isa<FunctionTemplateDecl>(OldD) &&
1067             !shouldLinkPossiblyHiddenDecl(*I, New))
1068           continue;
1069 
1070         Match = *I;
1071         return Ovl_Match;
1072       }
1073 
1074       // Builtins that have custom typechecking or have a reference should
1075       // not be overloadable or redeclarable.
1076       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1077         Match = *I;
1078         return Ovl_NonFunction;
1079       }
1080     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1081       // We can overload with these, which can show up when doing
1082       // redeclaration checks for UsingDecls.
1083       assert(Old.getLookupKind() == LookupUsingDeclName);
1084     } else if (isa<TagDecl>(OldD)) {
1085       // We can always overload with tags by hiding them.
1086     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1087       // Optimistically assume that an unresolved using decl will
1088       // overload; if it doesn't, we'll have to diagnose during
1089       // template instantiation.
1090       //
1091       // Exception: if the scope is dependent and this is not a class
1092       // member, the using declaration can only introduce an enumerator.
1093       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1094         Match = *I;
1095         return Ovl_NonFunction;
1096       }
1097     } else {
1098       // (C++ 13p1):
1099       //   Only function declarations can be overloaded; object and type
1100       //   declarations cannot be overloaded.
1101       Match = *I;
1102       return Ovl_NonFunction;
1103     }
1104   }
1105 
1106   // C++ [temp.friend]p1:
1107   //   For a friend function declaration that is not a template declaration:
1108   //    -- if the name of the friend is a qualified or unqualified template-id,
1109   //       [...], otherwise
1110   //    -- if the name of the friend is a qualified-id and a matching
1111   //       non-template function is found in the specified class or namespace,
1112   //       the friend declaration refers to that function, otherwise,
1113   //    -- if the name of the friend is a qualified-id and a matching function
1114   //       template is found in the specified class or namespace, the friend
1115   //       declaration refers to the deduced specialization of that function
1116   //       template, otherwise
1117   //    -- the name shall be an unqualified-id [...]
1118   // If we get here for a qualified friend declaration, we've just reached the
1119   // third bullet. If the type of the friend is dependent, skip this lookup
1120   // until instantiation.
1121   if (New->getFriendObjectKind() && New->getQualifier() &&
1122       !New->getDescribedFunctionTemplate() &&
1123       !New->getDependentSpecializationInfo() &&
1124       !New->getType()->isDependentType()) {
1125     LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1126     TemplateSpecResult.addAllDecls(Old);
1127     if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1128                                             /*QualifiedFriend*/true)) {
1129       New->setInvalidDecl();
1130       return Ovl_Overload;
1131     }
1132 
1133     Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1134     return Ovl_Match;
1135   }
1136 
1137   return Ovl_Overload;
1138 }
1139 
1140 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1141                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs,
1142                       bool ConsiderRequiresClauses) {
1143   // C++ [basic.start.main]p2: This function shall not be overloaded.
1144   if (New->isMain())
1145     return false;
1146 
1147   // MSVCRT user defined entry points cannot be overloaded.
1148   if (New->isMSVCRTEntryPoint())
1149     return false;
1150 
1151   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1152   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1153 
1154   // C++ [temp.fct]p2:
1155   //   A function template can be overloaded with other function templates
1156   //   and with normal (non-template) functions.
1157   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1158     return true;
1159 
1160   // Is the function New an overload of the function Old?
1161   QualType OldQType = Context.getCanonicalType(Old->getType());
1162   QualType NewQType = Context.getCanonicalType(New->getType());
1163 
1164   // Compare the signatures (C++ 1.3.10) of the two functions to
1165   // determine whether they are overloads. If we find any mismatch
1166   // in the signature, they are overloads.
1167 
1168   // If either of these functions is a K&R-style function (no
1169   // prototype), then we consider them to have matching signatures.
1170   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1171       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1172     return false;
1173 
1174   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1175   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1176 
1177   // The signature of a function includes the types of its
1178   // parameters (C++ 1.3.10), which includes the presence or absence
1179   // of the ellipsis; see C++ DR 357).
1180   if (OldQType != NewQType &&
1181       (OldType->getNumParams() != NewType->getNumParams() ||
1182        OldType->isVariadic() != NewType->isVariadic() ||
1183        !FunctionParamTypesAreEqual(OldType, NewType)))
1184     return true;
1185 
1186   // C++ [temp.over.link]p4:
1187   //   The signature of a function template consists of its function
1188   //   signature, its return type and its template parameter list. The names
1189   //   of the template parameters are significant only for establishing the
1190   //   relationship between the template parameters and the rest of the
1191   //   signature.
1192   //
1193   // We check the return type and template parameter lists for function
1194   // templates first; the remaining checks follow.
1195   //
1196   // However, we don't consider either of these when deciding whether
1197   // a member introduced by a shadow declaration is hidden.
1198   if (!UseMemberUsingDeclRules && NewTemplate &&
1199       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1200                                        OldTemplate->getTemplateParameters(),
1201                                        false, TPL_TemplateMatch) ||
1202        !Context.hasSameType(Old->getDeclaredReturnType(),
1203                             New->getDeclaredReturnType())))
1204     return true;
1205 
1206   // If the function is a class member, its signature includes the
1207   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1208   //
1209   // As part of this, also check whether one of the member functions
1210   // is static, in which case they are not overloads (C++
1211   // 13.1p2). While not part of the definition of the signature,
1212   // this check is important to determine whether these functions
1213   // can be overloaded.
1214   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1215   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1216   if (OldMethod && NewMethod &&
1217       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1218     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1219       if (!UseMemberUsingDeclRules &&
1220           (OldMethod->getRefQualifier() == RQ_None ||
1221            NewMethod->getRefQualifier() == RQ_None)) {
1222         // C++0x [over.load]p2:
1223         //   - Member function declarations with the same name and the same
1224         //     parameter-type-list as well as member function template
1225         //     declarations with the same name, the same parameter-type-list, and
1226         //     the same template parameter lists cannot be overloaded if any of
1227         //     them, but not all, have a ref-qualifier (8.3.5).
1228         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1229           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1230         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1231       }
1232       return true;
1233     }
1234 
1235     // We may not have applied the implicit const for a constexpr member
1236     // function yet (because we haven't yet resolved whether this is a static
1237     // or non-static member function). Add it now, on the assumption that this
1238     // is a redeclaration of OldMethod.
1239     auto OldQuals = OldMethod->getMethodQualifiers();
1240     auto NewQuals = NewMethod->getMethodQualifiers();
1241     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1242         !isa<CXXConstructorDecl>(NewMethod))
1243       NewQuals.addConst();
1244     // We do not allow overloading based off of '__restrict'.
1245     OldQuals.removeRestrict();
1246     NewQuals.removeRestrict();
1247     if (OldQuals != NewQuals)
1248       return true;
1249   }
1250 
1251   // Though pass_object_size is placed on parameters and takes an argument, we
1252   // consider it to be a function-level modifier for the sake of function
1253   // identity. Either the function has one or more parameters with
1254   // pass_object_size or it doesn't.
1255   if (functionHasPassObjectSizeParams(New) !=
1256       functionHasPassObjectSizeParams(Old))
1257     return true;
1258 
1259   // enable_if attributes are an order-sensitive part of the signature.
1260   for (specific_attr_iterator<EnableIfAttr>
1261          NewI = New->specific_attr_begin<EnableIfAttr>(),
1262          NewE = New->specific_attr_end<EnableIfAttr>(),
1263          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1264          OldE = Old->specific_attr_end<EnableIfAttr>();
1265        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1266     if (NewI == NewE || OldI == OldE)
1267       return true;
1268     llvm::FoldingSetNodeID NewID, OldID;
1269     NewI->getCond()->Profile(NewID, Context, true);
1270     OldI->getCond()->Profile(OldID, Context, true);
1271     if (NewID != OldID)
1272       return true;
1273   }
1274 
1275   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1276     // Don't allow overloading of destructors.  (In theory we could, but it
1277     // would be a giant change to clang.)
1278     if (!isa<CXXDestructorDecl>(New)) {
1279       CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1280                          OldTarget = IdentifyCUDATarget(Old);
1281       if (NewTarget != CFT_InvalidTarget) {
1282         assert((OldTarget != CFT_InvalidTarget) &&
1283                "Unexpected invalid target.");
1284 
1285         // Allow overloading of functions with same signature and different CUDA
1286         // target attributes.
1287         if (NewTarget != OldTarget)
1288           return true;
1289       }
1290     }
1291   }
1292 
1293   if (ConsiderRequiresClauses) {
1294     Expr *NewRC = New->getTrailingRequiresClause(),
1295          *OldRC = Old->getTrailingRequiresClause();
1296     if ((NewRC != nullptr) != (OldRC != nullptr))
1297       // RC are most certainly different - these are overloads.
1298       return true;
1299 
1300     if (NewRC) {
1301       llvm::FoldingSetNodeID NewID, OldID;
1302       NewRC->Profile(NewID, Context, /*Canonical=*/true);
1303       OldRC->Profile(OldID, Context, /*Canonical=*/true);
1304       if (NewID != OldID)
1305         // RCs are not equivalent - these are overloads.
1306         return true;
1307     }
1308   }
1309 
1310   // The signatures match; this is not an overload.
1311   return false;
1312 }
1313 
1314 /// Tries a user-defined conversion from From to ToType.
1315 ///
1316 /// Produces an implicit conversion sequence for when a standard conversion
1317 /// is not an option. See TryImplicitConversion for more information.
1318 static ImplicitConversionSequence
1319 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1320                          bool SuppressUserConversions,
1321                          AllowedExplicit AllowExplicit,
1322                          bool InOverloadResolution,
1323                          bool CStyle,
1324                          bool AllowObjCWritebackConversion,
1325                          bool AllowObjCConversionOnExplicit) {
1326   ImplicitConversionSequence ICS;
1327 
1328   if (SuppressUserConversions) {
1329     // We're not in the case above, so there is no conversion that
1330     // we can perform.
1331     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1332     return ICS;
1333   }
1334 
1335   // Attempt user-defined conversion.
1336   OverloadCandidateSet Conversions(From->getExprLoc(),
1337                                    OverloadCandidateSet::CSK_Normal);
1338   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1339                                   Conversions, AllowExplicit,
1340                                   AllowObjCConversionOnExplicit)) {
1341   case OR_Success:
1342   case OR_Deleted:
1343     ICS.setUserDefined();
1344     // C++ [over.ics.user]p4:
1345     //   A conversion of an expression of class type to the same class
1346     //   type is given Exact Match rank, and a conversion of an
1347     //   expression of class type to a base class of that type is
1348     //   given Conversion rank, in spite of the fact that a copy
1349     //   constructor (i.e., a user-defined conversion function) is
1350     //   called for those cases.
1351     if (CXXConstructorDecl *Constructor
1352           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1353       QualType FromCanon
1354         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1355       QualType ToCanon
1356         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1357       if (Constructor->isCopyConstructor() &&
1358           (FromCanon == ToCanon ||
1359            S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1360         // Turn this into a "standard" conversion sequence, so that it
1361         // gets ranked with standard conversion sequences.
1362         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1363         ICS.setStandard();
1364         ICS.Standard.setAsIdentityConversion();
1365         ICS.Standard.setFromType(From->getType());
1366         ICS.Standard.setAllToTypes(ToType);
1367         ICS.Standard.CopyConstructor = Constructor;
1368         ICS.Standard.FoundCopyConstructor = Found;
1369         if (ToCanon != FromCanon)
1370           ICS.Standard.Second = ICK_Derived_To_Base;
1371       }
1372     }
1373     break;
1374 
1375   case OR_Ambiguous:
1376     ICS.setAmbiguous();
1377     ICS.Ambiguous.setFromType(From->getType());
1378     ICS.Ambiguous.setToType(ToType);
1379     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1380          Cand != Conversions.end(); ++Cand)
1381       if (Cand->Best)
1382         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1383     break;
1384 
1385     // Fall through.
1386   case OR_No_Viable_Function:
1387     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1388     break;
1389   }
1390 
1391   return ICS;
1392 }
1393 
1394 /// TryImplicitConversion - Attempt to perform an implicit conversion
1395 /// from the given expression (Expr) to the given type (ToType). This
1396 /// function returns an implicit conversion sequence that can be used
1397 /// to perform the initialization. Given
1398 ///
1399 ///   void f(float f);
1400 ///   void g(int i) { f(i); }
1401 ///
1402 /// this routine would produce an implicit conversion sequence to
1403 /// describe the initialization of f from i, which will be a standard
1404 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1405 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1406 //
1407 /// Note that this routine only determines how the conversion can be
1408 /// performed; it does not actually perform the conversion. As such,
1409 /// it will not produce any diagnostics if no conversion is available,
1410 /// but will instead return an implicit conversion sequence of kind
1411 /// "BadConversion".
1412 ///
1413 /// If @p SuppressUserConversions, then user-defined conversions are
1414 /// not permitted.
1415 /// If @p AllowExplicit, then explicit user-defined conversions are
1416 /// permitted.
1417 ///
1418 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1419 /// writeback conversion, which allows __autoreleasing id* parameters to
1420 /// be initialized with __strong id* or __weak id* arguments.
1421 static ImplicitConversionSequence
1422 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1423                       bool SuppressUserConversions,
1424                       AllowedExplicit AllowExplicit,
1425                       bool InOverloadResolution,
1426                       bool CStyle,
1427                       bool AllowObjCWritebackConversion,
1428                       bool AllowObjCConversionOnExplicit) {
1429   ImplicitConversionSequence ICS;
1430   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1431                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1432     ICS.setStandard();
1433     return ICS;
1434   }
1435 
1436   if (!S.getLangOpts().CPlusPlus) {
1437     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1438     return ICS;
1439   }
1440 
1441   // C++ [over.ics.user]p4:
1442   //   A conversion of an expression of class type to the same class
1443   //   type is given Exact Match rank, and a conversion of an
1444   //   expression of class type to a base class of that type is
1445   //   given Conversion rank, in spite of the fact that a copy/move
1446   //   constructor (i.e., a user-defined conversion function) is
1447   //   called for those cases.
1448   QualType FromType = From->getType();
1449   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1450       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1451        S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1452     ICS.setStandard();
1453     ICS.Standard.setAsIdentityConversion();
1454     ICS.Standard.setFromType(FromType);
1455     ICS.Standard.setAllToTypes(ToType);
1456 
1457     // We don't actually check at this point whether there is a valid
1458     // copy/move constructor, since overloading just assumes that it
1459     // exists. When we actually perform initialization, we'll find the
1460     // appropriate constructor to copy the returned object, if needed.
1461     ICS.Standard.CopyConstructor = nullptr;
1462 
1463     // Determine whether this is considered a derived-to-base conversion.
1464     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1465       ICS.Standard.Second = ICK_Derived_To_Base;
1466 
1467     return ICS;
1468   }
1469 
1470   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1471                                   AllowExplicit, InOverloadResolution, CStyle,
1472                                   AllowObjCWritebackConversion,
1473                                   AllowObjCConversionOnExplicit);
1474 }
1475 
1476 ImplicitConversionSequence
1477 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1478                             bool SuppressUserConversions,
1479                             AllowedExplicit AllowExplicit,
1480                             bool InOverloadResolution,
1481                             bool CStyle,
1482                             bool AllowObjCWritebackConversion) {
1483   return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1484                                  AllowExplicit, InOverloadResolution, CStyle,
1485                                  AllowObjCWritebackConversion,
1486                                  /*AllowObjCConversionOnExplicit=*/false);
1487 }
1488 
1489 /// PerformImplicitConversion - Perform an implicit conversion of the
1490 /// expression From to the type ToType. Returns the
1491 /// converted expression. Flavor is the kind of conversion we're
1492 /// performing, used in the error message. If @p AllowExplicit,
1493 /// explicit user-defined conversions are permitted.
1494 ExprResult
1495 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1496                                 AssignmentAction Action, bool AllowExplicit) {
1497   ImplicitConversionSequence ICS;
1498   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1499 }
1500 
1501 ExprResult
1502 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1503                                 AssignmentAction Action, bool AllowExplicit,
1504                                 ImplicitConversionSequence& ICS) {
1505   if (checkPlaceholderForOverload(*this, From))
1506     return ExprError();
1507 
1508   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1509   bool AllowObjCWritebackConversion
1510     = getLangOpts().ObjCAutoRefCount &&
1511       (Action == AA_Passing || Action == AA_Sending);
1512   if (getLangOpts().ObjC)
1513     CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1514                                       From->getType(), From);
1515   ICS = ::TryImplicitConversion(*this, From, ToType,
1516                                 /*SuppressUserConversions=*/false,
1517                                 AllowExplicit ? AllowedExplicit::All
1518                                               : AllowedExplicit::None,
1519                                 /*InOverloadResolution=*/false,
1520                                 /*CStyle=*/false, AllowObjCWritebackConversion,
1521                                 /*AllowObjCConversionOnExplicit=*/false);
1522   return PerformImplicitConversion(From, ToType, ICS, Action);
1523 }
1524 
1525 /// Determine whether the conversion from FromType to ToType is a valid
1526 /// conversion that strips "noexcept" or "noreturn" off the nested function
1527 /// type.
1528 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1529                                 QualType &ResultTy) {
1530   if (Context.hasSameUnqualifiedType(FromType, ToType))
1531     return false;
1532 
1533   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1534   //                    or F(t noexcept) -> F(t)
1535   // where F adds one of the following at most once:
1536   //   - a pointer
1537   //   - a member pointer
1538   //   - a block pointer
1539   // Changes here need matching changes in FindCompositePointerType.
1540   CanQualType CanTo = Context.getCanonicalType(ToType);
1541   CanQualType CanFrom = Context.getCanonicalType(FromType);
1542   Type::TypeClass TyClass = CanTo->getTypeClass();
1543   if (TyClass != CanFrom->getTypeClass()) return false;
1544   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1545     if (TyClass == Type::Pointer) {
1546       CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1547       CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1548     } else if (TyClass == Type::BlockPointer) {
1549       CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1550       CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1551     } else if (TyClass == Type::MemberPointer) {
1552       auto ToMPT = CanTo.castAs<MemberPointerType>();
1553       auto FromMPT = CanFrom.castAs<MemberPointerType>();
1554       // A function pointer conversion cannot change the class of the function.
1555       if (ToMPT->getClass() != FromMPT->getClass())
1556         return false;
1557       CanTo = ToMPT->getPointeeType();
1558       CanFrom = FromMPT->getPointeeType();
1559     } else {
1560       return false;
1561     }
1562 
1563     TyClass = CanTo->getTypeClass();
1564     if (TyClass != CanFrom->getTypeClass()) return false;
1565     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1566       return false;
1567   }
1568 
1569   const auto *FromFn = cast<FunctionType>(CanFrom);
1570   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1571 
1572   const auto *ToFn = cast<FunctionType>(CanTo);
1573   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1574 
1575   bool Changed = false;
1576 
1577   // Drop 'noreturn' if not present in target type.
1578   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1579     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1580     Changed = true;
1581   }
1582 
1583   // Drop 'noexcept' if not present in target type.
1584   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1585     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1586     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1587       FromFn = cast<FunctionType>(
1588           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1589                                                    EST_None)
1590                  .getTypePtr());
1591       Changed = true;
1592     }
1593 
1594     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1595     // only if the ExtParameterInfo lists of the two function prototypes can be
1596     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1597     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1598     bool CanUseToFPT, CanUseFromFPT;
1599     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1600                                       CanUseFromFPT, NewParamInfos) &&
1601         CanUseToFPT && !CanUseFromFPT) {
1602       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1603       ExtInfo.ExtParameterInfos =
1604           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1605       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1606                                             FromFPT->getParamTypes(), ExtInfo);
1607       FromFn = QT->getAs<FunctionType>();
1608       Changed = true;
1609     }
1610   }
1611 
1612   if (!Changed)
1613     return false;
1614 
1615   assert(QualType(FromFn, 0).isCanonical());
1616   if (QualType(FromFn, 0) != CanTo) return false;
1617 
1618   ResultTy = ToType;
1619   return true;
1620 }
1621 
1622 /// Determine whether the conversion from FromType to ToType is a valid
1623 /// vector conversion.
1624 ///
1625 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1626 /// conversion.
1627 static bool IsVectorConversion(Sema &S, QualType FromType,
1628                                QualType ToType, ImplicitConversionKind &ICK) {
1629   // We need at least one of these types to be a vector type to have a vector
1630   // conversion.
1631   if (!ToType->isVectorType() && !FromType->isVectorType())
1632     return false;
1633 
1634   // Identical types require no conversions.
1635   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1636     return false;
1637 
1638   // There are no conversions between extended vector types, only identity.
1639   if (ToType->isExtVectorType()) {
1640     // There are no conversions between extended vector types other than the
1641     // identity conversion.
1642     if (FromType->isExtVectorType())
1643       return false;
1644 
1645     // Vector splat from any arithmetic type to a vector.
1646     if (FromType->isArithmeticType()) {
1647       ICK = ICK_Vector_Splat;
1648       return true;
1649     }
1650   }
1651 
1652   // We can perform the conversion between vector types in the following cases:
1653   // 1)vector types are equivalent AltiVec and GCC vector types
1654   // 2)lax vector conversions are permitted and the vector types are of the
1655   //   same size
1656   // 3)the destination type does not have the ARM MVE strict-polymorphism
1657   //   attribute, which inhibits lax vector conversion for overload resolution
1658   //   only
1659   if (ToType->isVectorType() && FromType->isVectorType()) {
1660     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1661         (S.isLaxVectorConversion(FromType, ToType) &&
1662          !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
1663       ICK = ICK_Vector_Conversion;
1664       return true;
1665     }
1666   }
1667 
1668   return false;
1669 }
1670 
1671 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1672                                 bool InOverloadResolution,
1673                                 StandardConversionSequence &SCS,
1674                                 bool CStyle);
1675 
1676 /// IsStandardConversion - Determines whether there is a standard
1677 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1678 /// expression From to the type ToType. Standard conversion sequences
1679 /// only consider non-class types; for conversions that involve class
1680 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1681 /// contain the standard conversion sequence required to perform this
1682 /// conversion and this routine will return true. Otherwise, this
1683 /// routine will return false and the value of SCS is unspecified.
1684 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1685                                  bool InOverloadResolution,
1686                                  StandardConversionSequence &SCS,
1687                                  bool CStyle,
1688                                  bool AllowObjCWritebackConversion) {
1689   QualType FromType = From->getType();
1690 
1691   // Standard conversions (C++ [conv])
1692   SCS.setAsIdentityConversion();
1693   SCS.IncompatibleObjC = false;
1694   SCS.setFromType(FromType);
1695   SCS.CopyConstructor = nullptr;
1696 
1697   // There are no standard conversions for class types in C++, so
1698   // abort early. When overloading in C, however, we do permit them.
1699   if (S.getLangOpts().CPlusPlus &&
1700       (FromType->isRecordType() || ToType->isRecordType()))
1701     return false;
1702 
1703   // The first conversion can be an lvalue-to-rvalue conversion,
1704   // array-to-pointer conversion, or function-to-pointer conversion
1705   // (C++ 4p1).
1706 
1707   if (FromType == S.Context.OverloadTy) {
1708     DeclAccessPair AccessPair;
1709     if (FunctionDecl *Fn
1710           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1711                                                  AccessPair)) {
1712       // We were able to resolve the address of the overloaded function,
1713       // so we can convert to the type of that function.
1714       FromType = Fn->getType();
1715       SCS.setFromType(FromType);
1716 
1717       // we can sometimes resolve &foo<int> regardless of ToType, so check
1718       // if the type matches (identity) or we are converting to bool
1719       if (!S.Context.hasSameUnqualifiedType(
1720                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1721         QualType resultTy;
1722         // if the function type matches except for [[noreturn]], it's ok
1723         if (!S.IsFunctionConversion(FromType,
1724               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1725           // otherwise, only a boolean conversion is standard
1726           if (!ToType->isBooleanType())
1727             return false;
1728       }
1729 
1730       // Check if the "from" expression is taking the address of an overloaded
1731       // function and recompute the FromType accordingly. Take advantage of the
1732       // fact that non-static member functions *must* have such an address-of
1733       // expression.
1734       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1735       if (Method && !Method->isStatic()) {
1736         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1737                "Non-unary operator on non-static member address");
1738         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1739                == UO_AddrOf &&
1740                "Non-address-of operator on non-static member address");
1741         const Type *ClassType
1742           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1743         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1744       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1745         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1746                UO_AddrOf &&
1747                "Non-address-of operator for overloaded function expression");
1748         FromType = S.Context.getPointerType(FromType);
1749       }
1750 
1751       // Check that we've computed the proper type after overload resolution.
1752       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1753       // be calling it from within an NDEBUG block.
1754       assert(S.Context.hasSameType(
1755         FromType,
1756         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1757     } else {
1758       return false;
1759     }
1760   }
1761   // Lvalue-to-rvalue conversion (C++11 4.1):
1762   //   A glvalue (3.10) of a non-function, non-array type T can
1763   //   be converted to a prvalue.
1764   bool argIsLValue = From->isGLValue();
1765   if (argIsLValue &&
1766       !FromType->isFunctionType() && !FromType->isArrayType() &&
1767       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1768     SCS.First = ICK_Lvalue_To_Rvalue;
1769 
1770     // C11 6.3.2.1p2:
1771     //   ... if the lvalue has atomic type, the value has the non-atomic version
1772     //   of the type of the lvalue ...
1773     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1774       FromType = Atomic->getValueType();
1775 
1776     // If T is a non-class type, the type of the rvalue is the
1777     // cv-unqualified version of T. Otherwise, the type of the rvalue
1778     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1779     // just strip the qualifiers because they don't matter.
1780     FromType = FromType.getUnqualifiedType();
1781   } else if (FromType->isArrayType()) {
1782     // Array-to-pointer conversion (C++ 4.2)
1783     SCS.First = ICK_Array_To_Pointer;
1784 
1785     // An lvalue or rvalue of type "array of N T" or "array of unknown
1786     // bound of T" can be converted to an rvalue of type "pointer to
1787     // T" (C++ 4.2p1).
1788     FromType = S.Context.getArrayDecayedType(FromType);
1789 
1790     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1791       // This conversion is deprecated in C++03 (D.4)
1792       SCS.DeprecatedStringLiteralToCharPtr = true;
1793 
1794       // For the purpose of ranking in overload resolution
1795       // (13.3.3.1.1), this conversion is considered an
1796       // array-to-pointer conversion followed by a qualification
1797       // conversion (4.4). (C++ 4.2p2)
1798       SCS.Second = ICK_Identity;
1799       SCS.Third = ICK_Qualification;
1800       SCS.QualificationIncludesObjCLifetime = false;
1801       SCS.setAllToTypes(FromType);
1802       return true;
1803     }
1804   } else if (FromType->isFunctionType() && argIsLValue) {
1805     // Function-to-pointer conversion (C++ 4.3).
1806     SCS.First = ICK_Function_To_Pointer;
1807 
1808     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1809       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1810         if (!S.checkAddressOfFunctionIsAvailable(FD))
1811           return false;
1812 
1813     // An lvalue of function type T can be converted to an rvalue of
1814     // type "pointer to T." The result is a pointer to the
1815     // function. (C++ 4.3p1).
1816     FromType = S.Context.getPointerType(FromType);
1817   } else {
1818     // We don't require any conversions for the first step.
1819     SCS.First = ICK_Identity;
1820   }
1821   SCS.setToType(0, FromType);
1822 
1823   // The second conversion can be an integral promotion, floating
1824   // point promotion, integral conversion, floating point conversion,
1825   // floating-integral conversion, pointer conversion,
1826   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1827   // For overloading in C, this can also be a "compatible-type"
1828   // conversion.
1829   bool IncompatibleObjC = false;
1830   ImplicitConversionKind SecondICK = ICK_Identity;
1831   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1832     // The unqualified versions of the types are the same: there's no
1833     // conversion to do.
1834     SCS.Second = ICK_Identity;
1835   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1836     // Integral promotion (C++ 4.5).
1837     SCS.Second = ICK_Integral_Promotion;
1838     FromType = ToType.getUnqualifiedType();
1839   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1840     // Floating point promotion (C++ 4.6).
1841     SCS.Second = ICK_Floating_Promotion;
1842     FromType = ToType.getUnqualifiedType();
1843   } else if (S.IsComplexPromotion(FromType, ToType)) {
1844     // Complex promotion (Clang extension)
1845     SCS.Second = ICK_Complex_Promotion;
1846     FromType = ToType.getUnqualifiedType();
1847   } else if (ToType->isBooleanType() &&
1848              (FromType->isArithmeticType() ||
1849               FromType->isAnyPointerType() ||
1850               FromType->isBlockPointerType() ||
1851               FromType->isMemberPointerType())) {
1852     // Boolean conversions (C++ 4.12).
1853     SCS.Second = ICK_Boolean_Conversion;
1854     FromType = S.Context.BoolTy;
1855   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1856              ToType->isIntegralType(S.Context)) {
1857     // Integral conversions (C++ 4.7).
1858     SCS.Second = ICK_Integral_Conversion;
1859     FromType = ToType.getUnqualifiedType();
1860   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1861     // Complex conversions (C99 6.3.1.6)
1862     SCS.Second = ICK_Complex_Conversion;
1863     FromType = ToType.getUnqualifiedType();
1864   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1865              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1866     // Complex-real conversions (C99 6.3.1.7)
1867     SCS.Second = ICK_Complex_Real;
1868     FromType = ToType.getUnqualifiedType();
1869   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1870     // FIXME: disable conversions between long double and __float128 if
1871     // their representation is different until there is back end support
1872     // We of course allow this conversion if long double is really double.
1873     if (&S.Context.getFloatTypeSemantics(FromType) !=
1874         &S.Context.getFloatTypeSemantics(ToType)) {
1875       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1876                                     ToType == S.Context.LongDoubleTy) ||
1877                                    (FromType == S.Context.LongDoubleTy &&
1878                                     ToType == S.Context.Float128Ty));
1879       if (Float128AndLongDouble &&
1880           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1881            &llvm::APFloat::PPCDoubleDouble()))
1882         return false;
1883     }
1884     // Floating point conversions (C++ 4.8).
1885     SCS.Second = ICK_Floating_Conversion;
1886     FromType = ToType.getUnqualifiedType();
1887   } else if ((FromType->isRealFloatingType() &&
1888               ToType->isIntegralType(S.Context)) ||
1889              (FromType->isIntegralOrUnscopedEnumerationType() &&
1890               ToType->isRealFloatingType())) {
1891     // Floating-integral conversions (C++ 4.9).
1892     SCS.Second = ICK_Floating_Integral;
1893     FromType = ToType.getUnqualifiedType();
1894   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1895     SCS.Second = ICK_Block_Pointer_Conversion;
1896   } else if (AllowObjCWritebackConversion &&
1897              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1898     SCS.Second = ICK_Writeback_Conversion;
1899   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1900                                    FromType, IncompatibleObjC)) {
1901     // Pointer conversions (C++ 4.10).
1902     SCS.Second = ICK_Pointer_Conversion;
1903     SCS.IncompatibleObjC = IncompatibleObjC;
1904     FromType = FromType.getUnqualifiedType();
1905   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1906                                          InOverloadResolution, FromType)) {
1907     // Pointer to member conversions (4.11).
1908     SCS.Second = ICK_Pointer_Member;
1909   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1910     SCS.Second = SecondICK;
1911     FromType = ToType.getUnqualifiedType();
1912   } else if (!S.getLangOpts().CPlusPlus &&
1913              S.Context.typesAreCompatible(ToType, FromType)) {
1914     // Compatible conversions (Clang extension for C function overloading)
1915     SCS.Second = ICK_Compatible_Conversion;
1916     FromType = ToType.getUnqualifiedType();
1917   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1918                                              InOverloadResolution,
1919                                              SCS, CStyle)) {
1920     SCS.Second = ICK_TransparentUnionConversion;
1921     FromType = ToType;
1922   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1923                                  CStyle)) {
1924     // tryAtomicConversion has updated the standard conversion sequence
1925     // appropriately.
1926     return true;
1927   } else if (ToType->isEventT() &&
1928              From->isIntegerConstantExpr(S.getASTContext()) &&
1929              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1930     SCS.Second = ICK_Zero_Event_Conversion;
1931     FromType = ToType;
1932   } else if (ToType->isQueueT() &&
1933              From->isIntegerConstantExpr(S.getASTContext()) &&
1934              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1935     SCS.Second = ICK_Zero_Queue_Conversion;
1936     FromType = ToType;
1937   } else if (ToType->isSamplerT() &&
1938              From->isIntegerConstantExpr(S.getASTContext())) {
1939     SCS.Second = ICK_Compatible_Conversion;
1940     FromType = ToType;
1941   } else {
1942     // No second conversion required.
1943     SCS.Second = ICK_Identity;
1944   }
1945   SCS.setToType(1, FromType);
1946 
1947   // The third conversion can be a function pointer conversion or a
1948   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1949   bool ObjCLifetimeConversion;
1950   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1951     // Function pointer conversions (removing 'noexcept') including removal of
1952     // 'noreturn' (Clang extension).
1953     SCS.Third = ICK_Function_Conversion;
1954   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1955                                          ObjCLifetimeConversion)) {
1956     SCS.Third = ICK_Qualification;
1957     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1958     FromType = ToType;
1959   } else {
1960     // No conversion required
1961     SCS.Third = ICK_Identity;
1962   }
1963 
1964   // C++ [over.best.ics]p6:
1965   //   [...] Any difference in top-level cv-qualification is
1966   //   subsumed by the initialization itself and does not constitute
1967   //   a conversion. [...]
1968   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1969   QualType CanonTo = S.Context.getCanonicalType(ToType);
1970   if (CanonFrom.getLocalUnqualifiedType()
1971                                      == CanonTo.getLocalUnqualifiedType() &&
1972       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1973     FromType = ToType;
1974     CanonFrom = CanonTo;
1975   }
1976 
1977   SCS.setToType(2, FromType);
1978 
1979   if (CanonFrom == CanonTo)
1980     return true;
1981 
1982   // If we have not converted the argument type to the parameter type,
1983   // this is a bad conversion sequence, unless we're resolving an overload in C.
1984   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1985     return false;
1986 
1987   ExprResult ER = ExprResult{From};
1988   Sema::AssignConvertType Conv =
1989       S.CheckSingleAssignmentConstraints(ToType, ER,
1990                                          /*Diagnose=*/false,
1991                                          /*DiagnoseCFAudited=*/false,
1992                                          /*ConvertRHS=*/false);
1993   ImplicitConversionKind SecondConv;
1994   switch (Conv) {
1995   case Sema::Compatible:
1996     SecondConv = ICK_C_Only_Conversion;
1997     break;
1998   // For our purposes, discarding qualifiers is just as bad as using an
1999   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2000   // qualifiers, as well.
2001   case Sema::CompatiblePointerDiscardsQualifiers:
2002   case Sema::IncompatiblePointer:
2003   case Sema::IncompatiblePointerSign:
2004     SecondConv = ICK_Incompatible_Pointer_Conversion;
2005     break;
2006   default:
2007     return false;
2008   }
2009 
2010   // First can only be an lvalue conversion, so we pretend that this was the
2011   // second conversion. First should already be valid from earlier in the
2012   // function.
2013   SCS.Second = SecondConv;
2014   SCS.setToType(1, ToType);
2015 
2016   // Third is Identity, because Second should rank us worse than any other
2017   // conversion. This could also be ICK_Qualification, but it's simpler to just
2018   // lump everything in with the second conversion, and we don't gain anything
2019   // from making this ICK_Qualification.
2020   SCS.Third = ICK_Identity;
2021   SCS.setToType(2, ToType);
2022   return true;
2023 }
2024 
2025 static bool
2026 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2027                                      QualType &ToType,
2028                                      bool InOverloadResolution,
2029                                      StandardConversionSequence &SCS,
2030                                      bool CStyle) {
2031 
2032   const RecordType *UT = ToType->getAsUnionType();
2033   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2034     return false;
2035   // The field to initialize within the transparent union.
2036   RecordDecl *UD = UT->getDecl();
2037   // It's compatible if the expression matches any of the fields.
2038   for (const auto *it : UD->fields()) {
2039     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2040                              CStyle, /*AllowObjCWritebackConversion=*/false)) {
2041       ToType = it->getType();
2042       return true;
2043     }
2044   }
2045   return false;
2046 }
2047 
2048 /// IsIntegralPromotion - Determines whether the conversion from the
2049 /// expression From (whose potentially-adjusted type is FromType) to
2050 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
2051 /// sets PromotedType to the promoted type.
2052 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2053   const BuiltinType *To = ToType->getAs<BuiltinType>();
2054   // All integers are built-in.
2055   if (!To) {
2056     return false;
2057   }
2058 
2059   // An rvalue of type char, signed char, unsigned char, short int, or
2060   // unsigned short int can be converted to an rvalue of type int if
2061   // int can represent all the values of the source type; otherwise,
2062   // the source rvalue can be converted to an rvalue of type unsigned
2063   // int (C++ 4.5p1).
2064   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
2065       !FromType->isEnumeralType()) {
2066     if (// We can promote any signed, promotable integer type to an int
2067         (FromType->isSignedIntegerType() ||
2068          // We can promote any unsigned integer type whose size is
2069          // less than int to an int.
2070          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2071       return To->getKind() == BuiltinType::Int;
2072     }
2073 
2074     return To->getKind() == BuiltinType::UInt;
2075   }
2076 
2077   // C++11 [conv.prom]p3:
2078   //   A prvalue of an unscoped enumeration type whose underlying type is not
2079   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2080   //   following types that can represent all the values of the enumeration
2081   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
2082   //   unsigned int, long int, unsigned long int, long long int, or unsigned
2083   //   long long int. If none of the types in that list can represent all the
2084   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2085   //   type can be converted to an rvalue a prvalue of the extended integer type
2086   //   with lowest integer conversion rank (4.13) greater than the rank of long
2087   //   long in which all the values of the enumeration can be represented. If
2088   //   there are two such extended types, the signed one is chosen.
2089   // C++11 [conv.prom]p4:
2090   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
2091   //   can be converted to a prvalue of its underlying type. Moreover, if
2092   //   integral promotion can be applied to its underlying type, a prvalue of an
2093   //   unscoped enumeration type whose underlying type is fixed can also be
2094   //   converted to a prvalue of the promoted underlying type.
2095   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2096     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2097     // provided for a scoped enumeration.
2098     if (FromEnumType->getDecl()->isScoped())
2099       return false;
2100 
2101     // We can perform an integral promotion to the underlying type of the enum,
2102     // even if that's not the promoted type. Note that the check for promoting
2103     // the underlying type is based on the type alone, and does not consider
2104     // the bitfield-ness of the actual source expression.
2105     if (FromEnumType->getDecl()->isFixed()) {
2106       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2107       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2108              IsIntegralPromotion(nullptr, Underlying, ToType);
2109     }
2110 
2111     // We have already pre-calculated the promotion type, so this is trivial.
2112     if (ToType->isIntegerType() &&
2113         isCompleteType(From->getBeginLoc(), FromType))
2114       return Context.hasSameUnqualifiedType(
2115           ToType, FromEnumType->getDecl()->getPromotionType());
2116 
2117     // C++ [conv.prom]p5:
2118     //   If the bit-field has an enumerated type, it is treated as any other
2119     //   value of that type for promotion purposes.
2120     //
2121     // ... so do not fall through into the bit-field checks below in C++.
2122     if (getLangOpts().CPlusPlus)
2123       return false;
2124   }
2125 
2126   // C++0x [conv.prom]p2:
2127   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2128   //   to an rvalue a prvalue of the first of the following types that can
2129   //   represent all the values of its underlying type: int, unsigned int,
2130   //   long int, unsigned long int, long long int, or unsigned long long int.
2131   //   If none of the types in that list can represent all the values of its
2132   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2133   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2134   //   type.
2135   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2136       ToType->isIntegerType()) {
2137     // Determine whether the type we're converting from is signed or
2138     // unsigned.
2139     bool FromIsSigned = FromType->isSignedIntegerType();
2140     uint64_t FromSize = Context.getTypeSize(FromType);
2141 
2142     // The types we'll try to promote to, in the appropriate
2143     // order. Try each of these types.
2144     QualType PromoteTypes[6] = {
2145       Context.IntTy, Context.UnsignedIntTy,
2146       Context.LongTy, Context.UnsignedLongTy ,
2147       Context.LongLongTy, Context.UnsignedLongLongTy
2148     };
2149     for (int Idx = 0; Idx < 6; ++Idx) {
2150       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2151       if (FromSize < ToSize ||
2152           (FromSize == ToSize &&
2153            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2154         // We found the type that we can promote to. If this is the
2155         // type we wanted, we have a promotion. Otherwise, no
2156         // promotion.
2157         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2158       }
2159     }
2160   }
2161 
2162   // An rvalue for an integral bit-field (9.6) can be converted to an
2163   // rvalue of type int if int can represent all the values of the
2164   // bit-field; otherwise, it can be converted to unsigned int if
2165   // unsigned int can represent all the values of the bit-field. If
2166   // the bit-field is larger yet, no integral promotion applies to
2167   // it. If the bit-field has an enumerated type, it is treated as any
2168   // other value of that type for promotion purposes (C++ 4.5p3).
2169   // FIXME: We should delay checking of bit-fields until we actually perform the
2170   // conversion.
2171   //
2172   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2173   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2174   // bit-fields and those whose underlying type is larger than int) for GCC
2175   // compatibility.
2176   if (From) {
2177     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2178       llvm::APSInt BitWidth;
2179       if (FromType->isIntegralType(Context) &&
2180           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2181         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2182         ToSize = Context.getTypeSize(ToType);
2183 
2184         // Are we promoting to an int from a bitfield that fits in an int?
2185         if (BitWidth < ToSize ||
2186             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2187           return To->getKind() == BuiltinType::Int;
2188         }
2189 
2190         // Are we promoting to an unsigned int from an unsigned bitfield
2191         // that fits into an unsigned int?
2192         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2193           return To->getKind() == BuiltinType::UInt;
2194         }
2195 
2196         return false;
2197       }
2198     }
2199   }
2200 
2201   // An rvalue of type bool can be converted to an rvalue of type int,
2202   // with false becoming zero and true becoming one (C++ 4.5p4).
2203   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2204     return true;
2205   }
2206 
2207   return false;
2208 }
2209 
2210 /// IsFloatingPointPromotion - Determines whether the conversion from
2211 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2212 /// returns true and sets PromotedType to the promoted type.
2213 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2214   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2215     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2216       /// An rvalue of type float can be converted to an rvalue of type
2217       /// double. (C++ 4.6p1).
2218       if (FromBuiltin->getKind() == BuiltinType::Float &&
2219           ToBuiltin->getKind() == BuiltinType::Double)
2220         return true;
2221 
2222       // C99 6.3.1.5p1:
2223       //   When a float is promoted to double or long double, or a
2224       //   double is promoted to long double [...].
2225       if (!getLangOpts().CPlusPlus &&
2226           (FromBuiltin->getKind() == BuiltinType::Float ||
2227            FromBuiltin->getKind() == BuiltinType::Double) &&
2228           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2229            ToBuiltin->getKind() == BuiltinType::Float128))
2230         return true;
2231 
2232       // Half can be promoted to float.
2233       if (!getLangOpts().NativeHalfType &&
2234            FromBuiltin->getKind() == BuiltinType::Half &&
2235           ToBuiltin->getKind() == BuiltinType::Float)
2236         return true;
2237     }
2238 
2239   return false;
2240 }
2241 
2242 /// Determine if a conversion is a complex promotion.
2243 ///
2244 /// A complex promotion is defined as a complex -> complex conversion
2245 /// where the conversion between the underlying real types is a
2246 /// floating-point or integral promotion.
2247 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2248   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2249   if (!FromComplex)
2250     return false;
2251 
2252   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2253   if (!ToComplex)
2254     return false;
2255 
2256   return IsFloatingPointPromotion(FromComplex->getElementType(),
2257                                   ToComplex->getElementType()) ||
2258     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2259                         ToComplex->getElementType());
2260 }
2261 
2262 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2263 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2264 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2265 /// if non-empty, will be a pointer to ToType that may or may not have
2266 /// the right set of qualifiers on its pointee.
2267 ///
2268 static QualType
2269 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2270                                    QualType ToPointee, QualType ToType,
2271                                    ASTContext &Context,
2272                                    bool StripObjCLifetime = false) {
2273   assert((FromPtr->getTypeClass() == Type::Pointer ||
2274           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2275          "Invalid similarly-qualified pointer type");
2276 
2277   /// Conversions to 'id' subsume cv-qualifier conversions.
2278   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2279     return ToType.getUnqualifiedType();
2280 
2281   QualType CanonFromPointee
2282     = Context.getCanonicalType(FromPtr->getPointeeType());
2283   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2284   Qualifiers Quals = CanonFromPointee.getQualifiers();
2285 
2286   if (StripObjCLifetime)
2287     Quals.removeObjCLifetime();
2288 
2289   // Exact qualifier match -> return the pointer type we're converting to.
2290   if (CanonToPointee.getLocalQualifiers() == Quals) {
2291     // ToType is exactly what we need. Return it.
2292     if (!ToType.isNull())
2293       return ToType.getUnqualifiedType();
2294 
2295     // Build a pointer to ToPointee. It has the right qualifiers
2296     // already.
2297     if (isa<ObjCObjectPointerType>(ToType))
2298       return Context.getObjCObjectPointerType(ToPointee);
2299     return Context.getPointerType(ToPointee);
2300   }
2301 
2302   // Just build a canonical type that has the right qualifiers.
2303   QualType QualifiedCanonToPointee
2304     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2305 
2306   if (isa<ObjCObjectPointerType>(ToType))
2307     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2308   return Context.getPointerType(QualifiedCanonToPointee);
2309 }
2310 
2311 static bool isNullPointerConstantForConversion(Expr *Expr,
2312                                                bool InOverloadResolution,
2313                                                ASTContext &Context) {
2314   // Handle value-dependent integral null pointer constants correctly.
2315   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2316   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2317       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2318     return !InOverloadResolution;
2319 
2320   return Expr->isNullPointerConstant(Context,
2321                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2322                                         : Expr::NPC_ValueDependentIsNull);
2323 }
2324 
2325 /// IsPointerConversion - Determines whether the conversion of the
2326 /// expression From, which has the (possibly adjusted) type FromType,
2327 /// can be converted to the type ToType via a pointer conversion (C++
2328 /// 4.10). If so, returns true and places the converted type (that
2329 /// might differ from ToType in its cv-qualifiers at some level) into
2330 /// ConvertedType.
2331 ///
2332 /// This routine also supports conversions to and from block pointers
2333 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2334 /// pointers to interfaces. FIXME: Once we've determined the
2335 /// appropriate overloading rules for Objective-C, we may want to
2336 /// split the Objective-C checks into a different routine; however,
2337 /// GCC seems to consider all of these conversions to be pointer
2338 /// conversions, so for now they live here. IncompatibleObjC will be
2339 /// set if the conversion is an allowed Objective-C conversion that
2340 /// should result in a warning.
2341 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2342                                bool InOverloadResolution,
2343                                QualType& ConvertedType,
2344                                bool &IncompatibleObjC) {
2345   IncompatibleObjC = false;
2346   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2347                               IncompatibleObjC))
2348     return true;
2349 
2350   // Conversion from a null pointer constant to any Objective-C pointer type.
2351   if (ToType->isObjCObjectPointerType() &&
2352       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2353     ConvertedType = ToType;
2354     return true;
2355   }
2356 
2357   // Blocks: Block pointers can be converted to void*.
2358   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2359       ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2360     ConvertedType = ToType;
2361     return true;
2362   }
2363   // Blocks: A null pointer constant can be converted to a block
2364   // pointer type.
2365   if (ToType->isBlockPointerType() &&
2366       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2367     ConvertedType = ToType;
2368     return true;
2369   }
2370 
2371   // If the left-hand-side is nullptr_t, the right side can be a null
2372   // pointer constant.
2373   if (ToType->isNullPtrType() &&
2374       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2375     ConvertedType = ToType;
2376     return true;
2377   }
2378 
2379   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2380   if (!ToTypePtr)
2381     return false;
2382 
2383   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2384   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2385     ConvertedType = ToType;
2386     return true;
2387   }
2388 
2389   // Beyond this point, both types need to be pointers
2390   // , including objective-c pointers.
2391   QualType ToPointeeType = ToTypePtr->getPointeeType();
2392   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2393       !getLangOpts().ObjCAutoRefCount) {
2394     ConvertedType = BuildSimilarlyQualifiedPointerType(
2395                                       FromType->getAs<ObjCObjectPointerType>(),
2396                                                        ToPointeeType,
2397                                                        ToType, Context);
2398     return true;
2399   }
2400   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2401   if (!FromTypePtr)
2402     return false;
2403 
2404   QualType FromPointeeType = FromTypePtr->getPointeeType();
2405 
2406   // If the unqualified pointee types are the same, this can't be a
2407   // pointer conversion, so don't do all of the work below.
2408   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2409     return false;
2410 
2411   // An rvalue of type "pointer to cv T," where T is an object type,
2412   // can be converted to an rvalue of type "pointer to cv void" (C++
2413   // 4.10p2).
2414   if (FromPointeeType->isIncompleteOrObjectType() &&
2415       ToPointeeType->isVoidType()) {
2416     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2417                                                        ToPointeeType,
2418                                                        ToType, Context,
2419                                                    /*StripObjCLifetime=*/true);
2420     return true;
2421   }
2422 
2423   // MSVC allows implicit function to void* type conversion.
2424   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2425       ToPointeeType->isVoidType()) {
2426     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2427                                                        ToPointeeType,
2428                                                        ToType, Context);
2429     return true;
2430   }
2431 
2432   // When we're overloading in C, we allow a special kind of pointer
2433   // conversion for compatible-but-not-identical pointee types.
2434   if (!getLangOpts().CPlusPlus &&
2435       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2436     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2437                                                        ToPointeeType,
2438                                                        ToType, Context);
2439     return true;
2440   }
2441 
2442   // C++ [conv.ptr]p3:
2443   //
2444   //   An rvalue of type "pointer to cv D," where D is a class type,
2445   //   can be converted to an rvalue of type "pointer to cv B," where
2446   //   B is a base class (clause 10) of D. If B is an inaccessible
2447   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2448   //   necessitates this conversion is ill-formed. The result of the
2449   //   conversion is a pointer to the base class sub-object of the
2450   //   derived class object. The null pointer value is converted to
2451   //   the null pointer value of the destination type.
2452   //
2453   // Note that we do not check for ambiguity or inaccessibility
2454   // here. That is handled by CheckPointerConversion.
2455   if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2456       ToPointeeType->isRecordType() &&
2457       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2458       IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2459     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2460                                                        ToPointeeType,
2461                                                        ToType, Context);
2462     return true;
2463   }
2464 
2465   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2466       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2467     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2468                                                        ToPointeeType,
2469                                                        ToType, Context);
2470     return true;
2471   }
2472 
2473   return false;
2474 }
2475 
2476 /// Adopt the given qualifiers for the given type.
2477 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2478   Qualifiers TQs = T.getQualifiers();
2479 
2480   // Check whether qualifiers already match.
2481   if (TQs == Qs)
2482     return T;
2483 
2484   if (Qs.compatiblyIncludes(TQs))
2485     return Context.getQualifiedType(T, Qs);
2486 
2487   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2488 }
2489 
2490 /// isObjCPointerConversion - Determines whether this is an
2491 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2492 /// with the same arguments and return values.
2493 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2494                                    QualType& ConvertedType,
2495                                    bool &IncompatibleObjC) {
2496   if (!getLangOpts().ObjC)
2497     return false;
2498 
2499   // The set of qualifiers on the type we're converting from.
2500   Qualifiers FromQualifiers = FromType.getQualifiers();
2501 
2502   // First, we handle all conversions on ObjC object pointer types.
2503   const ObjCObjectPointerType* ToObjCPtr =
2504     ToType->getAs<ObjCObjectPointerType>();
2505   const ObjCObjectPointerType *FromObjCPtr =
2506     FromType->getAs<ObjCObjectPointerType>();
2507 
2508   if (ToObjCPtr && FromObjCPtr) {
2509     // If the pointee types are the same (ignoring qualifications),
2510     // then this is not a pointer conversion.
2511     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2512                                        FromObjCPtr->getPointeeType()))
2513       return false;
2514 
2515     // Conversion between Objective-C pointers.
2516     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2517       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2518       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2519       if (getLangOpts().CPlusPlus && LHS && RHS &&
2520           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2521                                                 FromObjCPtr->getPointeeType()))
2522         return false;
2523       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2524                                                    ToObjCPtr->getPointeeType(),
2525                                                          ToType, Context);
2526       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2527       return true;
2528     }
2529 
2530     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2531       // Okay: this is some kind of implicit downcast of Objective-C
2532       // interfaces, which is permitted. However, we're going to
2533       // complain about it.
2534       IncompatibleObjC = true;
2535       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2536                                                    ToObjCPtr->getPointeeType(),
2537                                                          ToType, Context);
2538       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2539       return true;
2540     }
2541   }
2542   // Beyond this point, both types need to be C pointers or block pointers.
2543   QualType ToPointeeType;
2544   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2545     ToPointeeType = ToCPtr->getPointeeType();
2546   else if (const BlockPointerType *ToBlockPtr =
2547             ToType->getAs<BlockPointerType>()) {
2548     // Objective C++: We're able to convert from a pointer to any object
2549     // to a block pointer type.
2550     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2551       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2552       return true;
2553     }
2554     ToPointeeType = ToBlockPtr->getPointeeType();
2555   }
2556   else if (FromType->getAs<BlockPointerType>() &&
2557            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2558     // Objective C++: We're able to convert from a block pointer type to a
2559     // pointer to any object.
2560     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2561     return true;
2562   }
2563   else
2564     return false;
2565 
2566   QualType FromPointeeType;
2567   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2568     FromPointeeType = FromCPtr->getPointeeType();
2569   else if (const BlockPointerType *FromBlockPtr =
2570            FromType->getAs<BlockPointerType>())
2571     FromPointeeType = FromBlockPtr->getPointeeType();
2572   else
2573     return false;
2574 
2575   // If we have pointers to pointers, recursively check whether this
2576   // is an Objective-C conversion.
2577   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2578       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2579                               IncompatibleObjC)) {
2580     // We always complain about this conversion.
2581     IncompatibleObjC = true;
2582     ConvertedType = Context.getPointerType(ConvertedType);
2583     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2584     return true;
2585   }
2586   // Allow conversion of pointee being objective-c pointer to another one;
2587   // as in I* to id.
2588   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2589       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2590       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2591                               IncompatibleObjC)) {
2592 
2593     ConvertedType = Context.getPointerType(ConvertedType);
2594     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2595     return true;
2596   }
2597 
2598   // If we have pointers to functions or blocks, check whether the only
2599   // differences in the argument and result types are in Objective-C
2600   // pointer conversions. If so, we permit the conversion (but
2601   // complain about it).
2602   const FunctionProtoType *FromFunctionType
2603     = FromPointeeType->getAs<FunctionProtoType>();
2604   const FunctionProtoType *ToFunctionType
2605     = ToPointeeType->getAs<FunctionProtoType>();
2606   if (FromFunctionType && ToFunctionType) {
2607     // If the function types are exactly the same, this isn't an
2608     // Objective-C pointer conversion.
2609     if (Context.getCanonicalType(FromPointeeType)
2610           == Context.getCanonicalType(ToPointeeType))
2611       return false;
2612 
2613     // Perform the quick checks that will tell us whether these
2614     // function types are obviously different.
2615     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2616         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2617         FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2618       return false;
2619 
2620     bool HasObjCConversion = false;
2621     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2622         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2623       // Okay, the types match exactly. Nothing to do.
2624     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2625                                        ToFunctionType->getReturnType(),
2626                                        ConvertedType, IncompatibleObjC)) {
2627       // Okay, we have an Objective-C pointer conversion.
2628       HasObjCConversion = true;
2629     } else {
2630       // Function types are too different. Abort.
2631       return false;
2632     }
2633 
2634     // Check argument types.
2635     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2636          ArgIdx != NumArgs; ++ArgIdx) {
2637       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2638       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2639       if (Context.getCanonicalType(FromArgType)
2640             == Context.getCanonicalType(ToArgType)) {
2641         // Okay, the types match exactly. Nothing to do.
2642       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2643                                          ConvertedType, IncompatibleObjC)) {
2644         // Okay, we have an Objective-C pointer conversion.
2645         HasObjCConversion = true;
2646       } else {
2647         // Argument types are too different. Abort.
2648         return false;
2649       }
2650     }
2651 
2652     if (HasObjCConversion) {
2653       // We had an Objective-C conversion. Allow this pointer
2654       // conversion, but complain about it.
2655       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2656       IncompatibleObjC = true;
2657       return true;
2658     }
2659   }
2660 
2661   return false;
2662 }
2663 
2664 /// Determine whether this is an Objective-C writeback conversion,
2665 /// used for parameter passing when performing automatic reference counting.
2666 ///
2667 /// \param FromType The type we're converting form.
2668 ///
2669 /// \param ToType The type we're converting to.
2670 ///
2671 /// \param ConvertedType The type that will be produced after applying
2672 /// this conversion.
2673 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2674                                      QualType &ConvertedType) {
2675   if (!getLangOpts().ObjCAutoRefCount ||
2676       Context.hasSameUnqualifiedType(FromType, ToType))
2677     return false;
2678 
2679   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2680   QualType ToPointee;
2681   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2682     ToPointee = ToPointer->getPointeeType();
2683   else
2684     return false;
2685 
2686   Qualifiers ToQuals = ToPointee.getQualifiers();
2687   if (!ToPointee->isObjCLifetimeType() ||
2688       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2689       !ToQuals.withoutObjCLifetime().empty())
2690     return false;
2691 
2692   // Argument must be a pointer to __strong to __weak.
2693   QualType FromPointee;
2694   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2695     FromPointee = FromPointer->getPointeeType();
2696   else
2697     return false;
2698 
2699   Qualifiers FromQuals = FromPointee.getQualifiers();
2700   if (!FromPointee->isObjCLifetimeType() ||
2701       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2702        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2703     return false;
2704 
2705   // Make sure that we have compatible qualifiers.
2706   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2707   if (!ToQuals.compatiblyIncludes(FromQuals))
2708     return false;
2709 
2710   // Remove qualifiers from the pointee type we're converting from; they
2711   // aren't used in the compatibility check belong, and we'll be adding back
2712   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2713   FromPointee = FromPointee.getUnqualifiedType();
2714 
2715   // The unqualified form of the pointee types must be compatible.
2716   ToPointee = ToPointee.getUnqualifiedType();
2717   bool IncompatibleObjC;
2718   if (Context.typesAreCompatible(FromPointee, ToPointee))
2719     FromPointee = ToPointee;
2720   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2721                                     IncompatibleObjC))
2722     return false;
2723 
2724   /// Construct the type we're converting to, which is a pointer to
2725   /// __autoreleasing pointee.
2726   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2727   ConvertedType = Context.getPointerType(FromPointee);
2728   return true;
2729 }
2730 
2731 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2732                                     QualType& ConvertedType) {
2733   QualType ToPointeeType;
2734   if (const BlockPointerType *ToBlockPtr =
2735         ToType->getAs<BlockPointerType>())
2736     ToPointeeType = ToBlockPtr->getPointeeType();
2737   else
2738     return false;
2739 
2740   QualType FromPointeeType;
2741   if (const BlockPointerType *FromBlockPtr =
2742       FromType->getAs<BlockPointerType>())
2743     FromPointeeType = FromBlockPtr->getPointeeType();
2744   else
2745     return false;
2746   // We have pointer to blocks, check whether the only
2747   // differences in the argument and result types are in Objective-C
2748   // pointer conversions. If so, we permit the conversion.
2749 
2750   const FunctionProtoType *FromFunctionType
2751     = FromPointeeType->getAs<FunctionProtoType>();
2752   const FunctionProtoType *ToFunctionType
2753     = ToPointeeType->getAs<FunctionProtoType>();
2754 
2755   if (!FromFunctionType || !ToFunctionType)
2756     return false;
2757 
2758   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2759     return true;
2760 
2761   // Perform the quick checks that will tell us whether these
2762   // function types are obviously different.
2763   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2764       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2765     return false;
2766 
2767   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2768   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2769   if (FromEInfo != ToEInfo)
2770     return false;
2771 
2772   bool IncompatibleObjC = false;
2773   if (Context.hasSameType(FromFunctionType->getReturnType(),
2774                           ToFunctionType->getReturnType())) {
2775     // Okay, the types match exactly. Nothing to do.
2776   } else {
2777     QualType RHS = FromFunctionType->getReturnType();
2778     QualType LHS = ToFunctionType->getReturnType();
2779     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2780         !RHS.hasQualifiers() && LHS.hasQualifiers())
2781        LHS = LHS.getUnqualifiedType();
2782 
2783      if (Context.hasSameType(RHS,LHS)) {
2784        // OK exact match.
2785      } else if (isObjCPointerConversion(RHS, LHS,
2786                                         ConvertedType, IncompatibleObjC)) {
2787      if (IncompatibleObjC)
2788        return false;
2789      // Okay, we have an Objective-C pointer conversion.
2790      }
2791      else
2792        return false;
2793    }
2794 
2795    // Check argument types.
2796    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2797         ArgIdx != NumArgs; ++ArgIdx) {
2798      IncompatibleObjC = false;
2799      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2800      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2801      if (Context.hasSameType(FromArgType, ToArgType)) {
2802        // Okay, the types match exactly. Nothing to do.
2803      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2804                                         ConvertedType, IncompatibleObjC)) {
2805        if (IncompatibleObjC)
2806          return false;
2807        // Okay, we have an Objective-C pointer conversion.
2808      } else
2809        // Argument types are too different. Abort.
2810        return false;
2811    }
2812 
2813    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2814    bool CanUseToFPT, CanUseFromFPT;
2815    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2816                                       CanUseToFPT, CanUseFromFPT,
2817                                       NewParamInfos))
2818      return false;
2819 
2820    ConvertedType = ToType;
2821    return true;
2822 }
2823 
2824 enum {
2825   ft_default,
2826   ft_different_class,
2827   ft_parameter_arity,
2828   ft_parameter_mismatch,
2829   ft_return_type,
2830   ft_qualifer_mismatch,
2831   ft_noexcept
2832 };
2833 
2834 /// Attempts to get the FunctionProtoType from a Type. Handles
2835 /// MemberFunctionPointers properly.
2836 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2837   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2838     return FPT;
2839 
2840   if (auto *MPT = FromType->getAs<MemberPointerType>())
2841     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2842 
2843   return nullptr;
2844 }
2845 
2846 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2847 /// function types.  Catches different number of parameter, mismatch in
2848 /// parameter types, and different return types.
2849 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2850                                       QualType FromType, QualType ToType) {
2851   // If either type is not valid, include no extra info.
2852   if (FromType.isNull() || ToType.isNull()) {
2853     PDiag << ft_default;
2854     return;
2855   }
2856 
2857   // Get the function type from the pointers.
2858   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2859     const auto *FromMember = FromType->castAs<MemberPointerType>(),
2860                *ToMember = ToType->castAs<MemberPointerType>();
2861     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2862       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2863             << QualType(FromMember->getClass(), 0);
2864       return;
2865     }
2866     FromType = FromMember->getPointeeType();
2867     ToType = ToMember->getPointeeType();
2868   }
2869 
2870   if (FromType->isPointerType())
2871     FromType = FromType->getPointeeType();
2872   if (ToType->isPointerType())
2873     ToType = ToType->getPointeeType();
2874 
2875   // Remove references.
2876   FromType = FromType.getNonReferenceType();
2877   ToType = ToType.getNonReferenceType();
2878 
2879   // Don't print extra info for non-specialized template functions.
2880   if (FromType->isInstantiationDependentType() &&
2881       !FromType->getAs<TemplateSpecializationType>()) {
2882     PDiag << ft_default;
2883     return;
2884   }
2885 
2886   // No extra info for same types.
2887   if (Context.hasSameType(FromType, ToType)) {
2888     PDiag << ft_default;
2889     return;
2890   }
2891 
2892   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2893                           *ToFunction = tryGetFunctionProtoType(ToType);
2894 
2895   // Both types need to be function types.
2896   if (!FromFunction || !ToFunction) {
2897     PDiag << ft_default;
2898     return;
2899   }
2900 
2901   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2902     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2903           << FromFunction->getNumParams();
2904     return;
2905   }
2906 
2907   // Handle different parameter types.
2908   unsigned ArgPos;
2909   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2910     PDiag << ft_parameter_mismatch << ArgPos + 1
2911           << ToFunction->getParamType(ArgPos)
2912           << FromFunction->getParamType(ArgPos);
2913     return;
2914   }
2915 
2916   // Handle different return type.
2917   if (!Context.hasSameType(FromFunction->getReturnType(),
2918                            ToFunction->getReturnType())) {
2919     PDiag << ft_return_type << ToFunction->getReturnType()
2920           << FromFunction->getReturnType();
2921     return;
2922   }
2923 
2924   if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2925     PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2926           << FromFunction->getMethodQuals();
2927     return;
2928   }
2929 
2930   // Handle exception specification differences on canonical type (in C++17
2931   // onwards).
2932   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2933           ->isNothrow() !=
2934       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2935           ->isNothrow()) {
2936     PDiag << ft_noexcept;
2937     return;
2938   }
2939 
2940   // Unable to find a difference, so add no extra info.
2941   PDiag << ft_default;
2942 }
2943 
2944 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2945 /// for equality of their argument types. Caller has already checked that
2946 /// they have same number of arguments.  If the parameters are different,
2947 /// ArgPos will have the parameter index of the first different parameter.
2948 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2949                                       const FunctionProtoType *NewType,
2950                                       unsigned *ArgPos) {
2951   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2952                                               N = NewType->param_type_begin(),
2953                                               E = OldType->param_type_end();
2954        O && (O != E); ++O, ++N) {
2955     // Ignore address spaces in pointee type. This is to disallow overloading
2956     // on __ptr32/__ptr64 address spaces.
2957     QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType());
2958     QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType());
2959 
2960     if (!Context.hasSameType(Old, New)) {
2961       if (ArgPos)
2962         *ArgPos = O - OldType->param_type_begin();
2963       return false;
2964     }
2965   }
2966   return true;
2967 }
2968 
2969 /// CheckPointerConversion - Check the pointer conversion from the
2970 /// expression From to the type ToType. This routine checks for
2971 /// ambiguous or inaccessible derived-to-base pointer
2972 /// conversions for which IsPointerConversion has already returned
2973 /// true. It returns true and produces a diagnostic if there was an
2974 /// error, or returns false otherwise.
2975 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2976                                   CastKind &Kind,
2977                                   CXXCastPath& BasePath,
2978                                   bool IgnoreBaseAccess,
2979                                   bool Diagnose) {
2980   QualType FromType = From->getType();
2981   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2982 
2983   Kind = CK_BitCast;
2984 
2985   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2986       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2987           Expr::NPCK_ZeroExpression) {
2988     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2989       DiagRuntimeBehavior(From->getExprLoc(), From,
2990                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2991                             << ToType << From->getSourceRange());
2992     else if (!isUnevaluatedContext())
2993       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2994         << ToType << From->getSourceRange();
2995   }
2996   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2997     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2998       QualType FromPointeeType = FromPtrType->getPointeeType(),
2999                ToPointeeType   = ToPtrType->getPointeeType();
3000 
3001       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3002           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3003         // We must have a derived-to-base conversion. Check an
3004         // ambiguous or inaccessible conversion.
3005         unsigned InaccessibleID = 0;
3006         unsigned AmbigiousID = 0;
3007         if (Diagnose) {
3008           InaccessibleID = diag::err_upcast_to_inaccessible_base;
3009           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
3010         }
3011         if (CheckDerivedToBaseConversion(
3012                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
3013                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3014                 &BasePath, IgnoreBaseAccess))
3015           return true;
3016 
3017         // The conversion was successful.
3018         Kind = CK_DerivedToBase;
3019       }
3020 
3021       if (Diagnose && !IsCStyleOrFunctionalCast &&
3022           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3023         assert(getLangOpts().MSVCCompat &&
3024                "this should only be possible with MSVCCompat!");
3025         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3026             << From->getSourceRange();
3027       }
3028     }
3029   } else if (const ObjCObjectPointerType *ToPtrType =
3030                ToType->getAs<ObjCObjectPointerType>()) {
3031     if (const ObjCObjectPointerType *FromPtrType =
3032           FromType->getAs<ObjCObjectPointerType>()) {
3033       // Objective-C++ conversions are always okay.
3034       // FIXME: We should have a different class of conversions for the
3035       // Objective-C++ implicit conversions.
3036       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3037         return false;
3038     } else if (FromType->isBlockPointerType()) {
3039       Kind = CK_BlockPointerToObjCPointerCast;
3040     } else {
3041       Kind = CK_CPointerToObjCPointerCast;
3042     }
3043   } else if (ToType->isBlockPointerType()) {
3044     if (!FromType->isBlockPointerType())
3045       Kind = CK_AnyPointerToBlockPointerCast;
3046   }
3047 
3048   // We shouldn't fall into this case unless it's valid for other
3049   // reasons.
3050   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3051     Kind = CK_NullToPointer;
3052 
3053   return false;
3054 }
3055 
3056 /// IsMemberPointerConversion - Determines whether the conversion of the
3057 /// expression From, which has the (possibly adjusted) type FromType, can be
3058 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
3059 /// If so, returns true and places the converted type (that might differ from
3060 /// ToType in its cv-qualifiers at some level) into ConvertedType.
3061 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3062                                      QualType ToType,
3063                                      bool InOverloadResolution,
3064                                      QualType &ConvertedType) {
3065   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3066   if (!ToTypePtr)
3067     return false;
3068 
3069   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3070   if (From->isNullPointerConstant(Context,
3071                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3072                                         : Expr::NPC_ValueDependentIsNull)) {
3073     ConvertedType = ToType;
3074     return true;
3075   }
3076 
3077   // Otherwise, both types have to be member pointers.
3078   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3079   if (!FromTypePtr)
3080     return false;
3081 
3082   // A pointer to member of B can be converted to a pointer to member of D,
3083   // where D is derived from B (C++ 4.11p2).
3084   QualType FromClass(FromTypePtr->getClass(), 0);
3085   QualType ToClass(ToTypePtr->getClass(), 0);
3086 
3087   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3088       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3089     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3090                                                  ToClass.getTypePtr());
3091     return true;
3092   }
3093 
3094   return false;
3095 }
3096 
3097 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3098 /// expression From to the type ToType. This routine checks for ambiguous or
3099 /// virtual or inaccessible base-to-derived member pointer conversions
3100 /// for which IsMemberPointerConversion has already returned true. It returns
3101 /// true and produces a diagnostic if there was an error, or returns false
3102 /// otherwise.
3103 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3104                                         CastKind &Kind,
3105                                         CXXCastPath &BasePath,
3106                                         bool IgnoreBaseAccess) {
3107   QualType FromType = From->getType();
3108   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3109   if (!FromPtrType) {
3110     // This must be a null pointer to member pointer conversion
3111     assert(From->isNullPointerConstant(Context,
3112                                        Expr::NPC_ValueDependentIsNull) &&
3113            "Expr must be null pointer constant!");
3114     Kind = CK_NullToMemberPointer;
3115     return false;
3116   }
3117 
3118   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3119   assert(ToPtrType && "No member pointer cast has a target type "
3120                       "that is not a member pointer.");
3121 
3122   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3123   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3124 
3125   // FIXME: What about dependent types?
3126   assert(FromClass->isRecordType() && "Pointer into non-class.");
3127   assert(ToClass->isRecordType() && "Pointer into non-class.");
3128 
3129   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3130                      /*DetectVirtual=*/true);
3131   bool DerivationOkay =
3132       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3133   assert(DerivationOkay &&
3134          "Should not have been called if derivation isn't OK.");
3135   (void)DerivationOkay;
3136 
3137   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3138                                   getUnqualifiedType())) {
3139     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3140     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3141       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3142     return true;
3143   }
3144 
3145   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3146     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3147       << FromClass << ToClass << QualType(VBase, 0)
3148       << From->getSourceRange();
3149     return true;
3150   }
3151 
3152   if (!IgnoreBaseAccess)
3153     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3154                          Paths.front(),
3155                          diag::err_downcast_from_inaccessible_base);
3156 
3157   // Must be a base to derived member conversion.
3158   BuildBasePathArray(Paths, BasePath);
3159   Kind = CK_BaseToDerivedMemberPointer;
3160   return false;
3161 }
3162 
3163 /// Determine whether the lifetime conversion between the two given
3164 /// qualifiers sets is nontrivial.
3165 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3166                                                Qualifiers ToQuals) {
3167   // Converting anything to const __unsafe_unretained is trivial.
3168   if (ToQuals.hasConst() &&
3169       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3170     return false;
3171 
3172   return true;
3173 }
3174 
3175 /// Perform a single iteration of the loop for checking if a qualification
3176 /// conversion is valid.
3177 ///
3178 /// Specifically, check whether any change between the qualifiers of \p
3179 /// FromType and \p ToType is permissible, given knowledge about whether every
3180 /// outer layer is const-qualified.
3181 static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3182                                           bool CStyle, bool IsTopLevel,
3183                                           bool &PreviousToQualsIncludeConst,
3184                                           bool &ObjCLifetimeConversion) {
3185   Qualifiers FromQuals = FromType.getQualifiers();
3186   Qualifiers ToQuals = ToType.getQualifiers();
3187 
3188   // Ignore __unaligned qualifier if this type is void.
3189   if (ToType.getUnqualifiedType()->isVoidType())
3190     FromQuals.removeUnaligned();
3191 
3192   // Objective-C ARC:
3193   //   Check Objective-C lifetime conversions.
3194   if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3195     if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3196       if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3197         ObjCLifetimeConversion = true;
3198       FromQuals.removeObjCLifetime();
3199       ToQuals.removeObjCLifetime();
3200     } else {
3201       // Qualification conversions cannot cast between different
3202       // Objective-C lifetime qualifiers.
3203       return false;
3204     }
3205   }
3206 
3207   // Allow addition/removal of GC attributes but not changing GC attributes.
3208   if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3209       (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3210     FromQuals.removeObjCGCAttr();
3211     ToQuals.removeObjCGCAttr();
3212   }
3213 
3214   //   -- for every j > 0, if const is in cv 1,j then const is in cv
3215   //      2,j, and similarly for volatile.
3216   if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3217     return false;
3218 
3219   // If address spaces mismatch:
3220   //  - in top level it is only valid to convert to addr space that is a
3221   //    superset in all cases apart from C-style casts where we allow
3222   //    conversions between overlapping address spaces.
3223   //  - in non-top levels it is not a valid conversion.
3224   if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3225       (!IsTopLevel ||
3226        !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3227          (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3228     return false;
3229 
3230   //   -- if the cv 1,j and cv 2,j are different, then const is in
3231   //      every cv for 0 < k < j.
3232   if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3233       !PreviousToQualsIncludeConst)
3234     return false;
3235 
3236   // Keep track of whether all prior cv-qualifiers in the "to" type
3237   // include const.
3238   PreviousToQualsIncludeConst =
3239       PreviousToQualsIncludeConst && ToQuals.hasConst();
3240   return true;
3241 }
3242 
3243 /// IsQualificationConversion - Determines whether the conversion from
3244 /// an rvalue of type FromType to ToType is a qualification conversion
3245 /// (C++ 4.4).
3246 ///
3247 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3248 /// when the qualification conversion involves a change in the Objective-C
3249 /// object lifetime.
3250 bool
3251 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3252                                 bool CStyle, bool &ObjCLifetimeConversion) {
3253   FromType = Context.getCanonicalType(FromType);
3254   ToType = Context.getCanonicalType(ToType);
3255   ObjCLifetimeConversion = false;
3256 
3257   // If FromType and ToType are the same type, this is not a
3258   // qualification conversion.
3259   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3260     return false;
3261 
3262   // (C++ 4.4p4):
3263   //   A conversion can add cv-qualifiers at levels other than the first
3264   //   in multi-level pointers, subject to the following rules: [...]
3265   bool PreviousToQualsIncludeConst = true;
3266   bool UnwrappedAnyPointer = false;
3267   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3268     if (!isQualificationConversionStep(
3269             FromType, ToType, CStyle, !UnwrappedAnyPointer,
3270             PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3271       return false;
3272     UnwrappedAnyPointer = true;
3273   }
3274 
3275   // We are left with FromType and ToType being the pointee types
3276   // after unwrapping the original FromType and ToType the same number
3277   // of times. If we unwrapped any pointers, and if FromType and
3278   // ToType have the same unqualified type (since we checked
3279   // qualifiers above), then this is a qualification conversion.
3280   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3281 }
3282 
3283 /// - Determine whether this is a conversion from a scalar type to an
3284 /// atomic type.
3285 ///
3286 /// If successful, updates \c SCS's second and third steps in the conversion
3287 /// sequence to finish the conversion.
3288 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3289                                 bool InOverloadResolution,
3290                                 StandardConversionSequence &SCS,
3291                                 bool CStyle) {
3292   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3293   if (!ToAtomic)
3294     return false;
3295 
3296   StandardConversionSequence InnerSCS;
3297   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3298                             InOverloadResolution, InnerSCS,
3299                             CStyle, /*AllowObjCWritebackConversion=*/false))
3300     return false;
3301 
3302   SCS.Second = InnerSCS.Second;
3303   SCS.setToType(1, InnerSCS.getToType(1));
3304   SCS.Third = InnerSCS.Third;
3305   SCS.QualificationIncludesObjCLifetime
3306     = InnerSCS.QualificationIncludesObjCLifetime;
3307   SCS.setToType(2, InnerSCS.getToType(2));
3308   return true;
3309 }
3310 
3311 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3312                                               CXXConstructorDecl *Constructor,
3313                                               QualType Type) {
3314   const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3315   if (CtorType->getNumParams() > 0) {
3316     QualType FirstArg = CtorType->getParamType(0);
3317     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3318       return true;
3319   }
3320   return false;
3321 }
3322 
3323 static OverloadingResult
3324 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3325                                        CXXRecordDecl *To,
3326                                        UserDefinedConversionSequence &User,
3327                                        OverloadCandidateSet &CandidateSet,
3328                                        bool AllowExplicit) {
3329   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3330   for (auto *D : S.LookupConstructors(To)) {
3331     auto Info = getConstructorInfo(D);
3332     if (!Info)
3333       continue;
3334 
3335     bool Usable = !Info.Constructor->isInvalidDecl() &&
3336                   S.isInitListConstructor(Info.Constructor);
3337     if (Usable) {
3338       // If the first argument is (a reference to) the target type,
3339       // suppress conversions.
3340       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3341           S.Context, Info.Constructor, ToType);
3342       if (Info.ConstructorTmpl)
3343         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3344                                        /*ExplicitArgs*/ nullptr, From,
3345                                        CandidateSet, SuppressUserConversions,
3346                                        /*PartialOverloading*/ false,
3347                                        AllowExplicit);
3348       else
3349         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3350                                CandidateSet, SuppressUserConversions,
3351                                /*PartialOverloading*/ false, AllowExplicit);
3352     }
3353   }
3354 
3355   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3356 
3357   OverloadCandidateSet::iterator Best;
3358   switch (auto Result =
3359               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3360   case OR_Deleted:
3361   case OR_Success: {
3362     // Record the standard conversion we used and the conversion function.
3363     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3364     QualType ThisType = Constructor->getThisType();
3365     // Initializer lists don't have conversions as such.
3366     User.Before.setAsIdentityConversion();
3367     User.HadMultipleCandidates = HadMultipleCandidates;
3368     User.ConversionFunction = Constructor;
3369     User.FoundConversionFunction = Best->FoundDecl;
3370     User.After.setAsIdentityConversion();
3371     User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3372     User.After.setAllToTypes(ToType);
3373     return Result;
3374   }
3375 
3376   case OR_No_Viable_Function:
3377     return OR_No_Viable_Function;
3378   case OR_Ambiguous:
3379     return OR_Ambiguous;
3380   }
3381 
3382   llvm_unreachable("Invalid OverloadResult!");
3383 }
3384 
3385 /// Determines whether there is a user-defined conversion sequence
3386 /// (C++ [over.ics.user]) that converts expression From to the type
3387 /// ToType. If such a conversion exists, User will contain the
3388 /// user-defined conversion sequence that performs such a conversion
3389 /// and this routine will return true. Otherwise, this routine returns
3390 /// false and User is unspecified.
3391 ///
3392 /// \param AllowExplicit  true if the conversion should consider C++0x
3393 /// "explicit" conversion functions as well as non-explicit conversion
3394 /// functions (C++0x [class.conv.fct]p2).
3395 ///
3396 /// \param AllowObjCConversionOnExplicit true if the conversion should
3397 /// allow an extra Objective-C pointer conversion on uses of explicit
3398 /// constructors. Requires \c AllowExplicit to also be set.
3399 static OverloadingResult
3400 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3401                         UserDefinedConversionSequence &User,
3402                         OverloadCandidateSet &CandidateSet,
3403                         AllowedExplicit AllowExplicit,
3404                         bool AllowObjCConversionOnExplicit) {
3405   assert(AllowExplicit != AllowedExplicit::None ||
3406          !AllowObjCConversionOnExplicit);
3407   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3408 
3409   // Whether we will only visit constructors.
3410   bool ConstructorsOnly = false;
3411 
3412   // If the type we are conversion to is a class type, enumerate its
3413   // constructors.
3414   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3415     // C++ [over.match.ctor]p1:
3416     //   When objects of class type are direct-initialized (8.5), or
3417     //   copy-initialized from an expression of the same or a
3418     //   derived class type (8.5), overload resolution selects the
3419     //   constructor. [...] For copy-initialization, the candidate
3420     //   functions are all the converting constructors (12.3.1) of
3421     //   that class. The argument list is the expression-list within
3422     //   the parentheses of the initializer.
3423     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3424         (From->getType()->getAs<RecordType>() &&
3425          S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3426       ConstructorsOnly = true;
3427 
3428     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3429       // We're not going to find any constructors.
3430     } else if (CXXRecordDecl *ToRecordDecl
3431                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3432 
3433       Expr **Args = &From;
3434       unsigned NumArgs = 1;
3435       bool ListInitializing = false;
3436       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3437         // But first, see if there is an init-list-constructor that will work.
3438         OverloadingResult Result = IsInitializerListConstructorConversion(
3439             S, From, ToType, ToRecordDecl, User, CandidateSet,
3440             AllowExplicit == AllowedExplicit::All);
3441         if (Result != OR_No_Viable_Function)
3442           return Result;
3443         // Never mind.
3444         CandidateSet.clear(
3445             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3446 
3447         // If we're list-initializing, we pass the individual elements as
3448         // arguments, not the entire list.
3449         Args = InitList->getInits();
3450         NumArgs = InitList->getNumInits();
3451         ListInitializing = true;
3452       }
3453 
3454       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3455         auto Info = getConstructorInfo(D);
3456         if (!Info)
3457           continue;
3458 
3459         bool Usable = !Info.Constructor->isInvalidDecl();
3460         if (!ListInitializing)
3461           Usable = Usable && Info.Constructor->isConvertingConstructor(
3462                                  /*AllowExplicit*/ true);
3463         if (Usable) {
3464           bool SuppressUserConversions = !ConstructorsOnly;
3465           if (SuppressUserConversions && ListInitializing) {
3466             SuppressUserConversions = false;
3467             if (NumArgs == 1) {
3468               // If the first argument is (a reference to) the target type,
3469               // suppress conversions.
3470               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3471                   S.Context, Info.Constructor, ToType);
3472             }
3473           }
3474           if (Info.ConstructorTmpl)
3475             S.AddTemplateOverloadCandidate(
3476                 Info.ConstructorTmpl, Info.FoundDecl,
3477                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3478                 CandidateSet, SuppressUserConversions,
3479                 /*PartialOverloading*/ false,
3480                 AllowExplicit == AllowedExplicit::All);
3481           else
3482             // Allow one user-defined conversion when user specifies a
3483             // From->ToType conversion via an static cast (c-style, etc).
3484             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3485                                    llvm::makeArrayRef(Args, NumArgs),
3486                                    CandidateSet, SuppressUserConversions,
3487                                    /*PartialOverloading*/ false,
3488                                    AllowExplicit == AllowedExplicit::All);
3489         }
3490       }
3491     }
3492   }
3493 
3494   // Enumerate conversion functions, if we're allowed to.
3495   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3496   } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3497     // No conversion functions from incomplete types.
3498   } else if (const RecordType *FromRecordType =
3499                  From->getType()->getAs<RecordType>()) {
3500     if (CXXRecordDecl *FromRecordDecl
3501          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3502       // Add all of the conversion functions as candidates.
3503       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3504       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3505         DeclAccessPair FoundDecl = I.getPair();
3506         NamedDecl *D = FoundDecl.getDecl();
3507         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3508         if (isa<UsingShadowDecl>(D))
3509           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3510 
3511         CXXConversionDecl *Conv;
3512         FunctionTemplateDecl *ConvTemplate;
3513         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3514           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3515         else
3516           Conv = cast<CXXConversionDecl>(D);
3517 
3518         if (ConvTemplate)
3519           S.AddTemplateConversionCandidate(
3520               ConvTemplate, FoundDecl, ActingContext, From, ToType,
3521               CandidateSet, AllowObjCConversionOnExplicit,
3522               AllowExplicit != AllowedExplicit::None);
3523         else
3524           S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3525                                    CandidateSet, AllowObjCConversionOnExplicit,
3526                                    AllowExplicit != AllowedExplicit::None);
3527       }
3528     }
3529   }
3530 
3531   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3532 
3533   OverloadCandidateSet::iterator Best;
3534   switch (auto Result =
3535               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3536   case OR_Success:
3537   case OR_Deleted:
3538     // Record the standard conversion we used and the conversion function.
3539     if (CXXConstructorDecl *Constructor
3540           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3541       // C++ [over.ics.user]p1:
3542       //   If the user-defined conversion is specified by a
3543       //   constructor (12.3.1), the initial standard conversion
3544       //   sequence converts the source type to the type required by
3545       //   the argument of the constructor.
3546       //
3547       QualType ThisType = Constructor->getThisType();
3548       if (isa<InitListExpr>(From)) {
3549         // Initializer lists don't have conversions as such.
3550         User.Before.setAsIdentityConversion();
3551       } else {
3552         if (Best->Conversions[0].isEllipsis())
3553           User.EllipsisConversion = true;
3554         else {
3555           User.Before = Best->Conversions[0].Standard;
3556           User.EllipsisConversion = false;
3557         }
3558       }
3559       User.HadMultipleCandidates = HadMultipleCandidates;
3560       User.ConversionFunction = Constructor;
3561       User.FoundConversionFunction = Best->FoundDecl;
3562       User.After.setAsIdentityConversion();
3563       User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3564       User.After.setAllToTypes(ToType);
3565       return Result;
3566     }
3567     if (CXXConversionDecl *Conversion
3568                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3569       // C++ [over.ics.user]p1:
3570       //
3571       //   [...] If the user-defined conversion is specified by a
3572       //   conversion function (12.3.2), the initial standard
3573       //   conversion sequence converts the source type to the
3574       //   implicit object parameter of the conversion function.
3575       User.Before = Best->Conversions[0].Standard;
3576       User.HadMultipleCandidates = HadMultipleCandidates;
3577       User.ConversionFunction = Conversion;
3578       User.FoundConversionFunction = Best->FoundDecl;
3579       User.EllipsisConversion = false;
3580 
3581       // C++ [over.ics.user]p2:
3582       //   The second standard conversion sequence converts the
3583       //   result of the user-defined conversion to the target type
3584       //   for the sequence. Since an implicit conversion sequence
3585       //   is an initialization, the special rules for
3586       //   initialization by user-defined conversion apply when
3587       //   selecting the best user-defined conversion for a
3588       //   user-defined conversion sequence (see 13.3.3 and
3589       //   13.3.3.1).
3590       User.After = Best->FinalConversion;
3591       return Result;
3592     }
3593     llvm_unreachable("Not a constructor or conversion function?");
3594 
3595   case OR_No_Viable_Function:
3596     return OR_No_Viable_Function;
3597 
3598   case OR_Ambiguous:
3599     return OR_Ambiguous;
3600   }
3601 
3602   llvm_unreachable("Invalid OverloadResult!");
3603 }
3604 
3605 bool
3606 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3607   ImplicitConversionSequence ICS;
3608   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3609                                     OverloadCandidateSet::CSK_Normal);
3610   OverloadingResult OvResult =
3611     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3612                             CandidateSet, AllowedExplicit::None, false);
3613 
3614   if (!(OvResult == OR_Ambiguous ||
3615         (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3616     return false;
3617 
3618   auto Cands = CandidateSet.CompleteCandidates(
3619       *this,
3620       OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3621       From);
3622   if (OvResult == OR_Ambiguous)
3623     Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3624         << From->getType() << ToType << From->getSourceRange();
3625   else { // OR_No_Viable_Function && !CandidateSet.empty()
3626     if (!RequireCompleteType(From->getBeginLoc(), ToType,
3627                              diag::err_typecheck_nonviable_condition_incomplete,
3628                              From->getType(), From->getSourceRange()))
3629       Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3630           << false << From->getType() << From->getSourceRange() << ToType;
3631   }
3632 
3633   CandidateSet.NoteCandidates(
3634                               *this, From, Cands);
3635   return true;
3636 }
3637 
3638 /// Compare the user-defined conversion functions or constructors
3639 /// of two user-defined conversion sequences to determine whether any ordering
3640 /// is possible.
3641 static ImplicitConversionSequence::CompareKind
3642 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3643                            FunctionDecl *Function2) {
3644   if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11)
3645     return ImplicitConversionSequence::Indistinguishable;
3646 
3647   // Objective-C++:
3648   //   If both conversion functions are implicitly-declared conversions from
3649   //   a lambda closure type to a function pointer and a block pointer,
3650   //   respectively, always prefer the conversion to a function pointer,
3651   //   because the function pointer is more lightweight and is more likely
3652   //   to keep code working.
3653   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3654   if (!Conv1)
3655     return ImplicitConversionSequence::Indistinguishable;
3656 
3657   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3658   if (!Conv2)
3659     return ImplicitConversionSequence::Indistinguishable;
3660 
3661   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3662     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3663     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3664     if (Block1 != Block2)
3665       return Block1 ? ImplicitConversionSequence::Worse
3666                     : ImplicitConversionSequence::Better;
3667   }
3668 
3669   return ImplicitConversionSequence::Indistinguishable;
3670 }
3671 
3672 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3673     const ImplicitConversionSequence &ICS) {
3674   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3675          (ICS.isUserDefined() &&
3676           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3677 }
3678 
3679 /// CompareImplicitConversionSequences - Compare two implicit
3680 /// conversion sequences to determine whether one is better than the
3681 /// other or if they are indistinguishable (C++ 13.3.3.2).
3682 static ImplicitConversionSequence::CompareKind
3683 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3684                                    const ImplicitConversionSequence& ICS1,
3685                                    const ImplicitConversionSequence& ICS2)
3686 {
3687   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3688   // conversion sequences (as defined in 13.3.3.1)
3689   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3690   //      conversion sequence than a user-defined conversion sequence or
3691   //      an ellipsis conversion sequence, and
3692   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3693   //      conversion sequence than an ellipsis conversion sequence
3694   //      (13.3.3.1.3).
3695   //
3696   // C++0x [over.best.ics]p10:
3697   //   For the purpose of ranking implicit conversion sequences as
3698   //   described in 13.3.3.2, the ambiguous conversion sequence is
3699   //   treated as a user-defined sequence that is indistinguishable
3700   //   from any other user-defined conversion sequence.
3701 
3702   // String literal to 'char *' conversion has been deprecated in C++03. It has
3703   // been removed from C++11. We still accept this conversion, if it happens at
3704   // the best viable function. Otherwise, this conversion is considered worse
3705   // than ellipsis conversion. Consider this as an extension; this is not in the
3706   // standard. For example:
3707   //
3708   // int &f(...);    // #1
3709   // void f(char*);  // #2
3710   // void g() { int &r = f("foo"); }
3711   //
3712   // In C++03, we pick #2 as the best viable function.
3713   // In C++11, we pick #1 as the best viable function, because ellipsis
3714   // conversion is better than string-literal to char* conversion (since there
3715   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3716   // convert arguments, #2 would be the best viable function in C++11.
3717   // If the best viable function has this conversion, a warning will be issued
3718   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3719 
3720   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3721       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3722       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3723     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3724                ? ImplicitConversionSequence::Worse
3725                : ImplicitConversionSequence::Better;
3726 
3727   if (ICS1.getKindRank() < ICS2.getKindRank())
3728     return ImplicitConversionSequence::Better;
3729   if (ICS2.getKindRank() < ICS1.getKindRank())
3730     return ImplicitConversionSequence::Worse;
3731 
3732   // The following checks require both conversion sequences to be of
3733   // the same kind.
3734   if (ICS1.getKind() != ICS2.getKind())
3735     return ImplicitConversionSequence::Indistinguishable;
3736 
3737   ImplicitConversionSequence::CompareKind Result =
3738       ImplicitConversionSequence::Indistinguishable;
3739 
3740   // Two implicit conversion sequences of the same form are
3741   // indistinguishable conversion sequences unless one of the
3742   // following rules apply: (C++ 13.3.3.2p3):
3743 
3744   // List-initialization sequence L1 is a better conversion sequence than
3745   // list-initialization sequence L2 if:
3746   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3747   //   if not that,
3748   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3749   //   and N1 is smaller than N2.,
3750   // even if one of the other rules in this paragraph would otherwise apply.
3751   if (!ICS1.isBad()) {
3752     if (ICS1.isStdInitializerListElement() &&
3753         !ICS2.isStdInitializerListElement())
3754       return ImplicitConversionSequence::Better;
3755     if (!ICS1.isStdInitializerListElement() &&
3756         ICS2.isStdInitializerListElement())
3757       return ImplicitConversionSequence::Worse;
3758   }
3759 
3760   if (ICS1.isStandard())
3761     // Standard conversion sequence S1 is a better conversion sequence than
3762     // standard conversion sequence S2 if [...]
3763     Result = CompareStandardConversionSequences(S, Loc,
3764                                                 ICS1.Standard, ICS2.Standard);
3765   else if (ICS1.isUserDefined()) {
3766     // User-defined conversion sequence U1 is a better conversion
3767     // sequence than another user-defined conversion sequence U2 if
3768     // they contain the same user-defined conversion function or
3769     // constructor and if the second standard conversion sequence of
3770     // U1 is better than the second standard conversion sequence of
3771     // U2 (C++ 13.3.3.2p3).
3772     if (ICS1.UserDefined.ConversionFunction ==
3773           ICS2.UserDefined.ConversionFunction)
3774       Result = CompareStandardConversionSequences(S, Loc,
3775                                                   ICS1.UserDefined.After,
3776                                                   ICS2.UserDefined.After);
3777     else
3778       Result = compareConversionFunctions(S,
3779                                           ICS1.UserDefined.ConversionFunction,
3780                                           ICS2.UserDefined.ConversionFunction);
3781   }
3782 
3783   return Result;
3784 }
3785 
3786 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3787 // determine if one is a proper subset of the other.
3788 static ImplicitConversionSequence::CompareKind
3789 compareStandardConversionSubsets(ASTContext &Context,
3790                                  const StandardConversionSequence& SCS1,
3791                                  const StandardConversionSequence& SCS2) {
3792   ImplicitConversionSequence::CompareKind Result
3793     = ImplicitConversionSequence::Indistinguishable;
3794 
3795   // the identity conversion sequence is considered to be a subsequence of
3796   // any non-identity conversion sequence
3797   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3798     return ImplicitConversionSequence::Better;
3799   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3800     return ImplicitConversionSequence::Worse;
3801 
3802   if (SCS1.Second != SCS2.Second) {
3803     if (SCS1.Second == ICK_Identity)
3804       Result = ImplicitConversionSequence::Better;
3805     else if (SCS2.Second == ICK_Identity)
3806       Result = ImplicitConversionSequence::Worse;
3807     else
3808       return ImplicitConversionSequence::Indistinguishable;
3809   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3810     return ImplicitConversionSequence::Indistinguishable;
3811 
3812   if (SCS1.Third == SCS2.Third) {
3813     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3814                              : ImplicitConversionSequence::Indistinguishable;
3815   }
3816 
3817   if (SCS1.Third == ICK_Identity)
3818     return Result == ImplicitConversionSequence::Worse
3819              ? ImplicitConversionSequence::Indistinguishable
3820              : ImplicitConversionSequence::Better;
3821 
3822   if (SCS2.Third == ICK_Identity)
3823     return Result == ImplicitConversionSequence::Better
3824              ? ImplicitConversionSequence::Indistinguishable
3825              : ImplicitConversionSequence::Worse;
3826 
3827   return ImplicitConversionSequence::Indistinguishable;
3828 }
3829 
3830 /// Determine whether one of the given reference bindings is better
3831 /// than the other based on what kind of bindings they are.
3832 static bool
3833 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3834                              const StandardConversionSequence &SCS2) {
3835   // C++0x [over.ics.rank]p3b4:
3836   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3837   //      implicit object parameter of a non-static member function declared
3838   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3839   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3840   //      lvalue reference to a function lvalue and S2 binds an rvalue
3841   //      reference*.
3842   //
3843   // FIXME: Rvalue references. We're going rogue with the above edits,
3844   // because the semantics in the current C++0x working paper (N3225 at the
3845   // time of this writing) break the standard definition of std::forward
3846   // and std::reference_wrapper when dealing with references to functions.
3847   // Proposed wording changes submitted to CWG for consideration.
3848   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3849       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3850     return false;
3851 
3852   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3853           SCS2.IsLvalueReference) ||
3854          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3855           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3856 }
3857 
3858 enum class FixedEnumPromotion {
3859   None,
3860   ToUnderlyingType,
3861   ToPromotedUnderlyingType
3862 };
3863 
3864 /// Returns kind of fixed enum promotion the \a SCS uses.
3865 static FixedEnumPromotion
3866 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
3867 
3868   if (SCS.Second != ICK_Integral_Promotion)
3869     return FixedEnumPromotion::None;
3870 
3871   QualType FromType = SCS.getFromType();
3872   if (!FromType->isEnumeralType())
3873     return FixedEnumPromotion::None;
3874 
3875   EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl();
3876   if (!Enum->isFixed())
3877     return FixedEnumPromotion::None;
3878 
3879   QualType UnderlyingType = Enum->getIntegerType();
3880   if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
3881     return FixedEnumPromotion::ToUnderlyingType;
3882 
3883   return FixedEnumPromotion::ToPromotedUnderlyingType;
3884 }
3885 
3886 /// CompareStandardConversionSequences - Compare two standard
3887 /// conversion sequences to determine whether one is better than the
3888 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3889 static ImplicitConversionSequence::CompareKind
3890 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3891                                    const StandardConversionSequence& SCS1,
3892                                    const StandardConversionSequence& SCS2)
3893 {
3894   // Standard conversion sequence S1 is a better conversion sequence
3895   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3896 
3897   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3898   //     sequences in the canonical form defined by 13.3.3.1.1,
3899   //     excluding any Lvalue Transformation; the identity conversion
3900   //     sequence is considered to be a subsequence of any
3901   //     non-identity conversion sequence) or, if not that,
3902   if (ImplicitConversionSequence::CompareKind CK
3903         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3904     return CK;
3905 
3906   //  -- the rank of S1 is better than the rank of S2 (by the rules
3907   //     defined below), or, if not that,
3908   ImplicitConversionRank Rank1 = SCS1.getRank();
3909   ImplicitConversionRank Rank2 = SCS2.getRank();
3910   if (Rank1 < Rank2)
3911     return ImplicitConversionSequence::Better;
3912   else if (Rank2 < Rank1)
3913     return ImplicitConversionSequence::Worse;
3914 
3915   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3916   // are indistinguishable unless one of the following rules
3917   // applies:
3918 
3919   //   A conversion that is not a conversion of a pointer, or
3920   //   pointer to member, to bool is better than another conversion
3921   //   that is such a conversion.
3922   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3923     return SCS2.isPointerConversionToBool()
3924              ? ImplicitConversionSequence::Better
3925              : ImplicitConversionSequence::Worse;
3926 
3927   // C++14 [over.ics.rank]p4b2:
3928   // This is retroactively applied to C++11 by CWG 1601.
3929   //
3930   //   A conversion that promotes an enumeration whose underlying type is fixed
3931   //   to its underlying type is better than one that promotes to the promoted
3932   //   underlying type, if the two are different.
3933   FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
3934   FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
3935   if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
3936       FEP1 != FEP2)
3937     return FEP1 == FixedEnumPromotion::ToUnderlyingType
3938                ? ImplicitConversionSequence::Better
3939                : ImplicitConversionSequence::Worse;
3940 
3941   // C++ [over.ics.rank]p4b2:
3942   //
3943   //   If class B is derived directly or indirectly from class A,
3944   //   conversion of B* to A* is better than conversion of B* to
3945   //   void*, and conversion of A* to void* is better than conversion
3946   //   of B* to void*.
3947   bool SCS1ConvertsToVoid
3948     = SCS1.isPointerConversionToVoidPointer(S.Context);
3949   bool SCS2ConvertsToVoid
3950     = SCS2.isPointerConversionToVoidPointer(S.Context);
3951   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3952     // Exactly one of the conversion sequences is a conversion to
3953     // a void pointer; it's the worse conversion.
3954     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3955                               : ImplicitConversionSequence::Worse;
3956   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3957     // Neither conversion sequence converts to a void pointer; compare
3958     // their derived-to-base conversions.
3959     if (ImplicitConversionSequence::CompareKind DerivedCK
3960           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3961       return DerivedCK;
3962   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3963              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3964     // Both conversion sequences are conversions to void
3965     // pointers. Compare the source types to determine if there's an
3966     // inheritance relationship in their sources.
3967     QualType FromType1 = SCS1.getFromType();
3968     QualType FromType2 = SCS2.getFromType();
3969 
3970     // Adjust the types we're converting from via the array-to-pointer
3971     // conversion, if we need to.
3972     if (SCS1.First == ICK_Array_To_Pointer)
3973       FromType1 = S.Context.getArrayDecayedType(FromType1);
3974     if (SCS2.First == ICK_Array_To_Pointer)
3975       FromType2 = S.Context.getArrayDecayedType(FromType2);
3976 
3977     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3978     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3979 
3980     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3981       return ImplicitConversionSequence::Better;
3982     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3983       return ImplicitConversionSequence::Worse;
3984 
3985     // Objective-C++: If one interface is more specific than the
3986     // other, it is the better one.
3987     const ObjCObjectPointerType* FromObjCPtr1
3988       = FromType1->getAs<ObjCObjectPointerType>();
3989     const ObjCObjectPointerType* FromObjCPtr2
3990       = FromType2->getAs<ObjCObjectPointerType>();
3991     if (FromObjCPtr1 && FromObjCPtr2) {
3992       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3993                                                           FromObjCPtr2);
3994       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3995                                                            FromObjCPtr1);
3996       if (AssignLeft != AssignRight) {
3997         return AssignLeft? ImplicitConversionSequence::Better
3998                          : ImplicitConversionSequence::Worse;
3999       }
4000     }
4001   }
4002 
4003   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4004     // Check for a better reference binding based on the kind of bindings.
4005     if (isBetterReferenceBindingKind(SCS1, SCS2))
4006       return ImplicitConversionSequence::Better;
4007     else if (isBetterReferenceBindingKind(SCS2, SCS1))
4008       return ImplicitConversionSequence::Worse;
4009   }
4010 
4011   // Compare based on qualification conversions (C++ 13.3.3.2p3,
4012   // bullet 3).
4013   if (ImplicitConversionSequence::CompareKind QualCK
4014         = CompareQualificationConversions(S, SCS1, SCS2))
4015     return QualCK;
4016 
4017   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4018     // C++ [over.ics.rank]p3b4:
4019     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
4020     //      which the references refer are the same type except for
4021     //      top-level cv-qualifiers, and the type to which the reference
4022     //      initialized by S2 refers is more cv-qualified than the type
4023     //      to which the reference initialized by S1 refers.
4024     QualType T1 = SCS1.getToType(2);
4025     QualType T2 = SCS2.getToType(2);
4026     T1 = S.Context.getCanonicalType(T1);
4027     T2 = S.Context.getCanonicalType(T2);
4028     Qualifiers T1Quals, T2Quals;
4029     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4030     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4031     if (UnqualT1 == UnqualT2) {
4032       // Objective-C++ ARC: If the references refer to objects with different
4033       // lifetimes, prefer bindings that don't change lifetime.
4034       if (SCS1.ObjCLifetimeConversionBinding !=
4035                                           SCS2.ObjCLifetimeConversionBinding) {
4036         return SCS1.ObjCLifetimeConversionBinding
4037                                            ? ImplicitConversionSequence::Worse
4038                                            : ImplicitConversionSequence::Better;
4039       }
4040 
4041       // If the type is an array type, promote the element qualifiers to the
4042       // type for comparison.
4043       if (isa<ArrayType>(T1) && T1Quals)
4044         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4045       if (isa<ArrayType>(T2) && T2Quals)
4046         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4047       if (T2.isMoreQualifiedThan(T1))
4048         return ImplicitConversionSequence::Better;
4049       if (T1.isMoreQualifiedThan(T2))
4050         return ImplicitConversionSequence::Worse;
4051     }
4052   }
4053 
4054   // In Microsoft mode, prefer an integral conversion to a
4055   // floating-to-integral conversion if the integral conversion
4056   // is between types of the same size.
4057   // For example:
4058   // void f(float);
4059   // void f(int);
4060   // int main {
4061   //    long a;
4062   //    f(a);
4063   // }
4064   // Here, MSVC will call f(int) instead of generating a compile error
4065   // as clang will do in standard mode.
4066   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
4067       SCS2.Second == ICK_Floating_Integral &&
4068       S.Context.getTypeSize(SCS1.getFromType()) ==
4069           S.Context.getTypeSize(SCS1.getToType(2)))
4070     return ImplicitConversionSequence::Better;
4071 
4072   // Prefer a compatible vector conversion over a lax vector conversion
4073   // For example:
4074   //
4075   // typedef float __v4sf __attribute__((__vector_size__(16)));
4076   // void f(vector float);
4077   // void f(vector signed int);
4078   // int main() {
4079   //   __v4sf a;
4080   //   f(a);
4081   // }
4082   // Here, we'd like to choose f(vector float) and not
4083   // report an ambiguous call error
4084   if (SCS1.Second == ICK_Vector_Conversion &&
4085       SCS2.Second == ICK_Vector_Conversion) {
4086     bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4087         SCS1.getFromType(), SCS1.getToType(2));
4088     bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4089         SCS2.getFromType(), SCS2.getToType(2));
4090 
4091     if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4092       return SCS1IsCompatibleVectorConversion
4093                  ? ImplicitConversionSequence::Better
4094                  : ImplicitConversionSequence::Worse;
4095   }
4096 
4097   return ImplicitConversionSequence::Indistinguishable;
4098 }
4099 
4100 /// CompareQualificationConversions - Compares two standard conversion
4101 /// sequences to determine whether they can be ranked based on their
4102 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4103 static ImplicitConversionSequence::CompareKind
4104 CompareQualificationConversions(Sema &S,
4105                                 const StandardConversionSequence& SCS1,
4106                                 const StandardConversionSequence& SCS2) {
4107   // C++ 13.3.3.2p3:
4108   //  -- S1 and S2 differ only in their qualification conversion and
4109   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
4110   //     cv-qualification signature of type T1 is a proper subset of
4111   //     the cv-qualification signature of type T2, and S1 is not the
4112   //     deprecated string literal array-to-pointer conversion (4.2).
4113   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4114       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4115     return ImplicitConversionSequence::Indistinguishable;
4116 
4117   // FIXME: the example in the standard doesn't use a qualification
4118   // conversion (!)
4119   QualType T1 = SCS1.getToType(2);
4120   QualType T2 = SCS2.getToType(2);
4121   T1 = S.Context.getCanonicalType(T1);
4122   T2 = S.Context.getCanonicalType(T2);
4123   assert(!T1->isReferenceType() && !T2->isReferenceType());
4124   Qualifiers T1Quals, T2Quals;
4125   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4126   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4127 
4128   // If the types are the same, we won't learn anything by unwrapping
4129   // them.
4130   if (UnqualT1 == UnqualT2)
4131     return ImplicitConversionSequence::Indistinguishable;
4132 
4133   ImplicitConversionSequence::CompareKind Result
4134     = ImplicitConversionSequence::Indistinguishable;
4135 
4136   // Objective-C++ ARC:
4137   //   Prefer qualification conversions not involving a change in lifetime
4138   //   to qualification conversions that do not change lifetime.
4139   if (SCS1.QualificationIncludesObjCLifetime !=
4140                                       SCS2.QualificationIncludesObjCLifetime) {
4141     Result = SCS1.QualificationIncludesObjCLifetime
4142                ? ImplicitConversionSequence::Worse
4143                : ImplicitConversionSequence::Better;
4144   }
4145 
4146   while (S.Context.UnwrapSimilarTypes(T1, T2)) {
4147     // Within each iteration of the loop, we check the qualifiers to
4148     // determine if this still looks like a qualification
4149     // conversion. Then, if all is well, we unwrap one more level of
4150     // pointers or pointers-to-members and do it all again
4151     // until there are no more pointers or pointers-to-members left
4152     // to unwrap. This essentially mimics what
4153     // IsQualificationConversion does, but here we're checking for a
4154     // strict subset of qualifiers.
4155     if (T1.getQualifiers().withoutObjCLifetime() ==
4156         T2.getQualifiers().withoutObjCLifetime())
4157       // The qualifiers are the same, so this doesn't tell us anything
4158       // about how the sequences rank.
4159       // ObjC ownership quals are omitted above as they interfere with
4160       // the ARC overload rule.
4161       ;
4162     else if (T2.isMoreQualifiedThan(T1)) {
4163       // T1 has fewer qualifiers, so it could be the better sequence.
4164       if (Result == ImplicitConversionSequence::Worse)
4165         // Neither has qualifiers that are a subset of the other's
4166         // qualifiers.
4167         return ImplicitConversionSequence::Indistinguishable;
4168 
4169       Result = ImplicitConversionSequence::Better;
4170     } else if (T1.isMoreQualifiedThan(T2)) {
4171       // T2 has fewer qualifiers, so it could be the better sequence.
4172       if (Result == ImplicitConversionSequence::Better)
4173         // Neither has qualifiers that are a subset of the other's
4174         // qualifiers.
4175         return ImplicitConversionSequence::Indistinguishable;
4176 
4177       Result = ImplicitConversionSequence::Worse;
4178     } else {
4179       // Qualifiers are disjoint.
4180       return ImplicitConversionSequence::Indistinguishable;
4181     }
4182 
4183     // If the types after this point are equivalent, we're done.
4184     if (S.Context.hasSameUnqualifiedType(T1, T2))
4185       break;
4186   }
4187 
4188   // Check that the winning standard conversion sequence isn't using
4189   // the deprecated string literal array to pointer conversion.
4190   switch (Result) {
4191   case ImplicitConversionSequence::Better:
4192     if (SCS1.DeprecatedStringLiteralToCharPtr)
4193       Result = ImplicitConversionSequence::Indistinguishable;
4194     break;
4195 
4196   case ImplicitConversionSequence::Indistinguishable:
4197     break;
4198 
4199   case ImplicitConversionSequence::Worse:
4200     if (SCS2.DeprecatedStringLiteralToCharPtr)
4201       Result = ImplicitConversionSequence::Indistinguishable;
4202     break;
4203   }
4204 
4205   return Result;
4206 }
4207 
4208 /// CompareDerivedToBaseConversions - Compares two standard conversion
4209 /// sequences to determine whether they can be ranked based on their
4210 /// various kinds of derived-to-base conversions (C++
4211 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4212 /// conversions between Objective-C interface types.
4213 static ImplicitConversionSequence::CompareKind
4214 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4215                                 const StandardConversionSequence& SCS1,
4216                                 const StandardConversionSequence& SCS2) {
4217   QualType FromType1 = SCS1.getFromType();
4218   QualType ToType1 = SCS1.getToType(1);
4219   QualType FromType2 = SCS2.getFromType();
4220   QualType ToType2 = SCS2.getToType(1);
4221 
4222   // Adjust the types we're converting from via the array-to-pointer
4223   // conversion, if we need to.
4224   if (SCS1.First == ICK_Array_To_Pointer)
4225     FromType1 = S.Context.getArrayDecayedType(FromType1);
4226   if (SCS2.First == ICK_Array_To_Pointer)
4227     FromType2 = S.Context.getArrayDecayedType(FromType2);
4228 
4229   // Canonicalize all of the types.
4230   FromType1 = S.Context.getCanonicalType(FromType1);
4231   ToType1 = S.Context.getCanonicalType(ToType1);
4232   FromType2 = S.Context.getCanonicalType(FromType2);
4233   ToType2 = S.Context.getCanonicalType(ToType2);
4234 
4235   // C++ [over.ics.rank]p4b3:
4236   //
4237   //   If class B is derived directly or indirectly from class A and
4238   //   class C is derived directly or indirectly from B,
4239   //
4240   // Compare based on pointer conversions.
4241   if (SCS1.Second == ICK_Pointer_Conversion &&
4242       SCS2.Second == ICK_Pointer_Conversion &&
4243       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4244       FromType1->isPointerType() && FromType2->isPointerType() &&
4245       ToType1->isPointerType() && ToType2->isPointerType()) {
4246     QualType FromPointee1 =
4247         FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4248     QualType ToPointee1 =
4249         ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4250     QualType FromPointee2 =
4251         FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4252     QualType ToPointee2 =
4253         ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4254 
4255     //   -- conversion of C* to B* is better than conversion of C* to A*,
4256     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4257       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4258         return ImplicitConversionSequence::Better;
4259       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4260         return ImplicitConversionSequence::Worse;
4261     }
4262 
4263     //   -- conversion of B* to A* is better than conversion of C* to A*,
4264     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4265       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4266         return ImplicitConversionSequence::Better;
4267       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4268         return ImplicitConversionSequence::Worse;
4269     }
4270   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4271              SCS2.Second == ICK_Pointer_Conversion) {
4272     const ObjCObjectPointerType *FromPtr1
4273       = FromType1->getAs<ObjCObjectPointerType>();
4274     const ObjCObjectPointerType *FromPtr2
4275       = FromType2->getAs<ObjCObjectPointerType>();
4276     const ObjCObjectPointerType *ToPtr1
4277       = ToType1->getAs<ObjCObjectPointerType>();
4278     const ObjCObjectPointerType *ToPtr2
4279       = ToType2->getAs<ObjCObjectPointerType>();
4280 
4281     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4282       // Apply the same conversion ranking rules for Objective-C pointer types
4283       // that we do for C++ pointers to class types. However, we employ the
4284       // Objective-C pseudo-subtyping relationship used for assignment of
4285       // Objective-C pointer types.
4286       bool FromAssignLeft
4287         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4288       bool FromAssignRight
4289         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4290       bool ToAssignLeft
4291         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4292       bool ToAssignRight
4293         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4294 
4295       // A conversion to an a non-id object pointer type or qualified 'id'
4296       // type is better than a conversion to 'id'.
4297       if (ToPtr1->isObjCIdType() &&
4298           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4299         return ImplicitConversionSequence::Worse;
4300       if (ToPtr2->isObjCIdType() &&
4301           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4302         return ImplicitConversionSequence::Better;
4303 
4304       // A conversion to a non-id object pointer type is better than a
4305       // conversion to a qualified 'id' type
4306       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4307         return ImplicitConversionSequence::Worse;
4308       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4309         return ImplicitConversionSequence::Better;
4310 
4311       // A conversion to an a non-Class object pointer type or qualified 'Class'
4312       // type is better than a conversion to 'Class'.
4313       if (ToPtr1->isObjCClassType() &&
4314           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4315         return ImplicitConversionSequence::Worse;
4316       if (ToPtr2->isObjCClassType() &&
4317           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4318         return ImplicitConversionSequence::Better;
4319 
4320       // A conversion to a non-Class object pointer type is better than a
4321       // conversion to a qualified 'Class' type.
4322       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4323         return ImplicitConversionSequence::Worse;
4324       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4325         return ImplicitConversionSequence::Better;
4326 
4327       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4328       if (S.Context.hasSameType(FromType1, FromType2) &&
4329           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4330           (ToAssignLeft != ToAssignRight)) {
4331         if (FromPtr1->isSpecialized()) {
4332           // "conversion of B<A> * to B * is better than conversion of B * to
4333           // C *.
4334           bool IsFirstSame =
4335               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4336           bool IsSecondSame =
4337               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4338           if (IsFirstSame) {
4339             if (!IsSecondSame)
4340               return ImplicitConversionSequence::Better;
4341           } else if (IsSecondSame)
4342             return ImplicitConversionSequence::Worse;
4343         }
4344         return ToAssignLeft? ImplicitConversionSequence::Worse
4345                            : ImplicitConversionSequence::Better;
4346       }
4347 
4348       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4349       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4350           (FromAssignLeft != FromAssignRight))
4351         return FromAssignLeft? ImplicitConversionSequence::Better
4352         : ImplicitConversionSequence::Worse;
4353     }
4354   }
4355 
4356   // Ranking of member-pointer types.
4357   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4358       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4359       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4360     const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4361     const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4362     const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4363     const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4364     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4365     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4366     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4367     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4368     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4369     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4370     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4371     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4372     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4373     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4374       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4375         return ImplicitConversionSequence::Worse;
4376       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4377         return ImplicitConversionSequence::Better;
4378     }
4379     // conversion of B::* to C::* is better than conversion of A::* to C::*
4380     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4381       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4382         return ImplicitConversionSequence::Better;
4383       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4384         return ImplicitConversionSequence::Worse;
4385     }
4386   }
4387 
4388   if (SCS1.Second == ICK_Derived_To_Base) {
4389     //   -- conversion of C to B is better than conversion of C to A,
4390     //   -- binding of an expression of type C to a reference of type
4391     //      B& is better than binding an expression of type C to a
4392     //      reference of type A&,
4393     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4394         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4395       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4396         return ImplicitConversionSequence::Better;
4397       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4398         return ImplicitConversionSequence::Worse;
4399     }
4400 
4401     //   -- conversion of B to A is better than conversion of C to A.
4402     //   -- binding of an expression of type B to a reference of type
4403     //      A& is better than binding an expression of type C to a
4404     //      reference of type A&,
4405     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4406         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4407       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4408         return ImplicitConversionSequence::Better;
4409       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4410         return ImplicitConversionSequence::Worse;
4411     }
4412   }
4413 
4414   return ImplicitConversionSequence::Indistinguishable;
4415 }
4416 
4417 /// Determine whether the given type is valid, e.g., it is not an invalid
4418 /// C++ class.
4419 static bool isTypeValid(QualType T) {
4420   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4421     return !Record->isInvalidDecl();
4422 
4423   return true;
4424 }
4425 
4426 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4427   if (!T.getQualifiers().hasUnaligned())
4428     return T;
4429 
4430   Qualifiers Q;
4431   T = Ctx.getUnqualifiedArrayType(T, Q);
4432   Q.removeUnaligned();
4433   return Ctx.getQualifiedType(T, Q);
4434 }
4435 
4436 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4437 /// determine whether they are reference-compatible,
4438 /// reference-related, or incompatible, for use in C++ initialization by
4439 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4440 /// type, and the first type (T1) is the pointee type of the reference
4441 /// type being initialized.
4442 Sema::ReferenceCompareResult
4443 Sema::CompareReferenceRelationship(SourceLocation Loc,
4444                                    QualType OrigT1, QualType OrigT2,
4445                                    ReferenceConversions *ConvOut) {
4446   assert(!OrigT1->isReferenceType() &&
4447     "T1 must be the pointee type of the reference type");
4448   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4449 
4450   QualType T1 = Context.getCanonicalType(OrigT1);
4451   QualType T2 = Context.getCanonicalType(OrigT2);
4452   Qualifiers T1Quals, T2Quals;
4453   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4454   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4455 
4456   ReferenceConversions ConvTmp;
4457   ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4458   Conv = ReferenceConversions();
4459 
4460   // C++2a [dcl.init.ref]p4:
4461   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4462   //   reference-related to "cv2 T2" if T1 is similar to T2, or
4463   //   T1 is a base class of T2.
4464   //   "cv1 T1" is reference-compatible with "cv2 T2" if
4465   //   a prvalue of type "pointer to cv2 T2" can be converted to the type
4466   //   "pointer to cv1 T1" via a standard conversion sequence.
4467 
4468   // Check for standard conversions we can apply to pointers: derived-to-base
4469   // conversions, ObjC pointer conversions, and function pointer conversions.
4470   // (Qualification conversions are checked last.)
4471   QualType ConvertedT2;
4472   if (UnqualT1 == UnqualT2) {
4473     // Nothing to do.
4474   } else if (isCompleteType(Loc, OrigT2) &&
4475              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4476              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4477     Conv |= ReferenceConversions::DerivedToBase;
4478   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4479            UnqualT2->isObjCObjectOrInterfaceType() &&
4480            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4481     Conv |= ReferenceConversions::ObjC;
4482   else if (UnqualT2->isFunctionType() &&
4483            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4484     Conv |= ReferenceConversions::Function;
4485     // No need to check qualifiers; function types don't have them.
4486     return Ref_Compatible;
4487   }
4488   bool ConvertedReferent = Conv != 0;
4489 
4490   // We can have a qualification conversion. Compute whether the types are
4491   // similar at the same time.
4492   bool PreviousToQualsIncludeConst = true;
4493   bool TopLevel = true;
4494   do {
4495     if (T1 == T2)
4496       break;
4497 
4498     // We will need a qualification conversion.
4499     Conv |= ReferenceConversions::Qualification;
4500 
4501     // Track whether we performed a qualification conversion anywhere other
4502     // than the top level. This matters for ranking reference bindings in
4503     // overload resolution.
4504     if (!TopLevel)
4505       Conv |= ReferenceConversions::NestedQualification;
4506 
4507     // MS compiler ignores __unaligned qualifier for references; do the same.
4508     T1 = withoutUnaligned(Context, T1);
4509     T2 = withoutUnaligned(Context, T2);
4510 
4511     // If we find a qualifier mismatch, the types are not reference-compatible,
4512     // but are still be reference-related if they're similar.
4513     bool ObjCLifetimeConversion = false;
4514     if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4515                                        PreviousToQualsIncludeConst,
4516                                        ObjCLifetimeConversion))
4517       return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4518                  ? Ref_Related
4519                  : Ref_Incompatible;
4520 
4521     // FIXME: Should we track this for any level other than the first?
4522     if (ObjCLifetimeConversion)
4523       Conv |= ReferenceConversions::ObjCLifetime;
4524 
4525     TopLevel = false;
4526   } while (Context.UnwrapSimilarTypes(T1, T2));
4527 
4528   // At this point, if the types are reference-related, we must either have the
4529   // same inner type (ignoring qualifiers), or must have already worked out how
4530   // to convert the referent.
4531   return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4532              ? Ref_Compatible
4533              : Ref_Incompatible;
4534 }
4535 
4536 /// Look for a user-defined conversion to a value reference-compatible
4537 ///        with DeclType. Return true if something definite is found.
4538 static bool
4539 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4540                          QualType DeclType, SourceLocation DeclLoc,
4541                          Expr *Init, QualType T2, bool AllowRvalues,
4542                          bool AllowExplicit) {
4543   assert(T2->isRecordType() && "Can only find conversions of record types.");
4544   auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4545 
4546   OverloadCandidateSet CandidateSet(
4547       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4548   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4549   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4550     NamedDecl *D = *I;
4551     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4552     if (isa<UsingShadowDecl>(D))
4553       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4554 
4555     FunctionTemplateDecl *ConvTemplate
4556       = dyn_cast<FunctionTemplateDecl>(D);
4557     CXXConversionDecl *Conv;
4558     if (ConvTemplate)
4559       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4560     else
4561       Conv = cast<CXXConversionDecl>(D);
4562 
4563     if (AllowRvalues) {
4564       // If we are initializing an rvalue reference, don't permit conversion
4565       // functions that return lvalues.
4566       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4567         const ReferenceType *RefType
4568           = Conv->getConversionType()->getAs<LValueReferenceType>();
4569         if (RefType && !RefType->getPointeeType()->isFunctionType())
4570           continue;
4571       }
4572 
4573       if (!ConvTemplate &&
4574           S.CompareReferenceRelationship(
4575               DeclLoc,
4576               Conv->getConversionType()
4577                   .getNonReferenceType()
4578                   .getUnqualifiedType(),
4579               DeclType.getNonReferenceType().getUnqualifiedType()) ==
4580               Sema::Ref_Incompatible)
4581         continue;
4582     } else {
4583       // If the conversion function doesn't return a reference type,
4584       // it can't be considered for this conversion. An rvalue reference
4585       // is only acceptable if its referencee is a function type.
4586 
4587       const ReferenceType *RefType =
4588         Conv->getConversionType()->getAs<ReferenceType>();
4589       if (!RefType ||
4590           (!RefType->isLValueReferenceType() &&
4591            !RefType->getPointeeType()->isFunctionType()))
4592         continue;
4593     }
4594 
4595     if (ConvTemplate)
4596       S.AddTemplateConversionCandidate(
4597           ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4598           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4599     else
4600       S.AddConversionCandidate(
4601           Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4602           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4603   }
4604 
4605   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4606 
4607   OverloadCandidateSet::iterator Best;
4608   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4609   case OR_Success:
4610     // C++ [over.ics.ref]p1:
4611     //
4612     //   [...] If the parameter binds directly to the result of
4613     //   applying a conversion function to the argument
4614     //   expression, the implicit conversion sequence is a
4615     //   user-defined conversion sequence (13.3.3.1.2), with the
4616     //   second standard conversion sequence either an identity
4617     //   conversion or, if the conversion function returns an
4618     //   entity of a type that is a derived class of the parameter
4619     //   type, a derived-to-base Conversion.
4620     if (!Best->FinalConversion.DirectBinding)
4621       return false;
4622 
4623     ICS.setUserDefined();
4624     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4625     ICS.UserDefined.After = Best->FinalConversion;
4626     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4627     ICS.UserDefined.ConversionFunction = Best->Function;
4628     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4629     ICS.UserDefined.EllipsisConversion = false;
4630     assert(ICS.UserDefined.After.ReferenceBinding &&
4631            ICS.UserDefined.After.DirectBinding &&
4632            "Expected a direct reference binding!");
4633     return true;
4634 
4635   case OR_Ambiguous:
4636     ICS.setAmbiguous();
4637     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4638          Cand != CandidateSet.end(); ++Cand)
4639       if (Cand->Best)
4640         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4641     return true;
4642 
4643   case OR_No_Viable_Function:
4644   case OR_Deleted:
4645     // There was no suitable conversion, or we found a deleted
4646     // conversion; continue with other checks.
4647     return false;
4648   }
4649 
4650   llvm_unreachable("Invalid OverloadResult!");
4651 }
4652 
4653 /// Compute an implicit conversion sequence for reference
4654 /// initialization.
4655 static ImplicitConversionSequence
4656 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4657                  SourceLocation DeclLoc,
4658                  bool SuppressUserConversions,
4659                  bool AllowExplicit) {
4660   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4661 
4662   // Most paths end in a failed conversion.
4663   ImplicitConversionSequence ICS;
4664   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4665 
4666   QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4667   QualType T2 = Init->getType();
4668 
4669   // If the initializer is the address of an overloaded function, try
4670   // to resolve the overloaded function. If all goes well, T2 is the
4671   // type of the resulting function.
4672   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4673     DeclAccessPair Found;
4674     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4675                                                                 false, Found))
4676       T2 = Fn->getType();
4677   }
4678 
4679   // Compute some basic properties of the types and the initializer.
4680   bool isRValRef = DeclType->isRValueReferenceType();
4681   Expr::Classification InitCategory = Init->Classify(S.Context);
4682 
4683   Sema::ReferenceConversions RefConv;
4684   Sema::ReferenceCompareResult RefRelationship =
4685       S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4686 
4687   auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4688     ICS.setStandard();
4689     ICS.Standard.First = ICK_Identity;
4690     // FIXME: A reference binding can be a function conversion too. We should
4691     // consider that when ordering reference-to-function bindings.
4692     ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4693                               ? ICK_Derived_To_Base
4694                               : (RefConv & Sema::ReferenceConversions::ObjC)
4695                                     ? ICK_Compatible_Conversion
4696                                     : ICK_Identity;
4697     // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4698     // a reference binding that performs a non-top-level qualification
4699     // conversion as a qualification conversion, not as an identity conversion.
4700     ICS.Standard.Third = (RefConv &
4701                               Sema::ReferenceConversions::NestedQualification)
4702                              ? ICK_Qualification
4703                              : ICK_Identity;
4704     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4705     ICS.Standard.setToType(0, T2);
4706     ICS.Standard.setToType(1, T1);
4707     ICS.Standard.setToType(2, T1);
4708     ICS.Standard.ReferenceBinding = true;
4709     ICS.Standard.DirectBinding = BindsDirectly;
4710     ICS.Standard.IsLvalueReference = !isRValRef;
4711     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4712     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4713     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4714     ICS.Standard.ObjCLifetimeConversionBinding =
4715         (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4716     ICS.Standard.CopyConstructor = nullptr;
4717     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4718   };
4719 
4720   // C++0x [dcl.init.ref]p5:
4721   //   A reference to type "cv1 T1" is initialized by an expression
4722   //   of type "cv2 T2" as follows:
4723 
4724   //     -- If reference is an lvalue reference and the initializer expression
4725   if (!isRValRef) {
4726     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4727     //        reference-compatible with "cv2 T2," or
4728     //
4729     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4730     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4731       // C++ [over.ics.ref]p1:
4732       //   When a parameter of reference type binds directly (8.5.3)
4733       //   to an argument expression, the implicit conversion sequence
4734       //   is the identity conversion, unless the argument expression
4735       //   has a type that is a derived class of the parameter type,
4736       //   in which case the implicit conversion sequence is a
4737       //   derived-to-base Conversion (13.3.3.1).
4738       SetAsReferenceBinding(/*BindsDirectly=*/true);
4739 
4740       // Nothing more to do: the inaccessibility/ambiguity check for
4741       // derived-to-base conversions is suppressed when we're
4742       // computing the implicit conversion sequence (C++
4743       // [over.best.ics]p2).
4744       return ICS;
4745     }
4746 
4747     //       -- has a class type (i.e., T2 is a class type), where T1 is
4748     //          not reference-related to T2, and can be implicitly
4749     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4750     //          is reference-compatible with "cv3 T3" 92) (this
4751     //          conversion is selected by enumerating the applicable
4752     //          conversion functions (13.3.1.6) and choosing the best
4753     //          one through overload resolution (13.3)),
4754     if (!SuppressUserConversions && T2->isRecordType() &&
4755         S.isCompleteType(DeclLoc, T2) &&
4756         RefRelationship == Sema::Ref_Incompatible) {
4757       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4758                                    Init, T2, /*AllowRvalues=*/false,
4759                                    AllowExplicit))
4760         return ICS;
4761     }
4762   }
4763 
4764   //     -- Otherwise, the reference shall be an lvalue reference to a
4765   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4766   //        shall be an rvalue reference.
4767   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4768     return ICS;
4769 
4770   //       -- If the initializer expression
4771   //
4772   //            -- is an xvalue, class prvalue, array prvalue or function
4773   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4774   if (RefRelationship == Sema::Ref_Compatible &&
4775       (InitCategory.isXValue() ||
4776        (InitCategory.isPRValue() &&
4777           (T2->isRecordType() || T2->isArrayType())) ||
4778        (InitCategory.isLValue() && T2->isFunctionType()))) {
4779     // In C++11, this is always a direct binding. In C++98/03, it's a direct
4780     // binding unless we're binding to a class prvalue.
4781     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4782     // allow the use of rvalue references in C++98/03 for the benefit of
4783     // standard library implementors; therefore, we need the xvalue check here.
4784     SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4785                           !(InitCategory.isPRValue() || T2->isRecordType()));
4786     return ICS;
4787   }
4788 
4789   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4790   //               reference-related to T2, and can be implicitly converted to
4791   //               an xvalue, class prvalue, or function lvalue of type
4792   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4793   //               "cv3 T3",
4794   //
4795   //          then the reference is bound to the value of the initializer
4796   //          expression in the first case and to the result of the conversion
4797   //          in the second case (or, in either case, to an appropriate base
4798   //          class subobject).
4799   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4800       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4801       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4802                                Init, T2, /*AllowRvalues=*/true,
4803                                AllowExplicit)) {
4804     // In the second case, if the reference is an rvalue reference
4805     // and the second standard conversion sequence of the
4806     // user-defined conversion sequence includes an lvalue-to-rvalue
4807     // conversion, the program is ill-formed.
4808     if (ICS.isUserDefined() && isRValRef &&
4809         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4810       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4811 
4812     return ICS;
4813   }
4814 
4815   // A temporary of function type cannot be created; don't even try.
4816   if (T1->isFunctionType())
4817     return ICS;
4818 
4819   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4820   //          initialized from the initializer expression using the
4821   //          rules for a non-reference copy initialization (8.5). The
4822   //          reference is then bound to the temporary. If T1 is
4823   //          reference-related to T2, cv1 must be the same
4824   //          cv-qualification as, or greater cv-qualification than,
4825   //          cv2; otherwise, the program is ill-formed.
4826   if (RefRelationship == Sema::Ref_Related) {
4827     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4828     // we would be reference-compatible or reference-compatible with
4829     // added qualification. But that wasn't the case, so the reference
4830     // initialization fails.
4831     //
4832     // Note that we only want to check address spaces and cvr-qualifiers here.
4833     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4834     Qualifiers T1Quals = T1.getQualifiers();
4835     Qualifiers T2Quals = T2.getQualifiers();
4836     T1Quals.removeObjCGCAttr();
4837     T1Quals.removeObjCLifetime();
4838     T2Quals.removeObjCGCAttr();
4839     T2Quals.removeObjCLifetime();
4840     // MS compiler ignores __unaligned qualifier for references; do the same.
4841     T1Quals.removeUnaligned();
4842     T2Quals.removeUnaligned();
4843     if (!T1Quals.compatiblyIncludes(T2Quals))
4844       return ICS;
4845   }
4846 
4847   // If at least one of the types is a class type, the types are not
4848   // related, and we aren't allowed any user conversions, the
4849   // reference binding fails. This case is important for breaking
4850   // recursion, since TryImplicitConversion below will attempt to
4851   // create a temporary through the use of a copy constructor.
4852   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4853       (T1->isRecordType() || T2->isRecordType()))
4854     return ICS;
4855 
4856   // If T1 is reference-related to T2 and the reference is an rvalue
4857   // reference, the initializer expression shall not be an lvalue.
4858   if (RefRelationship >= Sema::Ref_Related &&
4859       isRValRef && Init->Classify(S.Context).isLValue())
4860     return ICS;
4861 
4862   // C++ [over.ics.ref]p2:
4863   //   When a parameter of reference type is not bound directly to
4864   //   an argument expression, the conversion sequence is the one
4865   //   required to convert the argument expression to the
4866   //   underlying type of the reference according to
4867   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4868   //   to copy-initializing a temporary of the underlying type with
4869   //   the argument expression. Any difference in top-level
4870   //   cv-qualification is subsumed by the initialization itself
4871   //   and does not constitute a conversion.
4872   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4873                               AllowedExplicit::None,
4874                               /*InOverloadResolution=*/false,
4875                               /*CStyle=*/false,
4876                               /*AllowObjCWritebackConversion=*/false,
4877                               /*AllowObjCConversionOnExplicit=*/false);
4878 
4879   // Of course, that's still a reference binding.
4880   if (ICS.isStandard()) {
4881     ICS.Standard.ReferenceBinding = true;
4882     ICS.Standard.IsLvalueReference = !isRValRef;
4883     ICS.Standard.BindsToFunctionLvalue = false;
4884     ICS.Standard.BindsToRvalue = true;
4885     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4886     ICS.Standard.ObjCLifetimeConversionBinding = false;
4887   } else if (ICS.isUserDefined()) {
4888     const ReferenceType *LValRefType =
4889         ICS.UserDefined.ConversionFunction->getReturnType()
4890             ->getAs<LValueReferenceType>();
4891 
4892     // C++ [over.ics.ref]p3:
4893     //   Except for an implicit object parameter, for which see 13.3.1, a
4894     //   standard conversion sequence cannot be formed if it requires [...]
4895     //   binding an rvalue reference to an lvalue other than a function
4896     //   lvalue.
4897     // Note that the function case is not possible here.
4898     if (DeclType->isRValueReferenceType() && LValRefType) {
4899       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4900       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4901       // reference to an rvalue!
4902       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4903       return ICS;
4904     }
4905 
4906     ICS.UserDefined.After.ReferenceBinding = true;
4907     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4908     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4909     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4910     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4911     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4912   }
4913 
4914   return ICS;
4915 }
4916 
4917 static ImplicitConversionSequence
4918 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4919                       bool SuppressUserConversions,
4920                       bool InOverloadResolution,
4921                       bool AllowObjCWritebackConversion,
4922                       bool AllowExplicit = false);
4923 
4924 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4925 /// initializer list From.
4926 static ImplicitConversionSequence
4927 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4928                   bool SuppressUserConversions,
4929                   bool InOverloadResolution,
4930                   bool AllowObjCWritebackConversion) {
4931   // C++11 [over.ics.list]p1:
4932   //   When an argument is an initializer list, it is not an expression and
4933   //   special rules apply for converting it to a parameter type.
4934 
4935   ImplicitConversionSequence Result;
4936   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4937 
4938   // We need a complete type for what follows. Incomplete types can never be
4939   // initialized from init lists.
4940   if (!S.isCompleteType(From->getBeginLoc(), ToType))
4941     return Result;
4942 
4943   // Per DR1467:
4944   //   If the parameter type is a class X and the initializer list has a single
4945   //   element of type cv U, where U is X or a class derived from X, the
4946   //   implicit conversion sequence is the one required to convert the element
4947   //   to the parameter type.
4948   //
4949   //   Otherwise, if the parameter type is a character array [... ]
4950   //   and the initializer list has a single element that is an
4951   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4952   //   implicit conversion sequence is the identity conversion.
4953   if (From->getNumInits() == 1) {
4954     if (ToType->isRecordType()) {
4955       QualType InitType = From->getInit(0)->getType();
4956       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4957           S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
4958         return TryCopyInitialization(S, From->getInit(0), ToType,
4959                                      SuppressUserConversions,
4960                                      InOverloadResolution,
4961                                      AllowObjCWritebackConversion);
4962     }
4963     // FIXME: Check the other conditions here: array of character type,
4964     // initializer is a string literal.
4965     if (ToType->isArrayType()) {
4966       InitializedEntity Entity =
4967         InitializedEntity::InitializeParameter(S.Context, ToType,
4968                                                /*Consumed=*/false);
4969       if (S.CanPerformCopyInitialization(Entity, From)) {
4970         Result.setStandard();
4971         Result.Standard.setAsIdentityConversion();
4972         Result.Standard.setFromType(ToType);
4973         Result.Standard.setAllToTypes(ToType);
4974         return Result;
4975       }
4976     }
4977   }
4978 
4979   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4980   // C++11 [over.ics.list]p2:
4981   //   If the parameter type is std::initializer_list<X> or "array of X" and
4982   //   all the elements can be implicitly converted to X, the implicit
4983   //   conversion sequence is the worst conversion necessary to convert an
4984   //   element of the list to X.
4985   //
4986   // C++14 [over.ics.list]p3:
4987   //   Otherwise, if the parameter type is "array of N X", if the initializer
4988   //   list has exactly N elements or if it has fewer than N elements and X is
4989   //   default-constructible, and if all the elements of the initializer list
4990   //   can be implicitly converted to X, the implicit conversion sequence is
4991   //   the worst conversion necessary to convert an element of the list to X.
4992   //
4993   // FIXME: We're missing a lot of these checks.
4994   bool toStdInitializerList = false;
4995   QualType X;
4996   if (ToType->isArrayType())
4997     X = S.Context.getAsArrayType(ToType)->getElementType();
4998   else
4999     toStdInitializerList = S.isStdInitializerList(ToType, &X);
5000   if (!X.isNull()) {
5001     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
5002       Expr *Init = From->getInit(i);
5003       ImplicitConversionSequence ICS =
5004           TryCopyInitialization(S, Init, X, SuppressUserConversions,
5005                                 InOverloadResolution,
5006                                 AllowObjCWritebackConversion);
5007       // If a single element isn't convertible, fail.
5008       if (ICS.isBad()) {
5009         Result = ICS;
5010         break;
5011       }
5012       // Otherwise, look for the worst conversion.
5013       if (Result.isBad() || CompareImplicitConversionSequences(
5014                                 S, From->getBeginLoc(), ICS, Result) ==
5015                                 ImplicitConversionSequence::Worse)
5016         Result = ICS;
5017     }
5018 
5019     // For an empty list, we won't have computed any conversion sequence.
5020     // Introduce the identity conversion sequence.
5021     if (From->getNumInits() == 0) {
5022       Result.setStandard();
5023       Result.Standard.setAsIdentityConversion();
5024       Result.Standard.setFromType(ToType);
5025       Result.Standard.setAllToTypes(ToType);
5026     }
5027 
5028     Result.setStdInitializerListElement(toStdInitializerList);
5029     return Result;
5030   }
5031 
5032   // C++14 [over.ics.list]p4:
5033   // C++11 [over.ics.list]p3:
5034   //   Otherwise, if the parameter is a non-aggregate class X and overload
5035   //   resolution chooses a single best constructor [...] the implicit
5036   //   conversion sequence is a user-defined conversion sequence. If multiple
5037   //   constructors are viable but none is better than the others, the
5038   //   implicit conversion sequence is a user-defined conversion sequence.
5039   if (ToType->isRecordType() && !ToType->isAggregateType()) {
5040     // This function can deal with initializer lists.
5041     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5042                                     AllowedExplicit::None,
5043                                     InOverloadResolution, /*CStyle=*/false,
5044                                     AllowObjCWritebackConversion,
5045                                     /*AllowObjCConversionOnExplicit=*/false);
5046   }
5047 
5048   // C++14 [over.ics.list]p5:
5049   // C++11 [over.ics.list]p4:
5050   //   Otherwise, if the parameter has an aggregate type which can be
5051   //   initialized from the initializer list [...] the implicit conversion
5052   //   sequence is a user-defined conversion sequence.
5053   if (ToType->isAggregateType()) {
5054     // Type is an aggregate, argument is an init list. At this point it comes
5055     // down to checking whether the initialization works.
5056     // FIXME: Find out whether this parameter is consumed or not.
5057     InitializedEntity Entity =
5058         InitializedEntity::InitializeParameter(S.Context, ToType,
5059                                                /*Consumed=*/false);
5060     if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5061                                                                  From)) {
5062       Result.setUserDefined();
5063       Result.UserDefined.Before.setAsIdentityConversion();
5064       // Initializer lists don't have a type.
5065       Result.UserDefined.Before.setFromType(QualType());
5066       Result.UserDefined.Before.setAllToTypes(QualType());
5067 
5068       Result.UserDefined.After.setAsIdentityConversion();
5069       Result.UserDefined.After.setFromType(ToType);
5070       Result.UserDefined.After.setAllToTypes(ToType);
5071       Result.UserDefined.ConversionFunction = nullptr;
5072     }
5073     return Result;
5074   }
5075 
5076   // C++14 [over.ics.list]p6:
5077   // C++11 [over.ics.list]p5:
5078   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5079   if (ToType->isReferenceType()) {
5080     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5081     // mention initializer lists in any way. So we go by what list-
5082     // initialization would do and try to extrapolate from that.
5083 
5084     QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5085 
5086     // If the initializer list has a single element that is reference-related
5087     // to the parameter type, we initialize the reference from that.
5088     if (From->getNumInits() == 1) {
5089       Expr *Init = From->getInit(0);
5090 
5091       QualType T2 = Init->getType();
5092 
5093       // If the initializer is the address of an overloaded function, try
5094       // to resolve the overloaded function. If all goes well, T2 is the
5095       // type of the resulting function.
5096       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5097         DeclAccessPair Found;
5098         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5099                                    Init, ToType, false, Found))
5100           T2 = Fn->getType();
5101       }
5102 
5103       // Compute some basic properties of the types and the initializer.
5104       Sema::ReferenceCompareResult RefRelationship =
5105           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5106 
5107       if (RefRelationship >= Sema::Ref_Related) {
5108         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5109                                 SuppressUserConversions,
5110                                 /*AllowExplicit=*/false);
5111       }
5112     }
5113 
5114     // Otherwise, we bind the reference to a temporary created from the
5115     // initializer list.
5116     Result = TryListConversion(S, From, T1, SuppressUserConversions,
5117                                InOverloadResolution,
5118                                AllowObjCWritebackConversion);
5119     if (Result.isFailure())
5120       return Result;
5121     assert(!Result.isEllipsis() &&
5122            "Sub-initialization cannot result in ellipsis conversion.");
5123 
5124     // Can we even bind to a temporary?
5125     if (ToType->isRValueReferenceType() ||
5126         (T1.isConstQualified() && !T1.isVolatileQualified())) {
5127       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5128                                             Result.UserDefined.After;
5129       SCS.ReferenceBinding = true;
5130       SCS.IsLvalueReference = ToType->isLValueReferenceType();
5131       SCS.BindsToRvalue = true;
5132       SCS.BindsToFunctionLvalue = false;
5133       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5134       SCS.ObjCLifetimeConversionBinding = false;
5135     } else
5136       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5137                     From, ToType);
5138     return Result;
5139   }
5140 
5141   // C++14 [over.ics.list]p7:
5142   // C++11 [over.ics.list]p6:
5143   //   Otherwise, if the parameter type is not a class:
5144   if (!ToType->isRecordType()) {
5145     //    - if the initializer list has one element that is not itself an
5146     //      initializer list, the implicit conversion sequence is the one
5147     //      required to convert the element to the parameter type.
5148     unsigned NumInits = From->getNumInits();
5149     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5150       Result = TryCopyInitialization(S, From->getInit(0), ToType,
5151                                      SuppressUserConversions,
5152                                      InOverloadResolution,
5153                                      AllowObjCWritebackConversion);
5154     //    - if the initializer list has no elements, the implicit conversion
5155     //      sequence is the identity conversion.
5156     else if (NumInits == 0) {
5157       Result.setStandard();
5158       Result.Standard.setAsIdentityConversion();
5159       Result.Standard.setFromType(ToType);
5160       Result.Standard.setAllToTypes(ToType);
5161     }
5162     return Result;
5163   }
5164 
5165   // C++14 [over.ics.list]p8:
5166   // C++11 [over.ics.list]p7:
5167   //   In all cases other than those enumerated above, no conversion is possible
5168   return Result;
5169 }
5170 
5171 /// TryCopyInitialization - Try to copy-initialize a value of type
5172 /// ToType from the expression From. Return the implicit conversion
5173 /// sequence required to pass this argument, which may be a bad
5174 /// conversion sequence (meaning that the argument cannot be passed to
5175 /// a parameter of this type). If @p SuppressUserConversions, then we
5176 /// do not permit any user-defined conversion sequences.
5177 static ImplicitConversionSequence
5178 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5179                       bool SuppressUserConversions,
5180                       bool InOverloadResolution,
5181                       bool AllowObjCWritebackConversion,
5182                       bool AllowExplicit) {
5183   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5184     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5185                              InOverloadResolution,AllowObjCWritebackConversion);
5186 
5187   if (ToType->isReferenceType())
5188     return TryReferenceInit(S, From, ToType,
5189                             /*FIXME:*/ From->getBeginLoc(),
5190                             SuppressUserConversions, AllowExplicit);
5191 
5192   return TryImplicitConversion(S, From, ToType,
5193                                SuppressUserConversions,
5194                                AllowedExplicit::None,
5195                                InOverloadResolution,
5196                                /*CStyle=*/false,
5197                                AllowObjCWritebackConversion,
5198                                /*AllowObjCConversionOnExplicit=*/false);
5199 }
5200 
5201 static bool TryCopyInitialization(const CanQualType FromQTy,
5202                                   const CanQualType ToQTy,
5203                                   Sema &S,
5204                                   SourceLocation Loc,
5205                                   ExprValueKind FromVK) {
5206   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5207   ImplicitConversionSequence ICS =
5208     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5209 
5210   return !ICS.isBad();
5211 }
5212 
5213 /// TryObjectArgumentInitialization - Try to initialize the object
5214 /// parameter of the given member function (@c Method) from the
5215 /// expression @p From.
5216 static ImplicitConversionSequence
5217 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5218                                 Expr::Classification FromClassification,
5219                                 CXXMethodDecl *Method,
5220                                 CXXRecordDecl *ActingContext) {
5221   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5222   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5223   //                 const volatile object.
5224   Qualifiers Quals = Method->getMethodQualifiers();
5225   if (isa<CXXDestructorDecl>(Method)) {
5226     Quals.addConst();
5227     Quals.addVolatile();
5228   }
5229 
5230   QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5231 
5232   // Set up the conversion sequence as a "bad" conversion, to allow us
5233   // to exit early.
5234   ImplicitConversionSequence ICS;
5235 
5236   // We need to have an object of class type.
5237   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5238     FromType = PT->getPointeeType();
5239 
5240     // When we had a pointer, it's implicitly dereferenced, so we
5241     // better have an lvalue.
5242     assert(FromClassification.isLValue());
5243   }
5244 
5245   assert(FromType->isRecordType());
5246 
5247   // C++0x [over.match.funcs]p4:
5248   //   For non-static member functions, the type of the implicit object
5249   //   parameter is
5250   //
5251   //     - "lvalue reference to cv X" for functions declared without a
5252   //        ref-qualifier or with the & ref-qualifier
5253   //     - "rvalue reference to cv X" for functions declared with the &&
5254   //        ref-qualifier
5255   //
5256   // where X is the class of which the function is a member and cv is the
5257   // cv-qualification on the member function declaration.
5258   //
5259   // However, when finding an implicit conversion sequence for the argument, we
5260   // are not allowed to perform user-defined conversions
5261   // (C++ [over.match.funcs]p5). We perform a simplified version of
5262   // reference binding here, that allows class rvalues to bind to
5263   // non-constant references.
5264 
5265   // First check the qualifiers.
5266   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5267   if (ImplicitParamType.getCVRQualifiers()
5268                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5269       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5270     ICS.setBad(BadConversionSequence::bad_qualifiers,
5271                FromType, ImplicitParamType);
5272     return ICS;
5273   }
5274 
5275   if (FromTypeCanon.hasAddressSpace()) {
5276     Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5277     Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5278     if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5279       ICS.setBad(BadConversionSequence::bad_qualifiers,
5280                  FromType, ImplicitParamType);
5281       return ICS;
5282     }
5283   }
5284 
5285   // Check that we have either the same type or a derived type. It
5286   // affects the conversion rank.
5287   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5288   ImplicitConversionKind SecondKind;
5289   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5290     SecondKind = ICK_Identity;
5291   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5292     SecondKind = ICK_Derived_To_Base;
5293   else {
5294     ICS.setBad(BadConversionSequence::unrelated_class,
5295                FromType, ImplicitParamType);
5296     return ICS;
5297   }
5298 
5299   // Check the ref-qualifier.
5300   switch (Method->getRefQualifier()) {
5301   case RQ_None:
5302     // Do nothing; we don't care about lvalueness or rvalueness.
5303     break;
5304 
5305   case RQ_LValue:
5306     if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5307       // non-const lvalue reference cannot bind to an rvalue
5308       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5309                  ImplicitParamType);
5310       return ICS;
5311     }
5312     break;
5313 
5314   case RQ_RValue:
5315     if (!FromClassification.isRValue()) {
5316       // rvalue reference cannot bind to an lvalue
5317       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5318                  ImplicitParamType);
5319       return ICS;
5320     }
5321     break;
5322   }
5323 
5324   // Success. Mark this as a reference binding.
5325   ICS.setStandard();
5326   ICS.Standard.setAsIdentityConversion();
5327   ICS.Standard.Second = SecondKind;
5328   ICS.Standard.setFromType(FromType);
5329   ICS.Standard.setAllToTypes(ImplicitParamType);
5330   ICS.Standard.ReferenceBinding = true;
5331   ICS.Standard.DirectBinding = true;
5332   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5333   ICS.Standard.BindsToFunctionLvalue = false;
5334   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5335   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5336     = (Method->getRefQualifier() == RQ_None);
5337   return ICS;
5338 }
5339 
5340 /// PerformObjectArgumentInitialization - Perform initialization of
5341 /// the implicit object parameter for the given Method with the given
5342 /// expression.
5343 ExprResult
5344 Sema::PerformObjectArgumentInitialization(Expr *From,
5345                                           NestedNameSpecifier *Qualifier,
5346                                           NamedDecl *FoundDecl,
5347                                           CXXMethodDecl *Method) {
5348   QualType FromRecordType, DestType;
5349   QualType ImplicitParamRecordType  =
5350     Method->getThisType()->castAs<PointerType>()->getPointeeType();
5351 
5352   Expr::Classification FromClassification;
5353   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5354     FromRecordType = PT->getPointeeType();
5355     DestType = Method->getThisType();
5356     FromClassification = Expr::Classification::makeSimpleLValue();
5357   } else {
5358     FromRecordType = From->getType();
5359     DestType = ImplicitParamRecordType;
5360     FromClassification = From->Classify(Context);
5361 
5362     // When performing member access on an rvalue, materialize a temporary.
5363     if (From->isRValue()) {
5364       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5365                                             Method->getRefQualifier() !=
5366                                                 RefQualifierKind::RQ_RValue);
5367     }
5368   }
5369 
5370   // Note that we always use the true parent context when performing
5371   // the actual argument initialization.
5372   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5373       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5374       Method->getParent());
5375   if (ICS.isBad()) {
5376     switch (ICS.Bad.Kind) {
5377     case BadConversionSequence::bad_qualifiers: {
5378       Qualifiers FromQs = FromRecordType.getQualifiers();
5379       Qualifiers ToQs = DestType.getQualifiers();
5380       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5381       if (CVR) {
5382         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5383             << Method->getDeclName() << FromRecordType << (CVR - 1)
5384             << From->getSourceRange();
5385         Diag(Method->getLocation(), diag::note_previous_decl)
5386           << Method->getDeclName();
5387         return ExprError();
5388       }
5389       break;
5390     }
5391 
5392     case BadConversionSequence::lvalue_ref_to_rvalue:
5393     case BadConversionSequence::rvalue_ref_to_lvalue: {
5394       bool IsRValueQualified =
5395         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5396       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5397           << Method->getDeclName() << FromClassification.isRValue()
5398           << IsRValueQualified;
5399       Diag(Method->getLocation(), diag::note_previous_decl)
5400         << Method->getDeclName();
5401       return ExprError();
5402     }
5403 
5404     case BadConversionSequence::no_conversion:
5405     case BadConversionSequence::unrelated_class:
5406       break;
5407     }
5408 
5409     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5410            << ImplicitParamRecordType << FromRecordType
5411            << From->getSourceRange();
5412   }
5413 
5414   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5415     ExprResult FromRes =
5416       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5417     if (FromRes.isInvalid())
5418       return ExprError();
5419     From = FromRes.get();
5420   }
5421 
5422   if (!Context.hasSameType(From->getType(), DestType)) {
5423     CastKind CK;
5424     QualType PteeTy = DestType->getPointeeType();
5425     LangAS DestAS =
5426         PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5427     if (FromRecordType.getAddressSpace() != DestAS)
5428       CK = CK_AddressSpaceConversion;
5429     else
5430       CK = CK_NoOp;
5431     From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5432   }
5433   return From;
5434 }
5435 
5436 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5437 /// expression From to bool (C++0x [conv]p3).
5438 static ImplicitConversionSequence
5439 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5440   // C++ [dcl.init]/17.8:
5441   //   - Otherwise, if the initialization is direct-initialization, the source
5442   //     type is std::nullptr_t, and the destination type is bool, the initial
5443   //     value of the object being initialized is false.
5444   if (From->getType()->isNullPtrType())
5445     return ImplicitConversionSequence::getNullptrToBool(From->getType(),
5446                                                         S.Context.BoolTy,
5447                                                         From->isGLValue());
5448 
5449   // All other direct-initialization of bool is equivalent to an implicit
5450   // conversion to bool in which explicit conversions are permitted.
5451   return TryImplicitConversion(S, From, S.Context.BoolTy,
5452                                /*SuppressUserConversions=*/false,
5453                                AllowedExplicit::Conversions,
5454                                /*InOverloadResolution=*/false,
5455                                /*CStyle=*/false,
5456                                /*AllowObjCWritebackConversion=*/false,
5457                                /*AllowObjCConversionOnExplicit=*/false);
5458 }
5459 
5460 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5461 /// of the expression From to bool (C++0x [conv]p3).
5462 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5463   if (checkPlaceholderForOverload(*this, From))
5464     return ExprError();
5465 
5466   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5467   if (!ICS.isBad())
5468     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5469 
5470   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5471     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5472            << From->getType() << From->getSourceRange();
5473   return ExprError();
5474 }
5475 
5476 /// Check that the specified conversion is permitted in a converted constant
5477 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5478 /// is acceptable.
5479 static bool CheckConvertedConstantConversions(Sema &S,
5480                                               StandardConversionSequence &SCS) {
5481   // Since we know that the target type is an integral or unscoped enumeration
5482   // type, most conversion kinds are impossible. All possible First and Third
5483   // conversions are fine.
5484   switch (SCS.Second) {
5485   case ICK_Identity:
5486   case ICK_Function_Conversion:
5487   case ICK_Integral_Promotion:
5488   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5489   case ICK_Zero_Queue_Conversion:
5490     return true;
5491 
5492   case ICK_Boolean_Conversion:
5493     // Conversion from an integral or unscoped enumeration type to bool is
5494     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5495     // conversion, so we allow it in a converted constant expression.
5496     //
5497     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5498     // a lot of popular code. We should at least add a warning for this
5499     // (non-conforming) extension.
5500     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5501            SCS.getToType(2)->isBooleanType();
5502 
5503   case ICK_Pointer_Conversion:
5504   case ICK_Pointer_Member:
5505     // C++1z: null pointer conversions and null member pointer conversions are
5506     // only permitted if the source type is std::nullptr_t.
5507     return SCS.getFromType()->isNullPtrType();
5508 
5509   case ICK_Floating_Promotion:
5510   case ICK_Complex_Promotion:
5511   case ICK_Floating_Conversion:
5512   case ICK_Complex_Conversion:
5513   case ICK_Floating_Integral:
5514   case ICK_Compatible_Conversion:
5515   case ICK_Derived_To_Base:
5516   case ICK_Vector_Conversion:
5517   case ICK_Vector_Splat:
5518   case ICK_Complex_Real:
5519   case ICK_Block_Pointer_Conversion:
5520   case ICK_TransparentUnionConversion:
5521   case ICK_Writeback_Conversion:
5522   case ICK_Zero_Event_Conversion:
5523   case ICK_C_Only_Conversion:
5524   case ICK_Incompatible_Pointer_Conversion:
5525     return false;
5526 
5527   case ICK_Lvalue_To_Rvalue:
5528   case ICK_Array_To_Pointer:
5529   case ICK_Function_To_Pointer:
5530     llvm_unreachable("found a first conversion kind in Second");
5531 
5532   case ICK_Qualification:
5533     llvm_unreachable("found a third conversion kind in Second");
5534 
5535   case ICK_Num_Conversion_Kinds:
5536     break;
5537   }
5538 
5539   llvm_unreachable("unknown conversion kind");
5540 }
5541 
5542 /// CheckConvertedConstantExpression - Check that the expression From is a
5543 /// converted constant expression of type T, perform the conversion and produce
5544 /// the converted expression, per C++11 [expr.const]p3.
5545 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5546                                                    QualType T, APValue &Value,
5547                                                    Sema::CCEKind CCE,
5548                                                    bool RequireInt) {
5549   assert(S.getLangOpts().CPlusPlus11 &&
5550          "converted constant expression outside C++11");
5551 
5552   if (checkPlaceholderForOverload(S, From))
5553     return ExprError();
5554 
5555   // C++1z [expr.const]p3:
5556   //  A converted constant expression of type T is an expression,
5557   //  implicitly converted to type T, where the converted
5558   //  expression is a constant expression and the implicit conversion
5559   //  sequence contains only [... list of conversions ...].
5560   // C++1z [stmt.if]p2:
5561   //  If the if statement is of the form if constexpr, the value of the
5562   //  condition shall be a contextually converted constant expression of type
5563   //  bool.
5564   ImplicitConversionSequence ICS =
5565       CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool
5566           ? TryContextuallyConvertToBool(S, From)
5567           : TryCopyInitialization(S, From, T,
5568                                   /*SuppressUserConversions=*/false,
5569                                   /*InOverloadResolution=*/false,
5570                                   /*AllowObjCWritebackConversion=*/false,
5571                                   /*AllowExplicit=*/false);
5572   StandardConversionSequence *SCS = nullptr;
5573   switch (ICS.getKind()) {
5574   case ImplicitConversionSequence::StandardConversion:
5575     SCS = &ICS.Standard;
5576     break;
5577   case ImplicitConversionSequence::UserDefinedConversion:
5578     // We are converting to a non-class type, so the Before sequence
5579     // must be trivial.
5580     SCS = &ICS.UserDefined.After;
5581     break;
5582   case ImplicitConversionSequence::AmbiguousConversion:
5583   case ImplicitConversionSequence::BadConversion:
5584     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5585       return S.Diag(From->getBeginLoc(),
5586                     diag::err_typecheck_converted_constant_expression)
5587              << From->getType() << From->getSourceRange() << T;
5588     return ExprError();
5589 
5590   case ImplicitConversionSequence::EllipsisConversion:
5591     llvm_unreachable("ellipsis conversion in converted constant expression");
5592   }
5593 
5594   // Check that we would only use permitted conversions.
5595   if (!CheckConvertedConstantConversions(S, *SCS)) {
5596     return S.Diag(From->getBeginLoc(),
5597                   diag::err_typecheck_converted_constant_expression_disallowed)
5598            << From->getType() << From->getSourceRange() << T;
5599   }
5600   // [...] and where the reference binding (if any) binds directly.
5601   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5602     return S.Diag(From->getBeginLoc(),
5603                   diag::err_typecheck_converted_constant_expression_indirect)
5604            << From->getType() << From->getSourceRange() << T;
5605   }
5606 
5607   ExprResult Result =
5608       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5609   if (Result.isInvalid())
5610     return Result;
5611 
5612   // C++2a [intro.execution]p5:
5613   //   A full-expression is [...] a constant-expression [...]
5614   Result =
5615       S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5616                             /*DiscardedValue=*/false, /*IsConstexpr=*/true);
5617   if (Result.isInvalid())
5618     return Result;
5619 
5620   // Check for a narrowing implicit conversion.
5621   APValue PreNarrowingValue;
5622   QualType PreNarrowingType;
5623   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5624                                 PreNarrowingType)) {
5625   case NK_Dependent_Narrowing:
5626     // Implicit conversion to a narrower type, but the expression is
5627     // value-dependent so we can't tell whether it's actually narrowing.
5628   case NK_Variable_Narrowing:
5629     // Implicit conversion to a narrower type, and the value is not a constant
5630     // expression. We'll diagnose this in a moment.
5631   case NK_Not_Narrowing:
5632     break;
5633 
5634   case NK_Constant_Narrowing:
5635     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5636         << CCE << /*Constant*/ 1
5637         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5638     break;
5639 
5640   case NK_Type_Narrowing:
5641     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5642         << CCE << /*Constant*/ 0 << From->getType() << T;
5643     break;
5644   }
5645 
5646   if (Result.get()->isValueDependent()) {
5647     Value = APValue();
5648     return Result;
5649   }
5650 
5651   // Check the expression is a constant expression.
5652   SmallVector<PartialDiagnosticAt, 8> Notes;
5653   Expr::EvalResult Eval;
5654   Eval.Diag = &Notes;
5655   Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5656                                    ? Expr::EvaluateForMangling
5657                                    : Expr::EvaluateForCodeGen;
5658 
5659   if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5660       (RequireInt && !Eval.Val.isInt())) {
5661     // The expression can't be folded, so we can't keep it at this position in
5662     // the AST.
5663     Result = ExprError();
5664   } else {
5665     Value = Eval.Val;
5666 
5667     if (Notes.empty()) {
5668       // It's a constant expression.
5669       return ConstantExpr::Create(S.Context, Result.get(), Value);
5670     }
5671   }
5672 
5673   // It's not a constant expression. Produce an appropriate diagnostic.
5674   if (Notes.size() == 1 &&
5675       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5676     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5677   else {
5678     S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5679         << CCE << From->getSourceRange();
5680     for (unsigned I = 0; I < Notes.size(); ++I)
5681       S.Diag(Notes[I].first, Notes[I].second);
5682   }
5683   return ExprError();
5684 }
5685 
5686 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5687                                                   APValue &Value, CCEKind CCE) {
5688   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5689 }
5690 
5691 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5692                                                   llvm::APSInt &Value,
5693                                                   CCEKind CCE) {
5694   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5695 
5696   APValue V;
5697   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5698   if (!R.isInvalid() && !R.get()->isValueDependent())
5699     Value = V.getInt();
5700   return R;
5701 }
5702 
5703 
5704 /// dropPointerConversions - If the given standard conversion sequence
5705 /// involves any pointer conversions, remove them.  This may change
5706 /// the result type of the conversion sequence.
5707 static void dropPointerConversion(StandardConversionSequence &SCS) {
5708   if (SCS.Second == ICK_Pointer_Conversion) {
5709     SCS.Second = ICK_Identity;
5710     SCS.Third = ICK_Identity;
5711     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5712   }
5713 }
5714 
5715 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5716 /// convert the expression From to an Objective-C pointer type.
5717 static ImplicitConversionSequence
5718 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5719   // Do an implicit conversion to 'id'.
5720   QualType Ty = S.Context.getObjCIdType();
5721   ImplicitConversionSequence ICS
5722     = TryImplicitConversion(S, From, Ty,
5723                             // FIXME: Are these flags correct?
5724                             /*SuppressUserConversions=*/false,
5725                             AllowedExplicit::Conversions,
5726                             /*InOverloadResolution=*/false,
5727                             /*CStyle=*/false,
5728                             /*AllowObjCWritebackConversion=*/false,
5729                             /*AllowObjCConversionOnExplicit=*/true);
5730 
5731   // Strip off any final conversions to 'id'.
5732   switch (ICS.getKind()) {
5733   case ImplicitConversionSequence::BadConversion:
5734   case ImplicitConversionSequence::AmbiguousConversion:
5735   case ImplicitConversionSequence::EllipsisConversion:
5736     break;
5737 
5738   case ImplicitConversionSequence::UserDefinedConversion:
5739     dropPointerConversion(ICS.UserDefined.After);
5740     break;
5741 
5742   case ImplicitConversionSequence::StandardConversion:
5743     dropPointerConversion(ICS.Standard);
5744     break;
5745   }
5746 
5747   return ICS;
5748 }
5749 
5750 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5751 /// conversion of the expression From to an Objective-C pointer type.
5752 /// Returns a valid but null ExprResult if no conversion sequence exists.
5753 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5754   if (checkPlaceholderForOverload(*this, From))
5755     return ExprError();
5756 
5757   QualType Ty = Context.getObjCIdType();
5758   ImplicitConversionSequence ICS =
5759     TryContextuallyConvertToObjCPointer(*this, From);
5760   if (!ICS.isBad())
5761     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5762   return ExprResult();
5763 }
5764 
5765 /// Determine whether the provided type is an integral type, or an enumeration
5766 /// type of a permitted flavor.
5767 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5768   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5769                                  : T->isIntegralOrUnscopedEnumerationType();
5770 }
5771 
5772 static ExprResult
5773 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5774                             Sema::ContextualImplicitConverter &Converter,
5775                             QualType T, UnresolvedSetImpl &ViableConversions) {
5776 
5777   if (Converter.Suppress)
5778     return ExprError();
5779 
5780   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5781   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5782     CXXConversionDecl *Conv =
5783         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5784     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5785     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5786   }
5787   return From;
5788 }
5789 
5790 static bool
5791 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5792                            Sema::ContextualImplicitConverter &Converter,
5793                            QualType T, bool HadMultipleCandidates,
5794                            UnresolvedSetImpl &ExplicitConversions) {
5795   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5796     DeclAccessPair Found = ExplicitConversions[0];
5797     CXXConversionDecl *Conversion =
5798         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5799 
5800     // The user probably meant to invoke the given explicit
5801     // conversion; use it.
5802     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5803     std::string TypeStr;
5804     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5805 
5806     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5807         << FixItHint::CreateInsertion(From->getBeginLoc(),
5808                                       "static_cast<" + TypeStr + ">(")
5809         << FixItHint::CreateInsertion(
5810                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5811     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5812 
5813     // If we aren't in a SFINAE context, build a call to the
5814     // explicit conversion function.
5815     if (SemaRef.isSFINAEContext())
5816       return true;
5817 
5818     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5819     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5820                                                        HadMultipleCandidates);
5821     if (Result.isInvalid())
5822       return true;
5823     // Record usage of conversion in an implicit cast.
5824     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5825                                     CK_UserDefinedConversion, Result.get(),
5826                                     nullptr, Result.get()->getValueKind());
5827   }
5828   return false;
5829 }
5830 
5831 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5832                              Sema::ContextualImplicitConverter &Converter,
5833                              QualType T, bool HadMultipleCandidates,
5834                              DeclAccessPair &Found) {
5835   CXXConversionDecl *Conversion =
5836       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5837   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5838 
5839   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5840   if (!Converter.SuppressConversion) {
5841     if (SemaRef.isSFINAEContext())
5842       return true;
5843 
5844     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5845         << From->getSourceRange();
5846   }
5847 
5848   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5849                                                      HadMultipleCandidates);
5850   if (Result.isInvalid())
5851     return true;
5852   // Record usage of conversion in an implicit cast.
5853   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5854                                   CK_UserDefinedConversion, Result.get(),
5855                                   nullptr, Result.get()->getValueKind());
5856   return false;
5857 }
5858 
5859 static ExprResult finishContextualImplicitConversion(
5860     Sema &SemaRef, SourceLocation Loc, Expr *From,
5861     Sema::ContextualImplicitConverter &Converter) {
5862   if (!Converter.match(From->getType()) && !Converter.Suppress)
5863     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5864         << From->getSourceRange();
5865 
5866   return SemaRef.DefaultLvalueConversion(From);
5867 }
5868 
5869 static void
5870 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5871                                   UnresolvedSetImpl &ViableConversions,
5872                                   OverloadCandidateSet &CandidateSet) {
5873   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5874     DeclAccessPair FoundDecl = ViableConversions[I];
5875     NamedDecl *D = FoundDecl.getDecl();
5876     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5877     if (isa<UsingShadowDecl>(D))
5878       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5879 
5880     CXXConversionDecl *Conv;
5881     FunctionTemplateDecl *ConvTemplate;
5882     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5883       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5884     else
5885       Conv = cast<CXXConversionDecl>(D);
5886 
5887     if (ConvTemplate)
5888       SemaRef.AddTemplateConversionCandidate(
5889           ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5890           /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
5891     else
5892       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5893                                      ToType, CandidateSet,
5894                                      /*AllowObjCConversionOnExplicit=*/false,
5895                                      /*AllowExplicit*/ true);
5896   }
5897 }
5898 
5899 /// Attempt to convert the given expression to a type which is accepted
5900 /// by the given converter.
5901 ///
5902 /// This routine will attempt to convert an expression of class type to a
5903 /// type accepted by the specified converter. In C++11 and before, the class
5904 /// must have a single non-explicit conversion function converting to a matching
5905 /// type. In C++1y, there can be multiple such conversion functions, but only
5906 /// one target type.
5907 ///
5908 /// \param Loc The source location of the construct that requires the
5909 /// conversion.
5910 ///
5911 /// \param From The expression we're converting from.
5912 ///
5913 /// \param Converter Used to control and diagnose the conversion process.
5914 ///
5915 /// \returns The expression, converted to an integral or enumeration type if
5916 /// successful.
5917 ExprResult Sema::PerformContextualImplicitConversion(
5918     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5919   // We can't perform any more checking for type-dependent expressions.
5920   if (From->isTypeDependent())
5921     return From;
5922 
5923   // Process placeholders immediately.
5924   if (From->hasPlaceholderType()) {
5925     ExprResult result = CheckPlaceholderExpr(From);
5926     if (result.isInvalid())
5927       return result;
5928     From = result.get();
5929   }
5930 
5931   // If the expression already has a matching type, we're golden.
5932   QualType T = From->getType();
5933   if (Converter.match(T))
5934     return DefaultLvalueConversion(From);
5935 
5936   // FIXME: Check for missing '()' if T is a function type?
5937 
5938   // We can only perform contextual implicit conversions on objects of class
5939   // type.
5940   const RecordType *RecordTy = T->getAs<RecordType>();
5941   if (!RecordTy || !getLangOpts().CPlusPlus) {
5942     if (!Converter.Suppress)
5943       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5944     return From;
5945   }
5946 
5947   // We must have a complete class type.
5948   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5949     ContextualImplicitConverter &Converter;
5950     Expr *From;
5951 
5952     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5953         : Converter(Converter), From(From) {}
5954 
5955     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5956       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5957     }
5958   } IncompleteDiagnoser(Converter, From);
5959 
5960   if (Converter.Suppress ? !isCompleteType(Loc, T)
5961                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5962     return From;
5963 
5964   // Look for a conversion to an integral or enumeration type.
5965   UnresolvedSet<4>
5966       ViableConversions; // These are *potentially* viable in C++1y.
5967   UnresolvedSet<4> ExplicitConversions;
5968   const auto &Conversions =
5969       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5970 
5971   bool HadMultipleCandidates =
5972       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5973 
5974   // To check that there is only one target type, in C++1y:
5975   QualType ToType;
5976   bool HasUniqueTargetType = true;
5977 
5978   // Collect explicit or viable (potentially in C++1y) conversions.
5979   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5980     NamedDecl *D = (*I)->getUnderlyingDecl();
5981     CXXConversionDecl *Conversion;
5982     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5983     if (ConvTemplate) {
5984       if (getLangOpts().CPlusPlus14)
5985         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5986       else
5987         continue; // C++11 does not consider conversion operator templates(?).
5988     } else
5989       Conversion = cast<CXXConversionDecl>(D);
5990 
5991     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5992            "Conversion operator templates are considered potentially "
5993            "viable in C++1y");
5994 
5995     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5996     if (Converter.match(CurToType) || ConvTemplate) {
5997 
5998       if (Conversion->isExplicit()) {
5999         // FIXME: For C++1y, do we need this restriction?
6000         // cf. diagnoseNoViableConversion()
6001         if (!ConvTemplate)
6002           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6003       } else {
6004         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6005           if (ToType.isNull())
6006             ToType = CurToType.getUnqualifiedType();
6007           else if (HasUniqueTargetType &&
6008                    (CurToType.getUnqualifiedType() != ToType))
6009             HasUniqueTargetType = false;
6010         }
6011         ViableConversions.addDecl(I.getDecl(), I.getAccess());
6012       }
6013     }
6014   }
6015 
6016   if (getLangOpts().CPlusPlus14) {
6017     // C++1y [conv]p6:
6018     // ... An expression e of class type E appearing in such a context
6019     // is said to be contextually implicitly converted to a specified
6020     // type T and is well-formed if and only if e can be implicitly
6021     // converted to a type T that is determined as follows: E is searched
6022     // for conversion functions whose return type is cv T or reference to
6023     // cv T such that T is allowed by the context. There shall be
6024     // exactly one such T.
6025 
6026     // If no unique T is found:
6027     if (ToType.isNull()) {
6028       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6029                                      HadMultipleCandidates,
6030                                      ExplicitConversions))
6031         return ExprError();
6032       return finishContextualImplicitConversion(*this, Loc, From, Converter);
6033     }
6034 
6035     // If more than one unique Ts are found:
6036     if (!HasUniqueTargetType)
6037       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6038                                          ViableConversions);
6039 
6040     // If one unique T is found:
6041     // First, build a candidate set from the previously recorded
6042     // potentially viable conversions.
6043     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6044     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6045                                       CandidateSet);
6046 
6047     // Then, perform overload resolution over the candidate set.
6048     OverloadCandidateSet::iterator Best;
6049     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6050     case OR_Success: {
6051       // Apply this conversion.
6052       DeclAccessPair Found =
6053           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6054       if (recordConversion(*this, Loc, From, Converter, T,
6055                            HadMultipleCandidates, Found))
6056         return ExprError();
6057       break;
6058     }
6059     case OR_Ambiguous:
6060       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6061                                          ViableConversions);
6062     case OR_No_Viable_Function:
6063       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6064                                      HadMultipleCandidates,
6065                                      ExplicitConversions))
6066         return ExprError();
6067       LLVM_FALLTHROUGH;
6068     case OR_Deleted:
6069       // We'll complain below about a non-integral condition type.
6070       break;
6071     }
6072   } else {
6073     switch (ViableConversions.size()) {
6074     case 0: {
6075       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6076                                      HadMultipleCandidates,
6077                                      ExplicitConversions))
6078         return ExprError();
6079 
6080       // We'll complain below about a non-integral condition type.
6081       break;
6082     }
6083     case 1: {
6084       // Apply this conversion.
6085       DeclAccessPair Found = ViableConversions[0];
6086       if (recordConversion(*this, Loc, From, Converter, T,
6087                            HadMultipleCandidates, Found))
6088         return ExprError();
6089       break;
6090     }
6091     default:
6092       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6093                                          ViableConversions);
6094     }
6095   }
6096 
6097   return finishContextualImplicitConversion(*this, Loc, From, Converter);
6098 }
6099 
6100 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6101 /// an acceptable non-member overloaded operator for a call whose
6102 /// arguments have types T1 (and, if non-empty, T2). This routine
6103 /// implements the check in C++ [over.match.oper]p3b2 concerning
6104 /// enumeration types.
6105 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6106                                                    FunctionDecl *Fn,
6107                                                    ArrayRef<Expr *> Args) {
6108   QualType T1 = Args[0]->getType();
6109   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6110 
6111   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6112     return true;
6113 
6114   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6115     return true;
6116 
6117   const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6118   if (Proto->getNumParams() < 1)
6119     return false;
6120 
6121   if (T1->isEnumeralType()) {
6122     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6123     if (Context.hasSameUnqualifiedType(T1, ArgType))
6124       return true;
6125   }
6126 
6127   if (Proto->getNumParams() < 2)
6128     return false;
6129 
6130   if (!T2.isNull() && T2->isEnumeralType()) {
6131     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6132     if (Context.hasSameUnqualifiedType(T2, ArgType))
6133       return true;
6134   }
6135 
6136   return false;
6137 }
6138 
6139 /// AddOverloadCandidate - Adds the given function to the set of
6140 /// candidate functions, using the given function call arguments.  If
6141 /// @p SuppressUserConversions, then don't allow user-defined
6142 /// conversions via constructors or conversion operators.
6143 ///
6144 /// \param PartialOverloading true if we are performing "partial" overloading
6145 /// based on an incomplete set of function arguments. This feature is used by
6146 /// code completion.
6147 void Sema::AddOverloadCandidate(
6148     FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6149     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6150     bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6151     ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6152     OverloadCandidateParamOrder PO) {
6153   const FunctionProtoType *Proto
6154     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6155   assert(Proto && "Functions without a prototype cannot be overloaded");
6156   assert(!Function->getDescribedFunctionTemplate() &&
6157          "Use AddTemplateOverloadCandidate for function templates");
6158 
6159   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6160     if (!isa<CXXConstructorDecl>(Method)) {
6161       // If we get here, it's because we're calling a member function
6162       // that is named without a member access expression (e.g.,
6163       // "this->f") that was either written explicitly or created
6164       // implicitly. This can happen with a qualified call to a member
6165       // function, e.g., X::f(). We use an empty type for the implied
6166       // object argument (C++ [over.call.func]p3), and the acting context
6167       // is irrelevant.
6168       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6169                          Expr::Classification::makeSimpleLValue(), Args,
6170                          CandidateSet, SuppressUserConversions,
6171                          PartialOverloading, EarlyConversions, PO);
6172       return;
6173     }
6174     // We treat a constructor like a non-member function, since its object
6175     // argument doesn't participate in overload resolution.
6176   }
6177 
6178   if (!CandidateSet.isNewCandidate(Function, PO))
6179     return;
6180 
6181   // C++11 [class.copy]p11: [DR1402]
6182   //   A defaulted move constructor that is defined as deleted is ignored by
6183   //   overload resolution.
6184   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6185   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6186       Constructor->isMoveConstructor())
6187     return;
6188 
6189   // Overload resolution is always an unevaluated context.
6190   EnterExpressionEvaluationContext Unevaluated(
6191       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6192 
6193   // C++ [over.match.oper]p3:
6194   //   if no operand has a class type, only those non-member functions in the
6195   //   lookup set that have a first parameter of type T1 or "reference to
6196   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6197   //   is a right operand) a second parameter of type T2 or "reference to
6198   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
6199   //   candidate functions.
6200   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6201       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6202     return;
6203 
6204   // Add this candidate
6205   OverloadCandidate &Candidate =
6206       CandidateSet.addCandidate(Args.size(), EarlyConversions);
6207   Candidate.FoundDecl = FoundDecl;
6208   Candidate.Function = Function;
6209   Candidate.Viable = true;
6210   Candidate.RewriteKind =
6211       CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6212   Candidate.IsSurrogate = false;
6213   Candidate.IsADLCandidate = IsADLCandidate;
6214   Candidate.IgnoreObjectArgument = false;
6215   Candidate.ExplicitCallArguments = Args.size();
6216 
6217   // Explicit functions are not actually candidates at all if we're not
6218   // allowing them in this context, but keep them around so we can point
6219   // to them in diagnostics.
6220   if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6221     Candidate.Viable = false;
6222     Candidate.FailureKind = ovl_fail_explicit;
6223     return;
6224   }
6225 
6226   if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6227       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6228     Candidate.Viable = false;
6229     Candidate.FailureKind = ovl_non_default_multiversion_function;
6230     return;
6231   }
6232 
6233   if (Constructor) {
6234     // C++ [class.copy]p3:
6235     //   A member function template is never instantiated to perform the copy
6236     //   of a class object to an object of its class type.
6237     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6238     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6239         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6240          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6241                        ClassType))) {
6242       Candidate.Viable = false;
6243       Candidate.FailureKind = ovl_fail_illegal_constructor;
6244       return;
6245     }
6246 
6247     // C++ [over.match.funcs]p8: (proposed DR resolution)
6248     //   A constructor inherited from class type C that has a first parameter
6249     //   of type "reference to P" (including such a constructor instantiated
6250     //   from a template) is excluded from the set of candidate functions when
6251     //   constructing an object of type cv D if the argument list has exactly
6252     //   one argument and D is reference-related to P and P is reference-related
6253     //   to C.
6254     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6255     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6256         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6257       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6258       QualType C = Context.getRecordType(Constructor->getParent());
6259       QualType D = Context.getRecordType(Shadow->getParent());
6260       SourceLocation Loc = Args.front()->getExprLoc();
6261       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6262           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6263         Candidate.Viable = false;
6264         Candidate.FailureKind = ovl_fail_inhctor_slice;
6265         return;
6266       }
6267     }
6268 
6269     // Check that the constructor is capable of constructing an object in the
6270     // destination address space.
6271     if (!Qualifiers::isAddressSpaceSupersetOf(
6272             Constructor->getMethodQualifiers().getAddressSpace(),
6273             CandidateSet.getDestAS())) {
6274       Candidate.Viable = false;
6275       Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6276     }
6277   }
6278 
6279   unsigned NumParams = Proto->getNumParams();
6280 
6281   // (C++ 13.3.2p2): A candidate function having fewer than m
6282   // parameters is viable only if it has an ellipsis in its parameter
6283   // list (8.3.5).
6284   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6285       !Proto->isVariadic()) {
6286     Candidate.Viable = false;
6287     Candidate.FailureKind = ovl_fail_too_many_arguments;
6288     return;
6289   }
6290 
6291   // (C++ 13.3.2p2): A candidate function having more than m parameters
6292   // is viable only if the (m+1)st parameter has a default argument
6293   // (8.3.6). For the purposes of overload resolution, the
6294   // parameter list is truncated on the right, so that there are
6295   // exactly m parameters.
6296   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6297   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6298     // Not enough arguments.
6299     Candidate.Viable = false;
6300     Candidate.FailureKind = ovl_fail_too_few_arguments;
6301     return;
6302   }
6303 
6304   // (CUDA B.1): Check for invalid calls between targets.
6305   if (getLangOpts().CUDA)
6306     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6307       // Skip the check for callers that are implicit members, because in this
6308       // case we may not yet know what the member's target is; the target is
6309       // inferred for the member automatically, based on the bases and fields of
6310       // the class.
6311       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6312         Candidate.Viable = false;
6313         Candidate.FailureKind = ovl_fail_bad_target;
6314         return;
6315       }
6316 
6317   if (Function->getTrailingRequiresClause()) {
6318     ConstraintSatisfaction Satisfaction;
6319     if (CheckFunctionConstraints(Function, Satisfaction) ||
6320         !Satisfaction.IsSatisfied) {
6321       Candidate.Viable = false;
6322       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6323       return;
6324     }
6325   }
6326 
6327   // Determine the implicit conversion sequences for each of the
6328   // arguments.
6329   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6330     unsigned ConvIdx =
6331         PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6332     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6333       // We already formed a conversion sequence for this parameter during
6334       // template argument deduction.
6335     } else if (ArgIdx < NumParams) {
6336       // (C++ 13.3.2p3): for F to be a viable function, there shall
6337       // exist for each argument an implicit conversion sequence
6338       // (13.3.3.1) that converts that argument to the corresponding
6339       // parameter of F.
6340       QualType ParamType = Proto->getParamType(ArgIdx);
6341       Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6342           *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6343           /*InOverloadResolution=*/true,
6344           /*AllowObjCWritebackConversion=*/
6345           getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6346       if (Candidate.Conversions[ConvIdx].isBad()) {
6347         Candidate.Viable = false;
6348         Candidate.FailureKind = ovl_fail_bad_conversion;
6349         return;
6350       }
6351     } else {
6352       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6353       // argument for which there is no corresponding parameter is
6354       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6355       Candidate.Conversions[ConvIdx].setEllipsis();
6356     }
6357   }
6358 
6359   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6360     Candidate.Viable = false;
6361     Candidate.FailureKind = ovl_fail_enable_if;
6362     Candidate.DeductionFailure.Data = FailedAttr;
6363     return;
6364   }
6365 
6366   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6367     Candidate.Viable = false;
6368     Candidate.FailureKind = ovl_fail_ext_disabled;
6369     return;
6370   }
6371 }
6372 
6373 ObjCMethodDecl *
6374 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6375                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6376   if (Methods.size() <= 1)
6377     return nullptr;
6378 
6379   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6380     bool Match = true;
6381     ObjCMethodDecl *Method = Methods[b];
6382     unsigned NumNamedArgs = Sel.getNumArgs();
6383     // Method might have more arguments than selector indicates. This is due
6384     // to addition of c-style arguments in method.
6385     if (Method->param_size() > NumNamedArgs)
6386       NumNamedArgs = Method->param_size();
6387     if (Args.size() < NumNamedArgs)
6388       continue;
6389 
6390     for (unsigned i = 0; i < NumNamedArgs; i++) {
6391       // We can't do any type-checking on a type-dependent argument.
6392       if (Args[i]->isTypeDependent()) {
6393         Match = false;
6394         break;
6395       }
6396 
6397       ParmVarDecl *param = Method->parameters()[i];
6398       Expr *argExpr = Args[i];
6399       assert(argExpr && "SelectBestMethod(): missing expression");
6400 
6401       // Strip the unbridged-cast placeholder expression off unless it's
6402       // a consumed argument.
6403       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6404           !param->hasAttr<CFConsumedAttr>())
6405         argExpr = stripARCUnbridgedCast(argExpr);
6406 
6407       // If the parameter is __unknown_anytype, move on to the next method.
6408       if (param->getType() == Context.UnknownAnyTy) {
6409         Match = false;
6410         break;
6411       }
6412 
6413       ImplicitConversionSequence ConversionState
6414         = TryCopyInitialization(*this, argExpr, param->getType(),
6415                                 /*SuppressUserConversions*/false,
6416                                 /*InOverloadResolution=*/true,
6417                                 /*AllowObjCWritebackConversion=*/
6418                                 getLangOpts().ObjCAutoRefCount,
6419                                 /*AllowExplicit*/false);
6420       // This function looks for a reasonably-exact match, so we consider
6421       // incompatible pointer conversions to be a failure here.
6422       if (ConversionState.isBad() ||
6423           (ConversionState.isStandard() &&
6424            ConversionState.Standard.Second ==
6425                ICK_Incompatible_Pointer_Conversion)) {
6426         Match = false;
6427         break;
6428       }
6429     }
6430     // Promote additional arguments to variadic methods.
6431     if (Match && Method->isVariadic()) {
6432       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6433         if (Args[i]->isTypeDependent()) {
6434           Match = false;
6435           break;
6436         }
6437         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6438                                                           nullptr);
6439         if (Arg.isInvalid()) {
6440           Match = false;
6441           break;
6442         }
6443       }
6444     } else {
6445       // Check for extra arguments to non-variadic methods.
6446       if (Args.size() != NumNamedArgs)
6447         Match = false;
6448       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6449         // Special case when selectors have no argument. In this case, select
6450         // one with the most general result type of 'id'.
6451         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6452           QualType ReturnT = Methods[b]->getReturnType();
6453           if (ReturnT->isObjCIdType())
6454             return Methods[b];
6455         }
6456       }
6457     }
6458 
6459     if (Match)
6460       return Method;
6461   }
6462   return nullptr;
6463 }
6464 
6465 static bool
6466 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6467                                  ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6468                                  bool MissingImplicitThis, Expr *&ConvertedThis,
6469                                  SmallVectorImpl<Expr *> &ConvertedArgs) {
6470   if (ThisArg) {
6471     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6472     assert(!isa<CXXConstructorDecl>(Method) &&
6473            "Shouldn't have `this` for ctors!");
6474     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6475     ExprResult R = S.PerformObjectArgumentInitialization(
6476         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6477     if (R.isInvalid())
6478       return false;
6479     ConvertedThis = R.get();
6480   } else {
6481     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6482       (void)MD;
6483       assert((MissingImplicitThis || MD->isStatic() ||
6484               isa<CXXConstructorDecl>(MD)) &&
6485              "Expected `this` for non-ctor instance methods");
6486     }
6487     ConvertedThis = nullptr;
6488   }
6489 
6490   // Ignore any variadic arguments. Converting them is pointless, since the
6491   // user can't refer to them in the function condition.
6492   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6493 
6494   // Convert the arguments.
6495   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6496     ExprResult R;
6497     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6498                                         S.Context, Function->getParamDecl(I)),
6499                                     SourceLocation(), Args[I]);
6500 
6501     if (R.isInvalid())
6502       return false;
6503 
6504     ConvertedArgs.push_back(R.get());
6505   }
6506 
6507   if (Trap.hasErrorOccurred())
6508     return false;
6509 
6510   // Push default arguments if needed.
6511   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6512     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6513       ParmVarDecl *P = Function->getParamDecl(i);
6514       Expr *DefArg = P->hasUninstantiatedDefaultArg()
6515                          ? P->getUninstantiatedDefaultArg()
6516                          : P->getDefaultArg();
6517       // This can only happen in code completion, i.e. when PartialOverloading
6518       // is true.
6519       if (!DefArg)
6520         return false;
6521       ExprResult R =
6522           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6523                                           S.Context, Function->getParamDecl(i)),
6524                                       SourceLocation(), DefArg);
6525       if (R.isInvalid())
6526         return false;
6527       ConvertedArgs.push_back(R.get());
6528     }
6529 
6530     if (Trap.hasErrorOccurred())
6531       return false;
6532   }
6533   return true;
6534 }
6535 
6536 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6537                                   bool MissingImplicitThis) {
6538   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6539   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6540     return nullptr;
6541 
6542   SFINAETrap Trap(*this);
6543   SmallVector<Expr *, 16> ConvertedArgs;
6544   // FIXME: We should look into making enable_if late-parsed.
6545   Expr *DiscardedThis;
6546   if (!convertArgsForAvailabilityChecks(
6547           *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6548           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6549     return *EnableIfAttrs.begin();
6550 
6551   for (auto *EIA : EnableIfAttrs) {
6552     APValue Result;
6553     // FIXME: This doesn't consider value-dependent cases, because doing so is
6554     // very difficult. Ideally, we should handle them more gracefully.
6555     if (EIA->getCond()->isValueDependent() ||
6556         !EIA->getCond()->EvaluateWithSubstitution(
6557             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6558       return EIA;
6559 
6560     if (!Result.isInt() || !Result.getInt().getBoolValue())
6561       return EIA;
6562   }
6563   return nullptr;
6564 }
6565 
6566 template <typename CheckFn>
6567 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6568                                         bool ArgDependent, SourceLocation Loc,
6569                                         CheckFn &&IsSuccessful) {
6570   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6571   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6572     if (ArgDependent == DIA->getArgDependent())
6573       Attrs.push_back(DIA);
6574   }
6575 
6576   // Common case: No diagnose_if attributes, so we can quit early.
6577   if (Attrs.empty())
6578     return false;
6579 
6580   auto WarningBegin = std::stable_partition(
6581       Attrs.begin(), Attrs.end(),
6582       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6583 
6584   // Note that diagnose_if attributes are late-parsed, so they appear in the
6585   // correct order (unlike enable_if attributes).
6586   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6587                                IsSuccessful);
6588   if (ErrAttr != WarningBegin) {
6589     const DiagnoseIfAttr *DIA = *ErrAttr;
6590     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6591     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6592         << DIA->getParent() << DIA->getCond()->getSourceRange();
6593     return true;
6594   }
6595 
6596   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6597     if (IsSuccessful(DIA)) {
6598       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6599       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6600           << DIA->getParent() << DIA->getCond()->getSourceRange();
6601     }
6602 
6603   return false;
6604 }
6605 
6606 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6607                                                const Expr *ThisArg,
6608                                                ArrayRef<const Expr *> Args,
6609                                                SourceLocation Loc) {
6610   return diagnoseDiagnoseIfAttrsWith(
6611       *this, Function, /*ArgDependent=*/true, Loc,
6612       [&](const DiagnoseIfAttr *DIA) {
6613         APValue Result;
6614         // It's sane to use the same Args for any redecl of this function, since
6615         // EvaluateWithSubstitution only cares about the position of each
6616         // argument in the arg list, not the ParmVarDecl* it maps to.
6617         if (!DIA->getCond()->EvaluateWithSubstitution(
6618                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6619           return false;
6620         return Result.isInt() && Result.getInt().getBoolValue();
6621       });
6622 }
6623 
6624 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6625                                                  SourceLocation Loc) {
6626   return diagnoseDiagnoseIfAttrsWith(
6627       *this, ND, /*ArgDependent=*/false, Loc,
6628       [&](const DiagnoseIfAttr *DIA) {
6629         bool Result;
6630         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6631                Result;
6632       });
6633 }
6634 
6635 /// Add all of the function declarations in the given function set to
6636 /// the overload candidate set.
6637 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6638                                  ArrayRef<Expr *> Args,
6639                                  OverloadCandidateSet &CandidateSet,
6640                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6641                                  bool SuppressUserConversions,
6642                                  bool PartialOverloading,
6643                                  bool FirstArgumentIsBase) {
6644   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6645     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6646     ArrayRef<Expr *> FunctionArgs = Args;
6647 
6648     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6649     FunctionDecl *FD =
6650         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6651 
6652     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6653       QualType ObjectType;
6654       Expr::Classification ObjectClassification;
6655       if (Args.size() > 0) {
6656         if (Expr *E = Args[0]) {
6657           // Use the explicit base to restrict the lookup:
6658           ObjectType = E->getType();
6659           // Pointers in the object arguments are implicitly dereferenced, so we
6660           // always classify them as l-values.
6661           if (!ObjectType.isNull() && ObjectType->isPointerType())
6662             ObjectClassification = Expr::Classification::makeSimpleLValue();
6663           else
6664             ObjectClassification = E->Classify(Context);
6665         } // .. else there is an implicit base.
6666         FunctionArgs = Args.slice(1);
6667       }
6668       if (FunTmpl) {
6669         AddMethodTemplateCandidate(
6670             FunTmpl, F.getPair(),
6671             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6672             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6673             FunctionArgs, CandidateSet, SuppressUserConversions,
6674             PartialOverloading);
6675       } else {
6676         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6677                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6678                            ObjectClassification, FunctionArgs, CandidateSet,
6679                            SuppressUserConversions, PartialOverloading);
6680       }
6681     } else {
6682       // This branch handles both standalone functions and static methods.
6683 
6684       // Slice the first argument (which is the base) when we access
6685       // static method as non-static.
6686       if (Args.size() > 0 &&
6687           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6688                         !isa<CXXConstructorDecl>(FD)))) {
6689         assert(cast<CXXMethodDecl>(FD)->isStatic());
6690         FunctionArgs = Args.slice(1);
6691       }
6692       if (FunTmpl) {
6693         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6694                                      ExplicitTemplateArgs, FunctionArgs,
6695                                      CandidateSet, SuppressUserConversions,
6696                                      PartialOverloading);
6697       } else {
6698         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6699                              SuppressUserConversions, PartialOverloading);
6700       }
6701     }
6702   }
6703 }
6704 
6705 /// AddMethodCandidate - Adds a named decl (which is some kind of
6706 /// method) as a method candidate to the given overload set.
6707 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
6708                               Expr::Classification ObjectClassification,
6709                               ArrayRef<Expr *> Args,
6710                               OverloadCandidateSet &CandidateSet,
6711                               bool SuppressUserConversions,
6712                               OverloadCandidateParamOrder PO) {
6713   NamedDecl *Decl = FoundDecl.getDecl();
6714   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6715 
6716   if (isa<UsingShadowDecl>(Decl))
6717     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6718 
6719   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6720     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6721            "Expected a member function template");
6722     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6723                                /*ExplicitArgs*/ nullptr, ObjectType,
6724                                ObjectClassification, Args, CandidateSet,
6725                                SuppressUserConversions, false, PO);
6726   } else {
6727     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6728                        ObjectType, ObjectClassification, Args, CandidateSet,
6729                        SuppressUserConversions, false, None, PO);
6730   }
6731 }
6732 
6733 /// AddMethodCandidate - Adds the given C++ member function to the set
6734 /// of candidate functions, using the given function call arguments
6735 /// and the object argument (@c Object). For example, in a call
6736 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6737 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6738 /// allow user-defined conversions via constructors or conversion
6739 /// operators.
6740 void
6741 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6742                          CXXRecordDecl *ActingContext, QualType ObjectType,
6743                          Expr::Classification ObjectClassification,
6744                          ArrayRef<Expr *> Args,
6745                          OverloadCandidateSet &CandidateSet,
6746                          bool SuppressUserConversions,
6747                          bool PartialOverloading,
6748                          ConversionSequenceList EarlyConversions,
6749                          OverloadCandidateParamOrder PO) {
6750   const FunctionProtoType *Proto
6751     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6752   assert(Proto && "Methods without a prototype cannot be overloaded");
6753   assert(!isa<CXXConstructorDecl>(Method) &&
6754          "Use AddOverloadCandidate for constructors");
6755 
6756   if (!CandidateSet.isNewCandidate(Method, PO))
6757     return;
6758 
6759   // C++11 [class.copy]p23: [DR1402]
6760   //   A defaulted move assignment operator that is defined as deleted is
6761   //   ignored by overload resolution.
6762   if (Method->isDefaulted() && Method->isDeleted() &&
6763       Method->isMoveAssignmentOperator())
6764     return;
6765 
6766   // Overload resolution is always an unevaluated context.
6767   EnterExpressionEvaluationContext Unevaluated(
6768       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6769 
6770   // Add this candidate
6771   OverloadCandidate &Candidate =
6772       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6773   Candidate.FoundDecl = FoundDecl;
6774   Candidate.Function = Method;
6775   Candidate.RewriteKind =
6776       CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
6777   Candidate.IsSurrogate = false;
6778   Candidate.IgnoreObjectArgument = false;
6779   Candidate.ExplicitCallArguments = Args.size();
6780 
6781   unsigned NumParams = Proto->getNumParams();
6782 
6783   // (C++ 13.3.2p2): A candidate function having fewer than m
6784   // parameters is viable only if it has an ellipsis in its parameter
6785   // list (8.3.5).
6786   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6787       !Proto->isVariadic()) {
6788     Candidate.Viable = false;
6789     Candidate.FailureKind = ovl_fail_too_many_arguments;
6790     return;
6791   }
6792 
6793   // (C++ 13.3.2p2): A candidate function having more than m parameters
6794   // is viable only if the (m+1)st parameter has a default argument
6795   // (8.3.6). For the purposes of overload resolution, the
6796   // parameter list is truncated on the right, so that there are
6797   // exactly m parameters.
6798   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6799   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6800     // Not enough arguments.
6801     Candidate.Viable = false;
6802     Candidate.FailureKind = ovl_fail_too_few_arguments;
6803     return;
6804   }
6805 
6806   Candidate.Viable = true;
6807 
6808   if (Method->isStatic() || ObjectType.isNull())
6809     // The implicit object argument is ignored.
6810     Candidate.IgnoreObjectArgument = true;
6811   else {
6812     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
6813     // Determine the implicit conversion sequence for the object
6814     // parameter.
6815     Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization(
6816         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6817         Method, ActingContext);
6818     if (Candidate.Conversions[ConvIdx].isBad()) {
6819       Candidate.Viable = false;
6820       Candidate.FailureKind = ovl_fail_bad_conversion;
6821       return;
6822     }
6823   }
6824 
6825   // (CUDA B.1): Check for invalid calls between targets.
6826   if (getLangOpts().CUDA)
6827     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6828       if (!IsAllowedCUDACall(Caller, Method)) {
6829         Candidate.Viable = false;
6830         Candidate.FailureKind = ovl_fail_bad_target;
6831         return;
6832       }
6833 
6834   if (Method->getTrailingRequiresClause()) {
6835     ConstraintSatisfaction Satisfaction;
6836     if (CheckFunctionConstraints(Method, Satisfaction) ||
6837         !Satisfaction.IsSatisfied) {
6838       Candidate.Viable = false;
6839       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6840       return;
6841     }
6842   }
6843 
6844   // Determine the implicit conversion sequences for each of the
6845   // arguments.
6846   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6847     unsigned ConvIdx =
6848         PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
6849     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6850       // We already formed a conversion sequence for this parameter during
6851       // template argument deduction.
6852     } else if (ArgIdx < NumParams) {
6853       // (C++ 13.3.2p3): for F to be a viable function, there shall
6854       // exist for each argument an implicit conversion sequence
6855       // (13.3.3.1) that converts that argument to the corresponding
6856       // parameter of F.
6857       QualType ParamType = Proto->getParamType(ArgIdx);
6858       Candidate.Conversions[ConvIdx]
6859         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6860                                 SuppressUserConversions,
6861                                 /*InOverloadResolution=*/true,
6862                                 /*AllowObjCWritebackConversion=*/
6863                                   getLangOpts().ObjCAutoRefCount);
6864       if (Candidate.Conversions[ConvIdx].isBad()) {
6865         Candidate.Viable = false;
6866         Candidate.FailureKind = ovl_fail_bad_conversion;
6867         return;
6868       }
6869     } else {
6870       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6871       // argument for which there is no corresponding parameter is
6872       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6873       Candidate.Conversions[ConvIdx].setEllipsis();
6874     }
6875   }
6876 
6877   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6878     Candidate.Viable = false;
6879     Candidate.FailureKind = ovl_fail_enable_if;
6880     Candidate.DeductionFailure.Data = FailedAttr;
6881     return;
6882   }
6883 
6884   if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6885       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6886     Candidate.Viable = false;
6887     Candidate.FailureKind = ovl_non_default_multiversion_function;
6888   }
6889 }
6890 
6891 /// Add a C++ member function template as a candidate to the candidate
6892 /// set, using template argument deduction to produce an appropriate member
6893 /// function template specialization.
6894 void Sema::AddMethodTemplateCandidate(
6895     FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
6896     CXXRecordDecl *ActingContext,
6897     TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
6898     Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
6899     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6900     bool PartialOverloading, OverloadCandidateParamOrder PO) {
6901   if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
6902     return;
6903 
6904   // C++ [over.match.funcs]p7:
6905   //   In each case where a candidate is a function template, candidate
6906   //   function template specializations are generated using template argument
6907   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6908   //   candidate functions in the usual way.113) A given name can refer to one
6909   //   or more function templates and also to a set of overloaded non-template
6910   //   functions. In such a case, the candidate functions generated from each
6911   //   function template are combined with the set of non-template candidate
6912   //   functions.
6913   TemplateDeductionInfo Info(CandidateSet.getLocation());
6914   FunctionDecl *Specialization = nullptr;
6915   ConversionSequenceList Conversions;
6916   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6917           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6918           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6919             return CheckNonDependentConversions(
6920                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6921                 SuppressUserConversions, ActingContext, ObjectType,
6922                 ObjectClassification, PO);
6923           })) {
6924     OverloadCandidate &Candidate =
6925         CandidateSet.addCandidate(Conversions.size(), Conversions);
6926     Candidate.FoundDecl = FoundDecl;
6927     Candidate.Function = MethodTmpl->getTemplatedDecl();
6928     Candidate.Viable = false;
6929     Candidate.RewriteKind =
6930       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
6931     Candidate.IsSurrogate = false;
6932     Candidate.IgnoreObjectArgument =
6933         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6934         ObjectType.isNull();
6935     Candidate.ExplicitCallArguments = Args.size();
6936     if (Result == TDK_NonDependentConversionFailure)
6937       Candidate.FailureKind = ovl_fail_bad_conversion;
6938     else {
6939       Candidate.FailureKind = ovl_fail_bad_deduction;
6940       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6941                                                             Info);
6942     }
6943     return;
6944   }
6945 
6946   // Add the function template specialization produced by template argument
6947   // deduction as a candidate.
6948   assert(Specialization && "Missing member function template specialization?");
6949   assert(isa<CXXMethodDecl>(Specialization) &&
6950          "Specialization is not a member function?");
6951   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6952                      ActingContext, ObjectType, ObjectClassification, Args,
6953                      CandidateSet, SuppressUserConversions, PartialOverloading,
6954                      Conversions, PO);
6955 }
6956 
6957 /// Determine whether a given function template has a simple explicit specifier
6958 /// or a non-value-dependent explicit-specification that evaluates to true.
6959 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
6960   return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
6961 }
6962 
6963 /// Add a C++ function template specialization as a candidate
6964 /// in the candidate set, using template argument deduction to produce
6965 /// an appropriate function template specialization.
6966 void Sema::AddTemplateOverloadCandidate(
6967     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
6968     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6969     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6970     bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
6971     OverloadCandidateParamOrder PO) {
6972   if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
6973     return;
6974 
6975   // If the function template has a non-dependent explicit specification,
6976   // exclude it now if appropriate; we are not permitted to perform deduction
6977   // and substitution in this case.
6978   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
6979     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6980     Candidate.FoundDecl = FoundDecl;
6981     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6982     Candidate.Viable = false;
6983     Candidate.FailureKind = ovl_fail_explicit;
6984     return;
6985   }
6986 
6987   // C++ [over.match.funcs]p7:
6988   //   In each case where a candidate is a function template, candidate
6989   //   function template specializations are generated using template argument
6990   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6991   //   candidate functions in the usual way.113) A given name can refer to one
6992   //   or more function templates and also to a set of overloaded non-template
6993   //   functions. In such a case, the candidate functions generated from each
6994   //   function template are combined with the set of non-template candidate
6995   //   functions.
6996   TemplateDeductionInfo Info(CandidateSet.getLocation());
6997   FunctionDecl *Specialization = nullptr;
6998   ConversionSequenceList Conversions;
6999   if (TemplateDeductionResult Result = DeduceTemplateArguments(
7000           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7001           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7002             return CheckNonDependentConversions(
7003                 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7004                 SuppressUserConversions, nullptr, QualType(), {}, PO);
7005           })) {
7006     OverloadCandidate &Candidate =
7007         CandidateSet.addCandidate(Conversions.size(), Conversions);
7008     Candidate.FoundDecl = FoundDecl;
7009     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7010     Candidate.Viable = false;
7011     Candidate.RewriteKind =
7012       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7013     Candidate.IsSurrogate = false;
7014     Candidate.IsADLCandidate = IsADLCandidate;
7015     // Ignore the object argument if there is one, since we don't have an object
7016     // type.
7017     Candidate.IgnoreObjectArgument =
7018         isa<CXXMethodDecl>(Candidate.Function) &&
7019         !isa<CXXConstructorDecl>(Candidate.Function);
7020     Candidate.ExplicitCallArguments = Args.size();
7021     if (Result == TDK_NonDependentConversionFailure)
7022       Candidate.FailureKind = ovl_fail_bad_conversion;
7023     else {
7024       Candidate.FailureKind = ovl_fail_bad_deduction;
7025       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7026                                                             Info);
7027     }
7028     return;
7029   }
7030 
7031   // Add the function template specialization produced by template argument
7032   // deduction as a candidate.
7033   assert(Specialization && "Missing function template specialization?");
7034   AddOverloadCandidate(
7035       Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7036       PartialOverloading, AllowExplicit,
7037       /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO);
7038 }
7039 
7040 /// Check that implicit conversion sequences can be formed for each argument
7041 /// whose corresponding parameter has a non-dependent type, per DR1391's
7042 /// [temp.deduct.call]p10.
7043 bool Sema::CheckNonDependentConversions(
7044     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7045     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7046     ConversionSequenceList &Conversions, bool SuppressUserConversions,
7047     CXXRecordDecl *ActingContext, QualType ObjectType,
7048     Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7049   // FIXME: The cases in which we allow explicit conversions for constructor
7050   // arguments never consider calling a constructor template. It's not clear
7051   // that is correct.
7052   const bool AllowExplicit = false;
7053 
7054   auto *FD = FunctionTemplate->getTemplatedDecl();
7055   auto *Method = dyn_cast<CXXMethodDecl>(FD);
7056   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7057   unsigned ThisConversions = HasThisConversion ? 1 : 0;
7058 
7059   Conversions =
7060       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7061 
7062   // Overload resolution is always an unevaluated context.
7063   EnterExpressionEvaluationContext Unevaluated(
7064       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7065 
7066   // For a method call, check the 'this' conversion here too. DR1391 doesn't
7067   // require that, but this check should never result in a hard error, and
7068   // overload resolution is permitted to sidestep instantiations.
7069   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7070       !ObjectType.isNull()) {
7071     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7072     Conversions[ConvIdx] = TryObjectArgumentInitialization(
7073         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7074         Method, ActingContext);
7075     if (Conversions[ConvIdx].isBad())
7076       return true;
7077   }
7078 
7079   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
7080        ++I) {
7081     QualType ParamType = ParamTypes[I];
7082     if (!ParamType->isDependentType()) {
7083       unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
7084                              ? 0
7085                              : (ThisConversions + I);
7086       Conversions[ConvIdx]
7087         = TryCopyInitialization(*this, Args[I], ParamType,
7088                                 SuppressUserConversions,
7089                                 /*InOverloadResolution=*/true,
7090                                 /*AllowObjCWritebackConversion=*/
7091                                   getLangOpts().ObjCAutoRefCount,
7092                                 AllowExplicit);
7093       if (Conversions[ConvIdx].isBad())
7094         return true;
7095     }
7096   }
7097 
7098   return false;
7099 }
7100 
7101 /// Determine whether this is an allowable conversion from the result
7102 /// of an explicit conversion operator to the expected type, per C++
7103 /// [over.match.conv]p1 and [over.match.ref]p1.
7104 ///
7105 /// \param ConvType The return type of the conversion function.
7106 ///
7107 /// \param ToType The type we are converting to.
7108 ///
7109 /// \param AllowObjCPointerConversion Allow a conversion from one
7110 /// Objective-C pointer to another.
7111 ///
7112 /// \returns true if the conversion is allowable, false otherwise.
7113 static bool isAllowableExplicitConversion(Sema &S,
7114                                           QualType ConvType, QualType ToType,
7115                                           bool AllowObjCPointerConversion) {
7116   QualType ToNonRefType = ToType.getNonReferenceType();
7117 
7118   // Easy case: the types are the same.
7119   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7120     return true;
7121 
7122   // Allow qualification conversions.
7123   bool ObjCLifetimeConversion;
7124   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7125                                   ObjCLifetimeConversion))
7126     return true;
7127 
7128   // If we're not allowed to consider Objective-C pointer conversions,
7129   // we're done.
7130   if (!AllowObjCPointerConversion)
7131     return false;
7132 
7133   // Is this an Objective-C pointer conversion?
7134   bool IncompatibleObjC = false;
7135   QualType ConvertedType;
7136   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7137                                    IncompatibleObjC);
7138 }
7139 
7140 /// AddConversionCandidate - Add a C++ conversion function as a
7141 /// candidate in the candidate set (C++ [over.match.conv],
7142 /// C++ [over.match.copy]). From is the expression we're converting from,
7143 /// and ToType is the type that we're eventually trying to convert to
7144 /// (which may or may not be the same type as the type that the
7145 /// conversion function produces).
7146 void Sema::AddConversionCandidate(
7147     CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7148     CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7149     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7150     bool AllowExplicit, bool AllowResultConversion) {
7151   assert(!Conversion->getDescribedFunctionTemplate() &&
7152          "Conversion function templates use AddTemplateConversionCandidate");
7153   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7154   if (!CandidateSet.isNewCandidate(Conversion))
7155     return;
7156 
7157   // If the conversion function has an undeduced return type, trigger its
7158   // deduction now.
7159   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7160     if (DeduceReturnType(Conversion, From->getExprLoc()))
7161       return;
7162     ConvType = Conversion->getConversionType().getNonReferenceType();
7163   }
7164 
7165   // If we don't allow any conversion of the result type, ignore conversion
7166   // functions that don't convert to exactly (possibly cv-qualified) T.
7167   if (!AllowResultConversion &&
7168       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7169     return;
7170 
7171   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7172   // operator is only a candidate if its return type is the target type or
7173   // can be converted to the target type with a qualification conversion.
7174   //
7175   // FIXME: Include such functions in the candidate list and explain why we
7176   // can't select them.
7177   if (Conversion->isExplicit() &&
7178       !isAllowableExplicitConversion(*this, ConvType, ToType,
7179                                      AllowObjCConversionOnExplicit))
7180     return;
7181 
7182   // Overload resolution is always an unevaluated context.
7183   EnterExpressionEvaluationContext Unevaluated(
7184       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7185 
7186   // Add this candidate
7187   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7188   Candidate.FoundDecl = FoundDecl;
7189   Candidate.Function = Conversion;
7190   Candidate.IsSurrogate = false;
7191   Candidate.IgnoreObjectArgument = false;
7192   Candidate.FinalConversion.setAsIdentityConversion();
7193   Candidate.FinalConversion.setFromType(ConvType);
7194   Candidate.FinalConversion.setAllToTypes(ToType);
7195   Candidate.Viable = true;
7196   Candidate.ExplicitCallArguments = 1;
7197 
7198   // Explicit functions are not actually candidates at all if we're not
7199   // allowing them in this context, but keep them around so we can point
7200   // to them in diagnostics.
7201   if (!AllowExplicit && Conversion->isExplicit()) {
7202     Candidate.Viable = false;
7203     Candidate.FailureKind = ovl_fail_explicit;
7204     return;
7205   }
7206 
7207   // C++ [over.match.funcs]p4:
7208   //   For conversion functions, the function is considered to be a member of
7209   //   the class of the implicit implied object argument for the purpose of
7210   //   defining the type of the implicit object parameter.
7211   //
7212   // Determine the implicit conversion sequence for the implicit
7213   // object parameter.
7214   QualType ImplicitParamType = From->getType();
7215   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7216     ImplicitParamType = FromPtrType->getPointeeType();
7217   CXXRecordDecl *ConversionContext
7218     = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
7219 
7220   Candidate.Conversions[0] = TryObjectArgumentInitialization(
7221       *this, CandidateSet.getLocation(), From->getType(),
7222       From->Classify(Context), Conversion, ConversionContext);
7223 
7224   if (Candidate.Conversions[0].isBad()) {
7225     Candidate.Viable = false;
7226     Candidate.FailureKind = ovl_fail_bad_conversion;
7227     return;
7228   }
7229 
7230   if (Conversion->getTrailingRequiresClause()) {
7231     ConstraintSatisfaction Satisfaction;
7232     if (CheckFunctionConstraints(Conversion, Satisfaction) ||
7233         !Satisfaction.IsSatisfied) {
7234       Candidate.Viable = false;
7235       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7236       return;
7237     }
7238   }
7239 
7240   // We won't go through a user-defined type conversion function to convert a
7241   // derived to base as such conversions are given Conversion Rank. They only
7242   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7243   QualType FromCanon
7244     = Context.getCanonicalType(From->getType().getUnqualifiedType());
7245   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7246   if (FromCanon == ToCanon ||
7247       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7248     Candidate.Viable = false;
7249     Candidate.FailureKind = ovl_fail_trivial_conversion;
7250     return;
7251   }
7252 
7253   // To determine what the conversion from the result of calling the
7254   // conversion function to the type we're eventually trying to
7255   // convert to (ToType), we need to synthesize a call to the
7256   // conversion function and attempt copy initialization from it. This
7257   // makes sure that we get the right semantics with respect to
7258   // lvalues/rvalues and the type. Fortunately, we can allocate this
7259   // call on the stack and we don't need its arguments to be
7260   // well-formed.
7261   DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7262                             VK_LValue, From->getBeginLoc());
7263   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7264                                 Context.getPointerType(Conversion->getType()),
7265                                 CK_FunctionToPointerDecay,
7266                                 &ConversionRef, VK_RValue);
7267 
7268   QualType ConversionType = Conversion->getConversionType();
7269   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7270     Candidate.Viable = false;
7271     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7272     return;
7273   }
7274 
7275   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7276 
7277   // Note that it is safe to allocate CallExpr on the stack here because
7278   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7279   // allocator).
7280   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7281 
7282   alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7283   CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7284       Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7285 
7286   ImplicitConversionSequence ICS =
7287       TryCopyInitialization(*this, TheTemporaryCall, ToType,
7288                             /*SuppressUserConversions=*/true,
7289                             /*InOverloadResolution=*/false,
7290                             /*AllowObjCWritebackConversion=*/false);
7291 
7292   switch (ICS.getKind()) {
7293   case ImplicitConversionSequence::StandardConversion:
7294     Candidate.FinalConversion = ICS.Standard;
7295 
7296     // C++ [over.ics.user]p3:
7297     //   If the user-defined conversion is specified by a specialization of a
7298     //   conversion function template, the second standard conversion sequence
7299     //   shall have exact match rank.
7300     if (Conversion->getPrimaryTemplate() &&
7301         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7302       Candidate.Viable = false;
7303       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7304       return;
7305     }
7306 
7307     // C++0x [dcl.init.ref]p5:
7308     //    In the second case, if the reference is an rvalue reference and
7309     //    the second standard conversion sequence of the user-defined
7310     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7311     //    program is ill-formed.
7312     if (ToType->isRValueReferenceType() &&
7313         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7314       Candidate.Viable = false;
7315       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7316       return;
7317     }
7318     break;
7319 
7320   case ImplicitConversionSequence::BadConversion:
7321     Candidate.Viable = false;
7322     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7323     return;
7324 
7325   default:
7326     llvm_unreachable(
7327            "Can only end up with a standard conversion sequence or failure");
7328   }
7329 
7330   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7331     Candidate.Viable = false;
7332     Candidate.FailureKind = ovl_fail_enable_if;
7333     Candidate.DeductionFailure.Data = FailedAttr;
7334     return;
7335   }
7336 
7337   if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7338       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7339     Candidate.Viable = false;
7340     Candidate.FailureKind = ovl_non_default_multiversion_function;
7341   }
7342 }
7343 
7344 /// Adds a conversion function template specialization
7345 /// candidate to the overload set, using template argument deduction
7346 /// to deduce the template arguments of the conversion function
7347 /// template from the type that we are converting to (C++
7348 /// [temp.deduct.conv]).
7349 void Sema::AddTemplateConversionCandidate(
7350     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7351     CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7352     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7353     bool AllowExplicit, bool AllowResultConversion) {
7354   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7355          "Only conversion function templates permitted here");
7356 
7357   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7358     return;
7359 
7360   // If the function template has a non-dependent explicit specification,
7361   // exclude it now if appropriate; we are not permitted to perform deduction
7362   // and substitution in this case.
7363   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7364     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7365     Candidate.FoundDecl = FoundDecl;
7366     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7367     Candidate.Viable = false;
7368     Candidate.FailureKind = ovl_fail_explicit;
7369     return;
7370   }
7371 
7372   TemplateDeductionInfo Info(CandidateSet.getLocation());
7373   CXXConversionDecl *Specialization = nullptr;
7374   if (TemplateDeductionResult Result
7375         = DeduceTemplateArguments(FunctionTemplate, ToType,
7376                                   Specialization, Info)) {
7377     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7378     Candidate.FoundDecl = FoundDecl;
7379     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7380     Candidate.Viable = false;
7381     Candidate.FailureKind = ovl_fail_bad_deduction;
7382     Candidate.IsSurrogate = false;
7383     Candidate.IgnoreObjectArgument = false;
7384     Candidate.ExplicitCallArguments = 1;
7385     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7386                                                           Info);
7387     return;
7388   }
7389 
7390   // Add the conversion function template specialization produced by
7391   // template argument deduction as a candidate.
7392   assert(Specialization && "Missing function template specialization?");
7393   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7394                          CandidateSet, AllowObjCConversionOnExplicit,
7395                          AllowExplicit, AllowResultConversion);
7396 }
7397 
7398 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7399 /// converts the given @c Object to a function pointer via the
7400 /// conversion function @c Conversion, and then attempts to call it
7401 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7402 /// the type of function that we'll eventually be calling.
7403 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7404                                  DeclAccessPair FoundDecl,
7405                                  CXXRecordDecl *ActingContext,
7406                                  const FunctionProtoType *Proto,
7407                                  Expr *Object,
7408                                  ArrayRef<Expr *> Args,
7409                                  OverloadCandidateSet& CandidateSet) {
7410   if (!CandidateSet.isNewCandidate(Conversion))
7411     return;
7412 
7413   // Overload resolution is always an unevaluated context.
7414   EnterExpressionEvaluationContext Unevaluated(
7415       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7416 
7417   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7418   Candidate.FoundDecl = FoundDecl;
7419   Candidate.Function = nullptr;
7420   Candidate.Surrogate = Conversion;
7421   Candidate.Viable = true;
7422   Candidate.IsSurrogate = true;
7423   Candidate.IgnoreObjectArgument = false;
7424   Candidate.ExplicitCallArguments = Args.size();
7425 
7426   // Determine the implicit conversion sequence for the implicit
7427   // object parameter.
7428   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7429       *this, CandidateSet.getLocation(), Object->getType(),
7430       Object->Classify(Context), Conversion, ActingContext);
7431   if (ObjectInit.isBad()) {
7432     Candidate.Viable = false;
7433     Candidate.FailureKind = ovl_fail_bad_conversion;
7434     Candidate.Conversions[0] = ObjectInit;
7435     return;
7436   }
7437 
7438   // The first conversion is actually a user-defined conversion whose
7439   // first conversion is ObjectInit's standard conversion (which is
7440   // effectively a reference binding). Record it as such.
7441   Candidate.Conversions[0].setUserDefined();
7442   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7443   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7444   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7445   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7446   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7447   Candidate.Conversions[0].UserDefined.After
7448     = Candidate.Conversions[0].UserDefined.Before;
7449   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7450 
7451   // Find the
7452   unsigned NumParams = Proto->getNumParams();
7453 
7454   // (C++ 13.3.2p2): A candidate function having fewer than m
7455   // parameters is viable only if it has an ellipsis in its parameter
7456   // list (8.3.5).
7457   if (Args.size() > NumParams && !Proto->isVariadic()) {
7458     Candidate.Viable = false;
7459     Candidate.FailureKind = ovl_fail_too_many_arguments;
7460     return;
7461   }
7462 
7463   // Function types don't have any default arguments, so just check if
7464   // we have enough arguments.
7465   if (Args.size() < NumParams) {
7466     // Not enough arguments.
7467     Candidate.Viable = false;
7468     Candidate.FailureKind = ovl_fail_too_few_arguments;
7469     return;
7470   }
7471 
7472   // Determine the implicit conversion sequences for each of the
7473   // arguments.
7474   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7475     if (ArgIdx < NumParams) {
7476       // (C++ 13.3.2p3): for F to be a viable function, there shall
7477       // exist for each argument an implicit conversion sequence
7478       // (13.3.3.1) that converts that argument to the corresponding
7479       // parameter of F.
7480       QualType ParamType = Proto->getParamType(ArgIdx);
7481       Candidate.Conversions[ArgIdx + 1]
7482         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7483                                 /*SuppressUserConversions=*/false,
7484                                 /*InOverloadResolution=*/false,
7485                                 /*AllowObjCWritebackConversion=*/
7486                                   getLangOpts().ObjCAutoRefCount);
7487       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7488         Candidate.Viable = false;
7489         Candidate.FailureKind = ovl_fail_bad_conversion;
7490         return;
7491       }
7492     } else {
7493       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7494       // argument for which there is no corresponding parameter is
7495       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7496       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7497     }
7498   }
7499 
7500   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7501     Candidate.Viable = false;
7502     Candidate.FailureKind = ovl_fail_enable_if;
7503     Candidate.DeductionFailure.Data = FailedAttr;
7504     return;
7505   }
7506 }
7507 
7508 /// Add all of the non-member operator function declarations in the given
7509 /// function set to the overload candidate set.
7510 void Sema::AddNonMemberOperatorCandidates(
7511     const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
7512     OverloadCandidateSet &CandidateSet,
7513     TemplateArgumentListInfo *ExplicitTemplateArgs) {
7514   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7515     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7516     ArrayRef<Expr *> FunctionArgs = Args;
7517 
7518     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7519     FunctionDecl *FD =
7520         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7521 
7522     // Don't consider rewritten functions if we're not rewriting.
7523     if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
7524       continue;
7525 
7526     assert(!isa<CXXMethodDecl>(FD) &&
7527            "unqualified operator lookup found a member function");
7528 
7529     if (FunTmpl) {
7530       AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
7531                                    FunctionArgs, CandidateSet);
7532       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7533         AddTemplateOverloadCandidate(
7534             FunTmpl, F.getPair(), ExplicitTemplateArgs,
7535             {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
7536             true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
7537     } else {
7538       if (ExplicitTemplateArgs)
7539         continue;
7540       AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
7541       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7542         AddOverloadCandidate(FD, F.getPair(),
7543                              {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
7544                              false, false, true, false, ADLCallKind::NotADL,
7545                              None, OverloadCandidateParamOrder::Reversed);
7546     }
7547   }
7548 }
7549 
7550 /// Add overload candidates for overloaded operators that are
7551 /// member functions.
7552 ///
7553 /// Add the overloaded operator candidates that are member functions
7554 /// for the operator Op that was used in an operator expression such
7555 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7556 /// CandidateSet will store the added overload candidates. (C++
7557 /// [over.match.oper]).
7558 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7559                                        SourceLocation OpLoc,
7560                                        ArrayRef<Expr *> Args,
7561                                        OverloadCandidateSet &CandidateSet,
7562                                        OverloadCandidateParamOrder PO) {
7563   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7564 
7565   // C++ [over.match.oper]p3:
7566   //   For a unary operator @ with an operand of a type whose
7567   //   cv-unqualified version is T1, and for a binary operator @ with
7568   //   a left operand of a type whose cv-unqualified version is T1 and
7569   //   a right operand of a type whose cv-unqualified version is T2,
7570   //   three sets of candidate functions, designated member
7571   //   candidates, non-member candidates and built-in candidates, are
7572   //   constructed as follows:
7573   QualType T1 = Args[0]->getType();
7574 
7575   //     -- If T1 is a complete class type or a class currently being
7576   //        defined, the set of member candidates is the result of the
7577   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7578   //        the set of member candidates is empty.
7579   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7580     // Complete the type if it can be completed.
7581     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7582       return;
7583     // If the type is neither complete nor being defined, bail out now.
7584     if (!T1Rec->getDecl()->getDefinition())
7585       return;
7586 
7587     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7588     LookupQualifiedName(Operators, T1Rec->getDecl());
7589     Operators.suppressDiagnostics();
7590 
7591     for (LookupResult::iterator Oper = Operators.begin(),
7592                              OperEnd = Operators.end();
7593          Oper != OperEnd;
7594          ++Oper)
7595       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7596                          Args[0]->Classify(Context), Args.slice(1),
7597                          CandidateSet, /*SuppressUserConversion=*/false, PO);
7598   }
7599 }
7600 
7601 /// AddBuiltinCandidate - Add a candidate for a built-in
7602 /// operator. ResultTy and ParamTys are the result and parameter types
7603 /// of the built-in candidate, respectively. Args and NumArgs are the
7604 /// arguments being passed to the candidate. IsAssignmentOperator
7605 /// should be true when this built-in candidate is an assignment
7606 /// operator. NumContextualBoolArguments is the number of arguments
7607 /// (at the beginning of the argument list) that will be contextually
7608 /// converted to bool.
7609 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7610                                OverloadCandidateSet& CandidateSet,
7611                                bool IsAssignmentOperator,
7612                                unsigned NumContextualBoolArguments) {
7613   // Overload resolution is always an unevaluated context.
7614   EnterExpressionEvaluationContext Unevaluated(
7615       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7616 
7617   // Add this candidate
7618   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7619   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7620   Candidate.Function = nullptr;
7621   Candidate.IsSurrogate = false;
7622   Candidate.IgnoreObjectArgument = false;
7623   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7624 
7625   // Determine the implicit conversion sequences for each of the
7626   // arguments.
7627   Candidate.Viable = true;
7628   Candidate.ExplicitCallArguments = Args.size();
7629   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7630     // C++ [over.match.oper]p4:
7631     //   For the built-in assignment operators, conversions of the
7632     //   left operand are restricted as follows:
7633     //     -- no temporaries are introduced to hold the left operand, and
7634     //     -- no user-defined conversions are applied to the left
7635     //        operand to achieve a type match with the left-most
7636     //        parameter of a built-in candidate.
7637     //
7638     // We block these conversions by turning off user-defined
7639     // conversions, since that is the only way that initialization of
7640     // a reference to a non-class type can occur from something that
7641     // is not of the same type.
7642     if (ArgIdx < NumContextualBoolArguments) {
7643       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7644              "Contextual conversion to bool requires bool type");
7645       Candidate.Conversions[ArgIdx]
7646         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7647     } else {
7648       Candidate.Conversions[ArgIdx]
7649         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7650                                 ArgIdx == 0 && IsAssignmentOperator,
7651                                 /*InOverloadResolution=*/false,
7652                                 /*AllowObjCWritebackConversion=*/
7653                                   getLangOpts().ObjCAutoRefCount);
7654     }
7655     if (Candidate.Conversions[ArgIdx].isBad()) {
7656       Candidate.Viable = false;
7657       Candidate.FailureKind = ovl_fail_bad_conversion;
7658       break;
7659     }
7660   }
7661 }
7662 
7663 namespace {
7664 
7665 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7666 /// candidate operator functions for built-in operators (C++
7667 /// [over.built]). The types are separated into pointer types and
7668 /// enumeration types.
7669 class BuiltinCandidateTypeSet  {
7670   /// TypeSet - A set of types.
7671   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7672                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7673 
7674   /// PointerTypes - The set of pointer types that will be used in the
7675   /// built-in candidates.
7676   TypeSet PointerTypes;
7677 
7678   /// MemberPointerTypes - The set of member pointer types that will be
7679   /// used in the built-in candidates.
7680   TypeSet MemberPointerTypes;
7681 
7682   /// EnumerationTypes - The set of enumeration types that will be
7683   /// used in the built-in candidates.
7684   TypeSet EnumerationTypes;
7685 
7686   /// The set of vector types that will be used in the built-in
7687   /// candidates.
7688   TypeSet VectorTypes;
7689 
7690   /// A flag indicating non-record types are viable candidates
7691   bool HasNonRecordTypes;
7692 
7693   /// A flag indicating whether either arithmetic or enumeration types
7694   /// were present in the candidate set.
7695   bool HasArithmeticOrEnumeralTypes;
7696 
7697   /// A flag indicating whether the nullptr type was present in the
7698   /// candidate set.
7699   bool HasNullPtrType;
7700 
7701   /// Sema - The semantic analysis instance where we are building the
7702   /// candidate type set.
7703   Sema &SemaRef;
7704 
7705   /// Context - The AST context in which we will build the type sets.
7706   ASTContext &Context;
7707 
7708   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7709                                                const Qualifiers &VisibleQuals);
7710   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7711 
7712 public:
7713   /// iterator - Iterates through the types that are part of the set.
7714   typedef TypeSet::iterator iterator;
7715 
7716   BuiltinCandidateTypeSet(Sema &SemaRef)
7717     : HasNonRecordTypes(false),
7718       HasArithmeticOrEnumeralTypes(false),
7719       HasNullPtrType(false),
7720       SemaRef(SemaRef),
7721       Context(SemaRef.Context) { }
7722 
7723   void AddTypesConvertedFrom(QualType Ty,
7724                              SourceLocation Loc,
7725                              bool AllowUserConversions,
7726                              bool AllowExplicitConversions,
7727                              const Qualifiers &VisibleTypeConversionsQuals);
7728 
7729   /// pointer_begin - First pointer type found;
7730   iterator pointer_begin() { return PointerTypes.begin(); }
7731 
7732   /// pointer_end - Past the last pointer type found;
7733   iterator pointer_end() { return PointerTypes.end(); }
7734 
7735   /// member_pointer_begin - First member pointer type found;
7736   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7737 
7738   /// member_pointer_end - Past the last member pointer type found;
7739   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7740 
7741   /// enumeration_begin - First enumeration type found;
7742   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7743 
7744   /// enumeration_end - Past the last enumeration type found;
7745   iterator enumeration_end() { return EnumerationTypes.end(); }
7746 
7747   iterator vector_begin() { return VectorTypes.begin(); }
7748   iterator vector_end() { return VectorTypes.end(); }
7749 
7750   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7751   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7752   bool hasNullPtrType() const { return HasNullPtrType; }
7753 };
7754 
7755 } // end anonymous namespace
7756 
7757 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7758 /// the set of pointer types along with any more-qualified variants of
7759 /// that type. For example, if @p Ty is "int const *", this routine
7760 /// will add "int const *", "int const volatile *", "int const
7761 /// restrict *", and "int const volatile restrict *" to the set of
7762 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7763 /// false otherwise.
7764 ///
7765 /// FIXME: what to do about extended qualifiers?
7766 bool
7767 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7768                                              const Qualifiers &VisibleQuals) {
7769 
7770   // Insert this type.
7771   if (!PointerTypes.insert(Ty))
7772     return false;
7773 
7774   QualType PointeeTy;
7775   const PointerType *PointerTy = Ty->getAs<PointerType>();
7776   bool buildObjCPtr = false;
7777   if (!PointerTy) {
7778     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7779     PointeeTy = PTy->getPointeeType();
7780     buildObjCPtr = true;
7781   } else {
7782     PointeeTy = PointerTy->getPointeeType();
7783   }
7784 
7785   // Don't add qualified variants of arrays. For one, they're not allowed
7786   // (the qualifier would sink to the element type), and for another, the
7787   // only overload situation where it matters is subscript or pointer +- int,
7788   // and those shouldn't have qualifier variants anyway.
7789   if (PointeeTy->isArrayType())
7790     return true;
7791 
7792   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7793   bool hasVolatile = VisibleQuals.hasVolatile();
7794   bool hasRestrict = VisibleQuals.hasRestrict();
7795 
7796   // Iterate through all strict supersets of BaseCVR.
7797   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7798     if ((CVR | BaseCVR) != CVR) continue;
7799     // Skip over volatile if no volatile found anywhere in the types.
7800     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7801 
7802     // Skip over restrict if no restrict found anywhere in the types, or if
7803     // the type cannot be restrict-qualified.
7804     if ((CVR & Qualifiers::Restrict) &&
7805         (!hasRestrict ||
7806          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7807       continue;
7808 
7809     // Build qualified pointee type.
7810     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7811 
7812     // Build qualified pointer type.
7813     QualType QPointerTy;
7814     if (!buildObjCPtr)
7815       QPointerTy = Context.getPointerType(QPointeeTy);
7816     else
7817       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7818 
7819     // Insert qualified pointer type.
7820     PointerTypes.insert(QPointerTy);
7821   }
7822 
7823   return true;
7824 }
7825 
7826 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7827 /// to the set of pointer types along with any more-qualified variants of
7828 /// that type. For example, if @p Ty is "int const *", this routine
7829 /// will add "int const *", "int const volatile *", "int const
7830 /// restrict *", and "int const volatile restrict *" to the set of
7831 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7832 /// false otherwise.
7833 ///
7834 /// FIXME: what to do about extended qualifiers?
7835 bool
7836 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7837     QualType Ty) {
7838   // Insert this type.
7839   if (!MemberPointerTypes.insert(Ty))
7840     return false;
7841 
7842   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7843   assert(PointerTy && "type was not a member pointer type!");
7844 
7845   QualType PointeeTy = PointerTy->getPointeeType();
7846   // Don't add qualified variants of arrays. For one, they're not allowed
7847   // (the qualifier would sink to the element type), and for another, the
7848   // only overload situation where it matters is subscript or pointer +- int,
7849   // and those shouldn't have qualifier variants anyway.
7850   if (PointeeTy->isArrayType())
7851     return true;
7852   const Type *ClassTy = PointerTy->getClass();
7853 
7854   // Iterate through all strict supersets of the pointee type's CVR
7855   // qualifiers.
7856   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7857   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7858     if ((CVR | BaseCVR) != CVR) continue;
7859 
7860     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7861     MemberPointerTypes.insert(
7862       Context.getMemberPointerType(QPointeeTy, ClassTy));
7863   }
7864 
7865   return true;
7866 }
7867 
7868 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7869 /// Ty can be implicit converted to the given set of @p Types. We're
7870 /// primarily interested in pointer types and enumeration types. We also
7871 /// take member pointer types, for the conditional operator.
7872 /// AllowUserConversions is true if we should look at the conversion
7873 /// functions of a class type, and AllowExplicitConversions if we
7874 /// should also include the explicit conversion functions of a class
7875 /// type.
7876 void
7877 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7878                                                SourceLocation Loc,
7879                                                bool AllowUserConversions,
7880                                                bool AllowExplicitConversions,
7881                                                const Qualifiers &VisibleQuals) {
7882   // Only deal with canonical types.
7883   Ty = Context.getCanonicalType(Ty);
7884 
7885   // Look through reference types; they aren't part of the type of an
7886   // expression for the purposes of conversions.
7887   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7888     Ty = RefTy->getPointeeType();
7889 
7890   // If we're dealing with an array type, decay to the pointer.
7891   if (Ty->isArrayType())
7892     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7893 
7894   // Otherwise, we don't care about qualifiers on the type.
7895   Ty = Ty.getLocalUnqualifiedType();
7896 
7897   // Flag if we ever add a non-record type.
7898   const RecordType *TyRec = Ty->getAs<RecordType>();
7899   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7900 
7901   // Flag if we encounter an arithmetic type.
7902   HasArithmeticOrEnumeralTypes =
7903     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7904 
7905   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7906     PointerTypes.insert(Ty);
7907   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7908     // Insert our type, and its more-qualified variants, into the set
7909     // of types.
7910     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7911       return;
7912   } else if (Ty->isMemberPointerType()) {
7913     // Member pointers are far easier, since the pointee can't be converted.
7914     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7915       return;
7916   } else if (Ty->isEnumeralType()) {
7917     HasArithmeticOrEnumeralTypes = true;
7918     EnumerationTypes.insert(Ty);
7919   } else if (Ty->isVectorType()) {
7920     // We treat vector types as arithmetic types in many contexts as an
7921     // extension.
7922     HasArithmeticOrEnumeralTypes = true;
7923     VectorTypes.insert(Ty);
7924   } else if (Ty->isNullPtrType()) {
7925     HasNullPtrType = true;
7926   } else if (AllowUserConversions && TyRec) {
7927     // No conversion functions in incomplete types.
7928     if (!SemaRef.isCompleteType(Loc, Ty))
7929       return;
7930 
7931     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7932     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7933       if (isa<UsingShadowDecl>(D))
7934         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7935 
7936       // Skip conversion function templates; they don't tell us anything
7937       // about which builtin types we can convert to.
7938       if (isa<FunctionTemplateDecl>(D))
7939         continue;
7940 
7941       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7942       if (AllowExplicitConversions || !Conv->isExplicit()) {
7943         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7944                               VisibleQuals);
7945       }
7946     }
7947   }
7948 }
7949 /// Helper function for adjusting address spaces for the pointer or reference
7950 /// operands of builtin operators depending on the argument.
7951 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
7952                                                         Expr *Arg) {
7953   return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
7954 }
7955 
7956 /// Helper function for AddBuiltinOperatorCandidates() that adds
7957 /// the volatile- and non-volatile-qualified assignment operators for the
7958 /// given type to the candidate set.
7959 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7960                                                    QualType T,
7961                                                    ArrayRef<Expr *> Args,
7962                                     OverloadCandidateSet &CandidateSet) {
7963   QualType ParamTypes[2];
7964 
7965   // T& operator=(T&, T)
7966   ParamTypes[0] = S.Context.getLValueReferenceType(
7967       AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
7968   ParamTypes[1] = T;
7969   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7970                         /*IsAssignmentOperator=*/true);
7971 
7972   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7973     // volatile T& operator=(volatile T&, T)
7974     ParamTypes[0] = S.Context.getLValueReferenceType(
7975         AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
7976                                                 Args[0]));
7977     ParamTypes[1] = T;
7978     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7979                           /*IsAssignmentOperator=*/true);
7980   }
7981 }
7982 
7983 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7984 /// if any, found in visible type conversion functions found in ArgExpr's type.
7985 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7986     Qualifiers VRQuals;
7987     const RecordType *TyRec;
7988     if (const MemberPointerType *RHSMPType =
7989         ArgExpr->getType()->getAs<MemberPointerType>())
7990       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7991     else
7992       TyRec = ArgExpr->getType()->getAs<RecordType>();
7993     if (!TyRec) {
7994       // Just to be safe, assume the worst case.
7995       VRQuals.addVolatile();
7996       VRQuals.addRestrict();
7997       return VRQuals;
7998     }
7999 
8000     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8001     if (!ClassDecl->hasDefinition())
8002       return VRQuals;
8003 
8004     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8005       if (isa<UsingShadowDecl>(D))
8006         D = cast<UsingShadowDecl>(D)->getTargetDecl();
8007       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8008         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8009         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8010           CanTy = ResTypeRef->getPointeeType();
8011         // Need to go down the pointer/mempointer chain and add qualifiers
8012         // as see them.
8013         bool done = false;
8014         while (!done) {
8015           if (CanTy.isRestrictQualified())
8016             VRQuals.addRestrict();
8017           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8018             CanTy = ResTypePtr->getPointeeType();
8019           else if (const MemberPointerType *ResTypeMPtr =
8020                 CanTy->getAs<MemberPointerType>())
8021             CanTy = ResTypeMPtr->getPointeeType();
8022           else
8023             done = true;
8024           if (CanTy.isVolatileQualified())
8025             VRQuals.addVolatile();
8026           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8027             return VRQuals;
8028         }
8029       }
8030     }
8031     return VRQuals;
8032 }
8033 
8034 namespace {
8035 
8036 /// Helper class to manage the addition of builtin operator overload
8037 /// candidates. It provides shared state and utility methods used throughout
8038 /// the process, as well as a helper method to add each group of builtin
8039 /// operator overloads from the standard to a candidate set.
8040 class BuiltinOperatorOverloadBuilder {
8041   // Common instance state available to all overload candidate addition methods.
8042   Sema &S;
8043   ArrayRef<Expr *> Args;
8044   Qualifiers VisibleTypeConversionsQuals;
8045   bool HasArithmeticOrEnumeralCandidateType;
8046   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8047   OverloadCandidateSet &CandidateSet;
8048 
8049   static constexpr int ArithmeticTypesCap = 24;
8050   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8051 
8052   // Define some indices used to iterate over the arithmetic types in
8053   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
8054   // types are that preserved by promotion (C++ [over.built]p2).
8055   unsigned FirstIntegralType,
8056            LastIntegralType;
8057   unsigned FirstPromotedIntegralType,
8058            LastPromotedIntegralType;
8059   unsigned FirstPromotedArithmeticType,
8060            LastPromotedArithmeticType;
8061   unsigned NumArithmeticTypes;
8062 
8063   void InitArithmeticTypes() {
8064     // Start of promoted types.
8065     FirstPromotedArithmeticType = 0;
8066     ArithmeticTypes.push_back(S.Context.FloatTy);
8067     ArithmeticTypes.push_back(S.Context.DoubleTy);
8068     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8069     if (S.Context.getTargetInfo().hasFloat128Type())
8070       ArithmeticTypes.push_back(S.Context.Float128Ty);
8071 
8072     // Start of integral types.
8073     FirstIntegralType = ArithmeticTypes.size();
8074     FirstPromotedIntegralType = ArithmeticTypes.size();
8075     ArithmeticTypes.push_back(S.Context.IntTy);
8076     ArithmeticTypes.push_back(S.Context.LongTy);
8077     ArithmeticTypes.push_back(S.Context.LongLongTy);
8078     if (S.Context.getTargetInfo().hasInt128Type())
8079       ArithmeticTypes.push_back(S.Context.Int128Ty);
8080     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8081     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8082     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8083     if (S.Context.getTargetInfo().hasInt128Type())
8084       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8085     LastPromotedIntegralType = ArithmeticTypes.size();
8086     LastPromotedArithmeticType = ArithmeticTypes.size();
8087     // End of promoted types.
8088 
8089     ArithmeticTypes.push_back(S.Context.BoolTy);
8090     ArithmeticTypes.push_back(S.Context.CharTy);
8091     ArithmeticTypes.push_back(S.Context.WCharTy);
8092     if (S.Context.getLangOpts().Char8)
8093       ArithmeticTypes.push_back(S.Context.Char8Ty);
8094     ArithmeticTypes.push_back(S.Context.Char16Ty);
8095     ArithmeticTypes.push_back(S.Context.Char32Ty);
8096     ArithmeticTypes.push_back(S.Context.SignedCharTy);
8097     ArithmeticTypes.push_back(S.Context.ShortTy);
8098     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8099     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8100     LastIntegralType = ArithmeticTypes.size();
8101     NumArithmeticTypes = ArithmeticTypes.size();
8102     // End of integral types.
8103     // FIXME: What about complex? What about half?
8104 
8105     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
8106            "Enough inline storage for all arithmetic types.");
8107   }
8108 
8109   /// Helper method to factor out the common pattern of adding overloads
8110   /// for '++' and '--' builtin operators.
8111   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8112                                            bool HasVolatile,
8113                                            bool HasRestrict) {
8114     QualType ParamTypes[2] = {
8115       S.Context.getLValueReferenceType(CandidateTy),
8116       S.Context.IntTy
8117     };
8118 
8119     // Non-volatile version.
8120     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8121 
8122     // Use a heuristic to reduce number of builtin candidates in the set:
8123     // add volatile version only if there are conversions to a volatile type.
8124     if (HasVolatile) {
8125       ParamTypes[0] =
8126         S.Context.getLValueReferenceType(
8127           S.Context.getVolatileType(CandidateTy));
8128       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8129     }
8130 
8131     // Add restrict version only if there are conversions to a restrict type
8132     // and our candidate type is a non-restrict-qualified pointer.
8133     if (HasRestrict && CandidateTy->isAnyPointerType() &&
8134         !CandidateTy.isRestrictQualified()) {
8135       ParamTypes[0]
8136         = S.Context.getLValueReferenceType(
8137             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8138       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8139 
8140       if (HasVolatile) {
8141         ParamTypes[0]
8142           = S.Context.getLValueReferenceType(
8143               S.Context.getCVRQualifiedType(CandidateTy,
8144                                             (Qualifiers::Volatile |
8145                                              Qualifiers::Restrict)));
8146         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8147       }
8148     }
8149 
8150   }
8151 
8152 public:
8153   BuiltinOperatorOverloadBuilder(
8154     Sema &S, ArrayRef<Expr *> Args,
8155     Qualifiers VisibleTypeConversionsQuals,
8156     bool HasArithmeticOrEnumeralCandidateType,
8157     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8158     OverloadCandidateSet &CandidateSet)
8159     : S(S), Args(Args),
8160       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8161       HasArithmeticOrEnumeralCandidateType(
8162         HasArithmeticOrEnumeralCandidateType),
8163       CandidateTypes(CandidateTypes),
8164       CandidateSet(CandidateSet) {
8165 
8166     InitArithmeticTypes();
8167   }
8168 
8169   // Increment is deprecated for bool since C++17.
8170   //
8171   // C++ [over.built]p3:
8172   //
8173   //   For every pair (T, VQ), where T is an arithmetic type other
8174   //   than bool, and VQ is either volatile or empty, there exist
8175   //   candidate operator functions of the form
8176   //
8177   //       VQ T&      operator++(VQ T&);
8178   //       T          operator++(VQ T&, int);
8179   //
8180   // C++ [over.built]p4:
8181   //
8182   //   For every pair (T, VQ), where T is an arithmetic type other
8183   //   than bool, and VQ is either volatile or empty, there exist
8184   //   candidate operator functions of the form
8185   //
8186   //       VQ T&      operator--(VQ T&);
8187   //       T          operator--(VQ T&, int);
8188   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8189     if (!HasArithmeticOrEnumeralCandidateType)
8190       return;
8191 
8192     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8193       const auto TypeOfT = ArithmeticTypes[Arith];
8194       if (TypeOfT == S.Context.BoolTy) {
8195         if (Op == OO_MinusMinus)
8196           continue;
8197         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8198           continue;
8199       }
8200       addPlusPlusMinusMinusStyleOverloads(
8201         TypeOfT,
8202         VisibleTypeConversionsQuals.hasVolatile(),
8203         VisibleTypeConversionsQuals.hasRestrict());
8204     }
8205   }
8206 
8207   // C++ [over.built]p5:
8208   //
8209   //   For every pair (T, VQ), where T is a cv-qualified or
8210   //   cv-unqualified object type, and VQ is either volatile or
8211   //   empty, there exist candidate operator functions of the form
8212   //
8213   //       T*VQ&      operator++(T*VQ&);
8214   //       T*VQ&      operator--(T*VQ&);
8215   //       T*         operator++(T*VQ&, int);
8216   //       T*         operator--(T*VQ&, int);
8217   void addPlusPlusMinusMinusPointerOverloads() {
8218     for (BuiltinCandidateTypeSet::iterator
8219               Ptr = CandidateTypes[0].pointer_begin(),
8220            PtrEnd = CandidateTypes[0].pointer_end();
8221          Ptr != PtrEnd; ++Ptr) {
8222       // Skip pointer types that aren't pointers to object types.
8223       if (!(*Ptr)->getPointeeType()->isObjectType())
8224         continue;
8225 
8226       addPlusPlusMinusMinusStyleOverloads(*Ptr,
8227         (!(*Ptr).isVolatileQualified() &&
8228          VisibleTypeConversionsQuals.hasVolatile()),
8229         (!(*Ptr).isRestrictQualified() &&
8230          VisibleTypeConversionsQuals.hasRestrict()));
8231     }
8232   }
8233 
8234   // C++ [over.built]p6:
8235   //   For every cv-qualified or cv-unqualified object type T, there
8236   //   exist candidate operator functions of the form
8237   //
8238   //       T&         operator*(T*);
8239   //
8240   // C++ [over.built]p7:
8241   //   For every function type T that does not have cv-qualifiers or a
8242   //   ref-qualifier, there exist candidate operator functions of the form
8243   //       T&         operator*(T*);
8244   void addUnaryStarPointerOverloads() {
8245     for (BuiltinCandidateTypeSet::iterator
8246               Ptr = CandidateTypes[0].pointer_begin(),
8247            PtrEnd = CandidateTypes[0].pointer_end();
8248          Ptr != PtrEnd; ++Ptr) {
8249       QualType ParamTy = *Ptr;
8250       QualType PointeeTy = ParamTy->getPointeeType();
8251       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8252         continue;
8253 
8254       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8255         if (Proto->getMethodQuals() || Proto->getRefQualifier())
8256           continue;
8257 
8258       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8259     }
8260   }
8261 
8262   // C++ [over.built]p9:
8263   //  For every promoted arithmetic type T, there exist candidate
8264   //  operator functions of the form
8265   //
8266   //       T         operator+(T);
8267   //       T         operator-(T);
8268   void addUnaryPlusOrMinusArithmeticOverloads() {
8269     if (!HasArithmeticOrEnumeralCandidateType)
8270       return;
8271 
8272     for (unsigned Arith = FirstPromotedArithmeticType;
8273          Arith < LastPromotedArithmeticType; ++Arith) {
8274       QualType ArithTy = ArithmeticTypes[Arith];
8275       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8276     }
8277 
8278     // Extension: We also add these operators for vector types.
8279     for (BuiltinCandidateTypeSet::iterator
8280               Vec = CandidateTypes[0].vector_begin(),
8281            VecEnd = CandidateTypes[0].vector_end();
8282          Vec != VecEnd; ++Vec) {
8283       QualType VecTy = *Vec;
8284       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8285     }
8286   }
8287 
8288   // C++ [over.built]p8:
8289   //   For every type T, there exist candidate operator functions of
8290   //   the form
8291   //
8292   //       T*         operator+(T*);
8293   void addUnaryPlusPointerOverloads() {
8294     for (BuiltinCandidateTypeSet::iterator
8295               Ptr = CandidateTypes[0].pointer_begin(),
8296            PtrEnd = CandidateTypes[0].pointer_end();
8297          Ptr != PtrEnd; ++Ptr) {
8298       QualType ParamTy = *Ptr;
8299       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8300     }
8301   }
8302 
8303   // C++ [over.built]p10:
8304   //   For every promoted integral type T, there exist candidate
8305   //   operator functions of the form
8306   //
8307   //        T         operator~(T);
8308   void addUnaryTildePromotedIntegralOverloads() {
8309     if (!HasArithmeticOrEnumeralCandidateType)
8310       return;
8311 
8312     for (unsigned Int = FirstPromotedIntegralType;
8313          Int < LastPromotedIntegralType; ++Int) {
8314       QualType IntTy = ArithmeticTypes[Int];
8315       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8316     }
8317 
8318     // Extension: We also add this operator for vector types.
8319     for (BuiltinCandidateTypeSet::iterator
8320               Vec = CandidateTypes[0].vector_begin(),
8321            VecEnd = CandidateTypes[0].vector_end();
8322          Vec != VecEnd; ++Vec) {
8323       QualType VecTy = *Vec;
8324       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8325     }
8326   }
8327 
8328   // C++ [over.match.oper]p16:
8329   //   For every pointer to member type T or type std::nullptr_t, there
8330   //   exist candidate operator functions of the form
8331   //
8332   //        bool operator==(T,T);
8333   //        bool operator!=(T,T);
8334   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8335     /// Set of (canonical) types that we've already handled.
8336     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8337 
8338     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8339       for (BuiltinCandidateTypeSet::iterator
8340                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8341              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8342            MemPtr != MemPtrEnd;
8343            ++MemPtr) {
8344         // Don't add the same builtin candidate twice.
8345         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8346           continue;
8347 
8348         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8349         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8350       }
8351 
8352       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8353         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8354         if (AddedTypes.insert(NullPtrTy).second) {
8355           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8356           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8357         }
8358       }
8359     }
8360   }
8361 
8362   // C++ [over.built]p15:
8363   //
8364   //   For every T, where T is an enumeration type or a pointer type,
8365   //   there exist candidate operator functions of the form
8366   //
8367   //        bool       operator<(T, T);
8368   //        bool       operator>(T, T);
8369   //        bool       operator<=(T, T);
8370   //        bool       operator>=(T, T);
8371   //        bool       operator==(T, T);
8372   //        bool       operator!=(T, T);
8373   //           R       operator<=>(T, T)
8374   void addGenericBinaryPointerOrEnumeralOverloads() {
8375     // C++ [over.match.oper]p3:
8376     //   [...]the built-in candidates include all of the candidate operator
8377     //   functions defined in 13.6 that, compared to the given operator, [...]
8378     //   do not have the same parameter-type-list as any non-template non-member
8379     //   candidate.
8380     //
8381     // Note that in practice, this only affects enumeration types because there
8382     // aren't any built-in candidates of record type, and a user-defined operator
8383     // must have an operand of record or enumeration type. Also, the only other
8384     // overloaded operator with enumeration arguments, operator=,
8385     // cannot be overloaded for enumeration types, so this is the only place
8386     // where we must suppress candidates like this.
8387     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8388       UserDefinedBinaryOperators;
8389 
8390     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8391       if (CandidateTypes[ArgIdx].enumeration_begin() !=
8392           CandidateTypes[ArgIdx].enumeration_end()) {
8393         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8394                                          CEnd = CandidateSet.end();
8395              C != CEnd; ++C) {
8396           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8397             continue;
8398 
8399           if (C->Function->isFunctionTemplateSpecialization())
8400             continue;
8401 
8402           // We interpret "same parameter-type-list" as applying to the
8403           // "synthesized candidate, with the order of the two parameters
8404           // reversed", not to the original function.
8405           bool Reversed = C->isReversed();
8406           QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
8407                                         ->getType()
8408                                         .getUnqualifiedType();
8409           QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
8410                                          ->getType()
8411                                          .getUnqualifiedType();
8412 
8413           // Skip if either parameter isn't of enumeral type.
8414           if (!FirstParamType->isEnumeralType() ||
8415               !SecondParamType->isEnumeralType())
8416             continue;
8417 
8418           // Add this operator to the set of known user-defined operators.
8419           UserDefinedBinaryOperators.insert(
8420             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8421                            S.Context.getCanonicalType(SecondParamType)));
8422         }
8423       }
8424     }
8425 
8426     /// Set of (canonical) types that we've already handled.
8427     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8428 
8429     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8430       for (BuiltinCandidateTypeSet::iterator
8431                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8432              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8433            Ptr != PtrEnd; ++Ptr) {
8434         // Don't add the same builtin candidate twice.
8435         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8436           continue;
8437 
8438         QualType ParamTypes[2] = { *Ptr, *Ptr };
8439         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8440       }
8441       for (BuiltinCandidateTypeSet::iterator
8442                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8443              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8444            Enum != EnumEnd; ++Enum) {
8445         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8446 
8447         // Don't add the same builtin candidate twice, or if a user defined
8448         // candidate exists.
8449         if (!AddedTypes.insert(CanonType).second ||
8450             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8451                                                             CanonType)))
8452           continue;
8453         QualType ParamTypes[2] = { *Enum, *Enum };
8454         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8455       }
8456     }
8457   }
8458 
8459   // C++ [over.built]p13:
8460   //
8461   //   For every cv-qualified or cv-unqualified object type T
8462   //   there exist candidate operator functions of the form
8463   //
8464   //      T*         operator+(T*, ptrdiff_t);
8465   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8466   //      T*         operator-(T*, ptrdiff_t);
8467   //      T*         operator+(ptrdiff_t, T*);
8468   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8469   //
8470   // C++ [over.built]p14:
8471   //
8472   //   For every T, where T is a pointer to object type, there
8473   //   exist candidate operator functions of the form
8474   //
8475   //      ptrdiff_t  operator-(T, T);
8476   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8477     /// Set of (canonical) types that we've already handled.
8478     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8479 
8480     for (int Arg = 0; Arg < 2; ++Arg) {
8481       QualType AsymmetricParamTypes[2] = {
8482         S.Context.getPointerDiffType(),
8483         S.Context.getPointerDiffType(),
8484       };
8485       for (BuiltinCandidateTypeSet::iterator
8486                 Ptr = CandidateTypes[Arg].pointer_begin(),
8487              PtrEnd = CandidateTypes[Arg].pointer_end();
8488            Ptr != PtrEnd; ++Ptr) {
8489         QualType PointeeTy = (*Ptr)->getPointeeType();
8490         if (!PointeeTy->isObjectType())
8491           continue;
8492 
8493         AsymmetricParamTypes[Arg] = *Ptr;
8494         if (Arg == 0 || Op == OO_Plus) {
8495           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8496           // T* operator+(ptrdiff_t, T*);
8497           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8498         }
8499         if (Op == OO_Minus) {
8500           // ptrdiff_t operator-(T, T);
8501           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8502             continue;
8503 
8504           QualType ParamTypes[2] = { *Ptr, *Ptr };
8505           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8506         }
8507       }
8508     }
8509   }
8510 
8511   // C++ [over.built]p12:
8512   //
8513   //   For every pair of promoted arithmetic types L and R, there
8514   //   exist candidate operator functions of the form
8515   //
8516   //        LR         operator*(L, R);
8517   //        LR         operator/(L, R);
8518   //        LR         operator+(L, R);
8519   //        LR         operator-(L, R);
8520   //        bool       operator<(L, R);
8521   //        bool       operator>(L, R);
8522   //        bool       operator<=(L, R);
8523   //        bool       operator>=(L, R);
8524   //        bool       operator==(L, R);
8525   //        bool       operator!=(L, R);
8526   //
8527   //   where LR is the result of the usual arithmetic conversions
8528   //   between types L and R.
8529   //
8530   // C++ [over.built]p24:
8531   //
8532   //   For every pair of promoted arithmetic types L and R, there exist
8533   //   candidate operator functions of the form
8534   //
8535   //        LR       operator?(bool, L, R);
8536   //
8537   //   where LR is the result of the usual arithmetic conversions
8538   //   between types L and R.
8539   // Our candidates ignore the first parameter.
8540   void addGenericBinaryArithmeticOverloads() {
8541     if (!HasArithmeticOrEnumeralCandidateType)
8542       return;
8543 
8544     for (unsigned Left = FirstPromotedArithmeticType;
8545          Left < LastPromotedArithmeticType; ++Left) {
8546       for (unsigned Right = FirstPromotedArithmeticType;
8547            Right < LastPromotedArithmeticType; ++Right) {
8548         QualType LandR[2] = { ArithmeticTypes[Left],
8549                               ArithmeticTypes[Right] };
8550         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8551       }
8552     }
8553 
8554     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8555     // conditional operator for vector types.
8556     for (BuiltinCandidateTypeSet::iterator
8557               Vec1 = CandidateTypes[0].vector_begin(),
8558            Vec1End = CandidateTypes[0].vector_end();
8559          Vec1 != Vec1End; ++Vec1) {
8560       for (BuiltinCandidateTypeSet::iterator
8561                 Vec2 = CandidateTypes[1].vector_begin(),
8562              Vec2End = CandidateTypes[1].vector_end();
8563            Vec2 != Vec2End; ++Vec2) {
8564         QualType LandR[2] = { *Vec1, *Vec2 };
8565         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8566       }
8567     }
8568   }
8569 
8570   // C++2a [over.built]p14:
8571   //
8572   //   For every integral type T there exists a candidate operator function
8573   //   of the form
8574   //
8575   //        std::strong_ordering operator<=>(T, T)
8576   //
8577   // C++2a [over.built]p15:
8578   //
8579   //   For every pair of floating-point types L and R, there exists a candidate
8580   //   operator function of the form
8581   //
8582   //       std::partial_ordering operator<=>(L, R);
8583   //
8584   // FIXME: The current specification for integral types doesn't play nice with
8585   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8586   // comparisons. Under the current spec this can lead to ambiguity during
8587   // overload resolution. For example:
8588   //
8589   //   enum A : int {a};
8590   //   auto x = (a <=> (long)42);
8591   //
8592   //   error: call is ambiguous for arguments 'A' and 'long'.
8593   //   note: candidate operator<=>(int, int)
8594   //   note: candidate operator<=>(long, long)
8595   //
8596   // To avoid this error, this function deviates from the specification and adds
8597   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8598   // arithmetic types (the same as the generic relational overloads).
8599   //
8600   // For now this function acts as a placeholder.
8601   void addThreeWayArithmeticOverloads() {
8602     addGenericBinaryArithmeticOverloads();
8603   }
8604 
8605   // C++ [over.built]p17:
8606   //
8607   //   For every pair of promoted integral types L and R, there
8608   //   exist candidate operator functions of the form
8609   //
8610   //      LR         operator%(L, R);
8611   //      LR         operator&(L, R);
8612   //      LR         operator^(L, R);
8613   //      LR         operator|(L, R);
8614   //      L          operator<<(L, R);
8615   //      L          operator>>(L, R);
8616   //
8617   //   where LR is the result of the usual arithmetic conversions
8618   //   between types L and R.
8619   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8620     if (!HasArithmeticOrEnumeralCandidateType)
8621       return;
8622 
8623     for (unsigned Left = FirstPromotedIntegralType;
8624          Left < LastPromotedIntegralType; ++Left) {
8625       for (unsigned Right = FirstPromotedIntegralType;
8626            Right < LastPromotedIntegralType; ++Right) {
8627         QualType LandR[2] = { ArithmeticTypes[Left],
8628                               ArithmeticTypes[Right] };
8629         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8630       }
8631     }
8632   }
8633 
8634   // C++ [over.built]p20:
8635   //
8636   //   For every pair (T, VQ), where T is an enumeration or
8637   //   pointer to member type and VQ is either volatile or
8638   //   empty, there exist candidate operator functions of the form
8639   //
8640   //        VQ T&      operator=(VQ T&, T);
8641   void addAssignmentMemberPointerOrEnumeralOverloads() {
8642     /// Set of (canonical) types that we've already handled.
8643     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8644 
8645     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8646       for (BuiltinCandidateTypeSet::iterator
8647                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8648              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8649            Enum != EnumEnd; ++Enum) {
8650         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8651           continue;
8652 
8653         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8654       }
8655 
8656       for (BuiltinCandidateTypeSet::iterator
8657                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8658              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8659            MemPtr != MemPtrEnd; ++MemPtr) {
8660         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8661           continue;
8662 
8663         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8664       }
8665     }
8666   }
8667 
8668   // C++ [over.built]p19:
8669   //
8670   //   For every pair (T, VQ), where T is any type and VQ is either
8671   //   volatile or empty, there exist candidate operator functions
8672   //   of the form
8673   //
8674   //        T*VQ&      operator=(T*VQ&, T*);
8675   //
8676   // C++ [over.built]p21:
8677   //
8678   //   For every pair (T, VQ), where T is a cv-qualified or
8679   //   cv-unqualified object type and VQ is either volatile or
8680   //   empty, there exist candidate operator functions of the form
8681   //
8682   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8683   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8684   void addAssignmentPointerOverloads(bool isEqualOp) {
8685     /// Set of (canonical) types that we've already handled.
8686     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8687 
8688     for (BuiltinCandidateTypeSet::iterator
8689               Ptr = CandidateTypes[0].pointer_begin(),
8690            PtrEnd = CandidateTypes[0].pointer_end();
8691          Ptr != PtrEnd; ++Ptr) {
8692       // If this is operator=, keep track of the builtin candidates we added.
8693       if (isEqualOp)
8694         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8695       else if (!(*Ptr)->getPointeeType()->isObjectType())
8696         continue;
8697 
8698       // non-volatile version
8699       QualType ParamTypes[2] = {
8700         S.Context.getLValueReferenceType(*Ptr),
8701         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8702       };
8703       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8704                             /*IsAssignmentOperator=*/ isEqualOp);
8705 
8706       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8707                           VisibleTypeConversionsQuals.hasVolatile();
8708       if (NeedVolatile) {
8709         // volatile version
8710         ParamTypes[0] =
8711           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8712         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8713                               /*IsAssignmentOperator=*/isEqualOp);
8714       }
8715 
8716       if (!(*Ptr).isRestrictQualified() &&
8717           VisibleTypeConversionsQuals.hasRestrict()) {
8718         // restrict version
8719         ParamTypes[0]
8720           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8721         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8722                               /*IsAssignmentOperator=*/isEqualOp);
8723 
8724         if (NeedVolatile) {
8725           // volatile restrict version
8726           ParamTypes[0]
8727             = S.Context.getLValueReferenceType(
8728                 S.Context.getCVRQualifiedType(*Ptr,
8729                                               (Qualifiers::Volatile |
8730                                                Qualifiers::Restrict)));
8731           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8732                                 /*IsAssignmentOperator=*/isEqualOp);
8733         }
8734       }
8735     }
8736 
8737     if (isEqualOp) {
8738       for (BuiltinCandidateTypeSet::iterator
8739                 Ptr = CandidateTypes[1].pointer_begin(),
8740              PtrEnd = CandidateTypes[1].pointer_end();
8741            Ptr != PtrEnd; ++Ptr) {
8742         // Make sure we don't add the same candidate twice.
8743         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8744           continue;
8745 
8746         QualType ParamTypes[2] = {
8747           S.Context.getLValueReferenceType(*Ptr),
8748           *Ptr,
8749         };
8750 
8751         // non-volatile version
8752         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8753                               /*IsAssignmentOperator=*/true);
8754 
8755         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8756                            VisibleTypeConversionsQuals.hasVolatile();
8757         if (NeedVolatile) {
8758           // volatile version
8759           ParamTypes[0] =
8760             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8761           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8762                                 /*IsAssignmentOperator=*/true);
8763         }
8764 
8765         if (!(*Ptr).isRestrictQualified() &&
8766             VisibleTypeConversionsQuals.hasRestrict()) {
8767           // restrict version
8768           ParamTypes[0]
8769             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8770           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8771                                 /*IsAssignmentOperator=*/true);
8772 
8773           if (NeedVolatile) {
8774             // volatile restrict version
8775             ParamTypes[0]
8776               = S.Context.getLValueReferenceType(
8777                   S.Context.getCVRQualifiedType(*Ptr,
8778                                                 (Qualifiers::Volatile |
8779                                                  Qualifiers::Restrict)));
8780             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8781                                   /*IsAssignmentOperator=*/true);
8782           }
8783         }
8784       }
8785     }
8786   }
8787 
8788   // C++ [over.built]p18:
8789   //
8790   //   For every triple (L, VQ, R), where L is an arithmetic type,
8791   //   VQ is either volatile or empty, and R is a promoted
8792   //   arithmetic type, there exist candidate operator functions of
8793   //   the form
8794   //
8795   //        VQ L&      operator=(VQ L&, R);
8796   //        VQ L&      operator*=(VQ L&, R);
8797   //        VQ L&      operator/=(VQ L&, R);
8798   //        VQ L&      operator+=(VQ L&, R);
8799   //        VQ L&      operator-=(VQ L&, R);
8800   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8801     if (!HasArithmeticOrEnumeralCandidateType)
8802       return;
8803 
8804     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8805       for (unsigned Right = FirstPromotedArithmeticType;
8806            Right < LastPromotedArithmeticType; ++Right) {
8807         QualType ParamTypes[2];
8808         ParamTypes[1] = ArithmeticTypes[Right];
8809         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8810             S, ArithmeticTypes[Left], Args[0]);
8811         // Add this built-in operator as a candidate (VQ is empty).
8812         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8813         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8814                               /*IsAssignmentOperator=*/isEqualOp);
8815 
8816         // Add this built-in operator as a candidate (VQ is 'volatile').
8817         if (VisibleTypeConversionsQuals.hasVolatile()) {
8818           ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy);
8819           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8820           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8821                                 /*IsAssignmentOperator=*/isEqualOp);
8822         }
8823       }
8824     }
8825 
8826     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8827     for (BuiltinCandidateTypeSet::iterator
8828               Vec1 = CandidateTypes[0].vector_begin(),
8829            Vec1End = CandidateTypes[0].vector_end();
8830          Vec1 != Vec1End; ++Vec1) {
8831       for (BuiltinCandidateTypeSet::iterator
8832                 Vec2 = CandidateTypes[1].vector_begin(),
8833              Vec2End = CandidateTypes[1].vector_end();
8834            Vec2 != Vec2End; ++Vec2) {
8835         QualType ParamTypes[2];
8836         ParamTypes[1] = *Vec2;
8837         // Add this built-in operator as a candidate (VQ is empty).
8838         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8839         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8840                               /*IsAssignmentOperator=*/isEqualOp);
8841 
8842         // Add this built-in operator as a candidate (VQ is 'volatile').
8843         if (VisibleTypeConversionsQuals.hasVolatile()) {
8844           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8845           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8846           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8847                                 /*IsAssignmentOperator=*/isEqualOp);
8848         }
8849       }
8850     }
8851   }
8852 
8853   // C++ [over.built]p22:
8854   //
8855   //   For every triple (L, VQ, R), where L is an integral type, VQ
8856   //   is either volatile or empty, and R is a promoted integral
8857   //   type, there exist candidate operator functions of the form
8858   //
8859   //        VQ L&       operator%=(VQ L&, R);
8860   //        VQ L&       operator<<=(VQ L&, R);
8861   //        VQ L&       operator>>=(VQ L&, R);
8862   //        VQ L&       operator&=(VQ L&, R);
8863   //        VQ L&       operator^=(VQ L&, R);
8864   //        VQ L&       operator|=(VQ L&, R);
8865   void addAssignmentIntegralOverloads() {
8866     if (!HasArithmeticOrEnumeralCandidateType)
8867       return;
8868 
8869     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8870       for (unsigned Right = FirstPromotedIntegralType;
8871            Right < LastPromotedIntegralType; ++Right) {
8872         QualType ParamTypes[2];
8873         ParamTypes[1] = ArithmeticTypes[Right];
8874         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8875             S, ArithmeticTypes[Left], Args[0]);
8876         // Add this built-in operator as a candidate (VQ is empty).
8877         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8878         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8879         if (VisibleTypeConversionsQuals.hasVolatile()) {
8880           // Add this built-in operator as a candidate (VQ is 'volatile').
8881           ParamTypes[0] = LeftBaseTy;
8882           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8883           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8884           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8885         }
8886       }
8887     }
8888   }
8889 
8890   // C++ [over.operator]p23:
8891   //
8892   //   There also exist candidate operator functions of the form
8893   //
8894   //        bool        operator!(bool);
8895   //        bool        operator&&(bool, bool);
8896   //        bool        operator||(bool, bool);
8897   void addExclaimOverload() {
8898     QualType ParamTy = S.Context.BoolTy;
8899     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8900                           /*IsAssignmentOperator=*/false,
8901                           /*NumContextualBoolArguments=*/1);
8902   }
8903   void addAmpAmpOrPipePipeOverload() {
8904     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8905     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8906                           /*IsAssignmentOperator=*/false,
8907                           /*NumContextualBoolArguments=*/2);
8908   }
8909 
8910   // C++ [over.built]p13:
8911   //
8912   //   For every cv-qualified or cv-unqualified object type T there
8913   //   exist candidate operator functions of the form
8914   //
8915   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8916   //        T&         operator[](T*, ptrdiff_t);
8917   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8918   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8919   //        T&         operator[](ptrdiff_t, T*);
8920   void addSubscriptOverloads() {
8921     for (BuiltinCandidateTypeSet::iterator
8922               Ptr = CandidateTypes[0].pointer_begin(),
8923            PtrEnd = CandidateTypes[0].pointer_end();
8924          Ptr != PtrEnd; ++Ptr) {
8925       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8926       QualType PointeeType = (*Ptr)->getPointeeType();
8927       if (!PointeeType->isObjectType())
8928         continue;
8929 
8930       // T& operator[](T*, ptrdiff_t)
8931       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8932     }
8933 
8934     for (BuiltinCandidateTypeSet::iterator
8935               Ptr = CandidateTypes[1].pointer_begin(),
8936            PtrEnd = CandidateTypes[1].pointer_end();
8937          Ptr != PtrEnd; ++Ptr) {
8938       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8939       QualType PointeeType = (*Ptr)->getPointeeType();
8940       if (!PointeeType->isObjectType())
8941         continue;
8942 
8943       // T& operator[](ptrdiff_t, T*)
8944       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8945     }
8946   }
8947 
8948   // C++ [over.built]p11:
8949   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8950   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8951   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8952   //    there exist candidate operator functions of the form
8953   //
8954   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8955   //
8956   //    where CV12 is the union of CV1 and CV2.
8957   void addArrowStarOverloads() {
8958     for (BuiltinCandidateTypeSet::iterator
8959              Ptr = CandidateTypes[0].pointer_begin(),
8960            PtrEnd = CandidateTypes[0].pointer_end();
8961          Ptr != PtrEnd; ++Ptr) {
8962       QualType C1Ty = (*Ptr);
8963       QualType C1;
8964       QualifierCollector Q1;
8965       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8966       if (!isa<RecordType>(C1))
8967         continue;
8968       // heuristic to reduce number of builtin candidates in the set.
8969       // Add volatile/restrict version only if there are conversions to a
8970       // volatile/restrict type.
8971       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8972         continue;
8973       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8974         continue;
8975       for (BuiltinCandidateTypeSet::iterator
8976                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8977              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8978            MemPtr != MemPtrEnd; ++MemPtr) {
8979         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8980         QualType C2 = QualType(mptr->getClass(), 0);
8981         C2 = C2.getUnqualifiedType();
8982         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8983           break;
8984         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8985         // build CV12 T&
8986         QualType T = mptr->getPointeeType();
8987         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8988             T.isVolatileQualified())
8989           continue;
8990         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8991             T.isRestrictQualified())
8992           continue;
8993         T = Q1.apply(S.Context, T);
8994         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8995       }
8996     }
8997   }
8998 
8999   // Note that we don't consider the first argument, since it has been
9000   // contextually converted to bool long ago. The candidates below are
9001   // therefore added as binary.
9002   //
9003   // C++ [over.built]p25:
9004   //   For every type T, where T is a pointer, pointer-to-member, or scoped
9005   //   enumeration type, there exist candidate operator functions of the form
9006   //
9007   //        T        operator?(bool, T, T);
9008   //
9009   void addConditionalOperatorOverloads() {
9010     /// Set of (canonical) types that we've already handled.
9011     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9012 
9013     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9014       for (BuiltinCandidateTypeSet::iterator
9015                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
9016              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
9017            Ptr != PtrEnd; ++Ptr) {
9018         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
9019           continue;
9020 
9021         QualType ParamTypes[2] = { *Ptr, *Ptr };
9022         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9023       }
9024 
9025       for (BuiltinCandidateTypeSet::iterator
9026                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
9027              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
9028            MemPtr != MemPtrEnd; ++MemPtr) {
9029         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
9030           continue;
9031 
9032         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
9033         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9034       }
9035 
9036       if (S.getLangOpts().CPlusPlus11) {
9037         for (BuiltinCandidateTypeSet::iterator
9038                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
9039                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
9040              Enum != EnumEnd; ++Enum) {
9041           if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped())
9042             continue;
9043 
9044           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
9045             continue;
9046 
9047           QualType ParamTypes[2] = { *Enum, *Enum };
9048           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9049         }
9050       }
9051     }
9052   }
9053 };
9054 
9055 } // end anonymous namespace
9056 
9057 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
9058 /// operator overloads to the candidate set (C++ [over.built]), based
9059 /// on the operator @p Op and the arguments given. For example, if the
9060 /// operator is a binary '+', this routine might add "int
9061 /// operator+(int, int)" to cover integer addition.
9062 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9063                                         SourceLocation OpLoc,
9064                                         ArrayRef<Expr *> Args,
9065                                         OverloadCandidateSet &CandidateSet) {
9066   // Find all of the types that the arguments can convert to, but only
9067   // if the operator we're looking at has built-in operator candidates
9068   // that make use of these types. Also record whether we encounter non-record
9069   // candidate types or either arithmetic or enumeral candidate types.
9070   Qualifiers VisibleTypeConversionsQuals;
9071   VisibleTypeConversionsQuals.addConst();
9072   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
9073     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9074 
9075   bool HasNonRecordCandidateType = false;
9076   bool HasArithmeticOrEnumeralCandidateType = false;
9077   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9078   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9079     CandidateTypes.emplace_back(*this);
9080     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9081                                                  OpLoc,
9082                                                  true,
9083                                                  (Op == OO_Exclaim ||
9084                                                   Op == OO_AmpAmp ||
9085                                                   Op == OO_PipePipe),
9086                                                  VisibleTypeConversionsQuals);
9087     HasNonRecordCandidateType = HasNonRecordCandidateType ||
9088         CandidateTypes[ArgIdx].hasNonRecordTypes();
9089     HasArithmeticOrEnumeralCandidateType =
9090         HasArithmeticOrEnumeralCandidateType ||
9091         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9092   }
9093 
9094   // Exit early when no non-record types have been added to the candidate set
9095   // for any of the arguments to the operator.
9096   //
9097   // We can't exit early for !, ||, or &&, since there we have always have
9098   // 'bool' overloads.
9099   if (!HasNonRecordCandidateType &&
9100       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9101     return;
9102 
9103   // Setup an object to manage the common state for building overloads.
9104   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9105                                            VisibleTypeConversionsQuals,
9106                                            HasArithmeticOrEnumeralCandidateType,
9107                                            CandidateTypes, CandidateSet);
9108 
9109   // Dispatch over the operation to add in only those overloads which apply.
9110   switch (Op) {
9111   case OO_None:
9112   case NUM_OVERLOADED_OPERATORS:
9113     llvm_unreachable("Expected an overloaded operator");
9114 
9115   case OO_New:
9116   case OO_Delete:
9117   case OO_Array_New:
9118   case OO_Array_Delete:
9119   case OO_Call:
9120     llvm_unreachable(
9121                     "Special operators don't use AddBuiltinOperatorCandidates");
9122 
9123   case OO_Comma:
9124   case OO_Arrow:
9125   case OO_Coawait:
9126     // C++ [over.match.oper]p3:
9127     //   -- For the operator ',', the unary operator '&', the
9128     //      operator '->', or the operator 'co_await', the
9129     //      built-in candidates set is empty.
9130     break;
9131 
9132   case OO_Plus: // '+' is either unary or binary
9133     if (Args.size() == 1)
9134       OpBuilder.addUnaryPlusPointerOverloads();
9135     LLVM_FALLTHROUGH;
9136 
9137   case OO_Minus: // '-' is either unary or binary
9138     if (Args.size() == 1) {
9139       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9140     } else {
9141       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9142       OpBuilder.addGenericBinaryArithmeticOverloads();
9143     }
9144     break;
9145 
9146   case OO_Star: // '*' is either unary or binary
9147     if (Args.size() == 1)
9148       OpBuilder.addUnaryStarPointerOverloads();
9149     else
9150       OpBuilder.addGenericBinaryArithmeticOverloads();
9151     break;
9152 
9153   case OO_Slash:
9154     OpBuilder.addGenericBinaryArithmeticOverloads();
9155     break;
9156 
9157   case OO_PlusPlus:
9158   case OO_MinusMinus:
9159     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9160     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9161     break;
9162 
9163   case OO_EqualEqual:
9164   case OO_ExclaimEqual:
9165     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9166     LLVM_FALLTHROUGH;
9167 
9168   case OO_Less:
9169   case OO_Greater:
9170   case OO_LessEqual:
9171   case OO_GreaterEqual:
9172     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9173     OpBuilder.addGenericBinaryArithmeticOverloads();
9174     break;
9175 
9176   case OO_Spaceship:
9177     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9178     OpBuilder.addThreeWayArithmeticOverloads();
9179     break;
9180 
9181   case OO_Percent:
9182   case OO_Caret:
9183   case OO_Pipe:
9184   case OO_LessLess:
9185   case OO_GreaterGreater:
9186     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9187     break;
9188 
9189   case OO_Amp: // '&' is either unary or binary
9190     if (Args.size() == 1)
9191       // C++ [over.match.oper]p3:
9192       //   -- For the operator ',', the unary operator '&', or the
9193       //      operator '->', the built-in candidates set is empty.
9194       break;
9195 
9196     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9197     break;
9198 
9199   case OO_Tilde:
9200     OpBuilder.addUnaryTildePromotedIntegralOverloads();
9201     break;
9202 
9203   case OO_Equal:
9204     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9205     LLVM_FALLTHROUGH;
9206 
9207   case OO_PlusEqual:
9208   case OO_MinusEqual:
9209     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9210     LLVM_FALLTHROUGH;
9211 
9212   case OO_StarEqual:
9213   case OO_SlashEqual:
9214     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9215     break;
9216 
9217   case OO_PercentEqual:
9218   case OO_LessLessEqual:
9219   case OO_GreaterGreaterEqual:
9220   case OO_AmpEqual:
9221   case OO_CaretEqual:
9222   case OO_PipeEqual:
9223     OpBuilder.addAssignmentIntegralOverloads();
9224     break;
9225 
9226   case OO_Exclaim:
9227     OpBuilder.addExclaimOverload();
9228     break;
9229 
9230   case OO_AmpAmp:
9231   case OO_PipePipe:
9232     OpBuilder.addAmpAmpOrPipePipeOverload();
9233     break;
9234 
9235   case OO_Subscript:
9236     OpBuilder.addSubscriptOverloads();
9237     break;
9238 
9239   case OO_ArrowStar:
9240     OpBuilder.addArrowStarOverloads();
9241     break;
9242 
9243   case OO_Conditional:
9244     OpBuilder.addConditionalOperatorOverloads();
9245     OpBuilder.addGenericBinaryArithmeticOverloads();
9246     break;
9247   }
9248 }
9249 
9250 /// Add function candidates found via argument-dependent lookup
9251 /// to the set of overloading candidates.
9252 ///
9253 /// This routine performs argument-dependent name lookup based on the
9254 /// given function name (which may also be an operator name) and adds
9255 /// all of the overload candidates found by ADL to the overload
9256 /// candidate set (C++ [basic.lookup.argdep]).
9257 void
9258 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9259                                            SourceLocation Loc,
9260                                            ArrayRef<Expr *> Args,
9261                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
9262                                            OverloadCandidateSet& CandidateSet,
9263                                            bool PartialOverloading) {
9264   ADLResult Fns;
9265 
9266   // FIXME: This approach for uniquing ADL results (and removing
9267   // redundant candidates from the set) relies on pointer-equality,
9268   // which means we need to key off the canonical decl.  However,
9269   // always going back to the canonical decl might not get us the
9270   // right set of default arguments.  What default arguments are
9271   // we supposed to consider on ADL candidates, anyway?
9272 
9273   // FIXME: Pass in the explicit template arguments?
9274   ArgumentDependentLookup(Name, Loc, Args, Fns);
9275 
9276   // Erase all of the candidates we already knew about.
9277   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9278                                    CandEnd = CandidateSet.end();
9279        Cand != CandEnd; ++Cand)
9280     if (Cand->Function) {
9281       Fns.erase(Cand->Function);
9282       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9283         Fns.erase(FunTmpl);
9284     }
9285 
9286   // For each of the ADL candidates we found, add it to the overload
9287   // set.
9288   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9289     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9290 
9291     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9292       if (ExplicitTemplateArgs)
9293         continue;
9294 
9295       AddOverloadCandidate(
9296           FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
9297           PartialOverloading, /*AllowExplicit=*/true,
9298           /*AllowExplicitConversions=*/false, ADLCallKind::UsesADL);
9299       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) {
9300         AddOverloadCandidate(
9301             FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
9302             /*SuppressUserConversions=*/false, PartialOverloading,
9303             /*AllowExplicit=*/true, /*AllowExplicitConversions=*/false,
9304             ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed);
9305       }
9306     } else {
9307       auto *FTD = cast<FunctionTemplateDecl>(*I);
9308       AddTemplateOverloadCandidate(
9309           FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
9310           /*SuppressUserConversions=*/false, PartialOverloading,
9311           /*AllowExplicit=*/true, ADLCallKind::UsesADL);
9312       if (CandidateSet.getRewriteInfo().shouldAddReversed(
9313               Context, FTD->getTemplatedDecl())) {
9314         AddTemplateOverloadCandidate(
9315             FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
9316             CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
9317             /*AllowExplicit=*/true, ADLCallKind::UsesADL,
9318             OverloadCandidateParamOrder::Reversed);
9319       }
9320     }
9321   }
9322 }
9323 
9324 namespace {
9325 enum class Comparison { Equal, Better, Worse };
9326 }
9327 
9328 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9329 /// overload resolution.
9330 ///
9331 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9332 /// Cand1's first N enable_if attributes have precisely the same conditions as
9333 /// Cand2's first N enable_if attributes (where N = the number of enable_if
9334 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9335 ///
9336 /// Note that you can have a pair of candidates such that Cand1's enable_if
9337 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9338 /// worse than Cand1's.
9339 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9340                                        const FunctionDecl *Cand2) {
9341   // Common case: One (or both) decls don't have enable_if attrs.
9342   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9343   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9344   if (!Cand1Attr || !Cand2Attr) {
9345     if (Cand1Attr == Cand2Attr)
9346       return Comparison::Equal;
9347     return Cand1Attr ? Comparison::Better : Comparison::Worse;
9348   }
9349 
9350   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9351   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9352 
9353   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9354   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9355     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9356     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9357 
9358     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9359     // has fewer enable_if attributes than Cand2, and vice versa.
9360     if (!Cand1A)
9361       return Comparison::Worse;
9362     if (!Cand2A)
9363       return Comparison::Better;
9364 
9365     Cand1ID.clear();
9366     Cand2ID.clear();
9367 
9368     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9369     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9370     if (Cand1ID != Cand2ID)
9371       return Comparison::Worse;
9372   }
9373 
9374   return Comparison::Equal;
9375 }
9376 
9377 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9378                                           const OverloadCandidate &Cand2) {
9379   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9380       !Cand2.Function->isMultiVersion())
9381     return false;
9382 
9383   // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this
9384   // is obviously better.
9385   if (Cand1.Function->isInvalidDecl()) return false;
9386   if (Cand2.Function->isInvalidDecl()) return true;
9387 
9388   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9389   // cpu_dispatch, else arbitrarily based on the identifiers.
9390   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9391   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9392   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9393   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9394 
9395   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9396     return false;
9397 
9398   if (Cand1CPUDisp && !Cand2CPUDisp)
9399     return true;
9400   if (Cand2CPUDisp && !Cand1CPUDisp)
9401     return false;
9402 
9403   if (Cand1CPUSpec && Cand2CPUSpec) {
9404     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9405       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size();
9406 
9407     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9408         FirstDiff = std::mismatch(
9409             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9410             Cand2CPUSpec->cpus_begin(),
9411             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9412               return LHS->getName() == RHS->getName();
9413             });
9414 
9415     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9416            "Two different cpu-specific versions should not have the same "
9417            "identifier list, otherwise they'd be the same decl!");
9418     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName();
9419   }
9420   llvm_unreachable("No way to get here unless both had cpu_dispatch");
9421 }
9422 
9423 /// isBetterOverloadCandidate - Determines whether the first overload
9424 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9425 bool clang::isBetterOverloadCandidate(
9426     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9427     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9428   // Define viable functions to be better candidates than non-viable
9429   // functions.
9430   if (!Cand2.Viable)
9431     return Cand1.Viable;
9432   else if (!Cand1.Viable)
9433     return false;
9434 
9435   // C++ [over.match.best]p1:
9436   //
9437   //   -- if F is a static member function, ICS1(F) is defined such
9438   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9439   //      any function G, and, symmetrically, ICS1(G) is neither
9440   //      better nor worse than ICS1(F).
9441   unsigned StartArg = 0;
9442   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9443     StartArg = 1;
9444 
9445   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9446     // We don't allow incompatible pointer conversions in C++.
9447     if (!S.getLangOpts().CPlusPlus)
9448       return ICS.isStandard() &&
9449              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9450 
9451     // The only ill-formed conversion we allow in C++ is the string literal to
9452     // char* conversion, which is only considered ill-formed after C++11.
9453     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9454            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9455   };
9456 
9457   // Define functions that don't require ill-formed conversions for a given
9458   // argument to be better candidates than functions that do.
9459   unsigned NumArgs = Cand1.Conversions.size();
9460   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9461   bool HasBetterConversion = false;
9462   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9463     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9464     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9465     if (Cand1Bad != Cand2Bad) {
9466       if (Cand1Bad)
9467         return false;
9468       HasBetterConversion = true;
9469     }
9470   }
9471 
9472   if (HasBetterConversion)
9473     return true;
9474 
9475   // C++ [over.match.best]p1:
9476   //   A viable function F1 is defined to be a better function than another
9477   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9478   //   conversion sequence than ICSi(F2), and then...
9479   bool HasWorseConversion = false;
9480   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9481     switch (CompareImplicitConversionSequences(S, Loc,
9482                                                Cand1.Conversions[ArgIdx],
9483                                                Cand2.Conversions[ArgIdx])) {
9484     case ImplicitConversionSequence::Better:
9485       // Cand1 has a better conversion sequence.
9486       HasBetterConversion = true;
9487       break;
9488 
9489     case ImplicitConversionSequence::Worse:
9490       if (Cand1.Function && Cand1.Function == Cand2.Function &&
9491           Cand2.isReversed()) {
9492         // Work around large-scale breakage caused by considering reversed
9493         // forms of operator== in C++20:
9494         //
9495         // When comparing a function against its reversed form, if we have a
9496         // better conversion for one argument and a worse conversion for the
9497         // other, we prefer the non-reversed form.
9498         //
9499         // This prevents a conversion function from being considered ambiguous
9500         // with its own reversed form in various where it's only incidentally
9501         // heterogeneous.
9502         //
9503         // We diagnose this as an extension from CreateOverloadedBinOp.
9504         HasWorseConversion = true;
9505         break;
9506       }
9507 
9508       // Cand1 can't be better than Cand2.
9509       return false;
9510 
9511     case ImplicitConversionSequence::Indistinguishable:
9512       // Do nothing.
9513       break;
9514     }
9515   }
9516 
9517   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9518   //       ICSj(F2), or, if not that,
9519   if (HasBetterConversion)
9520     return true;
9521   if (HasWorseConversion)
9522     return false;
9523 
9524   //   -- the context is an initialization by user-defined conversion
9525   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9526   //      from the return type of F1 to the destination type (i.e.,
9527   //      the type of the entity being initialized) is a better
9528   //      conversion sequence than the standard conversion sequence
9529   //      from the return type of F2 to the destination type.
9530   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9531       Cand1.Function && Cand2.Function &&
9532       isa<CXXConversionDecl>(Cand1.Function) &&
9533       isa<CXXConversionDecl>(Cand2.Function)) {
9534     // First check whether we prefer one of the conversion functions over the
9535     // other. This only distinguishes the results in non-standard, extension
9536     // cases such as the conversion from a lambda closure type to a function
9537     // pointer or block.
9538     ImplicitConversionSequence::CompareKind Result =
9539         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9540     if (Result == ImplicitConversionSequence::Indistinguishable)
9541       Result = CompareStandardConversionSequences(S, Loc,
9542                                                   Cand1.FinalConversion,
9543                                                   Cand2.FinalConversion);
9544 
9545     if (Result != ImplicitConversionSequence::Indistinguishable)
9546       return Result == ImplicitConversionSequence::Better;
9547 
9548     // FIXME: Compare kind of reference binding if conversion functions
9549     // convert to a reference type used in direct reference binding, per
9550     // C++14 [over.match.best]p1 section 2 bullet 3.
9551   }
9552 
9553   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9554   // as combined with the resolution to CWG issue 243.
9555   //
9556   // When the context is initialization by constructor ([over.match.ctor] or
9557   // either phase of [over.match.list]), a constructor is preferred over
9558   // a conversion function.
9559   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9560       Cand1.Function && Cand2.Function &&
9561       isa<CXXConstructorDecl>(Cand1.Function) !=
9562           isa<CXXConstructorDecl>(Cand2.Function))
9563     return isa<CXXConstructorDecl>(Cand1.Function);
9564 
9565   //    -- F1 is a non-template function and F2 is a function template
9566   //       specialization, or, if not that,
9567   bool Cand1IsSpecialization = Cand1.Function &&
9568                                Cand1.Function->getPrimaryTemplate();
9569   bool Cand2IsSpecialization = Cand2.Function &&
9570                                Cand2.Function->getPrimaryTemplate();
9571   if (Cand1IsSpecialization != Cand2IsSpecialization)
9572     return Cand2IsSpecialization;
9573 
9574   //   -- F1 and F2 are function template specializations, and the function
9575   //      template for F1 is more specialized than the template for F2
9576   //      according to the partial ordering rules described in 14.5.5.2, or,
9577   //      if not that,
9578   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9579     if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
9580             Cand1.Function->getPrimaryTemplate(),
9581             Cand2.Function->getPrimaryTemplate(), Loc,
9582             isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
9583                                                    : TPOC_Call,
9584             Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments,
9585             Cand1.isReversed() ^ Cand2.isReversed()))
9586       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9587   }
9588 
9589   //   -— F1 and F2 are non-template functions with the same
9590   //      parameter-type-lists, and F1 is more constrained than F2 [...],
9591   if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization &&
9592       !Cand2IsSpecialization && Cand1.Function->hasPrototype() &&
9593       Cand2.Function->hasPrototype()) {
9594     auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType());
9595     auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType());
9596     if (PT1->getNumParams() == PT2->getNumParams() &&
9597         PT1->isVariadic() == PT2->isVariadic() &&
9598         S.FunctionParamTypesAreEqual(PT1, PT2)) {
9599       Expr *RC1 = Cand1.Function->getTrailingRequiresClause();
9600       Expr *RC2 = Cand2.Function->getTrailingRequiresClause();
9601       if (RC1 && RC2) {
9602         bool AtLeastAsConstrained1, AtLeastAsConstrained2;
9603         if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function,
9604                                      {RC2}, AtLeastAsConstrained1) ||
9605             S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function,
9606                                      {RC1}, AtLeastAsConstrained2))
9607           return false;
9608         if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
9609           return AtLeastAsConstrained1;
9610       } else if (RC1 || RC2) {
9611         return RC1 != nullptr;
9612       }
9613     }
9614   }
9615 
9616   //   -- F1 is a constructor for a class D, F2 is a constructor for a base
9617   //      class B of D, and for all arguments the corresponding parameters of
9618   //      F1 and F2 have the same type.
9619   // FIXME: Implement the "all parameters have the same type" check.
9620   bool Cand1IsInherited =
9621       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9622   bool Cand2IsInherited =
9623       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9624   if (Cand1IsInherited != Cand2IsInherited)
9625     return Cand2IsInherited;
9626   else if (Cand1IsInherited) {
9627     assert(Cand2IsInherited);
9628     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9629     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9630     if (Cand1Class->isDerivedFrom(Cand2Class))
9631       return true;
9632     if (Cand2Class->isDerivedFrom(Cand1Class))
9633       return false;
9634     // Inherited from sibling base classes: still ambiguous.
9635   }
9636 
9637   //   -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
9638   //   -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
9639   //      with reversed order of parameters and F1 is not
9640   //
9641   // We rank reversed + different operator as worse than just reversed, but
9642   // that comparison can never happen, because we only consider reversing for
9643   // the maximally-rewritten operator (== or <=>).
9644   if (Cand1.RewriteKind != Cand2.RewriteKind)
9645     return Cand1.RewriteKind < Cand2.RewriteKind;
9646 
9647   // Check C++17 tie-breakers for deduction guides.
9648   {
9649     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9650     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9651     if (Guide1 && Guide2) {
9652       //  -- F1 is generated from a deduction-guide and F2 is not
9653       if (Guide1->isImplicit() != Guide2->isImplicit())
9654         return Guide2->isImplicit();
9655 
9656       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9657       if (Guide1->isCopyDeductionCandidate())
9658         return true;
9659     }
9660   }
9661 
9662   // Check for enable_if value-based overload resolution.
9663   if (Cand1.Function && Cand2.Function) {
9664     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9665     if (Cmp != Comparison::Equal)
9666       return Cmp == Comparison::Better;
9667   }
9668 
9669   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9670     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9671     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9672            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9673   }
9674 
9675   bool HasPS1 = Cand1.Function != nullptr &&
9676                 functionHasPassObjectSizeParams(Cand1.Function);
9677   bool HasPS2 = Cand2.Function != nullptr &&
9678                 functionHasPassObjectSizeParams(Cand2.Function);
9679   if (HasPS1 != HasPS2 && HasPS1)
9680     return true;
9681 
9682   return isBetterMultiversionCandidate(Cand1, Cand2);
9683 }
9684 
9685 /// Determine whether two declarations are "equivalent" for the purposes of
9686 /// name lookup and overload resolution. This applies when the same internal/no
9687 /// linkage entity is defined by two modules (probably by textually including
9688 /// the same header). In such a case, we don't consider the declarations to
9689 /// declare the same entity, but we also don't want lookups with both
9690 /// declarations visible to be ambiguous in some cases (this happens when using
9691 /// a modularized libstdc++).
9692 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9693                                                   const NamedDecl *B) {
9694   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9695   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9696   if (!VA || !VB)
9697     return false;
9698 
9699   // The declarations must be declaring the same name as an internal linkage
9700   // entity in different modules.
9701   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9702           VB->getDeclContext()->getRedeclContext()) ||
9703       getOwningModule(VA) == getOwningModule(VB) ||
9704       VA->isExternallyVisible() || VB->isExternallyVisible())
9705     return false;
9706 
9707   // Check that the declarations appear to be equivalent.
9708   //
9709   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9710   // For constants and functions, we should check the initializer or body is
9711   // the same. For non-constant variables, we shouldn't allow it at all.
9712   if (Context.hasSameType(VA->getType(), VB->getType()))
9713     return true;
9714 
9715   // Enum constants within unnamed enumerations will have different types, but
9716   // may still be similar enough to be interchangeable for our purposes.
9717   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9718     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9719       // Only handle anonymous enums. If the enumerations were named and
9720       // equivalent, they would have been merged to the same type.
9721       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9722       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9723       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9724           !Context.hasSameType(EnumA->getIntegerType(),
9725                                EnumB->getIntegerType()))
9726         return false;
9727       // Allow this only if the value is the same for both enumerators.
9728       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9729     }
9730   }
9731 
9732   // Nothing else is sufficiently similar.
9733   return false;
9734 }
9735 
9736 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9737     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9738   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9739 
9740   Module *M = getOwningModule(D);
9741   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9742       << !M << (M ? M->getFullModuleName() : "");
9743 
9744   for (auto *E : Equiv) {
9745     Module *M = getOwningModule(E);
9746     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9747         << !M << (M ? M->getFullModuleName() : "");
9748   }
9749 }
9750 
9751 /// Computes the best viable function (C++ 13.3.3)
9752 /// within an overload candidate set.
9753 ///
9754 /// \param Loc The location of the function name (or operator symbol) for
9755 /// which overload resolution occurs.
9756 ///
9757 /// \param Best If overload resolution was successful or found a deleted
9758 /// function, \p Best points to the candidate function found.
9759 ///
9760 /// \returns The result of overload resolution.
9761 OverloadingResult
9762 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9763                                          iterator &Best) {
9764   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9765   std::transform(begin(), end(), std::back_inserter(Candidates),
9766                  [](OverloadCandidate &Cand) { return &Cand; });
9767 
9768   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9769   // are accepted by both clang and NVCC. However, during a particular
9770   // compilation mode only one call variant is viable. We need to
9771   // exclude non-viable overload candidates from consideration based
9772   // only on their host/device attributes. Specifically, if one
9773   // candidate call is WrongSide and the other is SameSide, we ignore
9774   // the WrongSide candidate.
9775   if (S.getLangOpts().CUDA) {
9776     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9777     bool ContainsSameSideCandidate =
9778         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9779           // Check viable function only.
9780           return Cand->Viable && Cand->Function &&
9781                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9782                      Sema::CFP_SameSide;
9783         });
9784     if (ContainsSameSideCandidate) {
9785       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9786         // Check viable function only to avoid unnecessary data copying/moving.
9787         return Cand->Viable && Cand->Function &&
9788                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9789                    Sema::CFP_WrongSide;
9790       };
9791       llvm::erase_if(Candidates, IsWrongSideCandidate);
9792     }
9793   }
9794 
9795   // Find the best viable function.
9796   Best = end();
9797   for (auto *Cand : Candidates) {
9798     Cand->Best = false;
9799     if (Cand->Viable)
9800       if (Best == end() ||
9801           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9802         Best = Cand;
9803   }
9804 
9805   // If we didn't find any viable functions, abort.
9806   if (Best == end())
9807     return OR_No_Viable_Function;
9808 
9809   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9810 
9811   llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
9812   PendingBest.push_back(&*Best);
9813   Best->Best = true;
9814 
9815   // Make sure that this function is better than every other viable
9816   // function. If not, we have an ambiguity.
9817   while (!PendingBest.empty()) {
9818     auto *Curr = PendingBest.pop_back_val();
9819     for (auto *Cand : Candidates) {
9820       if (Cand->Viable && !Cand->Best &&
9821           !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
9822         PendingBest.push_back(Cand);
9823         Cand->Best = true;
9824 
9825         if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
9826                                                      Curr->Function))
9827           EquivalentCands.push_back(Cand->Function);
9828         else
9829           Best = end();
9830       }
9831     }
9832   }
9833 
9834   // If we found more than one best candidate, this is ambiguous.
9835   if (Best == end())
9836     return OR_Ambiguous;
9837 
9838   // Best is the best viable function.
9839   if (Best->Function && Best->Function->isDeleted())
9840     return OR_Deleted;
9841 
9842   if (!EquivalentCands.empty())
9843     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9844                                                     EquivalentCands);
9845 
9846   return OR_Success;
9847 }
9848 
9849 namespace {
9850 
9851 enum OverloadCandidateKind {
9852   oc_function,
9853   oc_method,
9854   oc_reversed_binary_operator,
9855   oc_constructor,
9856   oc_implicit_default_constructor,
9857   oc_implicit_copy_constructor,
9858   oc_implicit_move_constructor,
9859   oc_implicit_copy_assignment,
9860   oc_implicit_move_assignment,
9861   oc_implicit_equality_comparison,
9862   oc_inherited_constructor
9863 };
9864 
9865 enum OverloadCandidateSelect {
9866   ocs_non_template,
9867   ocs_template,
9868   ocs_described_template,
9869 };
9870 
9871 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
9872 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9873                           OverloadCandidateRewriteKind CRK,
9874                           std::string &Description) {
9875 
9876   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9877   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9878     isTemplate = true;
9879     Description = S.getTemplateArgumentBindingsText(
9880         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9881   }
9882 
9883   OverloadCandidateSelect Select = [&]() {
9884     if (!Description.empty())
9885       return ocs_described_template;
9886     return isTemplate ? ocs_template : ocs_non_template;
9887   }();
9888 
9889   OverloadCandidateKind Kind = [&]() {
9890     if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
9891       return oc_implicit_equality_comparison;
9892 
9893     if (CRK & CRK_Reversed)
9894       return oc_reversed_binary_operator;
9895 
9896     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9897       if (!Ctor->isImplicit()) {
9898         if (isa<ConstructorUsingShadowDecl>(Found))
9899           return oc_inherited_constructor;
9900         else
9901           return oc_constructor;
9902       }
9903 
9904       if (Ctor->isDefaultConstructor())
9905         return oc_implicit_default_constructor;
9906 
9907       if (Ctor->isMoveConstructor())
9908         return oc_implicit_move_constructor;
9909 
9910       assert(Ctor->isCopyConstructor() &&
9911              "unexpected sort of implicit constructor");
9912       return oc_implicit_copy_constructor;
9913     }
9914 
9915     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9916       // This actually gets spelled 'candidate function' for now, but
9917       // it doesn't hurt to split it out.
9918       if (!Meth->isImplicit())
9919         return oc_method;
9920 
9921       if (Meth->isMoveAssignmentOperator())
9922         return oc_implicit_move_assignment;
9923 
9924       if (Meth->isCopyAssignmentOperator())
9925         return oc_implicit_copy_assignment;
9926 
9927       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9928       return oc_method;
9929     }
9930 
9931     return oc_function;
9932   }();
9933 
9934   return std::make_pair(Kind, Select);
9935 }
9936 
9937 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9938   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9939   // set.
9940   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9941     S.Diag(FoundDecl->getLocation(),
9942            diag::note_ovl_candidate_inherited_constructor)
9943       << Shadow->getNominatedBaseClass();
9944 }
9945 
9946 } // end anonymous namespace
9947 
9948 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9949                                     const FunctionDecl *FD) {
9950   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9951     bool AlwaysTrue;
9952     if (EnableIf->getCond()->isValueDependent() ||
9953         !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9954       return false;
9955     if (!AlwaysTrue)
9956       return false;
9957   }
9958   return true;
9959 }
9960 
9961 /// Returns true if we can take the address of the function.
9962 ///
9963 /// \param Complain - If true, we'll emit a diagnostic
9964 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9965 ///   we in overload resolution?
9966 /// \param Loc - The location of the statement we're complaining about. Ignored
9967 ///   if we're not complaining, or if we're in overload resolution.
9968 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9969                                               bool Complain,
9970                                               bool InOverloadResolution,
9971                                               SourceLocation Loc) {
9972   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9973     if (Complain) {
9974       if (InOverloadResolution)
9975         S.Diag(FD->getBeginLoc(),
9976                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9977       else
9978         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9979     }
9980     return false;
9981   }
9982 
9983   if (FD->getTrailingRequiresClause()) {
9984     ConstraintSatisfaction Satisfaction;
9985     if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
9986       return false;
9987     if (!Satisfaction.IsSatisfied) {
9988       if (Complain) {
9989         if (InOverloadResolution)
9990           S.Diag(FD->getBeginLoc(),
9991                  diag::note_ovl_candidate_unsatisfied_constraints);
9992         else
9993           S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
9994               << FD;
9995         S.DiagnoseUnsatisfiedConstraint(Satisfaction);
9996       }
9997       return false;
9998     }
9999   }
10000 
10001   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
10002     return P->hasAttr<PassObjectSizeAttr>();
10003   });
10004   if (I == FD->param_end())
10005     return true;
10006 
10007   if (Complain) {
10008     // Add one to ParamNo because it's user-facing
10009     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
10010     if (InOverloadResolution)
10011       S.Diag(FD->getLocation(),
10012              diag::note_ovl_candidate_has_pass_object_size_params)
10013           << ParamNo;
10014     else
10015       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
10016           << FD << ParamNo;
10017   }
10018   return false;
10019 }
10020 
10021 static bool checkAddressOfCandidateIsAvailable(Sema &S,
10022                                                const FunctionDecl *FD) {
10023   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
10024                                            /*InOverloadResolution=*/true,
10025                                            /*Loc=*/SourceLocation());
10026 }
10027 
10028 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10029                                              bool Complain,
10030                                              SourceLocation Loc) {
10031   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
10032                                              /*InOverloadResolution=*/false,
10033                                              Loc);
10034 }
10035 
10036 // Notes the location of an overload candidate.
10037 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
10038                                  OverloadCandidateRewriteKind RewriteKind,
10039                                  QualType DestType, bool TakingAddress) {
10040   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
10041     return;
10042   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
10043       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
10044     return;
10045 
10046   std::string FnDesc;
10047   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
10048       ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
10049   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
10050                          << (unsigned)KSPair.first << (unsigned)KSPair.second
10051                          << Fn << FnDesc;
10052 
10053   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
10054   Diag(Fn->getLocation(), PD);
10055   MaybeEmitInheritedConstructorNote(*this, Found);
10056 }
10057 
10058 static void
10059 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
10060   // Perhaps the ambiguity was caused by two atomic constraints that are
10061   // 'identical' but not equivalent:
10062   //
10063   // void foo() requires (sizeof(T) > 4) { } // #1
10064   // void foo() requires (sizeof(T) > 4) && T::value { } // #2
10065   //
10066   // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
10067   // #2 to subsume #1, but these constraint are not considered equivalent
10068   // according to the subsumption rules because they are not the same
10069   // source-level construct. This behavior is quite confusing and we should try
10070   // to help the user figure out what happened.
10071 
10072   SmallVector<const Expr *, 3> FirstAC, SecondAC;
10073   FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
10074   for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10075     if (!I->Function)
10076       continue;
10077     SmallVector<const Expr *, 3> AC;
10078     if (auto *Template = I->Function->getPrimaryTemplate())
10079       Template->getAssociatedConstraints(AC);
10080     else
10081       I->Function->getAssociatedConstraints(AC);
10082     if (AC.empty())
10083       continue;
10084     if (FirstCand == nullptr) {
10085       FirstCand = I->Function;
10086       FirstAC = AC;
10087     } else if (SecondCand == nullptr) {
10088       SecondCand = I->Function;
10089       SecondAC = AC;
10090     } else {
10091       // We have more than one pair of constrained functions - this check is
10092       // expensive and we'd rather not try to diagnose it.
10093       return;
10094     }
10095   }
10096   if (!SecondCand)
10097     return;
10098   // The diagnostic can only happen if there are associated constraints on
10099   // both sides (there needs to be some identical atomic constraint).
10100   if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
10101                                                       SecondCand, SecondAC))
10102     // Just show the user one diagnostic, they'll probably figure it out
10103     // from here.
10104     return;
10105 }
10106 
10107 // Notes the location of all overload candidates designated through
10108 // OverloadedExpr
10109 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
10110                                      bool TakingAddress) {
10111   assert(OverloadedExpr->getType() == Context.OverloadTy);
10112 
10113   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
10114   OverloadExpr *OvlExpr = Ovl.Expression;
10115 
10116   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10117                             IEnd = OvlExpr->decls_end();
10118        I != IEnd; ++I) {
10119     if (FunctionTemplateDecl *FunTmpl =
10120                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
10121       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
10122                             TakingAddress);
10123     } else if (FunctionDecl *Fun
10124                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
10125       NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
10126     }
10127   }
10128 }
10129 
10130 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
10131 /// "lead" diagnostic; it will be given two arguments, the source and
10132 /// target types of the conversion.
10133 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
10134                                  Sema &S,
10135                                  SourceLocation CaretLoc,
10136                                  const PartialDiagnostic &PDiag) const {
10137   S.Diag(CaretLoc, PDiag)
10138     << Ambiguous.getFromType() << Ambiguous.getToType();
10139   // FIXME: The note limiting machinery is borrowed from
10140   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
10141   // refactoring here.
10142   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10143   unsigned CandsShown = 0;
10144   AmbiguousConversionSequence::const_iterator I, E;
10145   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
10146     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10147       break;
10148     ++CandsShown;
10149     S.NoteOverloadCandidate(I->first, I->second);
10150   }
10151   if (I != E)
10152     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
10153 }
10154 
10155 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
10156                                   unsigned I, bool TakingCandidateAddress) {
10157   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
10158   assert(Conv.isBad());
10159   assert(Cand->Function && "for now, candidate must be a function");
10160   FunctionDecl *Fn = Cand->Function;
10161 
10162   // There's a conversion slot for the object argument if this is a
10163   // non-constructor method.  Note that 'I' corresponds the
10164   // conversion-slot index.
10165   bool isObjectArgument = false;
10166   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
10167     if (I == 0)
10168       isObjectArgument = true;
10169     else
10170       I--;
10171   }
10172 
10173   std::string FnDesc;
10174   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10175       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
10176                                 FnDesc);
10177 
10178   Expr *FromExpr = Conv.Bad.FromExpr;
10179   QualType FromTy = Conv.Bad.getFromType();
10180   QualType ToTy = Conv.Bad.getToType();
10181 
10182   if (FromTy == S.Context.OverloadTy) {
10183     assert(FromExpr && "overload set argument came from implicit argument?");
10184     Expr *E = FromExpr->IgnoreParens();
10185     if (isa<UnaryOperator>(E))
10186       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
10187     DeclarationName Name = cast<OverloadExpr>(E)->getName();
10188 
10189     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
10190         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10191         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
10192         << Name << I + 1;
10193     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10194     return;
10195   }
10196 
10197   // Do some hand-waving analysis to see if the non-viability is due
10198   // to a qualifier mismatch.
10199   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
10200   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
10201   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
10202     CToTy = RT->getPointeeType();
10203   else {
10204     // TODO: detect and diagnose the full richness of const mismatches.
10205     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
10206       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
10207         CFromTy = FromPT->getPointeeType();
10208         CToTy = ToPT->getPointeeType();
10209       }
10210   }
10211 
10212   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
10213       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
10214     Qualifiers FromQs = CFromTy.getQualifiers();
10215     Qualifiers ToQs = CToTy.getQualifiers();
10216 
10217     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
10218       if (isObjectArgument)
10219         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
10220             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10221             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10222             << FromQs.getAddressSpace() << ToQs.getAddressSpace();
10223       else
10224         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
10225             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10226             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10227             << FromQs.getAddressSpace() << ToQs.getAddressSpace()
10228             << ToTy->isReferenceType() << I + 1;
10229       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10230       return;
10231     }
10232 
10233     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10234       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
10235           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10236           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10237           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
10238           << (unsigned)isObjectArgument << I + 1;
10239       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10240       return;
10241     }
10242 
10243     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
10244       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
10245           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10246           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10247           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
10248           << (unsigned)isObjectArgument << I + 1;
10249       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10250       return;
10251     }
10252 
10253     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
10254       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
10255           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10256           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10257           << FromQs.hasUnaligned() << I + 1;
10258       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10259       return;
10260     }
10261 
10262     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
10263     assert(CVR && "unexpected qualifiers mismatch");
10264 
10265     if (isObjectArgument) {
10266       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
10267           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10268           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10269           << (CVR - 1);
10270     } else {
10271       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
10272           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10273           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10274           << (CVR - 1) << I + 1;
10275     }
10276     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10277     return;
10278   }
10279 
10280   // Special diagnostic for failure to convert an initializer list, since
10281   // telling the user that it has type void is not useful.
10282   if (FromExpr && isa<InitListExpr>(FromExpr)) {
10283     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
10284         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10285         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10286         << ToTy << (unsigned)isObjectArgument << I + 1;
10287     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10288     return;
10289   }
10290 
10291   // Diagnose references or pointers to incomplete types differently,
10292   // since it's far from impossible that the incompleteness triggered
10293   // the failure.
10294   QualType TempFromTy = FromTy.getNonReferenceType();
10295   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
10296     TempFromTy = PTy->getPointeeType();
10297   if (TempFromTy->isIncompleteType()) {
10298     // Emit the generic diagnostic and, optionally, add the hints to it.
10299     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
10300         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10301         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10302         << ToTy << (unsigned)isObjectArgument << I + 1
10303         << (unsigned)(Cand->Fix.Kind);
10304 
10305     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10306     return;
10307   }
10308 
10309   // Diagnose base -> derived pointer conversions.
10310   unsigned BaseToDerivedConversion = 0;
10311   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
10312     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
10313       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10314                                                FromPtrTy->getPointeeType()) &&
10315           !FromPtrTy->getPointeeType()->isIncompleteType() &&
10316           !ToPtrTy->getPointeeType()->isIncompleteType() &&
10317           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
10318                           FromPtrTy->getPointeeType()))
10319         BaseToDerivedConversion = 1;
10320     }
10321   } else if (const ObjCObjectPointerType *FromPtrTy
10322                                     = FromTy->getAs<ObjCObjectPointerType>()) {
10323     if (const ObjCObjectPointerType *ToPtrTy
10324                                         = ToTy->getAs<ObjCObjectPointerType>())
10325       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
10326         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
10327           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10328                                                 FromPtrTy->getPointeeType()) &&
10329               FromIface->isSuperClassOf(ToIface))
10330             BaseToDerivedConversion = 2;
10331   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
10332     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
10333         !FromTy->isIncompleteType() &&
10334         !ToRefTy->getPointeeType()->isIncompleteType() &&
10335         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
10336       BaseToDerivedConversion = 3;
10337     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
10338                ToTy.getNonReferenceType().getCanonicalType() ==
10339                FromTy.getNonReferenceType().getCanonicalType()) {
10340       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
10341           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10342           << (unsigned)isObjectArgument << I + 1
10343           << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
10344       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10345       return;
10346     }
10347   }
10348 
10349   if (BaseToDerivedConversion) {
10350     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
10351         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10352         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10353         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
10354     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10355     return;
10356   }
10357 
10358   if (isa<ObjCObjectPointerType>(CFromTy) &&
10359       isa<PointerType>(CToTy)) {
10360       Qualifiers FromQs = CFromTy.getQualifiers();
10361       Qualifiers ToQs = CToTy.getQualifiers();
10362       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10363         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
10364             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10365             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10366             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
10367         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10368         return;
10369       }
10370   }
10371 
10372   if (TakingCandidateAddress &&
10373       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
10374     return;
10375 
10376   // Emit the generic diagnostic and, optionally, add the hints to it.
10377   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
10378   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10379         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10380         << ToTy << (unsigned)isObjectArgument << I + 1
10381         << (unsigned)(Cand->Fix.Kind);
10382 
10383   // If we can fix the conversion, suggest the FixIts.
10384   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
10385        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
10386     FDiag << *HI;
10387   S.Diag(Fn->getLocation(), FDiag);
10388 
10389   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10390 }
10391 
10392 /// Additional arity mismatch diagnosis specific to a function overload
10393 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
10394 /// over a candidate in any candidate set.
10395 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
10396                                unsigned NumArgs) {
10397   FunctionDecl *Fn = Cand->Function;
10398   unsigned MinParams = Fn->getMinRequiredArguments();
10399 
10400   // With invalid overloaded operators, it's possible that we think we
10401   // have an arity mismatch when in fact it looks like we have the
10402   // right number of arguments, because only overloaded operators have
10403   // the weird behavior of overloading member and non-member functions.
10404   // Just don't report anything.
10405   if (Fn->isInvalidDecl() &&
10406       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
10407     return true;
10408 
10409   if (NumArgs < MinParams) {
10410     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
10411            (Cand->FailureKind == ovl_fail_bad_deduction &&
10412             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
10413   } else {
10414     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
10415            (Cand->FailureKind == ovl_fail_bad_deduction &&
10416             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
10417   }
10418 
10419   return false;
10420 }
10421 
10422 /// General arity mismatch diagnosis over a candidate in a candidate set.
10423 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
10424                                   unsigned NumFormalArgs) {
10425   assert(isa<FunctionDecl>(D) &&
10426       "The templated declaration should at least be a function"
10427       " when diagnosing bad template argument deduction due to too many"
10428       " or too few arguments");
10429 
10430   FunctionDecl *Fn = cast<FunctionDecl>(D);
10431 
10432   // TODO: treat calls to a missing default constructor as a special case
10433   const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
10434   unsigned MinParams = Fn->getMinRequiredArguments();
10435 
10436   // at least / at most / exactly
10437   unsigned mode, modeCount;
10438   if (NumFormalArgs < MinParams) {
10439     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
10440         FnTy->isTemplateVariadic())
10441       mode = 0; // "at least"
10442     else
10443       mode = 2; // "exactly"
10444     modeCount = MinParams;
10445   } else {
10446     if (MinParams != FnTy->getNumParams())
10447       mode = 1; // "at most"
10448     else
10449       mode = 2; // "exactly"
10450     modeCount = FnTy->getNumParams();
10451   }
10452 
10453   std::string Description;
10454   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10455       ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
10456 
10457   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10458     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10459         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10460         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
10461   else
10462     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
10463         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10464         << Description << mode << modeCount << NumFormalArgs;
10465 
10466   MaybeEmitInheritedConstructorNote(S, Found);
10467 }
10468 
10469 /// Arity mismatch diagnosis specific to a function overload candidate.
10470 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
10471                                   unsigned NumFormalArgs) {
10472   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
10473     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10474 }
10475 
10476 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10477   if (TemplateDecl *TD = Templated->getDescribedTemplate())
10478     return TD;
10479   llvm_unreachable("Unsupported: Getting the described template declaration"
10480                    " for bad deduction diagnosis");
10481 }
10482 
10483 /// Diagnose a failed template-argument deduction.
10484 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10485                                  DeductionFailureInfo &DeductionFailure,
10486                                  unsigned NumArgs,
10487                                  bool TakingCandidateAddress) {
10488   TemplateParameter Param = DeductionFailure.getTemplateParameter();
10489   NamedDecl *ParamD;
10490   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10491   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10492   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10493   switch (DeductionFailure.Result) {
10494   case Sema::TDK_Success:
10495     llvm_unreachable("TDK_success while diagnosing bad deduction");
10496 
10497   case Sema::TDK_Incomplete: {
10498     assert(ParamD && "no parameter found for incomplete deduction result");
10499     S.Diag(Templated->getLocation(),
10500            diag::note_ovl_candidate_incomplete_deduction)
10501         << ParamD->getDeclName();
10502     MaybeEmitInheritedConstructorNote(S, Found);
10503     return;
10504   }
10505 
10506   case Sema::TDK_IncompletePack: {
10507     assert(ParamD && "no parameter found for incomplete deduction result");
10508     S.Diag(Templated->getLocation(),
10509            diag::note_ovl_candidate_incomplete_deduction_pack)
10510         << ParamD->getDeclName()
10511         << (DeductionFailure.getFirstArg()->pack_size() + 1)
10512         << *DeductionFailure.getFirstArg();
10513     MaybeEmitInheritedConstructorNote(S, Found);
10514     return;
10515   }
10516 
10517   case Sema::TDK_Underqualified: {
10518     assert(ParamD && "no parameter found for bad qualifiers deduction result");
10519     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10520 
10521     QualType Param = DeductionFailure.getFirstArg()->getAsType();
10522 
10523     // Param will have been canonicalized, but it should just be a
10524     // qualified version of ParamD, so move the qualifiers to that.
10525     QualifierCollector Qs;
10526     Qs.strip(Param);
10527     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10528     assert(S.Context.hasSameType(Param, NonCanonParam));
10529 
10530     // Arg has also been canonicalized, but there's nothing we can do
10531     // about that.  It also doesn't matter as much, because it won't
10532     // have any template parameters in it (because deduction isn't
10533     // done on dependent types).
10534     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10535 
10536     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10537         << ParamD->getDeclName() << Arg << NonCanonParam;
10538     MaybeEmitInheritedConstructorNote(S, Found);
10539     return;
10540   }
10541 
10542   case Sema::TDK_Inconsistent: {
10543     assert(ParamD && "no parameter found for inconsistent deduction result");
10544     int which = 0;
10545     if (isa<TemplateTypeParmDecl>(ParamD))
10546       which = 0;
10547     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10548       // Deduction might have failed because we deduced arguments of two
10549       // different types for a non-type template parameter.
10550       // FIXME: Use a different TDK value for this.
10551       QualType T1 =
10552           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10553       QualType T2 =
10554           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10555       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10556         S.Diag(Templated->getLocation(),
10557                diag::note_ovl_candidate_inconsistent_deduction_types)
10558           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10559           << *DeductionFailure.getSecondArg() << T2;
10560         MaybeEmitInheritedConstructorNote(S, Found);
10561         return;
10562       }
10563 
10564       which = 1;
10565     } else {
10566       which = 2;
10567     }
10568 
10569     // Tweak the diagnostic if the problem is that we deduced packs of
10570     // different arities. We'll print the actual packs anyway in case that
10571     // includes additional useful information.
10572     if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
10573         DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
10574         DeductionFailure.getFirstArg()->pack_size() !=
10575             DeductionFailure.getSecondArg()->pack_size()) {
10576       which = 3;
10577     }
10578 
10579     S.Diag(Templated->getLocation(),
10580            diag::note_ovl_candidate_inconsistent_deduction)
10581         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10582         << *DeductionFailure.getSecondArg();
10583     MaybeEmitInheritedConstructorNote(S, Found);
10584     return;
10585   }
10586 
10587   case Sema::TDK_InvalidExplicitArguments:
10588     assert(ParamD && "no parameter found for invalid explicit arguments");
10589     if (ParamD->getDeclName())
10590       S.Diag(Templated->getLocation(),
10591              diag::note_ovl_candidate_explicit_arg_mismatch_named)
10592           << ParamD->getDeclName();
10593     else {
10594       int index = 0;
10595       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10596         index = TTP->getIndex();
10597       else if (NonTypeTemplateParmDecl *NTTP
10598                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10599         index = NTTP->getIndex();
10600       else
10601         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10602       S.Diag(Templated->getLocation(),
10603              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10604           << (index + 1);
10605     }
10606     MaybeEmitInheritedConstructorNote(S, Found);
10607     return;
10608 
10609   case Sema::TDK_ConstraintsNotSatisfied: {
10610     // Format the template argument list into the argument string.
10611     SmallString<128> TemplateArgString;
10612     TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
10613     TemplateArgString = " ";
10614     TemplateArgString += S.getTemplateArgumentBindingsText(
10615         getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10616     if (TemplateArgString.size() == 1)
10617       TemplateArgString.clear();
10618     S.Diag(Templated->getLocation(),
10619            diag::note_ovl_candidate_unsatisfied_constraints)
10620         << TemplateArgString;
10621 
10622     S.DiagnoseUnsatisfiedConstraint(
10623         static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
10624     return;
10625   }
10626   case Sema::TDK_TooManyArguments:
10627   case Sema::TDK_TooFewArguments:
10628     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10629     return;
10630 
10631   case Sema::TDK_InstantiationDepth:
10632     S.Diag(Templated->getLocation(),
10633            diag::note_ovl_candidate_instantiation_depth);
10634     MaybeEmitInheritedConstructorNote(S, Found);
10635     return;
10636 
10637   case Sema::TDK_SubstitutionFailure: {
10638     // Format the template argument list into the argument string.
10639     SmallString<128> TemplateArgString;
10640     if (TemplateArgumentList *Args =
10641             DeductionFailure.getTemplateArgumentList()) {
10642       TemplateArgString = " ";
10643       TemplateArgString += S.getTemplateArgumentBindingsText(
10644           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10645       if (TemplateArgString.size() == 1)
10646         TemplateArgString.clear();
10647     }
10648 
10649     // If this candidate was disabled by enable_if, say so.
10650     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10651     if (PDiag && PDiag->second.getDiagID() ==
10652           diag::err_typename_nested_not_found_enable_if) {
10653       // FIXME: Use the source range of the condition, and the fully-qualified
10654       //        name of the enable_if template. These are both present in PDiag.
10655       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10656         << "'enable_if'" << TemplateArgString;
10657       return;
10658     }
10659 
10660     // We found a specific requirement that disabled the enable_if.
10661     if (PDiag && PDiag->second.getDiagID() ==
10662         diag::err_typename_nested_not_found_requirement) {
10663       S.Diag(Templated->getLocation(),
10664              diag::note_ovl_candidate_disabled_by_requirement)
10665         << PDiag->second.getStringArg(0) << TemplateArgString;
10666       return;
10667     }
10668 
10669     // Format the SFINAE diagnostic into the argument string.
10670     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10671     //        formatted message in another diagnostic.
10672     SmallString<128> SFINAEArgString;
10673     SourceRange R;
10674     if (PDiag) {
10675       SFINAEArgString = ": ";
10676       R = SourceRange(PDiag->first, PDiag->first);
10677       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10678     }
10679 
10680     S.Diag(Templated->getLocation(),
10681            diag::note_ovl_candidate_substitution_failure)
10682         << TemplateArgString << SFINAEArgString << R;
10683     MaybeEmitInheritedConstructorNote(S, Found);
10684     return;
10685   }
10686 
10687   case Sema::TDK_DeducedMismatch:
10688   case Sema::TDK_DeducedMismatchNested: {
10689     // Format the template argument list into the argument string.
10690     SmallString<128> TemplateArgString;
10691     if (TemplateArgumentList *Args =
10692             DeductionFailure.getTemplateArgumentList()) {
10693       TemplateArgString = " ";
10694       TemplateArgString += S.getTemplateArgumentBindingsText(
10695           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10696       if (TemplateArgString.size() == 1)
10697         TemplateArgString.clear();
10698     }
10699 
10700     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10701         << (*DeductionFailure.getCallArgIndex() + 1)
10702         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10703         << TemplateArgString
10704         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10705     break;
10706   }
10707 
10708   case Sema::TDK_NonDeducedMismatch: {
10709     // FIXME: Provide a source location to indicate what we couldn't match.
10710     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10711     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10712     if (FirstTA.getKind() == TemplateArgument::Template &&
10713         SecondTA.getKind() == TemplateArgument::Template) {
10714       TemplateName FirstTN = FirstTA.getAsTemplate();
10715       TemplateName SecondTN = SecondTA.getAsTemplate();
10716       if (FirstTN.getKind() == TemplateName::Template &&
10717           SecondTN.getKind() == TemplateName::Template) {
10718         if (FirstTN.getAsTemplateDecl()->getName() ==
10719             SecondTN.getAsTemplateDecl()->getName()) {
10720           // FIXME: This fixes a bad diagnostic where both templates are named
10721           // the same.  This particular case is a bit difficult since:
10722           // 1) It is passed as a string to the diagnostic printer.
10723           // 2) The diagnostic printer only attempts to find a better
10724           //    name for types, not decls.
10725           // Ideally, this should folded into the diagnostic printer.
10726           S.Diag(Templated->getLocation(),
10727                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10728               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10729           return;
10730         }
10731       }
10732     }
10733 
10734     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10735         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10736       return;
10737 
10738     // FIXME: For generic lambda parameters, check if the function is a lambda
10739     // call operator, and if so, emit a prettier and more informative
10740     // diagnostic that mentions 'auto' and lambda in addition to
10741     // (or instead of?) the canonical template type parameters.
10742     S.Diag(Templated->getLocation(),
10743            diag::note_ovl_candidate_non_deduced_mismatch)
10744         << FirstTA << SecondTA;
10745     return;
10746   }
10747   // TODO: diagnose these individually, then kill off
10748   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10749   case Sema::TDK_MiscellaneousDeductionFailure:
10750     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10751     MaybeEmitInheritedConstructorNote(S, Found);
10752     return;
10753   case Sema::TDK_CUDATargetMismatch:
10754     S.Diag(Templated->getLocation(),
10755            diag::note_cuda_ovl_candidate_target_mismatch);
10756     return;
10757   }
10758 }
10759 
10760 /// Diagnose a failed template-argument deduction, for function calls.
10761 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10762                                  unsigned NumArgs,
10763                                  bool TakingCandidateAddress) {
10764   unsigned TDK = Cand->DeductionFailure.Result;
10765   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10766     if (CheckArityMismatch(S, Cand, NumArgs))
10767       return;
10768   }
10769   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10770                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10771 }
10772 
10773 /// CUDA: diagnose an invalid call across targets.
10774 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10775   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10776   FunctionDecl *Callee = Cand->Function;
10777 
10778   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10779                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10780 
10781   std::string FnDesc;
10782   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10783       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
10784                                 Cand->getRewriteKind(), FnDesc);
10785 
10786   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10787       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10788       << FnDesc /* Ignored */
10789       << CalleeTarget << CallerTarget;
10790 
10791   // This could be an implicit constructor for which we could not infer the
10792   // target due to a collsion. Diagnose that case.
10793   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10794   if (Meth != nullptr && Meth->isImplicit()) {
10795     CXXRecordDecl *ParentClass = Meth->getParent();
10796     Sema::CXXSpecialMember CSM;
10797 
10798     switch (FnKindPair.first) {
10799     default:
10800       return;
10801     case oc_implicit_default_constructor:
10802       CSM = Sema::CXXDefaultConstructor;
10803       break;
10804     case oc_implicit_copy_constructor:
10805       CSM = Sema::CXXCopyConstructor;
10806       break;
10807     case oc_implicit_move_constructor:
10808       CSM = Sema::CXXMoveConstructor;
10809       break;
10810     case oc_implicit_copy_assignment:
10811       CSM = Sema::CXXCopyAssignment;
10812       break;
10813     case oc_implicit_move_assignment:
10814       CSM = Sema::CXXMoveAssignment;
10815       break;
10816     };
10817 
10818     bool ConstRHS = false;
10819     if (Meth->getNumParams()) {
10820       if (const ReferenceType *RT =
10821               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10822         ConstRHS = RT->getPointeeType().isConstQualified();
10823       }
10824     }
10825 
10826     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10827                                               /* ConstRHS */ ConstRHS,
10828                                               /* Diagnose */ true);
10829   }
10830 }
10831 
10832 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10833   FunctionDecl *Callee = Cand->Function;
10834   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10835 
10836   S.Diag(Callee->getLocation(),
10837          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10838       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10839 }
10840 
10841 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
10842   ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function);
10843   assert(ES.isExplicit() && "not an explicit candidate");
10844 
10845   unsigned Kind;
10846   switch (Cand->Function->getDeclKind()) {
10847   case Decl::Kind::CXXConstructor:
10848     Kind = 0;
10849     break;
10850   case Decl::Kind::CXXConversion:
10851     Kind = 1;
10852     break;
10853   case Decl::Kind::CXXDeductionGuide:
10854     Kind = Cand->Function->isImplicit() ? 0 : 2;
10855     break;
10856   default:
10857     llvm_unreachable("invalid Decl");
10858   }
10859 
10860   // Note the location of the first (in-class) declaration; a redeclaration
10861   // (particularly an out-of-class definition) will typically lack the
10862   // 'explicit' specifier.
10863   // FIXME: This is probably a good thing to do for all 'candidate' notes.
10864   FunctionDecl *First = Cand->Function->getFirstDecl();
10865   if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
10866     First = Pattern->getFirstDecl();
10867 
10868   S.Diag(First->getLocation(),
10869          diag::note_ovl_candidate_explicit)
10870       << Kind << (ES.getExpr() ? 1 : 0)
10871       << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
10872 }
10873 
10874 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10875   FunctionDecl *Callee = Cand->Function;
10876 
10877   S.Diag(Callee->getLocation(),
10878          diag::note_ovl_candidate_disabled_by_extension)
10879     << S.getOpenCLExtensionsFromDeclExtMap(Callee);
10880 }
10881 
10882 /// Generates a 'note' diagnostic for an overload candidate.  We've
10883 /// already generated a primary error at the call site.
10884 ///
10885 /// It really does need to be a single diagnostic with its caret
10886 /// pointed at the candidate declaration.  Yes, this creates some
10887 /// major challenges of technical writing.  Yes, this makes pointing
10888 /// out problems with specific arguments quite awkward.  It's still
10889 /// better than generating twenty screens of text for every failed
10890 /// overload.
10891 ///
10892 /// It would be great to be able to express per-candidate problems
10893 /// more richly for those diagnostic clients that cared, but we'd
10894 /// still have to be just as careful with the default diagnostics.
10895 /// \param CtorDestAS Addr space of object being constructed (for ctor
10896 /// candidates only).
10897 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10898                                   unsigned NumArgs,
10899                                   bool TakingCandidateAddress,
10900                                   LangAS CtorDestAS = LangAS::Default) {
10901   FunctionDecl *Fn = Cand->Function;
10902 
10903   // Note deleted candidates, but only if they're viable.
10904   if (Cand->Viable) {
10905     if (Fn->isDeleted()) {
10906       std::string FnDesc;
10907       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10908           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
10909                                     Cand->getRewriteKind(), FnDesc);
10910 
10911       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10912           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10913           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10914       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10915       return;
10916     }
10917 
10918     // We don't really have anything else to say about viable candidates.
10919     S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10920     return;
10921   }
10922 
10923   switch (Cand->FailureKind) {
10924   case ovl_fail_too_many_arguments:
10925   case ovl_fail_too_few_arguments:
10926     return DiagnoseArityMismatch(S, Cand, NumArgs);
10927 
10928   case ovl_fail_bad_deduction:
10929     return DiagnoseBadDeduction(S, Cand, NumArgs,
10930                                 TakingCandidateAddress);
10931 
10932   case ovl_fail_illegal_constructor: {
10933     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10934       << (Fn->getPrimaryTemplate() ? 1 : 0);
10935     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10936     return;
10937   }
10938 
10939   case ovl_fail_object_addrspace_mismatch: {
10940     Qualifiers QualsForPrinting;
10941     QualsForPrinting.setAddressSpace(CtorDestAS);
10942     S.Diag(Fn->getLocation(),
10943            diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
10944         << QualsForPrinting;
10945     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10946     return;
10947   }
10948 
10949   case ovl_fail_trivial_conversion:
10950   case ovl_fail_bad_final_conversion:
10951   case ovl_fail_final_conversion_not_exact:
10952     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10953 
10954   case ovl_fail_bad_conversion: {
10955     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10956     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10957       if (Cand->Conversions[I].isBad())
10958         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10959 
10960     // FIXME: this currently happens when we're called from SemaInit
10961     // when user-conversion overload fails.  Figure out how to handle
10962     // those conditions and diagnose them well.
10963     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10964   }
10965 
10966   case ovl_fail_bad_target:
10967     return DiagnoseBadTarget(S, Cand);
10968 
10969   case ovl_fail_enable_if:
10970     return DiagnoseFailedEnableIfAttr(S, Cand);
10971 
10972   case ovl_fail_explicit:
10973     return DiagnoseFailedExplicitSpec(S, Cand);
10974 
10975   case ovl_fail_ext_disabled:
10976     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10977 
10978   case ovl_fail_inhctor_slice:
10979     // It's generally not interesting to note copy/move constructors here.
10980     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10981       return;
10982     S.Diag(Fn->getLocation(),
10983            diag::note_ovl_candidate_inherited_constructor_slice)
10984       << (Fn->getPrimaryTemplate() ? 1 : 0)
10985       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10986     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10987     return;
10988 
10989   case ovl_fail_addr_not_available: {
10990     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10991     (void)Available;
10992     assert(!Available);
10993     break;
10994   }
10995   case ovl_non_default_multiversion_function:
10996     // Do nothing, these should simply be ignored.
10997     break;
10998 
10999   case ovl_fail_constraints_not_satisfied: {
11000     std::string FnDesc;
11001     std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11002         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11003                                   Cand->getRewriteKind(), FnDesc);
11004 
11005     S.Diag(Fn->getLocation(),
11006            diag::note_ovl_candidate_constraints_not_satisfied)
11007         << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11008         << FnDesc /* Ignored */;
11009     ConstraintSatisfaction Satisfaction;
11010     if (S.CheckFunctionConstraints(Fn, Satisfaction))
11011       break;
11012     S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11013   }
11014   }
11015 }
11016 
11017 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
11018   // Desugar the type of the surrogate down to a function type,
11019   // retaining as many typedefs as possible while still showing
11020   // the function type (and, therefore, its parameter types).
11021   QualType FnType = Cand->Surrogate->getConversionType();
11022   bool isLValueReference = false;
11023   bool isRValueReference = false;
11024   bool isPointer = false;
11025   if (const LValueReferenceType *FnTypeRef =
11026         FnType->getAs<LValueReferenceType>()) {
11027     FnType = FnTypeRef->getPointeeType();
11028     isLValueReference = true;
11029   } else if (const RValueReferenceType *FnTypeRef =
11030                FnType->getAs<RValueReferenceType>()) {
11031     FnType = FnTypeRef->getPointeeType();
11032     isRValueReference = true;
11033   }
11034   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
11035     FnType = FnTypePtr->getPointeeType();
11036     isPointer = true;
11037   }
11038   // Desugar down to a function type.
11039   FnType = QualType(FnType->getAs<FunctionType>(), 0);
11040   // Reconstruct the pointer/reference as appropriate.
11041   if (isPointer) FnType = S.Context.getPointerType(FnType);
11042   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
11043   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
11044 
11045   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
11046     << FnType;
11047 }
11048 
11049 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
11050                                          SourceLocation OpLoc,
11051                                          OverloadCandidate *Cand) {
11052   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
11053   std::string TypeStr("operator");
11054   TypeStr += Opc;
11055   TypeStr += "(";
11056   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
11057   if (Cand->Conversions.size() == 1) {
11058     TypeStr += ")";
11059     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11060   } else {
11061     TypeStr += ", ";
11062     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
11063     TypeStr += ")";
11064     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11065   }
11066 }
11067 
11068 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
11069                                          OverloadCandidate *Cand) {
11070   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
11071     if (ICS.isBad()) break; // all meaningless after first invalid
11072     if (!ICS.isAmbiguous()) continue;
11073 
11074     ICS.DiagnoseAmbiguousConversion(
11075         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
11076   }
11077 }
11078 
11079 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
11080   if (Cand->Function)
11081     return Cand->Function->getLocation();
11082   if (Cand->IsSurrogate)
11083     return Cand->Surrogate->getLocation();
11084   return SourceLocation();
11085 }
11086 
11087 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
11088   switch ((Sema::TemplateDeductionResult)DFI.Result) {
11089   case Sema::TDK_Success:
11090   case Sema::TDK_NonDependentConversionFailure:
11091     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
11092 
11093   case Sema::TDK_Invalid:
11094   case Sema::TDK_Incomplete:
11095   case Sema::TDK_IncompletePack:
11096     return 1;
11097 
11098   case Sema::TDK_Underqualified:
11099   case Sema::TDK_Inconsistent:
11100     return 2;
11101 
11102   case Sema::TDK_SubstitutionFailure:
11103   case Sema::TDK_DeducedMismatch:
11104   case Sema::TDK_ConstraintsNotSatisfied:
11105   case Sema::TDK_DeducedMismatchNested:
11106   case Sema::TDK_NonDeducedMismatch:
11107   case Sema::TDK_MiscellaneousDeductionFailure:
11108   case Sema::TDK_CUDATargetMismatch:
11109     return 3;
11110 
11111   case Sema::TDK_InstantiationDepth:
11112     return 4;
11113 
11114   case Sema::TDK_InvalidExplicitArguments:
11115     return 5;
11116 
11117   case Sema::TDK_TooManyArguments:
11118   case Sema::TDK_TooFewArguments:
11119     return 6;
11120   }
11121   llvm_unreachable("Unhandled deduction result");
11122 }
11123 
11124 namespace {
11125 struct CompareOverloadCandidatesForDisplay {
11126   Sema &S;
11127   SourceLocation Loc;
11128   size_t NumArgs;
11129   OverloadCandidateSet::CandidateSetKind CSK;
11130 
11131   CompareOverloadCandidatesForDisplay(
11132       Sema &S, SourceLocation Loc, size_t NArgs,
11133       OverloadCandidateSet::CandidateSetKind CSK)
11134       : S(S), NumArgs(NArgs), CSK(CSK) {}
11135 
11136   OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
11137     // If there are too many or too few arguments, that's the high-order bit we
11138     // want to sort by, even if the immediate failure kind was something else.
11139     if (C->FailureKind == ovl_fail_too_many_arguments ||
11140         C->FailureKind == ovl_fail_too_few_arguments)
11141       return static_cast<OverloadFailureKind>(C->FailureKind);
11142 
11143     if (C->Function) {
11144       if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
11145         return ovl_fail_too_many_arguments;
11146       if (NumArgs < C->Function->getMinRequiredArguments())
11147         return ovl_fail_too_few_arguments;
11148     }
11149 
11150     return static_cast<OverloadFailureKind>(C->FailureKind);
11151   }
11152 
11153   bool operator()(const OverloadCandidate *L,
11154                   const OverloadCandidate *R) {
11155     // Fast-path this check.
11156     if (L == R) return false;
11157 
11158     // Order first by viability.
11159     if (L->Viable) {
11160       if (!R->Viable) return true;
11161 
11162       // TODO: introduce a tri-valued comparison for overload
11163       // candidates.  Would be more worthwhile if we had a sort
11164       // that could exploit it.
11165       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
11166         return true;
11167       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
11168         return false;
11169     } else if (R->Viable)
11170       return false;
11171 
11172     assert(L->Viable == R->Viable);
11173 
11174     // Criteria by which we can sort non-viable candidates:
11175     if (!L->Viable) {
11176       OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
11177       OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
11178 
11179       // 1. Arity mismatches come after other candidates.
11180       if (LFailureKind == ovl_fail_too_many_arguments ||
11181           LFailureKind == ovl_fail_too_few_arguments) {
11182         if (RFailureKind == ovl_fail_too_many_arguments ||
11183             RFailureKind == ovl_fail_too_few_arguments) {
11184           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
11185           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
11186           if (LDist == RDist) {
11187             if (LFailureKind == RFailureKind)
11188               // Sort non-surrogates before surrogates.
11189               return !L->IsSurrogate && R->IsSurrogate;
11190             // Sort candidates requiring fewer parameters than there were
11191             // arguments given after candidates requiring more parameters
11192             // than there were arguments given.
11193             return LFailureKind == ovl_fail_too_many_arguments;
11194           }
11195           return LDist < RDist;
11196         }
11197         return false;
11198       }
11199       if (RFailureKind == ovl_fail_too_many_arguments ||
11200           RFailureKind == ovl_fail_too_few_arguments)
11201         return true;
11202 
11203       // 2. Bad conversions come first and are ordered by the number
11204       // of bad conversions and quality of good conversions.
11205       if (LFailureKind == ovl_fail_bad_conversion) {
11206         if (RFailureKind != ovl_fail_bad_conversion)
11207           return true;
11208 
11209         // The conversion that can be fixed with a smaller number of changes,
11210         // comes first.
11211         unsigned numLFixes = L->Fix.NumConversionsFixed;
11212         unsigned numRFixes = R->Fix.NumConversionsFixed;
11213         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
11214         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
11215         if (numLFixes != numRFixes) {
11216           return numLFixes < numRFixes;
11217         }
11218 
11219         // If there's any ordering between the defined conversions...
11220         // FIXME: this might not be transitive.
11221         assert(L->Conversions.size() == R->Conversions.size());
11222 
11223         int leftBetter = 0;
11224         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
11225         for (unsigned E = L->Conversions.size(); I != E; ++I) {
11226           switch (CompareImplicitConversionSequences(S, Loc,
11227                                                      L->Conversions[I],
11228                                                      R->Conversions[I])) {
11229           case ImplicitConversionSequence::Better:
11230             leftBetter++;
11231             break;
11232 
11233           case ImplicitConversionSequence::Worse:
11234             leftBetter--;
11235             break;
11236 
11237           case ImplicitConversionSequence::Indistinguishable:
11238             break;
11239           }
11240         }
11241         if (leftBetter > 0) return true;
11242         if (leftBetter < 0) return false;
11243 
11244       } else if (RFailureKind == ovl_fail_bad_conversion)
11245         return false;
11246 
11247       if (LFailureKind == ovl_fail_bad_deduction) {
11248         if (RFailureKind != ovl_fail_bad_deduction)
11249           return true;
11250 
11251         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11252           return RankDeductionFailure(L->DeductionFailure)
11253                < RankDeductionFailure(R->DeductionFailure);
11254       } else if (RFailureKind == ovl_fail_bad_deduction)
11255         return false;
11256 
11257       // TODO: others?
11258     }
11259 
11260     // Sort everything else by location.
11261     SourceLocation LLoc = GetLocationForCandidate(L);
11262     SourceLocation RLoc = GetLocationForCandidate(R);
11263 
11264     // Put candidates without locations (e.g. builtins) at the end.
11265     if (LLoc.isInvalid()) return false;
11266     if (RLoc.isInvalid()) return true;
11267 
11268     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11269   }
11270 };
11271 }
11272 
11273 /// CompleteNonViableCandidate - Normally, overload resolution only
11274 /// computes up to the first bad conversion. Produces the FixIt set if
11275 /// possible.
11276 static void
11277 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
11278                            ArrayRef<Expr *> Args,
11279                            OverloadCandidateSet::CandidateSetKind CSK) {
11280   assert(!Cand->Viable);
11281 
11282   // Don't do anything on failures other than bad conversion.
11283   if (Cand->FailureKind != ovl_fail_bad_conversion)
11284     return;
11285 
11286   // We only want the FixIts if all the arguments can be corrected.
11287   bool Unfixable = false;
11288   // Use a implicit copy initialization to check conversion fixes.
11289   Cand->Fix.setConversionChecker(TryCopyInitialization);
11290 
11291   // Attempt to fix the bad conversion.
11292   unsigned ConvCount = Cand->Conversions.size();
11293   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
11294        ++ConvIdx) {
11295     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
11296     if (Cand->Conversions[ConvIdx].isInitialized() &&
11297         Cand->Conversions[ConvIdx].isBad()) {
11298       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11299       break;
11300     }
11301   }
11302 
11303   // FIXME: this should probably be preserved from the overload
11304   // operation somehow.
11305   bool SuppressUserConversions = false;
11306 
11307   unsigned ConvIdx = 0;
11308   unsigned ArgIdx = 0;
11309   ArrayRef<QualType> ParamTypes;
11310   bool Reversed = Cand->isReversed();
11311 
11312   if (Cand->IsSurrogate) {
11313     QualType ConvType
11314       = Cand->Surrogate->getConversionType().getNonReferenceType();
11315     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11316       ConvType = ConvPtrType->getPointeeType();
11317     ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
11318     // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11319     ConvIdx = 1;
11320   } else if (Cand->Function) {
11321     ParamTypes =
11322         Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
11323     if (isa<CXXMethodDecl>(Cand->Function) &&
11324         !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
11325       // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11326       ConvIdx = 1;
11327       if (CSK == OverloadCandidateSet::CSK_Operator &&
11328           Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call)
11329         // Argument 0 is 'this', which doesn't have a corresponding parameter.
11330         ArgIdx = 1;
11331     }
11332   } else {
11333     // Builtin operator.
11334     assert(ConvCount <= 3);
11335     ParamTypes = Cand->BuiltinParamTypes;
11336   }
11337 
11338   // Fill in the rest of the conversions.
11339   for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
11340        ConvIdx != ConvCount;
11341        ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
11342     assert(ArgIdx < Args.size() && "no argument for this arg conversion");
11343     if (Cand->Conversions[ConvIdx].isInitialized()) {
11344       // We've already checked this conversion.
11345     } else if (ParamIdx < ParamTypes.size()) {
11346       if (ParamTypes[ParamIdx]->isDependentType())
11347         Cand->Conversions[ConvIdx].setAsIdentityConversion(
11348             Args[ArgIdx]->getType());
11349       else {
11350         Cand->Conversions[ConvIdx] =
11351             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
11352                                   SuppressUserConversions,
11353                                   /*InOverloadResolution=*/true,
11354                                   /*AllowObjCWritebackConversion=*/
11355                                   S.getLangOpts().ObjCAutoRefCount);
11356         // Store the FixIt in the candidate if it exists.
11357         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
11358           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11359       }
11360     } else
11361       Cand->Conversions[ConvIdx].setEllipsis();
11362   }
11363 }
11364 
11365 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
11366     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11367     SourceLocation OpLoc,
11368     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11369   // Sort the candidates by viability and position.  Sorting directly would
11370   // be prohibitive, so we make a set of pointers and sort those.
11371   SmallVector<OverloadCandidate*, 32> Cands;
11372   if (OCD == OCD_AllCandidates) Cands.reserve(size());
11373   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11374     if (!Filter(*Cand))
11375       continue;
11376     switch (OCD) {
11377     case OCD_AllCandidates:
11378       if (!Cand->Viable) {
11379         if (!Cand->Function && !Cand->IsSurrogate) {
11380           // This a non-viable builtin candidate.  We do not, in general,
11381           // want to list every possible builtin candidate.
11382           continue;
11383         }
11384         CompleteNonViableCandidate(S, Cand, Args, Kind);
11385       }
11386       break;
11387 
11388     case OCD_ViableCandidates:
11389       if (!Cand->Viable)
11390         continue;
11391       break;
11392 
11393     case OCD_AmbiguousCandidates:
11394       if (!Cand->Best)
11395         continue;
11396       break;
11397     }
11398 
11399     Cands.push_back(Cand);
11400   }
11401 
11402   llvm::stable_sort(
11403       Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
11404 
11405   return Cands;
11406 }
11407 
11408 /// When overload resolution fails, prints diagnostic messages containing the
11409 /// candidates in the candidate set.
11410 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD,
11411     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11412     StringRef Opc, SourceLocation OpLoc,
11413     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11414 
11415   auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
11416 
11417   S.Diag(PD.first, PD.second);
11418 
11419   NoteCandidates(S, Args, Cands, Opc, OpLoc);
11420 
11421   if (OCD == OCD_AmbiguousCandidates)
11422     MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
11423 }
11424 
11425 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
11426                                           ArrayRef<OverloadCandidate *> Cands,
11427                                           StringRef Opc, SourceLocation OpLoc) {
11428   bool ReportedAmbiguousConversions = false;
11429 
11430   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11431   unsigned CandsShown = 0;
11432   auto I = Cands.begin(), E = Cands.end();
11433   for (; I != E; ++I) {
11434     OverloadCandidate *Cand = *I;
11435 
11436     // Set an arbitrary limit on the number of candidate functions we'll spam
11437     // the user with.  FIXME: This limit should depend on details of the
11438     // candidate list.
11439     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
11440       break;
11441     }
11442     ++CandsShown;
11443 
11444     if (Cand->Function)
11445       NoteFunctionCandidate(S, Cand, Args.size(),
11446                             /*TakingCandidateAddress=*/false, DestAS);
11447     else if (Cand->IsSurrogate)
11448       NoteSurrogateCandidate(S, Cand);
11449     else {
11450       assert(Cand->Viable &&
11451              "Non-viable built-in candidates are not added to Cands.");
11452       // Generally we only see ambiguities including viable builtin
11453       // operators if overload resolution got screwed up by an
11454       // ambiguous user-defined conversion.
11455       //
11456       // FIXME: It's quite possible for different conversions to see
11457       // different ambiguities, though.
11458       if (!ReportedAmbiguousConversions) {
11459         NoteAmbiguousUserConversions(S, OpLoc, Cand);
11460         ReportedAmbiguousConversions = true;
11461       }
11462 
11463       // If this is a viable builtin, print it.
11464       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
11465     }
11466   }
11467 
11468   if (I != E)
11469     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
11470 }
11471 
11472 static SourceLocation
11473 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
11474   return Cand->Specialization ? Cand->Specialization->getLocation()
11475                               : SourceLocation();
11476 }
11477 
11478 namespace {
11479 struct CompareTemplateSpecCandidatesForDisplay {
11480   Sema &S;
11481   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
11482 
11483   bool operator()(const TemplateSpecCandidate *L,
11484                   const TemplateSpecCandidate *R) {
11485     // Fast-path this check.
11486     if (L == R)
11487       return false;
11488 
11489     // Assuming that both candidates are not matches...
11490 
11491     // Sort by the ranking of deduction failures.
11492     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11493       return RankDeductionFailure(L->DeductionFailure) <
11494              RankDeductionFailure(R->DeductionFailure);
11495 
11496     // Sort everything else by location.
11497     SourceLocation LLoc = GetLocationForCandidate(L);
11498     SourceLocation RLoc = GetLocationForCandidate(R);
11499 
11500     // Put candidates without locations (e.g. builtins) at the end.
11501     if (LLoc.isInvalid())
11502       return false;
11503     if (RLoc.isInvalid())
11504       return true;
11505 
11506     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11507   }
11508 };
11509 }
11510 
11511 /// Diagnose a template argument deduction failure.
11512 /// We are treating these failures as overload failures due to bad
11513 /// deductions.
11514 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
11515                                                  bool ForTakingAddress) {
11516   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
11517                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
11518 }
11519 
11520 void TemplateSpecCandidateSet::destroyCandidates() {
11521   for (iterator i = begin(), e = end(); i != e; ++i) {
11522     i->DeductionFailure.Destroy();
11523   }
11524 }
11525 
11526 void TemplateSpecCandidateSet::clear() {
11527   destroyCandidates();
11528   Candidates.clear();
11529 }
11530 
11531 /// NoteCandidates - When no template specialization match is found, prints
11532 /// diagnostic messages containing the non-matching specializations that form
11533 /// the candidate set.
11534 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
11535 /// OCD == OCD_AllCandidates and Cand->Viable == false.
11536 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
11537   // Sort the candidates by position (assuming no candidate is a match).
11538   // Sorting directly would be prohibitive, so we make a set of pointers
11539   // and sort those.
11540   SmallVector<TemplateSpecCandidate *, 32> Cands;
11541   Cands.reserve(size());
11542   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11543     if (Cand->Specialization)
11544       Cands.push_back(Cand);
11545     // Otherwise, this is a non-matching builtin candidate.  We do not,
11546     // in general, want to list every possible builtin candidate.
11547   }
11548 
11549   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
11550 
11551   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
11552   // for generalization purposes (?).
11553   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11554 
11555   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
11556   unsigned CandsShown = 0;
11557   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11558     TemplateSpecCandidate *Cand = *I;
11559 
11560     // Set an arbitrary limit on the number of candidates we'll spam
11561     // the user with.  FIXME: This limit should depend on details of the
11562     // candidate list.
11563     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
11564       break;
11565     ++CandsShown;
11566 
11567     assert(Cand->Specialization &&
11568            "Non-matching built-in candidates are not added to Cands.");
11569     Cand->NoteDeductionFailure(S, ForTakingAddress);
11570   }
11571 
11572   if (I != E)
11573     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
11574 }
11575 
11576 // [PossiblyAFunctionType]  -->   [Return]
11577 // NonFunctionType --> NonFunctionType
11578 // R (A) --> R(A)
11579 // R (*)(A) --> R (A)
11580 // R (&)(A) --> R (A)
11581 // R (S::*)(A) --> R (A)
11582 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
11583   QualType Ret = PossiblyAFunctionType;
11584   if (const PointerType *ToTypePtr =
11585     PossiblyAFunctionType->getAs<PointerType>())
11586     Ret = ToTypePtr->getPointeeType();
11587   else if (const ReferenceType *ToTypeRef =
11588     PossiblyAFunctionType->getAs<ReferenceType>())
11589     Ret = ToTypeRef->getPointeeType();
11590   else if (const MemberPointerType *MemTypePtr =
11591     PossiblyAFunctionType->getAs<MemberPointerType>())
11592     Ret = MemTypePtr->getPointeeType();
11593   Ret =
11594     Context.getCanonicalType(Ret).getUnqualifiedType();
11595   return Ret;
11596 }
11597 
11598 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
11599                                  bool Complain = true) {
11600   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
11601       S.DeduceReturnType(FD, Loc, Complain))
11602     return true;
11603 
11604   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
11605   if (S.getLangOpts().CPlusPlus17 &&
11606       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
11607       !S.ResolveExceptionSpec(Loc, FPT))
11608     return true;
11609 
11610   return false;
11611 }
11612 
11613 namespace {
11614 // A helper class to help with address of function resolution
11615 // - allows us to avoid passing around all those ugly parameters
11616 class AddressOfFunctionResolver {
11617   Sema& S;
11618   Expr* SourceExpr;
11619   const QualType& TargetType;
11620   QualType TargetFunctionType; // Extracted function type from target type
11621 
11622   bool Complain;
11623   //DeclAccessPair& ResultFunctionAccessPair;
11624   ASTContext& Context;
11625 
11626   bool TargetTypeIsNonStaticMemberFunction;
11627   bool FoundNonTemplateFunction;
11628   bool StaticMemberFunctionFromBoundPointer;
11629   bool HasComplained;
11630 
11631   OverloadExpr::FindResult OvlExprInfo;
11632   OverloadExpr *OvlExpr;
11633   TemplateArgumentListInfo OvlExplicitTemplateArgs;
11634   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
11635   TemplateSpecCandidateSet FailedCandidates;
11636 
11637 public:
11638   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
11639                             const QualType &TargetType, bool Complain)
11640       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
11641         Complain(Complain), Context(S.getASTContext()),
11642         TargetTypeIsNonStaticMemberFunction(
11643             !!TargetType->getAs<MemberPointerType>()),
11644         FoundNonTemplateFunction(false),
11645         StaticMemberFunctionFromBoundPointer(false),
11646         HasComplained(false),
11647         OvlExprInfo(OverloadExpr::find(SourceExpr)),
11648         OvlExpr(OvlExprInfo.Expression),
11649         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
11650     ExtractUnqualifiedFunctionTypeFromTargetType();
11651 
11652     if (TargetFunctionType->isFunctionType()) {
11653       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
11654         if (!UME->isImplicitAccess() &&
11655             !S.ResolveSingleFunctionTemplateSpecialization(UME))
11656           StaticMemberFunctionFromBoundPointer = true;
11657     } else if (OvlExpr->hasExplicitTemplateArgs()) {
11658       DeclAccessPair dap;
11659       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
11660               OvlExpr, false, &dap)) {
11661         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
11662           if (!Method->isStatic()) {
11663             // If the target type is a non-function type and the function found
11664             // is a non-static member function, pretend as if that was the
11665             // target, it's the only possible type to end up with.
11666             TargetTypeIsNonStaticMemberFunction = true;
11667 
11668             // And skip adding the function if its not in the proper form.
11669             // We'll diagnose this due to an empty set of functions.
11670             if (!OvlExprInfo.HasFormOfMemberPointer)
11671               return;
11672           }
11673 
11674         Matches.push_back(std::make_pair(dap, Fn));
11675       }
11676       return;
11677     }
11678 
11679     if (OvlExpr->hasExplicitTemplateArgs())
11680       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
11681 
11682     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
11683       // C++ [over.over]p4:
11684       //   If more than one function is selected, [...]
11685       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
11686         if (FoundNonTemplateFunction)
11687           EliminateAllTemplateMatches();
11688         else
11689           EliminateAllExceptMostSpecializedTemplate();
11690       }
11691     }
11692 
11693     if (S.getLangOpts().CUDA && Matches.size() > 1)
11694       EliminateSuboptimalCudaMatches();
11695   }
11696 
11697   bool hasComplained() const { return HasComplained; }
11698 
11699 private:
11700   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
11701     QualType Discard;
11702     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
11703            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
11704   }
11705 
11706   /// \return true if A is considered a better overload candidate for the
11707   /// desired type than B.
11708   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
11709     // If A doesn't have exactly the correct type, we don't want to classify it
11710     // as "better" than anything else. This way, the user is required to
11711     // disambiguate for us if there are multiple candidates and no exact match.
11712     return candidateHasExactlyCorrectType(A) &&
11713            (!candidateHasExactlyCorrectType(B) ||
11714             compareEnableIfAttrs(S, A, B) == Comparison::Better);
11715   }
11716 
11717   /// \return true if we were able to eliminate all but one overload candidate,
11718   /// false otherwise.
11719   bool eliminiateSuboptimalOverloadCandidates() {
11720     // Same algorithm as overload resolution -- one pass to pick the "best",
11721     // another pass to be sure that nothing is better than the best.
11722     auto Best = Matches.begin();
11723     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11724       if (isBetterCandidate(I->second, Best->second))
11725         Best = I;
11726 
11727     const FunctionDecl *BestFn = Best->second;
11728     auto IsBestOrInferiorToBest = [this, BestFn](
11729         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11730       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11731     };
11732 
11733     // Note: We explicitly leave Matches unmodified if there isn't a clear best
11734     // option, so we can potentially give the user a better error
11735     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
11736       return false;
11737     Matches[0] = *Best;
11738     Matches.resize(1);
11739     return true;
11740   }
11741 
11742   bool isTargetTypeAFunction() const {
11743     return TargetFunctionType->isFunctionType();
11744   }
11745 
11746   // [ToType]     [Return]
11747 
11748   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11749   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11750   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11751   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11752     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11753   }
11754 
11755   // return true if any matching specializations were found
11756   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
11757                                    const DeclAccessPair& CurAccessFunPair) {
11758     if (CXXMethodDecl *Method
11759               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11760       // Skip non-static function templates when converting to pointer, and
11761       // static when converting to member pointer.
11762       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11763         return false;
11764     }
11765     else if (TargetTypeIsNonStaticMemberFunction)
11766       return false;
11767 
11768     // C++ [over.over]p2:
11769     //   If the name is a function template, template argument deduction is
11770     //   done (14.8.2.2), and if the argument deduction succeeds, the
11771     //   resulting template argument list is used to generate a single
11772     //   function template specialization, which is added to the set of
11773     //   overloaded functions considered.
11774     FunctionDecl *Specialization = nullptr;
11775     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11776     if (Sema::TemplateDeductionResult Result
11777           = S.DeduceTemplateArguments(FunctionTemplate,
11778                                       &OvlExplicitTemplateArgs,
11779                                       TargetFunctionType, Specialization,
11780                                       Info, /*IsAddressOfFunction*/true)) {
11781       // Make a note of the failed deduction for diagnostics.
11782       FailedCandidates.addCandidate()
11783           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
11784                MakeDeductionFailureInfo(Context, Result, Info));
11785       return false;
11786     }
11787 
11788     // Template argument deduction ensures that we have an exact match or
11789     // compatible pointer-to-function arguments that would be adjusted by ICS.
11790     // This function template specicalization works.
11791     assert(S.isSameOrCompatibleFunctionType(
11792               Context.getCanonicalType(Specialization->getType()),
11793               Context.getCanonicalType(TargetFunctionType)));
11794 
11795     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11796       return false;
11797 
11798     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11799     return true;
11800   }
11801 
11802   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11803                                       const DeclAccessPair& CurAccessFunPair) {
11804     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11805       // Skip non-static functions when converting to pointer, and static
11806       // when converting to member pointer.
11807       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11808         return false;
11809     }
11810     else if (TargetTypeIsNonStaticMemberFunction)
11811       return false;
11812 
11813     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11814       if (S.getLangOpts().CUDA)
11815         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11816           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11817             return false;
11818       if (FunDecl->isMultiVersion()) {
11819         const auto *TA = FunDecl->getAttr<TargetAttr>();
11820         if (TA && !TA->isDefaultVersion())
11821           return false;
11822       }
11823 
11824       // If any candidate has a placeholder return type, trigger its deduction
11825       // now.
11826       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
11827                                Complain)) {
11828         HasComplained |= Complain;
11829         return false;
11830       }
11831 
11832       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11833         return false;
11834 
11835       // If we're in C, we need to support types that aren't exactly identical.
11836       if (!S.getLangOpts().CPlusPlus ||
11837           candidateHasExactlyCorrectType(FunDecl)) {
11838         Matches.push_back(std::make_pair(
11839             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11840         FoundNonTemplateFunction = true;
11841         return true;
11842       }
11843     }
11844 
11845     return false;
11846   }
11847 
11848   bool FindAllFunctionsThatMatchTargetTypeExactly() {
11849     bool Ret = false;
11850 
11851     // If the overload expression doesn't have the form of a pointer to
11852     // member, don't try to convert it to a pointer-to-member type.
11853     if (IsInvalidFormOfPointerToMemberFunction())
11854       return false;
11855 
11856     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11857                                E = OvlExpr->decls_end();
11858          I != E; ++I) {
11859       // Look through any using declarations to find the underlying function.
11860       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11861 
11862       // C++ [over.over]p3:
11863       //   Non-member functions and static member functions match
11864       //   targets of type "pointer-to-function" or "reference-to-function."
11865       //   Nonstatic member functions match targets of
11866       //   type "pointer-to-member-function."
11867       // Note that according to DR 247, the containing class does not matter.
11868       if (FunctionTemplateDecl *FunctionTemplate
11869                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11870         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11871           Ret = true;
11872       }
11873       // If we have explicit template arguments supplied, skip non-templates.
11874       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11875                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11876         Ret = true;
11877     }
11878     assert(Ret || Matches.empty());
11879     return Ret;
11880   }
11881 
11882   void EliminateAllExceptMostSpecializedTemplate() {
11883     //   [...] and any given function template specialization F1 is
11884     //   eliminated if the set contains a second function template
11885     //   specialization whose function template is more specialized
11886     //   than the function template of F1 according to the partial
11887     //   ordering rules of 14.5.5.2.
11888 
11889     // The algorithm specified above is quadratic. We instead use a
11890     // two-pass algorithm (similar to the one used to identify the
11891     // best viable function in an overload set) that identifies the
11892     // best function template (if it exists).
11893 
11894     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11895     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11896       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11897 
11898     // TODO: It looks like FailedCandidates does not serve much purpose
11899     // here, since the no_viable diagnostic has index 0.
11900     UnresolvedSetIterator Result = S.getMostSpecialized(
11901         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11902         SourceExpr->getBeginLoc(), S.PDiag(),
11903         S.PDiag(diag::err_addr_ovl_ambiguous)
11904             << Matches[0].second->getDeclName(),
11905         S.PDiag(diag::note_ovl_candidate)
11906             << (unsigned)oc_function << (unsigned)ocs_described_template,
11907         Complain, TargetFunctionType);
11908 
11909     if (Result != MatchesCopy.end()) {
11910       // Make it the first and only element
11911       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11912       Matches[0].second = cast<FunctionDecl>(*Result);
11913       Matches.resize(1);
11914     } else
11915       HasComplained |= Complain;
11916   }
11917 
11918   void EliminateAllTemplateMatches() {
11919     //   [...] any function template specializations in the set are
11920     //   eliminated if the set also contains a non-template function, [...]
11921     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11922       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11923         ++I;
11924       else {
11925         Matches[I] = Matches[--N];
11926         Matches.resize(N);
11927       }
11928     }
11929   }
11930 
11931   void EliminateSuboptimalCudaMatches() {
11932     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11933   }
11934 
11935 public:
11936   void ComplainNoMatchesFound() const {
11937     assert(Matches.empty());
11938     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
11939         << OvlExpr->getName() << TargetFunctionType
11940         << OvlExpr->getSourceRange();
11941     if (FailedCandidates.empty())
11942       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11943                                   /*TakingAddress=*/true);
11944     else {
11945       // We have some deduction failure messages. Use them to diagnose
11946       // the function templates, and diagnose the non-template candidates
11947       // normally.
11948       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11949                                  IEnd = OvlExpr->decls_end();
11950            I != IEnd; ++I)
11951         if (FunctionDecl *Fun =
11952                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11953           if (!functionHasPassObjectSizeParams(Fun))
11954             S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
11955                                     /*TakingAddress=*/true);
11956       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
11957     }
11958   }
11959 
11960   bool IsInvalidFormOfPointerToMemberFunction() const {
11961     return TargetTypeIsNonStaticMemberFunction &&
11962       !OvlExprInfo.HasFormOfMemberPointer;
11963   }
11964 
11965   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11966       // TODO: Should we condition this on whether any functions might
11967       // have matched, or is it more appropriate to do that in callers?
11968       // TODO: a fixit wouldn't hurt.
11969       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11970         << TargetType << OvlExpr->getSourceRange();
11971   }
11972 
11973   bool IsStaticMemberFunctionFromBoundPointer() const {
11974     return StaticMemberFunctionFromBoundPointer;
11975   }
11976 
11977   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11978     S.Diag(OvlExpr->getBeginLoc(),
11979            diag::err_invalid_form_pointer_member_function)
11980         << OvlExpr->getSourceRange();
11981   }
11982 
11983   void ComplainOfInvalidConversion() const {
11984     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
11985         << OvlExpr->getName() << TargetType;
11986   }
11987 
11988   void ComplainMultipleMatchesFound() const {
11989     assert(Matches.size() > 1);
11990     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
11991         << OvlExpr->getName() << OvlExpr->getSourceRange();
11992     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11993                                 /*TakingAddress=*/true);
11994   }
11995 
11996   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11997 
11998   int getNumMatches() const { return Matches.size(); }
11999 
12000   FunctionDecl* getMatchingFunctionDecl() const {
12001     if (Matches.size() != 1) return nullptr;
12002     return Matches[0].second;
12003   }
12004 
12005   const DeclAccessPair* getMatchingFunctionAccessPair() const {
12006     if (Matches.size() != 1) return nullptr;
12007     return &Matches[0].first;
12008   }
12009 };
12010 }
12011 
12012 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
12013 /// an overloaded function (C++ [over.over]), where @p From is an
12014 /// expression with overloaded function type and @p ToType is the type
12015 /// we're trying to resolve to. For example:
12016 ///
12017 /// @code
12018 /// int f(double);
12019 /// int f(int);
12020 ///
12021 /// int (*pfd)(double) = f; // selects f(double)
12022 /// @endcode
12023 ///
12024 /// This routine returns the resulting FunctionDecl if it could be
12025 /// resolved, and NULL otherwise. When @p Complain is true, this
12026 /// routine will emit diagnostics if there is an error.
12027 FunctionDecl *
12028 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
12029                                          QualType TargetType,
12030                                          bool Complain,
12031                                          DeclAccessPair &FoundResult,
12032                                          bool *pHadMultipleCandidates) {
12033   assert(AddressOfExpr->getType() == Context.OverloadTy);
12034 
12035   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
12036                                      Complain);
12037   int NumMatches = Resolver.getNumMatches();
12038   FunctionDecl *Fn = nullptr;
12039   bool ShouldComplain = Complain && !Resolver.hasComplained();
12040   if (NumMatches == 0 && ShouldComplain) {
12041     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
12042       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
12043     else
12044       Resolver.ComplainNoMatchesFound();
12045   }
12046   else if (NumMatches > 1 && ShouldComplain)
12047     Resolver.ComplainMultipleMatchesFound();
12048   else if (NumMatches == 1) {
12049     Fn = Resolver.getMatchingFunctionDecl();
12050     assert(Fn);
12051     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
12052       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
12053     FoundResult = *Resolver.getMatchingFunctionAccessPair();
12054     if (Complain) {
12055       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
12056         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
12057       else
12058         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
12059     }
12060   }
12061 
12062   if (pHadMultipleCandidates)
12063     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
12064   return Fn;
12065 }
12066 
12067 /// Given an expression that refers to an overloaded function, try to
12068 /// resolve that function to a single function that can have its address taken.
12069 /// This will modify `Pair` iff it returns non-null.
12070 ///
12071 /// This routine can only succeed if from all of the candidates in the overload
12072 /// set for SrcExpr that can have their addresses taken, there is one candidate
12073 /// that is more constrained than the rest.
12074 FunctionDecl *
12075 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
12076   OverloadExpr::FindResult R = OverloadExpr::find(E);
12077   OverloadExpr *Ovl = R.Expression;
12078   bool IsResultAmbiguous = false;
12079   FunctionDecl *Result = nullptr;
12080   DeclAccessPair DAP;
12081   SmallVector<FunctionDecl *, 2> AmbiguousDecls;
12082 
12083   auto CheckMoreConstrained =
12084       [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> {
12085         SmallVector<const Expr *, 1> AC1, AC2;
12086         FD1->getAssociatedConstraints(AC1);
12087         FD2->getAssociatedConstraints(AC2);
12088         bool AtLeastAsConstrained1, AtLeastAsConstrained2;
12089         if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
12090           return None;
12091         if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
12092           return None;
12093         if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
12094           return None;
12095         return AtLeastAsConstrained1;
12096       };
12097 
12098   // Don't use the AddressOfResolver because we're specifically looking for
12099   // cases where we have one overload candidate that lacks
12100   // enable_if/pass_object_size/...
12101   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
12102     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
12103     if (!FD)
12104       return nullptr;
12105 
12106     if (!checkAddressOfFunctionIsAvailable(FD))
12107       continue;
12108 
12109     // We have more than one result - see if it is more constrained than the
12110     // previous one.
12111     if (Result) {
12112       Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD,
12113                                                                         Result);
12114       if (!MoreConstrainedThanPrevious) {
12115         IsResultAmbiguous = true;
12116         AmbiguousDecls.push_back(FD);
12117         continue;
12118       }
12119       if (!*MoreConstrainedThanPrevious)
12120         continue;
12121       // FD is more constrained - replace Result with it.
12122     }
12123     IsResultAmbiguous = false;
12124     DAP = I.getPair();
12125     Result = FD;
12126   }
12127 
12128   if (IsResultAmbiguous)
12129     return nullptr;
12130 
12131   if (Result) {
12132     SmallVector<const Expr *, 1> ResultAC;
12133     // We skipped over some ambiguous declarations which might be ambiguous with
12134     // the selected result.
12135     for (FunctionDecl *Skipped : AmbiguousDecls)
12136       if (!CheckMoreConstrained(Skipped, Result).hasValue())
12137         return nullptr;
12138     Pair = DAP;
12139   }
12140   return Result;
12141 }
12142 
12143 /// Given an overloaded function, tries to turn it into a non-overloaded
12144 /// function reference using resolveAddressOfSingleOverloadCandidate. This
12145 /// will perform access checks, diagnose the use of the resultant decl, and, if
12146 /// requested, potentially perform a function-to-pointer decay.
12147 ///
12148 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
12149 /// Otherwise, returns true. This may emit diagnostics and return true.
12150 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
12151     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
12152   Expr *E = SrcExpr.get();
12153   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
12154 
12155   DeclAccessPair DAP;
12156   FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
12157   if (!Found || Found->isCPUDispatchMultiVersion() ||
12158       Found->isCPUSpecificMultiVersion())
12159     return false;
12160 
12161   // Emitting multiple diagnostics for a function that is both inaccessible and
12162   // unavailable is consistent with our behavior elsewhere. So, always check
12163   // for both.
12164   DiagnoseUseOfDecl(Found, E->getExprLoc());
12165   CheckAddressOfMemberAccess(E, DAP);
12166   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
12167   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
12168     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
12169   else
12170     SrcExpr = Fixed;
12171   return true;
12172 }
12173 
12174 /// Given an expression that refers to an overloaded function, try to
12175 /// resolve that overloaded function expression down to a single function.
12176 ///
12177 /// This routine can only resolve template-ids that refer to a single function
12178 /// template, where that template-id refers to a single template whose template
12179 /// arguments are either provided by the template-id or have defaults,
12180 /// as described in C++0x [temp.arg.explicit]p3.
12181 ///
12182 /// If no template-ids are found, no diagnostics are emitted and NULL is
12183 /// returned.
12184 FunctionDecl *
12185 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
12186                                                   bool Complain,
12187                                                   DeclAccessPair *FoundResult) {
12188   // C++ [over.over]p1:
12189   //   [...] [Note: any redundant set of parentheses surrounding the
12190   //   overloaded function name is ignored (5.1). ]
12191   // C++ [over.over]p1:
12192   //   [...] The overloaded function name can be preceded by the &
12193   //   operator.
12194 
12195   // If we didn't actually find any template-ids, we're done.
12196   if (!ovl->hasExplicitTemplateArgs())
12197     return nullptr;
12198 
12199   TemplateArgumentListInfo ExplicitTemplateArgs;
12200   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
12201   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
12202 
12203   // Look through all of the overloaded functions, searching for one
12204   // whose type matches exactly.
12205   FunctionDecl *Matched = nullptr;
12206   for (UnresolvedSetIterator I = ovl->decls_begin(),
12207          E = ovl->decls_end(); I != E; ++I) {
12208     // C++0x [temp.arg.explicit]p3:
12209     //   [...] In contexts where deduction is done and fails, or in contexts
12210     //   where deduction is not done, if a template argument list is
12211     //   specified and it, along with any default template arguments,
12212     //   identifies a single function template specialization, then the
12213     //   template-id is an lvalue for the function template specialization.
12214     FunctionTemplateDecl *FunctionTemplate
12215       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
12216 
12217     // C++ [over.over]p2:
12218     //   If the name is a function template, template argument deduction is
12219     //   done (14.8.2.2), and if the argument deduction succeeds, the
12220     //   resulting template argument list is used to generate a single
12221     //   function template specialization, which is added to the set of
12222     //   overloaded functions considered.
12223     FunctionDecl *Specialization = nullptr;
12224     TemplateDeductionInfo Info(FailedCandidates.getLocation());
12225     if (TemplateDeductionResult Result
12226           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
12227                                     Specialization, Info,
12228                                     /*IsAddressOfFunction*/true)) {
12229       // Make a note of the failed deduction for diagnostics.
12230       // TODO: Actually use the failed-deduction info?
12231       FailedCandidates.addCandidate()
12232           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
12233                MakeDeductionFailureInfo(Context, Result, Info));
12234       continue;
12235     }
12236 
12237     assert(Specialization && "no specialization and no error?");
12238 
12239     // Multiple matches; we can't resolve to a single declaration.
12240     if (Matched) {
12241       if (Complain) {
12242         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
12243           << ovl->getName();
12244         NoteAllOverloadCandidates(ovl);
12245       }
12246       return nullptr;
12247     }
12248 
12249     Matched = Specialization;
12250     if (FoundResult) *FoundResult = I.getPair();
12251   }
12252 
12253   if (Matched &&
12254       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
12255     return nullptr;
12256 
12257   return Matched;
12258 }
12259 
12260 // Resolve and fix an overloaded expression that can be resolved
12261 // because it identifies a single function template specialization.
12262 //
12263 // Last three arguments should only be supplied if Complain = true
12264 //
12265 // Return true if it was logically possible to so resolve the
12266 // expression, regardless of whether or not it succeeded.  Always
12267 // returns true if 'complain' is set.
12268 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
12269                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
12270                       bool complain, SourceRange OpRangeForComplaining,
12271                                            QualType DestTypeForComplaining,
12272                                             unsigned DiagIDForComplaining) {
12273   assert(SrcExpr.get()->getType() == Context.OverloadTy);
12274 
12275   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
12276 
12277   DeclAccessPair found;
12278   ExprResult SingleFunctionExpression;
12279   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
12280                            ovl.Expression, /*complain*/ false, &found)) {
12281     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
12282       SrcExpr = ExprError();
12283       return true;
12284     }
12285 
12286     // It is only correct to resolve to an instance method if we're
12287     // resolving a form that's permitted to be a pointer to member.
12288     // Otherwise we'll end up making a bound member expression, which
12289     // is illegal in all the contexts we resolve like this.
12290     if (!ovl.HasFormOfMemberPointer &&
12291         isa<CXXMethodDecl>(fn) &&
12292         cast<CXXMethodDecl>(fn)->isInstance()) {
12293       if (!complain) return false;
12294 
12295       Diag(ovl.Expression->getExprLoc(),
12296            diag::err_bound_member_function)
12297         << 0 << ovl.Expression->getSourceRange();
12298 
12299       // TODO: I believe we only end up here if there's a mix of
12300       // static and non-static candidates (otherwise the expression
12301       // would have 'bound member' type, not 'overload' type).
12302       // Ideally we would note which candidate was chosen and why
12303       // the static candidates were rejected.
12304       SrcExpr = ExprError();
12305       return true;
12306     }
12307 
12308     // Fix the expression to refer to 'fn'.
12309     SingleFunctionExpression =
12310         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
12311 
12312     // If desired, do function-to-pointer decay.
12313     if (doFunctionPointerConverion) {
12314       SingleFunctionExpression =
12315         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
12316       if (SingleFunctionExpression.isInvalid()) {
12317         SrcExpr = ExprError();
12318         return true;
12319       }
12320     }
12321   }
12322 
12323   if (!SingleFunctionExpression.isUsable()) {
12324     if (complain) {
12325       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
12326         << ovl.Expression->getName()
12327         << DestTypeForComplaining
12328         << OpRangeForComplaining
12329         << ovl.Expression->getQualifierLoc().getSourceRange();
12330       NoteAllOverloadCandidates(SrcExpr.get());
12331 
12332       SrcExpr = ExprError();
12333       return true;
12334     }
12335 
12336     return false;
12337   }
12338 
12339   SrcExpr = SingleFunctionExpression;
12340   return true;
12341 }
12342 
12343 /// Add a single candidate to the overload set.
12344 static void AddOverloadedCallCandidate(Sema &S,
12345                                        DeclAccessPair FoundDecl,
12346                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
12347                                        ArrayRef<Expr *> Args,
12348                                        OverloadCandidateSet &CandidateSet,
12349                                        bool PartialOverloading,
12350                                        bool KnownValid) {
12351   NamedDecl *Callee = FoundDecl.getDecl();
12352   if (isa<UsingShadowDecl>(Callee))
12353     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
12354 
12355   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
12356     if (ExplicitTemplateArgs) {
12357       assert(!KnownValid && "Explicit template arguments?");
12358       return;
12359     }
12360     // Prevent ill-formed function decls to be added as overload candidates.
12361     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
12362       return;
12363 
12364     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
12365                            /*SuppressUserConversions=*/false,
12366                            PartialOverloading);
12367     return;
12368   }
12369 
12370   if (FunctionTemplateDecl *FuncTemplate
12371       = dyn_cast<FunctionTemplateDecl>(Callee)) {
12372     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
12373                                    ExplicitTemplateArgs, Args, CandidateSet,
12374                                    /*SuppressUserConversions=*/false,
12375                                    PartialOverloading);
12376     return;
12377   }
12378 
12379   assert(!KnownValid && "unhandled case in overloaded call candidate");
12380 }
12381 
12382 /// Add the overload candidates named by callee and/or found by argument
12383 /// dependent lookup to the given overload set.
12384 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
12385                                        ArrayRef<Expr *> Args,
12386                                        OverloadCandidateSet &CandidateSet,
12387                                        bool PartialOverloading) {
12388 
12389 #ifndef NDEBUG
12390   // Verify that ArgumentDependentLookup is consistent with the rules
12391   // in C++0x [basic.lookup.argdep]p3:
12392   //
12393   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
12394   //   and let Y be the lookup set produced by argument dependent
12395   //   lookup (defined as follows). If X contains
12396   //
12397   //     -- a declaration of a class member, or
12398   //
12399   //     -- a block-scope function declaration that is not a
12400   //        using-declaration, or
12401   //
12402   //     -- a declaration that is neither a function or a function
12403   //        template
12404   //
12405   //   then Y is empty.
12406 
12407   if (ULE->requiresADL()) {
12408     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12409            E = ULE->decls_end(); I != E; ++I) {
12410       assert(!(*I)->getDeclContext()->isRecord());
12411       assert(isa<UsingShadowDecl>(*I) ||
12412              !(*I)->getDeclContext()->isFunctionOrMethod());
12413       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
12414     }
12415   }
12416 #endif
12417 
12418   // It would be nice to avoid this copy.
12419   TemplateArgumentListInfo TABuffer;
12420   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12421   if (ULE->hasExplicitTemplateArgs()) {
12422     ULE->copyTemplateArgumentsInto(TABuffer);
12423     ExplicitTemplateArgs = &TABuffer;
12424   }
12425 
12426   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12427          E = ULE->decls_end(); I != E; ++I)
12428     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12429                                CandidateSet, PartialOverloading,
12430                                /*KnownValid*/ true);
12431 
12432   if (ULE->requiresADL())
12433     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
12434                                          Args, ExplicitTemplateArgs,
12435                                          CandidateSet, PartialOverloading);
12436 }
12437 
12438 /// Determine whether a declaration with the specified name could be moved into
12439 /// a different namespace.
12440 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
12441   switch (Name.getCXXOverloadedOperator()) {
12442   case OO_New: case OO_Array_New:
12443   case OO_Delete: case OO_Array_Delete:
12444     return false;
12445 
12446   default:
12447     return true;
12448   }
12449 }
12450 
12451 /// Attempt to recover from an ill-formed use of a non-dependent name in a
12452 /// template, where the non-dependent name was declared after the template
12453 /// was defined. This is common in code written for a compilers which do not
12454 /// correctly implement two-stage name lookup.
12455 ///
12456 /// Returns true if a viable candidate was found and a diagnostic was issued.
12457 static bool
12458 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
12459                        const CXXScopeSpec &SS, LookupResult &R,
12460                        OverloadCandidateSet::CandidateSetKind CSK,
12461                        TemplateArgumentListInfo *ExplicitTemplateArgs,
12462                        ArrayRef<Expr *> Args,
12463                        bool *DoDiagnoseEmptyLookup = nullptr) {
12464   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
12465     return false;
12466 
12467   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
12468     if (DC->isTransparentContext())
12469       continue;
12470 
12471     SemaRef.LookupQualifiedName(R, DC);
12472 
12473     if (!R.empty()) {
12474       R.suppressDiagnostics();
12475 
12476       if (isa<CXXRecordDecl>(DC)) {
12477         // Don't diagnose names we find in classes; we get much better
12478         // diagnostics for these from DiagnoseEmptyLookup.
12479         R.clear();
12480         if (DoDiagnoseEmptyLookup)
12481           *DoDiagnoseEmptyLookup = true;
12482         return false;
12483       }
12484 
12485       OverloadCandidateSet Candidates(FnLoc, CSK);
12486       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12487         AddOverloadedCallCandidate(SemaRef, I.getPair(),
12488                                    ExplicitTemplateArgs, Args,
12489                                    Candidates, false, /*KnownValid*/ false);
12490 
12491       OverloadCandidateSet::iterator Best;
12492       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
12493         // No viable functions. Don't bother the user with notes for functions
12494         // which don't work and shouldn't be found anyway.
12495         R.clear();
12496         return false;
12497       }
12498 
12499       // Find the namespaces where ADL would have looked, and suggest
12500       // declaring the function there instead.
12501       Sema::AssociatedNamespaceSet AssociatedNamespaces;
12502       Sema::AssociatedClassSet AssociatedClasses;
12503       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
12504                                                  AssociatedNamespaces,
12505                                                  AssociatedClasses);
12506       Sema::AssociatedNamespaceSet SuggestedNamespaces;
12507       if (canBeDeclaredInNamespace(R.getLookupName())) {
12508         DeclContext *Std = SemaRef.getStdNamespace();
12509         for (Sema::AssociatedNamespaceSet::iterator
12510                it = AssociatedNamespaces.begin(),
12511                end = AssociatedNamespaces.end(); it != end; ++it) {
12512           // Never suggest declaring a function within namespace 'std'.
12513           if (Std && Std->Encloses(*it))
12514             continue;
12515 
12516           // Never suggest declaring a function within a namespace with a
12517           // reserved name, like __gnu_cxx.
12518           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
12519           if (NS &&
12520               NS->getQualifiedNameAsString().find("__") != std::string::npos)
12521             continue;
12522 
12523           SuggestedNamespaces.insert(*it);
12524         }
12525       }
12526 
12527       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
12528         << R.getLookupName();
12529       if (SuggestedNamespaces.empty()) {
12530         SemaRef.Diag(Best->Function->getLocation(),
12531                      diag::note_not_found_by_two_phase_lookup)
12532           << R.getLookupName() << 0;
12533       } else if (SuggestedNamespaces.size() == 1) {
12534         SemaRef.Diag(Best->Function->getLocation(),
12535                      diag::note_not_found_by_two_phase_lookup)
12536           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
12537       } else {
12538         // FIXME: It would be useful to list the associated namespaces here,
12539         // but the diagnostics infrastructure doesn't provide a way to produce
12540         // a localized representation of a list of items.
12541         SemaRef.Diag(Best->Function->getLocation(),
12542                      diag::note_not_found_by_two_phase_lookup)
12543           << R.getLookupName() << 2;
12544       }
12545 
12546       // Try to recover by calling this function.
12547       return true;
12548     }
12549 
12550     R.clear();
12551   }
12552 
12553   return false;
12554 }
12555 
12556 /// Attempt to recover from ill-formed use of a non-dependent operator in a
12557 /// template, where the non-dependent operator was declared after the template
12558 /// was defined.
12559 ///
12560 /// Returns true if a viable candidate was found and a diagnostic was issued.
12561 static bool
12562 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
12563                                SourceLocation OpLoc,
12564                                ArrayRef<Expr *> Args) {
12565   DeclarationName OpName =
12566     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
12567   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
12568   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
12569                                 OverloadCandidateSet::CSK_Operator,
12570                                 /*ExplicitTemplateArgs=*/nullptr, Args);
12571 }
12572 
12573 namespace {
12574 class BuildRecoveryCallExprRAII {
12575   Sema &SemaRef;
12576 public:
12577   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
12578     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
12579     SemaRef.IsBuildingRecoveryCallExpr = true;
12580   }
12581 
12582   ~BuildRecoveryCallExprRAII() {
12583     SemaRef.IsBuildingRecoveryCallExpr = false;
12584   }
12585 };
12586 
12587 }
12588 
12589 /// Attempts to recover from a call where no functions were found.
12590 ///
12591 /// Returns true if new candidates were found.
12592 static ExprResult
12593 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12594                       UnresolvedLookupExpr *ULE,
12595                       SourceLocation LParenLoc,
12596                       MutableArrayRef<Expr *> Args,
12597                       SourceLocation RParenLoc,
12598                       bool EmptyLookup, bool AllowTypoCorrection) {
12599   // Do not try to recover if it is already building a recovery call.
12600   // This stops infinite loops for template instantiations like
12601   //
12602   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
12603   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
12604   //
12605   if (SemaRef.IsBuildingRecoveryCallExpr)
12606     return ExprError();
12607   BuildRecoveryCallExprRAII RCE(SemaRef);
12608 
12609   CXXScopeSpec SS;
12610   SS.Adopt(ULE->getQualifierLoc());
12611   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
12612 
12613   TemplateArgumentListInfo TABuffer;
12614   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12615   if (ULE->hasExplicitTemplateArgs()) {
12616     ULE->copyTemplateArgumentsInto(TABuffer);
12617     ExplicitTemplateArgs = &TABuffer;
12618   }
12619 
12620   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
12621                  Sema::LookupOrdinaryName);
12622   bool DoDiagnoseEmptyLookup = EmptyLookup;
12623   if (!DiagnoseTwoPhaseLookup(
12624           SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal,
12625           ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) {
12626     NoTypoCorrectionCCC NoTypoValidator{};
12627     FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
12628                                                 ExplicitTemplateArgs != nullptr,
12629                                                 dyn_cast<MemberExpr>(Fn));
12630     CorrectionCandidateCallback &Validator =
12631         AllowTypoCorrection
12632             ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
12633             : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
12634     if (!DoDiagnoseEmptyLookup ||
12635         SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
12636                                     Args))
12637       return ExprError();
12638   }
12639 
12640   assert(!R.empty() && "lookup results empty despite recovery");
12641 
12642   // If recovery created an ambiguity, just bail out.
12643   if (R.isAmbiguous()) {
12644     R.suppressDiagnostics();
12645     return ExprError();
12646   }
12647 
12648   // Build an implicit member call if appropriate.  Just drop the
12649   // casts and such from the call, we don't really care.
12650   ExprResult NewFn = ExprError();
12651   if ((*R.begin())->isCXXClassMember())
12652     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12653                                                     ExplicitTemplateArgs, S);
12654   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
12655     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
12656                                         ExplicitTemplateArgs);
12657   else
12658     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
12659 
12660   if (NewFn.isInvalid())
12661     return ExprError();
12662 
12663   // This shouldn't cause an infinite loop because we're giving it
12664   // an expression with viable lookup results, which should never
12665   // end up here.
12666   return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
12667                                MultiExprArg(Args.data(), Args.size()),
12668                                RParenLoc);
12669 }
12670 
12671 /// Constructs and populates an OverloadedCandidateSet from
12672 /// the given function.
12673 /// \returns true when an the ExprResult output parameter has been set.
12674 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
12675                                   UnresolvedLookupExpr *ULE,
12676                                   MultiExprArg Args,
12677                                   SourceLocation RParenLoc,
12678                                   OverloadCandidateSet *CandidateSet,
12679                                   ExprResult *Result) {
12680 #ifndef NDEBUG
12681   if (ULE->requiresADL()) {
12682     // To do ADL, we must have found an unqualified name.
12683     assert(!ULE->getQualifier() && "qualified name with ADL");
12684 
12685     // We don't perform ADL for implicit declarations of builtins.
12686     // Verify that this was correctly set up.
12687     FunctionDecl *F;
12688     if (ULE->decls_begin() != ULE->decls_end() &&
12689         ULE->decls_begin() + 1 == ULE->decls_end() &&
12690         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
12691         F->getBuiltinID() && F->isImplicit())
12692       llvm_unreachable("performing ADL for builtin");
12693 
12694     // We don't perform ADL in C.
12695     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
12696   }
12697 #endif
12698 
12699   UnbridgedCastsSet UnbridgedCasts;
12700   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
12701     *Result = ExprError();
12702     return true;
12703   }
12704 
12705   // Add the functions denoted by the callee to the set of candidate
12706   // functions, including those from argument-dependent lookup.
12707   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
12708 
12709   if (getLangOpts().MSVCCompat &&
12710       CurContext->isDependentContext() && !isSFINAEContext() &&
12711       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
12712 
12713     OverloadCandidateSet::iterator Best;
12714     if (CandidateSet->empty() ||
12715         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
12716             OR_No_Viable_Function) {
12717       // In Microsoft mode, if we are inside a template class member function
12718       // then create a type dependent CallExpr. The goal is to postpone name
12719       // lookup to instantiation time to be able to search into type dependent
12720       // base classes.
12721       CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy,
12722                                       VK_RValue, RParenLoc);
12723       CE->addDependence(ExprDependence::TypeValueInstantiation);
12724       *Result = CE;
12725       return true;
12726     }
12727   }
12728 
12729   if (CandidateSet->empty())
12730     return false;
12731 
12732   UnbridgedCasts.restore();
12733   return false;
12734 }
12735 
12736 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
12737 /// the completed call expression. If overload resolution fails, emits
12738 /// diagnostics and returns ExprError()
12739 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12740                                            UnresolvedLookupExpr *ULE,
12741                                            SourceLocation LParenLoc,
12742                                            MultiExprArg Args,
12743                                            SourceLocation RParenLoc,
12744                                            Expr *ExecConfig,
12745                                            OverloadCandidateSet *CandidateSet,
12746                                            OverloadCandidateSet::iterator *Best,
12747                                            OverloadingResult OverloadResult,
12748                                            bool AllowTypoCorrection) {
12749   if (CandidateSet->empty())
12750     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
12751                                  RParenLoc, /*EmptyLookup=*/true,
12752                                  AllowTypoCorrection);
12753 
12754   switch (OverloadResult) {
12755   case OR_Success: {
12756     FunctionDecl *FDecl = (*Best)->Function;
12757     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
12758     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
12759       return ExprError();
12760     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12761     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12762                                          ExecConfig, /*IsExecConfig=*/false,
12763                                          (*Best)->IsADLCandidate);
12764   }
12765 
12766   case OR_No_Viable_Function: {
12767     // Try to recover by looking for viable functions which the user might
12768     // have meant to call.
12769     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
12770                                                 Args, RParenLoc,
12771                                                 /*EmptyLookup=*/false,
12772                                                 AllowTypoCorrection);
12773     if (!Recovery.isInvalid())
12774       return Recovery;
12775 
12776     // If the user passes in a function that we can't take the address of, we
12777     // generally end up emitting really bad error messages. Here, we attempt to
12778     // emit better ones.
12779     for (const Expr *Arg : Args) {
12780       if (!Arg->getType()->isFunctionType())
12781         continue;
12782       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12783         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12784         if (FD &&
12785             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12786                                                        Arg->getExprLoc()))
12787           return ExprError();
12788       }
12789     }
12790 
12791     CandidateSet->NoteCandidates(
12792         PartialDiagnosticAt(
12793             Fn->getBeginLoc(),
12794             SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
12795                 << ULE->getName() << Fn->getSourceRange()),
12796         SemaRef, OCD_AllCandidates, Args);
12797     break;
12798   }
12799 
12800   case OR_Ambiguous:
12801     CandidateSet->NoteCandidates(
12802         PartialDiagnosticAt(Fn->getBeginLoc(),
12803                             SemaRef.PDiag(diag::err_ovl_ambiguous_call)
12804                                 << ULE->getName() << Fn->getSourceRange()),
12805         SemaRef, OCD_AmbiguousCandidates, Args);
12806     break;
12807 
12808   case OR_Deleted: {
12809     CandidateSet->NoteCandidates(
12810         PartialDiagnosticAt(Fn->getBeginLoc(),
12811                             SemaRef.PDiag(diag::err_ovl_deleted_call)
12812                                 << ULE->getName() << Fn->getSourceRange()),
12813         SemaRef, OCD_AllCandidates, Args);
12814 
12815     // We emitted an error for the unavailable/deleted function call but keep
12816     // the call in the AST.
12817     FunctionDecl *FDecl = (*Best)->Function;
12818     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12819     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12820                                          ExecConfig, /*IsExecConfig=*/false,
12821                                          (*Best)->IsADLCandidate);
12822   }
12823   }
12824 
12825   // Overload resolution failed.
12826   return ExprError();
12827 }
12828 
12829 static void markUnaddressableCandidatesUnviable(Sema &S,
12830                                                 OverloadCandidateSet &CS) {
12831   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12832     if (I->Viable &&
12833         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12834       I->Viable = false;
12835       I->FailureKind = ovl_fail_addr_not_available;
12836     }
12837   }
12838 }
12839 
12840 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
12841 /// (which eventually refers to the declaration Func) and the call
12842 /// arguments Args/NumArgs, attempt to resolve the function call down
12843 /// to a specific function. If overload resolution succeeds, returns
12844 /// the call expression produced by overload resolution.
12845 /// Otherwise, emits diagnostics and returns ExprError.
12846 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12847                                          UnresolvedLookupExpr *ULE,
12848                                          SourceLocation LParenLoc,
12849                                          MultiExprArg Args,
12850                                          SourceLocation RParenLoc,
12851                                          Expr *ExecConfig,
12852                                          bool AllowTypoCorrection,
12853                                          bool CalleesAddressIsTaken) {
12854   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12855                                     OverloadCandidateSet::CSK_Normal);
12856   ExprResult result;
12857 
12858   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12859                              &result))
12860     return result;
12861 
12862   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12863   // functions that aren't addressible are considered unviable.
12864   if (CalleesAddressIsTaken)
12865     markUnaddressableCandidatesUnviable(*this, CandidateSet);
12866 
12867   OverloadCandidateSet::iterator Best;
12868   OverloadingResult OverloadResult =
12869       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
12870 
12871   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
12872                                   ExecConfig, &CandidateSet, &Best,
12873                                   OverloadResult, AllowTypoCorrection);
12874 }
12875 
12876 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
12877   return Functions.size() > 1 ||
12878     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12879 }
12880 
12881 /// Create a unary operation that may resolve to an overloaded
12882 /// operator.
12883 ///
12884 /// \param OpLoc The location of the operator itself (e.g., '*').
12885 ///
12886 /// \param Opc The UnaryOperatorKind that describes this operator.
12887 ///
12888 /// \param Fns The set of non-member functions that will be
12889 /// considered by overload resolution. The caller needs to build this
12890 /// set based on the context using, e.g.,
12891 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12892 /// set should not contain any member functions; those will be added
12893 /// by CreateOverloadedUnaryOp().
12894 ///
12895 /// \param Input The input argument.
12896 ExprResult
12897 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12898                               const UnresolvedSetImpl &Fns,
12899                               Expr *Input, bool PerformADL) {
12900   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12901   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12902   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12903   // TODO: provide better source location info.
12904   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12905 
12906   if (checkPlaceholderForOverload(*this, Input))
12907     return ExprError();
12908 
12909   Expr *Args[2] = { Input, nullptr };
12910   unsigned NumArgs = 1;
12911 
12912   // For post-increment and post-decrement, add the implicit '0' as
12913   // the second argument, so that we know this is a post-increment or
12914   // post-decrement.
12915   if (Opc == UO_PostInc || Opc == UO_PostDec) {
12916     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12917     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12918                                      SourceLocation());
12919     NumArgs = 2;
12920   }
12921 
12922   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12923 
12924   if (Input->isTypeDependent()) {
12925     if (Fns.empty())
12926       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12927                                          VK_RValue, OK_Ordinary, OpLoc, false);
12928 
12929     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12930     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
12931         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
12932         /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end());
12933     return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray,
12934                                        Context.DependentTy, VK_RValue, OpLoc,
12935                                        FPOptions());
12936   }
12937 
12938   // Build an empty overload set.
12939   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12940 
12941   // Add the candidates from the given function set.
12942   AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
12943 
12944   // Add operator candidates that are member functions.
12945   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12946 
12947   // Add candidates from ADL.
12948   if (PerformADL) {
12949     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12950                                          /*ExplicitTemplateArgs*/nullptr,
12951                                          CandidateSet);
12952   }
12953 
12954   // Add builtin operator candidates.
12955   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12956 
12957   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12958 
12959   // Perform overload resolution.
12960   OverloadCandidateSet::iterator Best;
12961   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12962   case OR_Success: {
12963     // We found a built-in operator or an overloaded operator.
12964     FunctionDecl *FnDecl = Best->Function;
12965 
12966     if (FnDecl) {
12967       Expr *Base = nullptr;
12968       // We matched an overloaded operator. Build a call to that
12969       // operator.
12970 
12971       // Convert the arguments.
12972       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12973         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12974 
12975         ExprResult InputRes =
12976           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12977                                               Best->FoundDecl, Method);
12978         if (InputRes.isInvalid())
12979           return ExprError();
12980         Base = Input = InputRes.get();
12981       } else {
12982         // Convert the arguments.
12983         ExprResult InputInit
12984           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12985                                                       Context,
12986                                                       FnDecl->getParamDecl(0)),
12987                                       SourceLocation(),
12988                                       Input);
12989         if (InputInit.isInvalid())
12990           return ExprError();
12991         Input = InputInit.get();
12992       }
12993 
12994       // Build the actual expression node.
12995       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12996                                                 Base, HadMultipleCandidates,
12997                                                 OpLoc);
12998       if (FnExpr.isInvalid())
12999         return ExprError();
13000 
13001       // Determine the result type.
13002       QualType ResultTy = FnDecl->getReturnType();
13003       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13004       ResultTy = ResultTy.getNonLValueExprType(Context);
13005 
13006       Args[0] = Input;
13007       CallExpr *TheCall = CXXOperatorCallExpr::Create(
13008           Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
13009           FPOptions(), Best->IsADLCandidate);
13010 
13011       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
13012         return ExprError();
13013 
13014       if (CheckFunctionCall(FnDecl, TheCall,
13015                             FnDecl->getType()->castAs<FunctionProtoType>()))
13016         return ExprError();
13017       return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
13018     } else {
13019       // We matched a built-in operator. Convert the arguments, then
13020       // break out so that we will build the appropriate built-in
13021       // operator node.
13022       ExprResult InputRes = PerformImplicitConversion(
13023           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
13024           CCK_ForBuiltinOverloadedOp);
13025       if (InputRes.isInvalid())
13026         return ExprError();
13027       Input = InputRes.get();
13028       break;
13029     }
13030   }
13031 
13032   case OR_No_Viable_Function:
13033     // This is an erroneous use of an operator which can be overloaded by
13034     // a non-member function. Check for non-member operators which were
13035     // defined too late to be candidates.
13036     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
13037       // FIXME: Recover by calling the found function.
13038       return ExprError();
13039 
13040     // No viable function; fall through to handling this as a
13041     // built-in operator, which will produce an error message for us.
13042     break;
13043 
13044   case OR_Ambiguous:
13045     CandidateSet.NoteCandidates(
13046         PartialDiagnosticAt(OpLoc,
13047                             PDiag(diag::err_ovl_ambiguous_oper_unary)
13048                                 << UnaryOperator::getOpcodeStr(Opc)
13049                                 << Input->getType() << Input->getSourceRange()),
13050         *this, OCD_AmbiguousCandidates, ArgsArray,
13051         UnaryOperator::getOpcodeStr(Opc), OpLoc);
13052     return ExprError();
13053 
13054   case OR_Deleted:
13055     CandidateSet.NoteCandidates(
13056         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
13057                                        << UnaryOperator::getOpcodeStr(Opc)
13058                                        << Input->getSourceRange()),
13059         *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
13060         OpLoc);
13061     return ExprError();
13062   }
13063 
13064   // Either we found no viable overloaded operator or we matched a
13065   // built-in operator. In either case, fall through to trying to
13066   // build a built-in operation.
13067   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13068 }
13069 
13070 /// Perform lookup for an overloaded binary operator.
13071 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
13072                                  OverloadedOperatorKind Op,
13073                                  const UnresolvedSetImpl &Fns,
13074                                  ArrayRef<Expr *> Args, bool PerformADL) {
13075   SourceLocation OpLoc = CandidateSet.getLocation();
13076 
13077   OverloadedOperatorKind ExtraOp =
13078       CandidateSet.getRewriteInfo().AllowRewrittenCandidates
13079           ? getRewrittenOverloadedOperator(Op)
13080           : OO_None;
13081 
13082   // Add the candidates from the given function set. This also adds the
13083   // rewritten candidates using these functions if necessary.
13084   AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
13085 
13086   // Add operator candidates that are member functions.
13087   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13088   if (CandidateSet.getRewriteInfo().shouldAddReversed(Op))
13089     AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
13090                                 OverloadCandidateParamOrder::Reversed);
13091 
13092   // In C++20, also add any rewritten member candidates.
13093   if (ExtraOp) {
13094     AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
13095     if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp))
13096       AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
13097                                   CandidateSet,
13098                                   OverloadCandidateParamOrder::Reversed);
13099   }
13100 
13101   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
13102   // performed for an assignment operator (nor for operator[] nor operator->,
13103   // which don't get here).
13104   if (Op != OO_Equal && PerformADL) {
13105     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13106     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
13107                                          /*ExplicitTemplateArgs*/ nullptr,
13108                                          CandidateSet);
13109     if (ExtraOp) {
13110       DeclarationName ExtraOpName =
13111           Context.DeclarationNames.getCXXOperatorName(ExtraOp);
13112       AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
13113                                            /*ExplicitTemplateArgs*/ nullptr,
13114                                            CandidateSet);
13115     }
13116   }
13117 
13118   // Add builtin operator candidates.
13119   //
13120   // FIXME: We don't add any rewritten candidates here. This is strictly
13121   // incorrect; a builtin candidate could be hidden by a non-viable candidate,
13122   // resulting in our selecting a rewritten builtin candidate. For example:
13123   //
13124   //   enum class E { e };
13125   //   bool operator!=(E, E) requires false;
13126   //   bool k = E::e != E::e;
13127   //
13128   // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
13129   // it seems unreasonable to consider rewritten builtin candidates. A core
13130   // issue has been filed proposing to removed this requirement.
13131   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13132 }
13133 
13134 /// Create a binary operation that may resolve to an overloaded
13135 /// operator.
13136 ///
13137 /// \param OpLoc The location of the operator itself (e.g., '+').
13138 ///
13139 /// \param Opc The BinaryOperatorKind that describes this operator.
13140 ///
13141 /// \param Fns The set of non-member functions that will be
13142 /// considered by overload resolution. The caller needs to build this
13143 /// set based on the context using, e.g.,
13144 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13145 /// set should not contain any member functions; those will be added
13146 /// by CreateOverloadedBinOp().
13147 ///
13148 /// \param LHS Left-hand argument.
13149 /// \param RHS Right-hand argument.
13150 /// \param PerformADL Whether to consider operator candidates found by ADL.
13151 /// \param AllowRewrittenCandidates Whether to consider candidates found by
13152 ///        C++20 operator rewrites.
13153 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
13154 ///        the function in question. Such a function is never a candidate in
13155 ///        our overload resolution. This also enables synthesizing a three-way
13156 ///        comparison from < and == as described in C++20 [class.spaceship]p1.
13157 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
13158                                        BinaryOperatorKind Opc,
13159                                        const UnresolvedSetImpl &Fns, Expr *LHS,
13160                                        Expr *RHS, bool PerformADL,
13161                                        bool AllowRewrittenCandidates,
13162                                        FunctionDecl *DefaultedFn) {
13163   Expr *Args[2] = { LHS, RHS };
13164   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
13165 
13166   if (!getLangOpts().CPlusPlus2a)
13167     AllowRewrittenCandidates = false;
13168 
13169   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
13170 
13171   // If either side is type-dependent, create an appropriate dependent
13172   // expression.
13173   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13174     if (Fns.empty()) {
13175       // If there are no functions to store, just build a dependent
13176       // BinaryOperator or CompoundAssignment.
13177       if (Opc <= BO_Assign || Opc > BO_OrAssign)
13178         return new (Context) BinaryOperator(
13179             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
13180             OpLoc, FPFeatures);
13181 
13182       return new (Context) CompoundAssignOperator(
13183           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
13184           Context.DependentTy, Context.DependentTy, OpLoc,
13185           FPFeatures);
13186     }
13187 
13188     // FIXME: save results of ADL from here?
13189     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13190     // TODO: provide better source location info in DNLoc component.
13191     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13192     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13193     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
13194         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
13195         /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end());
13196     return CXXOperatorCallExpr::Create(Context, Op, Fn, Args,
13197                                        Context.DependentTy, VK_RValue, OpLoc,
13198                                        FPFeatures);
13199   }
13200 
13201   // Always do placeholder-like conversions on the RHS.
13202   if (checkPlaceholderForOverload(*this, Args[1]))
13203     return ExprError();
13204 
13205   // Do placeholder-like conversion on the LHS; note that we should
13206   // not get here with a PseudoObject LHS.
13207   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
13208   if (checkPlaceholderForOverload(*this, Args[0]))
13209     return ExprError();
13210 
13211   // If this is the assignment operator, we only perform overload resolution
13212   // if the left-hand side is a class or enumeration type. This is actually
13213   // a hack. The standard requires that we do overload resolution between the
13214   // various built-in candidates, but as DR507 points out, this can lead to
13215   // problems. So we do it this way, which pretty much follows what GCC does.
13216   // Note that we go the traditional code path for compound assignment forms.
13217   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
13218     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13219 
13220   // If this is the .* operator, which is not overloadable, just
13221   // create a built-in binary operator.
13222   if (Opc == BO_PtrMemD)
13223     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13224 
13225   // Build the overload set.
13226   OverloadCandidateSet CandidateSet(
13227       OpLoc, OverloadCandidateSet::CSK_Operator,
13228       OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates));
13229   if (DefaultedFn)
13230     CandidateSet.exclude(DefaultedFn);
13231   LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
13232 
13233   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13234 
13235   // Perform overload resolution.
13236   OverloadCandidateSet::iterator Best;
13237   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13238     case OR_Success: {
13239       // We found a built-in operator or an overloaded operator.
13240       FunctionDecl *FnDecl = Best->Function;
13241 
13242       bool IsReversed = Best->isReversed();
13243       if (IsReversed)
13244         std::swap(Args[0], Args[1]);
13245 
13246       if (FnDecl) {
13247         Expr *Base = nullptr;
13248         // We matched an overloaded operator. Build a call to that
13249         // operator.
13250 
13251         OverloadedOperatorKind ChosenOp =
13252             FnDecl->getDeclName().getCXXOverloadedOperator();
13253 
13254         // C++2a [over.match.oper]p9:
13255         //   If a rewritten operator== candidate is selected by overload
13256         //   resolution for an operator@, its return type shall be cv bool
13257         if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
13258             !FnDecl->getReturnType()->isBooleanType()) {
13259           Diag(OpLoc, diag::err_ovl_rewrite_equalequal_not_bool)
13260               << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
13261               << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13262           Diag(FnDecl->getLocation(), diag::note_declared_at);
13263           return ExprError();
13264         }
13265 
13266         if (AllowRewrittenCandidates && !IsReversed &&
13267             CandidateSet.getRewriteInfo().shouldAddReversed(ChosenOp)) {
13268           // We could have reversed this operator, but didn't. Check if the
13269           // reversed form was a viable candidate, and if so, if it had a
13270           // better conversion for either parameter. If so, this call is
13271           // formally ambiguous, and allowing it is an extension.
13272           for (OverloadCandidate &Cand : CandidateSet) {
13273             if (Cand.Viable && Cand.Function == FnDecl &&
13274                 Cand.isReversed()) {
13275               for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
13276                 if (CompareImplicitConversionSequences(
13277                         *this, OpLoc, Cand.Conversions[ArgIdx],
13278                         Best->Conversions[ArgIdx]) ==
13279                     ImplicitConversionSequence::Better) {
13280                   Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
13281                       << BinaryOperator::getOpcodeStr(Opc)
13282                       << Args[0]->getType() << Args[1]->getType()
13283                       << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13284                   Diag(FnDecl->getLocation(),
13285                        diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
13286                 }
13287               }
13288               break;
13289             }
13290           }
13291         }
13292 
13293         // Convert the arguments.
13294         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13295           // Best->Access is only meaningful for class members.
13296           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
13297 
13298           ExprResult Arg1 =
13299             PerformCopyInitialization(
13300               InitializedEntity::InitializeParameter(Context,
13301                                                      FnDecl->getParamDecl(0)),
13302               SourceLocation(), Args[1]);
13303           if (Arg1.isInvalid())
13304             return ExprError();
13305 
13306           ExprResult Arg0 =
13307             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13308                                                 Best->FoundDecl, Method);
13309           if (Arg0.isInvalid())
13310             return ExprError();
13311           Base = Args[0] = Arg0.getAs<Expr>();
13312           Args[1] = RHS = Arg1.getAs<Expr>();
13313         } else {
13314           // Convert the arguments.
13315           ExprResult Arg0 = PerformCopyInitialization(
13316             InitializedEntity::InitializeParameter(Context,
13317                                                    FnDecl->getParamDecl(0)),
13318             SourceLocation(), Args[0]);
13319           if (Arg0.isInvalid())
13320             return ExprError();
13321 
13322           ExprResult Arg1 =
13323             PerformCopyInitialization(
13324               InitializedEntity::InitializeParameter(Context,
13325                                                      FnDecl->getParamDecl(1)),
13326               SourceLocation(), Args[1]);
13327           if (Arg1.isInvalid())
13328             return ExprError();
13329           Args[0] = LHS = Arg0.getAs<Expr>();
13330           Args[1] = RHS = Arg1.getAs<Expr>();
13331         }
13332 
13333         // Build the actual expression node.
13334         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13335                                                   Best->FoundDecl, Base,
13336                                                   HadMultipleCandidates, OpLoc);
13337         if (FnExpr.isInvalid())
13338           return ExprError();
13339 
13340         // Determine the result type.
13341         QualType ResultTy = FnDecl->getReturnType();
13342         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13343         ResultTy = ResultTy.getNonLValueExprType(Context);
13344 
13345         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13346             Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
13347             FPFeatures, Best->IsADLCandidate);
13348 
13349         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
13350                                 FnDecl))
13351           return ExprError();
13352 
13353         ArrayRef<const Expr *> ArgsArray(Args, 2);
13354         const Expr *ImplicitThis = nullptr;
13355         // Cut off the implicit 'this'.
13356         if (isa<CXXMethodDecl>(FnDecl)) {
13357           ImplicitThis = ArgsArray[0];
13358           ArgsArray = ArgsArray.slice(1);
13359         }
13360 
13361         // Check for a self move.
13362         if (Op == OO_Equal)
13363           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
13364 
13365         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
13366                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
13367                   VariadicDoesNotApply);
13368 
13369         ExprResult R = MaybeBindToTemporary(TheCall);
13370         if (R.isInvalid())
13371           return ExprError();
13372 
13373         // For a rewritten candidate, we've already reversed the arguments
13374         // if needed. Perform the rest of the rewrite now.
13375         if ((Best->RewriteKind & CRK_DifferentOperator) ||
13376             (Op == OO_Spaceship && IsReversed)) {
13377           if (Op == OO_ExclaimEqual) {
13378             assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
13379             R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
13380           } else {
13381             assert(ChosenOp == OO_Spaceship && "unexpected operator name");
13382             llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13383             Expr *ZeroLiteral =
13384                 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
13385 
13386             Sema::CodeSynthesisContext Ctx;
13387             Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
13388             Ctx.Entity = FnDecl;
13389             pushCodeSynthesisContext(Ctx);
13390 
13391             R = CreateOverloadedBinOp(
13392                 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
13393                 IsReversed ? R.get() : ZeroLiteral, PerformADL,
13394                 /*AllowRewrittenCandidates=*/false);
13395 
13396             popCodeSynthesisContext();
13397           }
13398           if (R.isInvalid())
13399             return ExprError();
13400         } else {
13401           assert(ChosenOp == Op && "unexpected operator name");
13402         }
13403 
13404         // Make a note in the AST if we did any rewriting.
13405         if (Best->RewriteKind != CRK_None)
13406           R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
13407 
13408         return CheckForImmediateInvocation(R, FnDecl);
13409       } else {
13410         // We matched a built-in operator. Convert the arguments, then
13411         // break out so that we will build the appropriate built-in
13412         // operator node.
13413         ExprResult ArgsRes0 = PerformImplicitConversion(
13414             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13415             AA_Passing, CCK_ForBuiltinOverloadedOp);
13416         if (ArgsRes0.isInvalid())
13417           return ExprError();
13418         Args[0] = ArgsRes0.get();
13419 
13420         ExprResult ArgsRes1 = PerformImplicitConversion(
13421             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13422             AA_Passing, CCK_ForBuiltinOverloadedOp);
13423         if (ArgsRes1.isInvalid())
13424           return ExprError();
13425         Args[1] = ArgsRes1.get();
13426         break;
13427       }
13428     }
13429 
13430     case OR_No_Viable_Function: {
13431       // C++ [over.match.oper]p9:
13432       //   If the operator is the operator , [...] and there are no
13433       //   viable functions, then the operator is assumed to be the
13434       //   built-in operator and interpreted according to clause 5.
13435       if (Opc == BO_Comma)
13436         break;
13437 
13438       // When defaulting an 'operator<=>', we can try to synthesize a three-way
13439       // compare result using '==' and '<'.
13440       if (DefaultedFn && Opc == BO_Cmp) {
13441         ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
13442                                                           Args[1], DefaultedFn);
13443         if (E.isInvalid() || E.isUsable())
13444           return E;
13445       }
13446 
13447       // For class as left operand for assignment or compound assignment
13448       // operator do not fall through to handling in built-in, but report that
13449       // no overloaded assignment operator found
13450       ExprResult Result = ExprError();
13451       StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
13452       auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
13453                                                    Args, OpLoc);
13454       if (Args[0]->getType()->isRecordType() &&
13455           Opc >= BO_Assign && Opc <= BO_OrAssign) {
13456         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
13457              << BinaryOperator::getOpcodeStr(Opc)
13458              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13459         if (Args[0]->getType()->isIncompleteType()) {
13460           Diag(OpLoc, diag::note_assign_lhs_incomplete)
13461             << Args[0]->getType()
13462             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13463         }
13464       } else {
13465         // This is an erroneous use of an operator which can be overloaded by
13466         // a non-member function. Check for non-member operators which were
13467         // defined too late to be candidates.
13468         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
13469           // FIXME: Recover by calling the found function.
13470           return ExprError();
13471 
13472         // No viable function; try to create a built-in operation, which will
13473         // produce an error. Then, show the non-viable candidates.
13474         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13475       }
13476       assert(Result.isInvalid() &&
13477              "C++ binary operator overloading is missing candidates!");
13478       CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
13479       return Result;
13480     }
13481 
13482     case OR_Ambiguous:
13483       CandidateSet.NoteCandidates(
13484           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13485                                          << BinaryOperator::getOpcodeStr(Opc)
13486                                          << Args[0]->getType()
13487                                          << Args[1]->getType()
13488                                          << Args[0]->getSourceRange()
13489                                          << Args[1]->getSourceRange()),
13490           *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13491           OpLoc);
13492       return ExprError();
13493 
13494     case OR_Deleted:
13495       if (isImplicitlyDeleted(Best->Function)) {
13496         FunctionDecl *DeletedFD = Best->Function;
13497         DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
13498         if (DFK.isSpecialMember()) {
13499           Diag(OpLoc, diag::err_ovl_deleted_special_oper)
13500             << Args[0]->getType() << DFK.asSpecialMember();
13501         } else {
13502           assert(DFK.isComparison());
13503           Diag(OpLoc, diag::err_ovl_deleted_comparison)
13504             << Args[0]->getType() << DeletedFD;
13505         }
13506 
13507         // The user probably meant to call this special member. Just
13508         // explain why it's deleted.
13509         NoteDeletedFunction(DeletedFD);
13510         return ExprError();
13511       }
13512       CandidateSet.NoteCandidates(
13513           PartialDiagnosticAt(
13514               OpLoc, PDiag(diag::err_ovl_deleted_oper)
13515                          << getOperatorSpelling(Best->Function->getDeclName()
13516                                                     .getCXXOverloadedOperator())
13517                          << Args[0]->getSourceRange()
13518                          << Args[1]->getSourceRange()),
13519           *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13520           OpLoc);
13521       return ExprError();
13522   }
13523 
13524   // We matched a built-in operator; build it.
13525   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13526 }
13527 
13528 ExprResult Sema::BuildSynthesizedThreeWayComparison(
13529     SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
13530     FunctionDecl *DefaultedFn) {
13531   const ComparisonCategoryInfo *Info =
13532       Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
13533   // If we're not producing a known comparison category type, we can't
13534   // synthesize a three-way comparison. Let the caller diagnose this.
13535   if (!Info)
13536     return ExprResult((Expr*)nullptr);
13537 
13538   // If we ever want to perform this synthesis more generally, we will need to
13539   // apply the temporary materialization conversion to the operands.
13540   assert(LHS->isGLValue() && RHS->isGLValue() &&
13541          "cannot use prvalue expressions more than once");
13542   Expr *OrigLHS = LHS;
13543   Expr *OrigRHS = RHS;
13544 
13545   // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
13546   // each of them multiple times below.
13547   LHS = new (Context)
13548       OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
13549                       LHS->getObjectKind(), LHS);
13550   RHS = new (Context)
13551       OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
13552                       RHS->getObjectKind(), RHS);
13553 
13554   ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
13555                                         DefaultedFn);
13556   if (Eq.isInvalid())
13557     return ExprError();
13558 
13559   ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
13560                                           true, DefaultedFn);
13561   if (Less.isInvalid())
13562     return ExprError();
13563 
13564   ExprResult Greater;
13565   if (Info->isPartial()) {
13566     Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
13567                                     DefaultedFn);
13568     if (Greater.isInvalid())
13569       return ExprError();
13570   }
13571 
13572   // Form the list of comparisons we're going to perform.
13573   struct Comparison {
13574     ExprResult Cmp;
13575     ComparisonCategoryResult Result;
13576   } Comparisons[4] =
13577   { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
13578                           : ComparisonCategoryResult::Equivalent},
13579     {Less, ComparisonCategoryResult::Less},
13580     {Greater, ComparisonCategoryResult::Greater},
13581     {ExprResult(), ComparisonCategoryResult::Unordered},
13582   };
13583 
13584   int I = Info->isPartial() ? 3 : 2;
13585 
13586   // Combine the comparisons with suitable conditional expressions.
13587   ExprResult Result;
13588   for (; I >= 0; --I) {
13589     // Build a reference to the comparison category constant.
13590     auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
13591     // FIXME: Missing a constant for a comparison category. Diagnose this?
13592     if (!VI)
13593       return ExprResult((Expr*)nullptr);
13594     ExprResult ThisResult =
13595         BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
13596     if (ThisResult.isInvalid())
13597       return ExprError();
13598 
13599     // Build a conditional unless this is the final case.
13600     if (Result.get()) {
13601       Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
13602                                   ThisResult.get(), Result.get());
13603       if (Result.isInvalid())
13604         return ExprError();
13605     } else {
13606       Result = ThisResult;
13607     }
13608   }
13609 
13610   // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
13611   // bind the OpaqueValueExprs before they're (repeatedly) used.
13612   Expr *SyntacticForm = new (Context)
13613       BinaryOperator(OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
13614                      Result.get()->getValueKind(),
13615                      Result.get()->getObjectKind(), OpLoc, FPFeatures);
13616   Expr *SemanticForm[] = {LHS, RHS, Result.get()};
13617   return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
13618 }
13619 
13620 ExprResult
13621 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
13622                                          SourceLocation RLoc,
13623                                          Expr *Base, Expr *Idx) {
13624   Expr *Args[2] = { Base, Idx };
13625   DeclarationName OpName =
13626       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
13627 
13628   // If either side is type-dependent, create an appropriate dependent
13629   // expression.
13630   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13631 
13632     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13633     // CHECKME: no 'operator' keyword?
13634     DeclarationNameInfo OpNameInfo(OpName, LLoc);
13635     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13636     UnresolvedLookupExpr *Fn
13637       = UnresolvedLookupExpr::Create(Context, NamingClass,
13638                                      NestedNameSpecifierLoc(), OpNameInfo,
13639                                      /*ADL*/ true, /*Overloaded*/ false,
13640                                      UnresolvedSetIterator(),
13641                                      UnresolvedSetIterator());
13642     // Can't add any actual overloads yet
13643 
13644     return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args,
13645                                        Context.DependentTy, VK_RValue, RLoc,
13646                                        FPOptions());
13647   }
13648 
13649   // Handle placeholders on both operands.
13650   if (checkPlaceholderForOverload(*this, Args[0]))
13651     return ExprError();
13652   if (checkPlaceholderForOverload(*this, Args[1]))
13653     return ExprError();
13654 
13655   // Build an empty overload set.
13656   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
13657 
13658   // Subscript can only be overloaded as a member function.
13659 
13660   // Add operator candidates that are member functions.
13661   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13662 
13663   // Add builtin operator candidates.
13664   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13665 
13666   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13667 
13668   // Perform overload resolution.
13669   OverloadCandidateSet::iterator Best;
13670   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
13671     case OR_Success: {
13672       // We found a built-in operator or an overloaded operator.
13673       FunctionDecl *FnDecl = Best->Function;
13674 
13675       if (FnDecl) {
13676         // We matched an overloaded operator. Build a call to that
13677         // operator.
13678 
13679         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
13680 
13681         // Convert the arguments.
13682         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
13683         ExprResult Arg0 =
13684           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13685                                               Best->FoundDecl, Method);
13686         if (Arg0.isInvalid())
13687           return ExprError();
13688         Args[0] = Arg0.get();
13689 
13690         // Convert the arguments.
13691         ExprResult InputInit
13692           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13693                                                       Context,
13694                                                       FnDecl->getParamDecl(0)),
13695                                       SourceLocation(),
13696                                       Args[1]);
13697         if (InputInit.isInvalid())
13698           return ExprError();
13699 
13700         Args[1] = InputInit.getAs<Expr>();
13701 
13702         // Build the actual expression node.
13703         DeclarationNameInfo OpLocInfo(OpName, LLoc);
13704         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13705         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13706                                                   Best->FoundDecl,
13707                                                   Base,
13708                                                   HadMultipleCandidates,
13709                                                   OpLocInfo.getLoc(),
13710                                                   OpLocInfo.getInfo());
13711         if (FnExpr.isInvalid())
13712           return ExprError();
13713 
13714         // Determine the result type
13715         QualType ResultTy = FnDecl->getReturnType();
13716         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13717         ResultTy = ResultTy.getNonLValueExprType(Context);
13718 
13719         CXXOperatorCallExpr *TheCall =
13720             CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(),
13721                                         Args, ResultTy, VK, RLoc, FPOptions());
13722 
13723         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
13724           return ExprError();
13725 
13726         if (CheckFunctionCall(Method, TheCall,
13727                               Method->getType()->castAs<FunctionProtoType>()))
13728           return ExprError();
13729 
13730         return MaybeBindToTemporary(TheCall);
13731       } else {
13732         // We matched a built-in operator. Convert the arguments, then
13733         // break out so that we will build the appropriate built-in
13734         // operator node.
13735         ExprResult ArgsRes0 = PerformImplicitConversion(
13736             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13737             AA_Passing, CCK_ForBuiltinOverloadedOp);
13738         if (ArgsRes0.isInvalid())
13739           return ExprError();
13740         Args[0] = ArgsRes0.get();
13741 
13742         ExprResult ArgsRes1 = PerformImplicitConversion(
13743             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13744             AA_Passing, CCK_ForBuiltinOverloadedOp);
13745         if (ArgsRes1.isInvalid())
13746           return ExprError();
13747         Args[1] = ArgsRes1.get();
13748 
13749         break;
13750       }
13751     }
13752 
13753     case OR_No_Viable_Function: {
13754       PartialDiagnostic PD = CandidateSet.empty()
13755           ? (PDiag(diag::err_ovl_no_oper)
13756              << Args[0]->getType() << /*subscript*/ 0
13757              << Args[0]->getSourceRange() << Args[1]->getSourceRange())
13758           : (PDiag(diag::err_ovl_no_viable_subscript)
13759              << Args[0]->getType() << Args[0]->getSourceRange()
13760              << Args[1]->getSourceRange());
13761       CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
13762                                   OCD_AllCandidates, Args, "[]", LLoc);
13763       return ExprError();
13764     }
13765 
13766     case OR_Ambiguous:
13767       CandidateSet.NoteCandidates(
13768           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13769                                         << "[]" << Args[0]->getType()
13770                                         << Args[1]->getType()
13771                                         << Args[0]->getSourceRange()
13772                                         << Args[1]->getSourceRange()),
13773           *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
13774       return ExprError();
13775 
13776     case OR_Deleted:
13777       CandidateSet.NoteCandidates(
13778           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
13779                                         << "[]" << Args[0]->getSourceRange()
13780                                         << Args[1]->getSourceRange()),
13781           *this, OCD_AllCandidates, Args, "[]", LLoc);
13782       return ExprError();
13783     }
13784 
13785   // We matched a built-in operator; build it.
13786   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
13787 }
13788 
13789 /// BuildCallToMemberFunction - Build a call to a member
13790 /// function. MemExpr is the expression that refers to the member
13791 /// function (and includes the object parameter), Args/NumArgs are the
13792 /// arguments to the function call (not including the object
13793 /// parameter). The caller needs to validate that the member
13794 /// expression refers to a non-static member function or an overloaded
13795 /// member function.
13796 ExprResult
13797 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
13798                                 SourceLocation LParenLoc,
13799                                 MultiExprArg Args,
13800                                 SourceLocation RParenLoc) {
13801   assert(MemExprE->getType() == Context.BoundMemberTy ||
13802          MemExprE->getType() == Context.OverloadTy);
13803 
13804   // Dig out the member expression. This holds both the object
13805   // argument and the member function we're referring to.
13806   Expr *NakedMemExpr = MemExprE->IgnoreParens();
13807 
13808   // Determine whether this is a call to a pointer-to-member function.
13809   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
13810     assert(op->getType() == Context.BoundMemberTy);
13811     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
13812 
13813     QualType fnType =
13814       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
13815 
13816     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
13817     QualType resultType = proto->getCallResultType(Context);
13818     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
13819 
13820     // Check that the object type isn't more qualified than the
13821     // member function we're calling.
13822     Qualifiers funcQuals = proto->getMethodQuals();
13823 
13824     QualType objectType = op->getLHS()->getType();
13825     if (op->getOpcode() == BO_PtrMemI)
13826       objectType = objectType->castAs<PointerType>()->getPointeeType();
13827     Qualifiers objectQuals = objectType.getQualifiers();
13828 
13829     Qualifiers difference = objectQuals - funcQuals;
13830     difference.removeObjCGCAttr();
13831     difference.removeAddressSpace();
13832     if (difference) {
13833       std::string qualsString = difference.getAsString();
13834       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
13835         << fnType.getUnqualifiedType()
13836         << qualsString
13837         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
13838     }
13839 
13840     CXXMemberCallExpr *call =
13841         CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType,
13842                                   valueKind, RParenLoc, proto->getNumParams());
13843 
13844     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
13845                             call, nullptr))
13846       return ExprError();
13847 
13848     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
13849       return ExprError();
13850 
13851     if (CheckOtherCall(call, proto))
13852       return ExprError();
13853 
13854     return MaybeBindToTemporary(call);
13855   }
13856 
13857   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
13858     return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue,
13859                             RParenLoc);
13860 
13861   UnbridgedCastsSet UnbridgedCasts;
13862   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13863     return ExprError();
13864 
13865   MemberExpr *MemExpr;
13866   CXXMethodDecl *Method = nullptr;
13867   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
13868   NestedNameSpecifier *Qualifier = nullptr;
13869   if (isa<MemberExpr>(NakedMemExpr)) {
13870     MemExpr = cast<MemberExpr>(NakedMemExpr);
13871     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
13872     FoundDecl = MemExpr->getFoundDecl();
13873     Qualifier = MemExpr->getQualifier();
13874     UnbridgedCasts.restore();
13875   } else {
13876     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
13877     Qualifier = UnresExpr->getQualifier();
13878 
13879     QualType ObjectType = UnresExpr->getBaseType();
13880     Expr::Classification ObjectClassification
13881       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
13882                             : UnresExpr->getBase()->Classify(Context);
13883 
13884     // Add overload candidates
13885     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
13886                                       OverloadCandidateSet::CSK_Normal);
13887 
13888     // FIXME: avoid copy.
13889     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13890     if (UnresExpr->hasExplicitTemplateArgs()) {
13891       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13892       TemplateArgs = &TemplateArgsBuffer;
13893     }
13894 
13895     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
13896            E = UnresExpr->decls_end(); I != E; ++I) {
13897 
13898       NamedDecl *Func = *I;
13899       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
13900       if (isa<UsingShadowDecl>(Func))
13901         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
13902 
13903 
13904       // Microsoft supports direct constructor calls.
13905       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
13906         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
13907                              CandidateSet,
13908                              /*SuppressUserConversions*/ false);
13909       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
13910         // If explicit template arguments were provided, we can't call a
13911         // non-template member function.
13912         if (TemplateArgs)
13913           continue;
13914 
13915         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
13916                            ObjectClassification, Args, CandidateSet,
13917                            /*SuppressUserConversions=*/false);
13918       } else {
13919         AddMethodTemplateCandidate(
13920             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
13921             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
13922             /*SuppressUserConversions=*/false);
13923       }
13924     }
13925 
13926     DeclarationName DeclName = UnresExpr->getMemberName();
13927 
13928     UnbridgedCasts.restore();
13929 
13930     OverloadCandidateSet::iterator Best;
13931     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
13932                                             Best)) {
13933     case OR_Success:
13934       Method = cast<CXXMethodDecl>(Best->Function);
13935       FoundDecl = Best->FoundDecl;
13936       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
13937       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
13938         return ExprError();
13939       // If FoundDecl is different from Method (such as if one is a template
13940       // and the other a specialization), make sure DiagnoseUseOfDecl is
13941       // called on both.
13942       // FIXME: This would be more comprehensively addressed by modifying
13943       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
13944       // being used.
13945       if (Method != FoundDecl.getDecl() &&
13946                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
13947         return ExprError();
13948       break;
13949 
13950     case OR_No_Viable_Function:
13951       CandidateSet.NoteCandidates(
13952           PartialDiagnosticAt(
13953               UnresExpr->getMemberLoc(),
13954               PDiag(diag::err_ovl_no_viable_member_function_in_call)
13955                   << DeclName << MemExprE->getSourceRange()),
13956           *this, OCD_AllCandidates, Args);
13957       // FIXME: Leaking incoming expressions!
13958       return ExprError();
13959 
13960     case OR_Ambiguous:
13961       CandidateSet.NoteCandidates(
13962           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
13963                               PDiag(diag::err_ovl_ambiguous_member_call)
13964                                   << DeclName << MemExprE->getSourceRange()),
13965           *this, OCD_AmbiguousCandidates, Args);
13966       // FIXME: Leaking incoming expressions!
13967       return ExprError();
13968 
13969     case OR_Deleted:
13970       CandidateSet.NoteCandidates(
13971           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
13972                               PDiag(diag::err_ovl_deleted_member_call)
13973                                   << DeclName << MemExprE->getSourceRange()),
13974           *this, OCD_AllCandidates, Args);
13975       // FIXME: Leaking incoming expressions!
13976       return ExprError();
13977     }
13978 
13979     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
13980 
13981     // If overload resolution picked a static member, build a
13982     // non-member call based on that function.
13983     if (Method->isStatic()) {
13984       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
13985                                    RParenLoc);
13986     }
13987 
13988     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
13989   }
13990 
13991   QualType ResultType = Method->getReturnType();
13992   ExprValueKind VK = Expr::getValueKindForType(ResultType);
13993   ResultType = ResultType.getNonLValueExprType(Context);
13994 
13995   assert(Method && "Member call to something that isn't a method?");
13996   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
13997   CXXMemberCallExpr *TheCall =
13998       CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
13999                                 RParenLoc, Proto->getNumParams());
14000 
14001   // Check for a valid return type.
14002   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
14003                           TheCall, Method))
14004     return ExprError();
14005 
14006   // Convert the object argument (for a non-static member function call).
14007   // We only need to do this if there was actually an overload; otherwise
14008   // it was done at lookup.
14009   if (!Method->isStatic()) {
14010     ExprResult ObjectArg =
14011       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
14012                                           FoundDecl, Method);
14013     if (ObjectArg.isInvalid())
14014       return ExprError();
14015     MemExpr->setBase(ObjectArg.get());
14016   }
14017 
14018   // Convert the rest of the arguments
14019   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
14020                               RParenLoc))
14021     return ExprError();
14022 
14023   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14024 
14025   if (CheckFunctionCall(Method, TheCall, Proto))
14026     return ExprError();
14027 
14028   // In the case the method to call was not selected by the overloading
14029   // resolution process, we still need to handle the enable_if attribute. Do
14030   // that here, so it will not hide previous -- and more relevant -- errors.
14031   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
14032     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
14033       Diag(MemE->getMemberLoc(),
14034            diag::err_ovl_no_viable_member_function_in_call)
14035           << Method << Method->getSourceRange();
14036       Diag(Method->getLocation(),
14037            diag::note_ovl_candidate_disabled_by_function_cond_attr)
14038           << Attr->getCond()->getSourceRange() << Attr->getMessage();
14039       return ExprError();
14040     }
14041   }
14042 
14043   if ((isa<CXXConstructorDecl>(CurContext) ||
14044        isa<CXXDestructorDecl>(CurContext)) &&
14045       TheCall->getMethodDecl()->isPure()) {
14046     const CXXMethodDecl *MD = TheCall->getMethodDecl();
14047 
14048     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
14049         MemExpr->performsVirtualDispatch(getLangOpts())) {
14050       Diag(MemExpr->getBeginLoc(),
14051            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
14052           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
14053           << MD->getParent()->getDeclName();
14054 
14055       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
14056       if (getLangOpts().AppleKext)
14057         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
14058             << MD->getParent()->getDeclName() << MD->getDeclName();
14059     }
14060   }
14061 
14062   if (CXXDestructorDecl *DD =
14063           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
14064     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
14065     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
14066     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
14067                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
14068                          MemExpr->getMemberLoc());
14069   }
14070 
14071   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14072                                      TheCall->getMethodDecl());
14073 }
14074 
14075 /// BuildCallToObjectOfClassType - Build a call to an object of class
14076 /// type (C++ [over.call.object]), which can end up invoking an
14077 /// overloaded function call operator (@c operator()) or performing a
14078 /// user-defined conversion on the object argument.
14079 ExprResult
14080 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
14081                                    SourceLocation LParenLoc,
14082                                    MultiExprArg Args,
14083                                    SourceLocation RParenLoc) {
14084   if (checkPlaceholderForOverload(*this, Obj))
14085     return ExprError();
14086   ExprResult Object = Obj;
14087 
14088   UnbridgedCastsSet UnbridgedCasts;
14089   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14090     return ExprError();
14091 
14092   assert(Object.get()->getType()->isRecordType() &&
14093          "Requires object type argument");
14094 
14095   // C++ [over.call.object]p1:
14096   //  If the primary-expression E in the function call syntax
14097   //  evaluates to a class object of type "cv T", then the set of
14098   //  candidate functions includes at least the function call
14099   //  operators of T. The function call operators of T are obtained by
14100   //  ordinary lookup of the name operator() in the context of
14101   //  (E).operator().
14102   OverloadCandidateSet CandidateSet(LParenLoc,
14103                                     OverloadCandidateSet::CSK_Operator);
14104   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
14105 
14106   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
14107                           diag::err_incomplete_object_call, Object.get()))
14108     return true;
14109 
14110   const auto *Record = Object.get()->getType()->castAs<RecordType>();
14111   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
14112   LookupQualifiedName(R, Record->getDecl());
14113   R.suppressDiagnostics();
14114 
14115   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14116        Oper != OperEnd; ++Oper) {
14117     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
14118                        Object.get()->Classify(Context), Args, CandidateSet,
14119                        /*SuppressUserConversion=*/false);
14120   }
14121 
14122   // C++ [over.call.object]p2:
14123   //   In addition, for each (non-explicit in C++0x) conversion function
14124   //   declared in T of the form
14125   //
14126   //        operator conversion-type-id () cv-qualifier;
14127   //
14128   //   where cv-qualifier is the same cv-qualification as, or a
14129   //   greater cv-qualification than, cv, and where conversion-type-id
14130   //   denotes the type "pointer to function of (P1,...,Pn) returning
14131   //   R", or the type "reference to pointer to function of
14132   //   (P1,...,Pn) returning R", or the type "reference to function
14133   //   of (P1,...,Pn) returning R", a surrogate call function [...]
14134   //   is also considered as a candidate function. Similarly,
14135   //   surrogate call functions are added to the set of candidate
14136   //   functions for each conversion function declared in an
14137   //   accessible base class provided the function is not hidden
14138   //   within T by another intervening declaration.
14139   const auto &Conversions =
14140       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
14141   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
14142     NamedDecl *D = *I;
14143     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
14144     if (isa<UsingShadowDecl>(D))
14145       D = cast<UsingShadowDecl>(D)->getTargetDecl();
14146 
14147     // Skip over templated conversion functions; they aren't
14148     // surrogates.
14149     if (isa<FunctionTemplateDecl>(D))
14150       continue;
14151 
14152     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
14153     if (!Conv->isExplicit()) {
14154       // Strip the reference type (if any) and then the pointer type (if
14155       // any) to get down to what might be a function type.
14156       QualType ConvType = Conv->getConversionType().getNonReferenceType();
14157       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
14158         ConvType = ConvPtrType->getPointeeType();
14159 
14160       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
14161       {
14162         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
14163                               Object.get(), Args, CandidateSet);
14164       }
14165     }
14166   }
14167 
14168   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14169 
14170   // Perform overload resolution.
14171   OverloadCandidateSet::iterator Best;
14172   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
14173                                           Best)) {
14174   case OR_Success:
14175     // Overload resolution succeeded; we'll build the appropriate call
14176     // below.
14177     break;
14178 
14179   case OR_No_Viable_Function: {
14180     PartialDiagnostic PD =
14181         CandidateSet.empty()
14182             ? (PDiag(diag::err_ovl_no_oper)
14183                << Object.get()->getType() << /*call*/ 1
14184                << Object.get()->getSourceRange())
14185             : (PDiag(diag::err_ovl_no_viable_object_call)
14186                << Object.get()->getType() << Object.get()->getSourceRange());
14187     CandidateSet.NoteCandidates(
14188         PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
14189         OCD_AllCandidates, Args);
14190     break;
14191   }
14192   case OR_Ambiguous:
14193     CandidateSet.NoteCandidates(
14194         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14195                             PDiag(diag::err_ovl_ambiguous_object_call)
14196                                 << Object.get()->getType()
14197                                 << Object.get()->getSourceRange()),
14198         *this, OCD_AmbiguousCandidates, Args);
14199     break;
14200 
14201   case OR_Deleted:
14202     CandidateSet.NoteCandidates(
14203         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14204                             PDiag(diag::err_ovl_deleted_object_call)
14205                                 << Object.get()->getType()
14206                                 << Object.get()->getSourceRange()),
14207         *this, OCD_AllCandidates, Args);
14208     break;
14209   }
14210 
14211   if (Best == CandidateSet.end())
14212     return true;
14213 
14214   UnbridgedCasts.restore();
14215 
14216   if (Best->Function == nullptr) {
14217     // Since there is no function declaration, this is one of the
14218     // surrogate candidates. Dig out the conversion function.
14219     CXXConversionDecl *Conv
14220       = cast<CXXConversionDecl>(
14221                          Best->Conversions[0].UserDefined.ConversionFunction);
14222 
14223     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
14224                               Best->FoundDecl);
14225     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
14226       return ExprError();
14227     assert(Conv == Best->FoundDecl.getDecl() &&
14228              "Found Decl & conversion-to-functionptr should be same, right?!");
14229     // We selected one of the surrogate functions that converts the
14230     // object parameter to a function pointer. Perform the conversion
14231     // on the object argument, then let BuildCallExpr finish the job.
14232 
14233     // Create an implicit member expr to refer to the conversion operator.
14234     // and then call it.
14235     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
14236                                              Conv, HadMultipleCandidates);
14237     if (Call.isInvalid())
14238       return ExprError();
14239     // Record usage of conversion in an implicit cast.
14240     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
14241                                     CK_UserDefinedConversion, Call.get(),
14242                                     nullptr, VK_RValue);
14243 
14244     return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
14245   }
14246 
14247   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
14248 
14249   // We found an overloaded operator(). Build a CXXOperatorCallExpr
14250   // that calls this method, using Object for the implicit object
14251   // parameter and passing along the remaining arguments.
14252   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14253 
14254   // An error diagnostic has already been printed when parsing the declaration.
14255   if (Method->isInvalidDecl())
14256     return ExprError();
14257 
14258   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14259   unsigned NumParams = Proto->getNumParams();
14260 
14261   DeclarationNameInfo OpLocInfo(
14262                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
14263   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
14264   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14265                                            Obj, HadMultipleCandidates,
14266                                            OpLocInfo.getLoc(),
14267                                            OpLocInfo.getInfo());
14268   if (NewFn.isInvalid())
14269     return true;
14270 
14271   // The number of argument slots to allocate in the call. If we have default
14272   // arguments we need to allocate space for them as well. We additionally
14273   // need one more slot for the object parameter.
14274   unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
14275 
14276   // Build the full argument list for the method call (the implicit object
14277   // parameter is placed at the beginning of the list).
14278   SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
14279 
14280   bool IsError = false;
14281 
14282   // Initialize the implicit object parameter.
14283   ExprResult ObjRes =
14284     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
14285                                         Best->FoundDecl, Method);
14286   if (ObjRes.isInvalid())
14287     IsError = true;
14288   else
14289     Object = ObjRes;
14290   MethodArgs[0] = Object.get();
14291 
14292   // Check the argument types.
14293   for (unsigned i = 0; i != NumParams; i++) {
14294     Expr *Arg;
14295     if (i < Args.size()) {
14296       Arg = Args[i];
14297 
14298       // Pass the argument.
14299 
14300       ExprResult InputInit
14301         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14302                                                     Context,
14303                                                     Method->getParamDecl(i)),
14304                                     SourceLocation(), Arg);
14305 
14306       IsError |= InputInit.isInvalid();
14307       Arg = InputInit.getAs<Expr>();
14308     } else {
14309       ExprResult DefArg
14310         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14311       if (DefArg.isInvalid()) {
14312         IsError = true;
14313         break;
14314       }
14315 
14316       Arg = DefArg.getAs<Expr>();
14317     }
14318 
14319     MethodArgs[i + 1] = Arg;
14320   }
14321 
14322   // If this is a variadic call, handle args passed through "...".
14323   if (Proto->isVariadic()) {
14324     // Promote the arguments (C99 6.5.2.2p7).
14325     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
14326       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
14327                                                         nullptr);
14328       IsError |= Arg.isInvalid();
14329       MethodArgs[i + 1] = Arg.get();
14330     }
14331   }
14332 
14333   if (IsError)
14334     return true;
14335 
14336   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14337 
14338   // Once we've built TheCall, all of the expressions are properly owned.
14339   QualType ResultTy = Method->getReturnType();
14340   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14341   ResultTy = ResultTy.getNonLValueExprType(Context);
14342 
14343   CXXOperatorCallExpr *TheCall =
14344       CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs,
14345                                   ResultTy, VK, RParenLoc, FPOptions());
14346 
14347   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
14348     return true;
14349 
14350   if (CheckFunctionCall(Method, TheCall, Proto))
14351     return true;
14352 
14353   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
14354 }
14355 
14356 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
14357 ///  (if one exists), where @c Base is an expression of class type and
14358 /// @c Member is the name of the member we're trying to find.
14359 ExprResult
14360 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
14361                                bool *NoArrowOperatorFound) {
14362   assert(Base->getType()->isRecordType() &&
14363          "left-hand side must have class type");
14364 
14365   if (checkPlaceholderForOverload(*this, Base))
14366     return ExprError();
14367 
14368   SourceLocation Loc = Base->getExprLoc();
14369 
14370   // C++ [over.ref]p1:
14371   //
14372   //   [...] An expression x->m is interpreted as (x.operator->())->m
14373   //   for a class object x of type T if T::operator->() exists and if
14374   //   the operator is selected as the best match function by the
14375   //   overload resolution mechanism (13.3).
14376   DeclarationName OpName =
14377     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
14378   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
14379 
14380   if (RequireCompleteType(Loc, Base->getType(),
14381                           diag::err_typecheck_incomplete_tag, Base))
14382     return ExprError();
14383 
14384   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
14385   LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
14386   R.suppressDiagnostics();
14387 
14388   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14389        Oper != OperEnd; ++Oper) {
14390     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
14391                        None, CandidateSet, /*SuppressUserConversion=*/false);
14392   }
14393 
14394   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14395 
14396   // Perform overload resolution.
14397   OverloadCandidateSet::iterator Best;
14398   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14399   case OR_Success:
14400     // Overload resolution succeeded; we'll build the call below.
14401     break;
14402 
14403   case OR_No_Viable_Function: {
14404     auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
14405     if (CandidateSet.empty()) {
14406       QualType BaseType = Base->getType();
14407       if (NoArrowOperatorFound) {
14408         // Report this specific error to the caller instead of emitting a
14409         // diagnostic, as requested.
14410         *NoArrowOperatorFound = true;
14411         return ExprError();
14412       }
14413       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
14414         << BaseType << Base->getSourceRange();
14415       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
14416         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
14417           << FixItHint::CreateReplacement(OpLoc, ".");
14418       }
14419     } else
14420       Diag(OpLoc, diag::err_ovl_no_viable_oper)
14421         << "operator->" << Base->getSourceRange();
14422     CandidateSet.NoteCandidates(*this, Base, Cands);
14423     return ExprError();
14424   }
14425   case OR_Ambiguous:
14426     CandidateSet.NoteCandidates(
14427         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
14428                                        << "->" << Base->getType()
14429                                        << Base->getSourceRange()),
14430         *this, OCD_AmbiguousCandidates, Base);
14431     return ExprError();
14432 
14433   case OR_Deleted:
14434     CandidateSet.NoteCandidates(
14435         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14436                                        << "->" << Base->getSourceRange()),
14437         *this, OCD_AllCandidates, Base);
14438     return ExprError();
14439   }
14440 
14441   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
14442 
14443   // Convert the object parameter.
14444   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14445   ExprResult BaseResult =
14446     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
14447                                         Best->FoundDecl, Method);
14448   if (BaseResult.isInvalid())
14449     return ExprError();
14450   Base = BaseResult.get();
14451 
14452   // Build the operator call.
14453   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14454                                             Base, HadMultipleCandidates, OpLoc);
14455   if (FnExpr.isInvalid())
14456     return ExprError();
14457 
14458   QualType ResultTy = Method->getReturnType();
14459   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14460   ResultTy = ResultTy.getNonLValueExprType(Context);
14461   CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14462       Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions());
14463 
14464   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
14465     return ExprError();
14466 
14467   if (CheckFunctionCall(Method, TheCall,
14468                         Method->getType()->castAs<FunctionProtoType>()))
14469     return ExprError();
14470 
14471   return MaybeBindToTemporary(TheCall);
14472 }
14473 
14474 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
14475 /// a literal operator described by the provided lookup results.
14476 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
14477                                           DeclarationNameInfo &SuffixInfo,
14478                                           ArrayRef<Expr*> Args,
14479                                           SourceLocation LitEndLoc,
14480                                        TemplateArgumentListInfo *TemplateArgs) {
14481   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
14482 
14483   OverloadCandidateSet CandidateSet(UDSuffixLoc,
14484                                     OverloadCandidateSet::CSK_Normal);
14485   AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
14486                                  TemplateArgs);
14487 
14488   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14489 
14490   // Perform overload resolution. This will usually be trivial, but might need
14491   // to perform substitutions for a literal operator template.
14492   OverloadCandidateSet::iterator Best;
14493   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
14494   case OR_Success:
14495   case OR_Deleted:
14496     break;
14497 
14498   case OR_No_Viable_Function:
14499     CandidateSet.NoteCandidates(
14500         PartialDiagnosticAt(UDSuffixLoc,
14501                             PDiag(diag::err_ovl_no_viable_function_in_call)
14502                                 << R.getLookupName()),
14503         *this, OCD_AllCandidates, Args);
14504     return ExprError();
14505 
14506   case OR_Ambiguous:
14507     CandidateSet.NoteCandidates(
14508         PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
14509                                                 << R.getLookupName()),
14510         *this, OCD_AmbiguousCandidates, Args);
14511     return ExprError();
14512   }
14513 
14514   FunctionDecl *FD = Best->Function;
14515   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
14516                                         nullptr, HadMultipleCandidates,
14517                                         SuffixInfo.getLoc(),
14518                                         SuffixInfo.getInfo());
14519   if (Fn.isInvalid())
14520     return true;
14521 
14522   // Check the argument types. This should almost always be a no-op, except
14523   // that array-to-pointer decay is applied to string literals.
14524   Expr *ConvArgs[2];
14525   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
14526     ExprResult InputInit = PerformCopyInitialization(
14527       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
14528       SourceLocation(), Args[ArgIdx]);
14529     if (InputInit.isInvalid())
14530       return true;
14531     ConvArgs[ArgIdx] = InputInit.get();
14532   }
14533 
14534   QualType ResultTy = FD->getReturnType();
14535   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14536   ResultTy = ResultTy.getNonLValueExprType(Context);
14537 
14538   UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
14539       Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
14540       VK, LitEndLoc, UDSuffixLoc);
14541 
14542   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
14543     return ExprError();
14544 
14545   if (CheckFunctionCall(FD, UDL, nullptr))
14546     return ExprError();
14547 
14548   return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
14549 }
14550 
14551 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
14552 /// given LookupResult is non-empty, it is assumed to describe a member which
14553 /// will be invoked. Otherwise, the function will be found via argument
14554 /// dependent lookup.
14555 /// CallExpr is set to a valid expression and FRS_Success returned on success,
14556 /// otherwise CallExpr is set to ExprError() and some non-success value
14557 /// is returned.
14558 Sema::ForRangeStatus
14559 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
14560                                 SourceLocation RangeLoc,
14561                                 const DeclarationNameInfo &NameInfo,
14562                                 LookupResult &MemberLookup,
14563                                 OverloadCandidateSet *CandidateSet,
14564                                 Expr *Range, ExprResult *CallExpr) {
14565   Scope *S = nullptr;
14566 
14567   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
14568   if (!MemberLookup.empty()) {
14569     ExprResult MemberRef =
14570         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
14571                                  /*IsPtr=*/false, CXXScopeSpec(),
14572                                  /*TemplateKWLoc=*/SourceLocation(),
14573                                  /*FirstQualifierInScope=*/nullptr,
14574                                  MemberLookup,
14575                                  /*TemplateArgs=*/nullptr, S);
14576     if (MemberRef.isInvalid()) {
14577       *CallExpr = ExprError();
14578       return FRS_DiagnosticIssued;
14579     }
14580     *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
14581     if (CallExpr->isInvalid()) {
14582       *CallExpr = ExprError();
14583       return FRS_DiagnosticIssued;
14584     }
14585   } else {
14586     UnresolvedSet<0> FoundNames;
14587     UnresolvedLookupExpr *Fn =
14588       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
14589                                    NestedNameSpecifierLoc(), NameInfo,
14590                                    /*NeedsADL=*/true, /*Overloaded=*/false,
14591                                    FoundNames.begin(), FoundNames.end());
14592 
14593     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
14594                                                     CandidateSet, CallExpr);
14595     if (CandidateSet->empty() || CandidateSetError) {
14596       *CallExpr = ExprError();
14597       return FRS_NoViableFunction;
14598     }
14599     OverloadCandidateSet::iterator Best;
14600     OverloadingResult OverloadResult =
14601         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
14602 
14603     if (OverloadResult == OR_No_Viable_Function) {
14604       *CallExpr = ExprError();
14605       return FRS_NoViableFunction;
14606     }
14607     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
14608                                          Loc, nullptr, CandidateSet, &Best,
14609                                          OverloadResult,
14610                                          /*AllowTypoCorrection=*/false);
14611     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
14612       *CallExpr = ExprError();
14613       return FRS_DiagnosticIssued;
14614     }
14615   }
14616   return FRS_Success;
14617 }
14618 
14619 
14620 /// FixOverloadedFunctionReference - E is an expression that refers to
14621 /// a C++ overloaded function (possibly with some parentheses and
14622 /// perhaps a '&' around it). We have resolved the overloaded function
14623 /// to the function declaration Fn, so patch up the expression E to
14624 /// refer (possibly indirectly) to Fn. Returns the new expr.
14625 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
14626                                            FunctionDecl *Fn) {
14627   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
14628     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
14629                                                    Found, Fn);
14630     if (SubExpr == PE->getSubExpr())
14631       return PE;
14632 
14633     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
14634   }
14635 
14636   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
14637     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
14638                                                    Found, Fn);
14639     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
14640                                SubExpr->getType()) &&
14641            "Implicit cast type cannot be determined from overload");
14642     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
14643     if (SubExpr == ICE->getSubExpr())
14644       return ICE;
14645 
14646     return ImplicitCastExpr::Create(Context, ICE->getType(),
14647                                     ICE->getCastKind(),
14648                                     SubExpr, nullptr,
14649                                     ICE->getValueKind());
14650   }
14651 
14652   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
14653     if (!GSE->isResultDependent()) {
14654       Expr *SubExpr =
14655           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
14656       if (SubExpr == GSE->getResultExpr())
14657         return GSE;
14658 
14659       // Replace the resulting type information before rebuilding the generic
14660       // selection expression.
14661       ArrayRef<Expr *> A = GSE->getAssocExprs();
14662       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
14663       unsigned ResultIdx = GSE->getResultIndex();
14664       AssocExprs[ResultIdx] = SubExpr;
14665 
14666       return GenericSelectionExpr::Create(
14667           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
14668           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
14669           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
14670           ResultIdx);
14671     }
14672     // Rather than fall through to the unreachable, return the original generic
14673     // selection expression.
14674     return GSE;
14675   }
14676 
14677   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
14678     assert(UnOp->getOpcode() == UO_AddrOf &&
14679            "Can only take the address of an overloaded function");
14680     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
14681       if (Method->isStatic()) {
14682         // Do nothing: static member functions aren't any different
14683         // from non-member functions.
14684       } else {
14685         // Fix the subexpression, which really has to be an
14686         // UnresolvedLookupExpr holding an overloaded member function
14687         // or template.
14688         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14689                                                        Found, Fn);
14690         if (SubExpr == UnOp->getSubExpr())
14691           return UnOp;
14692 
14693         assert(isa<DeclRefExpr>(SubExpr)
14694                && "fixed to something other than a decl ref");
14695         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
14696                && "fixed to a member ref with no nested name qualifier");
14697 
14698         // We have taken the address of a pointer to member
14699         // function. Perform the computation here so that we get the
14700         // appropriate pointer to member type.
14701         QualType ClassType
14702           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
14703         QualType MemPtrType
14704           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
14705         // Under the MS ABI, lock down the inheritance model now.
14706         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14707           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
14708 
14709         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
14710                                            VK_RValue, OK_Ordinary,
14711                                            UnOp->getOperatorLoc(), false);
14712       }
14713     }
14714     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14715                                                    Found, Fn);
14716     if (SubExpr == UnOp->getSubExpr())
14717       return UnOp;
14718 
14719     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
14720                                      Context.getPointerType(SubExpr->getType()),
14721                                        VK_RValue, OK_Ordinary,
14722                                        UnOp->getOperatorLoc(), false);
14723   }
14724 
14725   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14726     // FIXME: avoid copy.
14727     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14728     if (ULE->hasExplicitTemplateArgs()) {
14729       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
14730       TemplateArgs = &TemplateArgsBuffer;
14731     }
14732 
14733     DeclRefExpr *DRE =
14734         BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(),
14735                          ULE->getQualifierLoc(), Found.getDecl(),
14736                          ULE->getTemplateKeywordLoc(), TemplateArgs);
14737     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
14738     return DRE;
14739   }
14740 
14741   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
14742     // FIXME: avoid copy.
14743     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14744     if (MemExpr->hasExplicitTemplateArgs()) {
14745       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14746       TemplateArgs = &TemplateArgsBuffer;
14747     }
14748 
14749     Expr *Base;
14750 
14751     // If we're filling in a static method where we used to have an
14752     // implicit member access, rewrite to a simple decl ref.
14753     if (MemExpr->isImplicitAccess()) {
14754       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14755         DeclRefExpr *DRE = BuildDeclRefExpr(
14756             Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
14757             MemExpr->getQualifierLoc(), Found.getDecl(),
14758             MemExpr->getTemplateKeywordLoc(), TemplateArgs);
14759         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
14760         return DRE;
14761       } else {
14762         SourceLocation Loc = MemExpr->getMemberLoc();
14763         if (MemExpr->getQualifier())
14764           Loc = MemExpr->getQualifierLoc().getBeginLoc();
14765         Base =
14766             BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
14767       }
14768     } else
14769       Base = MemExpr->getBase();
14770 
14771     ExprValueKind valueKind;
14772     QualType type;
14773     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14774       valueKind = VK_LValue;
14775       type = Fn->getType();
14776     } else {
14777       valueKind = VK_RValue;
14778       type = Context.BoundMemberTy;
14779     }
14780 
14781     return BuildMemberExpr(
14782         Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
14783         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
14784         /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
14785         type, valueKind, OK_Ordinary, TemplateArgs);
14786   }
14787 
14788   llvm_unreachable("Invalid reference to overloaded function");
14789 }
14790 
14791 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
14792                                                 DeclAccessPair Found,
14793                                                 FunctionDecl *Fn) {
14794   return FixOverloadedFunctionReference(E.get(), Found, Fn);
14795 }
14796