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       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
350       assert(Initializer && "Unknown conversion expression");
351 
352       // If it's value-dependent, we can't tell whether it's narrowing.
353       if (Initializer->isValueDependent())
354         return NK_Dependent_Narrowing;
355 
356       if (Optional<llvm::APSInt> IntConstantValue =
357               Initializer->getIntegerConstantExpr(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       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
434 
435       // If it's value-dependent, we can't tell whether it's narrowing.
436       if (Initializer->isValueDependent())
437         return NK_Dependent_Narrowing;
438 
439       Optional<llvm::APSInt> OptInitializerValue;
440       if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) {
441         // Such conversions on variables are always narrowing.
442         return NK_Variable_Narrowing;
443       }
444       llvm::APSInt &InitializerValue = *OptInitializerValue;
445       bool Narrowing = false;
446       if (FromWidth < ToWidth) {
447         // Negative -> unsigned is narrowing. Otherwise, more bits is never
448         // narrowing.
449         if (InitializerValue.isSigned() && InitializerValue.isNegative())
450           Narrowing = true;
451       } else {
452         // Add a bit to the InitializerValue so we don't have to worry about
453         // signed vs. unsigned comparisons.
454         InitializerValue = InitializerValue.extend(
455           InitializerValue.getBitWidth() + 1);
456         // Convert the initializer to and from the target width and signed-ness.
457         llvm::APSInt ConvertedValue = InitializerValue;
458         ConvertedValue = ConvertedValue.trunc(ToWidth);
459         ConvertedValue.setIsSigned(ToSigned);
460         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
461         ConvertedValue.setIsSigned(InitializerValue.isSigned());
462         // If the result is different, this was a narrowing conversion.
463         if (ConvertedValue != InitializerValue)
464           Narrowing = true;
465       }
466       if (Narrowing) {
467         ConstantType = Initializer->getType();
468         ConstantValue = APValue(InitializerValue);
469         return NK_Constant_Narrowing;
470       }
471     }
472     return NK_Not_Narrowing;
473   }
474 
475   default:
476     // Other kinds of conversions are not narrowings.
477     return NK_Not_Narrowing;
478   }
479 }
480 
481 /// dump - Print this standard conversion sequence to standard
482 /// error. Useful for debugging overloading issues.
483 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
484   raw_ostream &OS = llvm::errs();
485   bool PrintedSomething = false;
486   if (First != ICK_Identity) {
487     OS << GetImplicitConversionName(First);
488     PrintedSomething = true;
489   }
490 
491   if (Second != ICK_Identity) {
492     if (PrintedSomething) {
493       OS << " -> ";
494     }
495     OS << GetImplicitConversionName(Second);
496 
497     if (CopyConstructor) {
498       OS << " (by copy constructor)";
499     } else if (DirectBinding) {
500       OS << " (direct reference binding)";
501     } else if (ReferenceBinding) {
502       OS << " (reference binding)";
503     }
504     PrintedSomething = true;
505   }
506 
507   if (Third != ICK_Identity) {
508     if (PrintedSomething) {
509       OS << " -> ";
510     }
511     OS << GetImplicitConversionName(Third);
512     PrintedSomething = true;
513   }
514 
515   if (!PrintedSomething) {
516     OS << "No conversions required";
517   }
518 }
519 
520 /// dump - Print this user-defined conversion sequence to standard
521 /// error. Useful for debugging overloading issues.
522 void UserDefinedConversionSequence::dump() const {
523   raw_ostream &OS = llvm::errs();
524   if (Before.First || Before.Second || Before.Third) {
525     Before.dump();
526     OS << " -> ";
527   }
528   if (ConversionFunction)
529     OS << '\'' << *ConversionFunction << '\'';
530   else
531     OS << "aggregate initialization";
532   if (After.First || After.Second || After.Third) {
533     OS << " -> ";
534     After.dump();
535   }
536 }
537 
538 /// dump - Print this implicit conversion sequence to standard
539 /// error. Useful for debugging overloading issues.
540 void ImplicitConversionSequence::dump() const {
541   raw_ostream &OS = llvm::errs();
542   if (isStdInitializerListElement())
543     OS << "Worst std::initializer_list element conversion: ";
544   switch (ConversionKind) {
545   case StandardConversion:
546     OS << "Standard conversion: ";
547     Standard.dump();
548     break;
549   case UserDefinedConversion:
550     OS << "User-defined conversion: ";
551     UserDefined.dump();
552     break;
553   case EllipsisConversion:
554     OS << "Ellipsis conversion";
555     break;
556   case AmbiguousConversion:
557     OS << "Ambiguous conversion";
558     break;
559   case BadConversion:
560     OS << "Bad conversion";
561     break;
562   }
563 
564   OS << "\n";
565 }
566 
567 void AmbiguousConversionSequence::construct() {
568   new (&conversions()) ConversionSet();
569 }
570 
571 void AmbiguousConversionSequence::destruct() {
572   conversions().~ConversionSet();
573 }
574 
575 void
576 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
577   FromTypePtr = O.FromTypePtr;
578   ToTypePtr = O.ToTypePtr;
579   new (&conversions()) ConversionSet(O.conversions());
580 }
581 
582 namespace {
583   // Structure used by DeductionFailureInfo to store
584   // template argument information.
585   struct DFIArguments {
586     TemplateArgument FirstArg;
587     TemplateArgument SecondArg;
588   };
589   // Structure used by DeductionFailureInfo to store
590   // template parameter and template argument information.
591   struct DFIParamWithArguments : DFIArguments {
592     TemplateParameter Param;
593   };
594   // Structure used by DeductionFailureInfo to store template argument
595   // information and the index of the problematic call argument.
596   struct DFIDeducedMismatchArgs : DFIArguments {
597     TemplateArgumentList *TemplateArgs;
598     unsigned CallArgIndex;
599   };
600   // Structure used by DeductionFailureInfo to store information about
601   // unsatisfied constraints.
602   struct CNSInfo {
603     TemplateArgumentList *TemplateArgs;
604     ConstraintSatisfaction Satisfaction;
605   };
606 }
607 
608 /// Convert from Sema's representation of template deduction information
609 /// to the form used in overload-candidate information.
610 DeductionFailureInfo
611 clang::MakeDeductionFailureInfo(ASTContext &Context,
612                                 Sema::TemplateDeductionResult TDK,
613                                 TemplateDeductionInfo &Info) {
614   DeductionFailureInfo Result;
615   Result.Result = static_cast<unsigned>(TDK);
616   Result.HasDiagnostic = false;
617   switch (TDK) {
618   case Sema::TDK_Invalid:
619   case Sema::TDK_InstantiationDepth:
620   case Sema::TDK_TooManyArguments:
621   case Sema::TDK_TooFewArguments:
622   case Sema::TDK_MiscellaneousDeductionFailure:
623   case Sema::TDK_CUDATargetMismatch:
624     Result.Data = nullptr;
625     break;
626 
627   case Sema::TDK_Incomplete:
628   case Sema::TDK_InvalidExplicitArguments:
629     Result.Data = Info.Param.getOpaqueValue();
630     break;
631 
632   case Sema::TDK_DeducedMismatch:
633   case Sema::TDK_DeducedMismatchNested: {
634     // FIXME: Should allocate from normal heap so that we can free this later.
635     auto *Saved = new (Context) DFIDeducedMismatchArgs;
636     Saved->FirstArg = Info.FirstArg;
637     Saved->SecondArg = Info.SecondArg;
638     Saved->TemplateArgs = Info.take();
639     Saved->CallArgIndex = Info.CallArgIndex;
640     Result.Data = Saved;
641     break;
642   }
643 
644   case Sema::TDK_NonDeducedMismatch: {
645     // FIXME: Should allocate from normal heap so that we can free this later.
646     DFIArguments *Saved = new (Context) DFIArguments;
647     Saved->FirstArg = Info.FirstArg;
648     Saved->SecondArg = Info.SecondArg;
649     Result.Data = Saved;
650     break;
651   }
652 
653   case Sema::TDK_IncompletePack:
654     // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
655   case Sema::TDK_Inconsistent:
656   case Sema::TDK_Underqualified: {
657     // FIXME: Should allocate from normal heap so that we can free this later.
658     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
659     Saved->Param = Info.Param;
660     Saved->FirstArg = Info.FirstArg;
661     Saved->SecondArg = Info.SecondArg;
662     Result.Data = Saved;
663     break;
664   }
665 
666   case Sema::TDK_SubstitutionFailure:
667     Result.Data = Info.take();
668     if (Info.hasSFINAEDiagnostic()) {
669       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
670           SourceLocation(), PartialDiagnostic::NullDiagnostic());
671       Info.takeSFINAEDiagnostic(*Diag);
672       Result.HasDiagnostic = true;
673     }
674     break;
675 
676   case Sema::TDK_ConstraintsNotSatisfied: {
677     CNSInfo *Saved = new (Context) CNSInfo;
678     Saved->TemplateArgs = Info.take();
679     Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
680     Result.Data = Saved;
681     break;
682   }
683 
684   case Sema::TDK_Success:
685   case Sema::TDK_NonDependentConversionFailure:
686     llvm_unreachable("not a deduction failure");
687   }
688 
689   return Result;
690 }
691 
692 void DeductionFailureInfo::Destroy() {
693   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
694   case Sema::TDK_Success:
695   case Sema::TDK_Invalid:
696   case Sema::TDK_InstantiationDepth:
697   case Sema::TDK_Incomplete:
698   case Sema::TDK_TooManyArguments:
699   case Sema::TDK_TooFewArguments:
700   case Sema::TDK_InvalidExplicitArguments:
701   case Sema::TDK_CUDATargetMismatch:
702   case Sema::TDK_NonDependentConversionFailure:
703     break;
704 
705   case Sema::TDK_IncompletePack:
706   case Sema::TDK_Inconsistent:
707   case Sema::TDK_Underqualified:
708   case Sema::TDK_DeducedMismatch:
709   case Sema::TDK_DeducedMismatchNested:
710   case Sema::TDK_NonDeducedMismatch:
711     // FIXME: Destroy the data?
712     Data = nullptr;
713     break;
714 
715   case Sema::TDK_SubstitutionFailure:
716     // FIXME: Destroy the template argument list?
717     Data = nullptr;
718     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
719       Diag->~PartialDiagnosticAt();
720       HasDiagnostic = false;
721     }
722     break;
723 
724   case Sema::TDK_ConstraintsNotSatisfied:
725     // FIXME: Destroy the template argument list?
726     Data = nullptr;
727     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
728       Diag->~PartialDiagnosticAt();
729       HasDiagnostic = false;
730     }
731     break;
732 
733   // Unhandled
734   case Sema::TDK_MiscellaneousDeductionFailure:
735     break;
736   }
737 }
738 
739 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
740   if (HasDiagnostic)
741     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
742   return nullptr;
743 }
744 
745 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
746   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
747   case Sema::TDK_Success:
748   case Sema::TDK_Invalid:
749   case Sema::TDK_InstantiationDepth:
750   case Sema::TDK_TooManyArguments:
751   case Sema::TDK_TooFewArguments:
752   case Sema::TDK_SubstitutionFailure:
753   case Sema::TDK_DeducedMismatch:
754   case Sema::TDK_DeducedMismatchNested:
755   case Sema::TDK_NonDeducedMismatch:
756   case Sema::TDK_CUDATargetMismatch:
757   case Sema::TDK_NonDependentConversionFailure:
758   case Sema::TDK_ConstraintsNotSatisfied:
759     return TemplateParameter();
760 
761   case Sema::TDK_Incomplete:
762   case Sema::TDK_InvalidExplicitArguments:
763     return TemplateParameter::getFromOpaqueValue(Data);
764 
765   case Sema::TDK_IncompletePack:
766   case Sema::TDK_Inconsistent:
767   case Sema::TDK_Underqualified:
768     return static_cast<DFIParamWithArguments*>(Data)->Param;
769 
770   // Unhandled
771   case Sema::TDK_MiscellaneousDeductionFailure:
772     break;
773   }
774 
775   return TemplateParameter();
776 }
777 
778 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
779   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
780   case Sema::TDK_Success:
781   case Sema::TDK_Invalid:
782   case Sema::TDK_InstantiationDepth:
783   case Sema::TDK_TooManyArguments:
784   case Sema::TDK_TooFewArguments:
785   case Sema::TDK_Incomplete:
786   case Sema::TDK_IncompletePack:
787   case Sema::TDK_InvalidExplicitArguments:
788   case Sema::TDK_Inconsistent:
789   case Sema::TDK_Underqualified:
790   case Sema::TDK_NonDeducedMismatch:
791   case Sema::TDK_CUDATargetMismatch:
792   case Sema::TDK_NonDependentConversionFailure:
793     return nullptr;
794 
795   case Sema::TDK_DeducedMismatch:
796   case Sema::TDK_DeducedMismatchNested:
797     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
798 
799   case Sema::TDK_SubstitutionFailure:
800     return static_cast<TemplateArgumentList*>(Data);
801 
802   case Sema::TDK_ConstraintsNotSatisfied:
803     return static_cast<CNSInfo*>(Data)->TemplateArgs;
804 
805   // Unhandled
806   case Sema::TDK_MiscellaneousDeductionFailure:
807     break;
808   }
809 
810   return nullptr;
811 }
812 
813 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
814   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
815   case Sema::TDK_Success:
816   case Sema::TDK_Invalid:
817   case Sema::TDK_InstantiationDepth:
818   case Sema::TDK_Incomplete:
819   case Sema::TDK_TooManyArguments:
820   case Sema::TDK_TooFewArguments:
821   case Sema::TDK_InvalidExplicitArguments:
822   case Sema::TDK_SubstitutionFailure:
823   case Sema::TDK_CUDATargetMismatch:
824   case Sema::TDK_NonDependentConversionFailure:
825   case Sema::TDK_ConstraintsNotSatisfied:
826     return nullptr;
827 
828   case Sema::TDK_IncompletePack:
829   case Sema::TDK_Inconsistent:
830   case Sema::TDK_Underqualified:
831   case Sema::TDK_DeducedMismatch:
832   case Sema::TDK_DeducedMismatchNested:
833   case Sema::TDK_NonDeducedMismatch:
834     return &static_cast<DFIArguments*>(Data)->FirstArg;
835 
836   // Unhandled
837   case Sema::TDK_MiscellaneousDeductionFailure:
838     break;
839   }
840 
841   return nullptr;
842 }
843 
844 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
845   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
846   case Sema::TDK_Success:
847   case Sema::TDK_Invalid:
848   case Sema::TDK_InstantiationDepth:
849   case Sema::TDK_Incomplete:
850   case Sema::TDK_IncompletePack:
851   case Sema::TDK_TooManyArguments:
852   case Sema::TDK_TooFewArguments:
853   case Sema::TDK_InvalidExplicitArguments:
854   case Sema::TDK_SubstitutionFailure:
855   case Sema::TDK_CUDATargetMismatch:
856   case Sema::TDK_NonDependentConversionFailure:
857   case Sema::TDK_ConstraintsNotSatisfied:
858     return nullptr;
859 
860   case Sema::TDK_Inconsistent:
861   case Sema::TDK_Underqualified:
862   case Sema::TDK_DeducedMismatch:
863   case Sema::TDK_DeducedMismatchNested:
864   case Sema::TDK_NonDeducedMismatch:
865     return &static_cast<DFIArguments*>(Data)->SecondArg;
866 
867   // Unhandled
868   case Sema::TDK_MiscellaneousDeductionFailure:
869     break;
870   }
871 
872   return nullptr;
873 }
874 
875 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
876   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
877   case Sema::TDK_DeducedMismatch:
878   case Sema::TDK_DeducedMismatchNested:
879     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
880 
881   default:
882     return llvm::None;
883   }
884 }
885 
886 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
887     OverloadedOperatorKind Op) {
888   if (!AllowRewrittenCandidates)
889     return false;
890   return Op == OO_EqualEqual || Op == OO_Spaceship;
891 }
892 
893 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
894     ASTContext &Ctx, const FunctionDecl *FD) {
895   if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator()))
896     return false;
897   // Don't bother adding a reversed candidate that can never be a better
898   // match than the non-reversed version.
899   return FD->getNumParams() != 2 ||
900          !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
901                                      FD->getParamDecl(1)->getType()) ||
902          FD->hasAttr<EnableIfAttr>();
903 }
904 
905 void OverloadCandidateSet::destroyCandidates() {
906   for (iterator i = begin(), e = end(); i != e; ++i) {
907     for (auto &C : i->Conversions)
908       C.~ImplicitConversionSequence();
909     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
910       i->DeductionFailure.Destroy();
911   }
912 }
913 
914 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
915   destroyCandidates();
916   SlabAllocator.Reset();
917   NumInlineBytesUsed = 0;
918   Candidates.clear();
919   Functions.clear();
920   Kind = CSK;
921 }
922 
923 namespace {
924   class UnbridgedCastsSet {
925     struct Entry {
926       Expr **Addr;
927       Expr *Saved;
928     };
929     SmallVector<Entry, 2> Entries;
930 
931   public:
932     void save(Sema &S, Expr *&E) {
933       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
934       Entry entry = { &E, E };
935       Entries.push_back(entry);
936       E = S.stripARCUnbridgedCast(E);
937     }
938 
939     void restore() {
940       for (SmallVectorImpl<Entry>::iterator
941              i = Entries.begin(), e = Entries.end(); i != e; ++i)
942         *i->Addr = i->Saved;
943     }
944   };
945 }
946 
947 /// checkPlaceholderForOverload - Do any interesting placeholder-like
948 /// preprocessing on the given expression.
949 ///
950 /// \param unbridgedCasts a collection to which to add unbridged casts;
951 ///   without this, they will be immediately diagnosed as errors
952 ///
953 /// Return true on unrecoverable error.
954 static bool
955 checkPlaceholderForOverload(Sema &S, Expr *&E,
956                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
957   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
958     // We can't handle overloaded expressions here because overload
959     // resolution might reasonably tweak them.
960     if (placeholder->getKind() == BuiltinType::Overload) return false;
961 
962     // If the context potentially accepts unbridged ARC casts, strip
963     // the unbridged cast and add it to the collection for later restoration.
964     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
965         unbridgedCasts) {
966       unbridgedCasts->save(S, E);
967       return false;
968     }
969 
970     // Go ahead and check everything else.
971     ExprResult result = S.CheckPlaceholderExpr(E);
972     if (result.isInvalid())
973       return true;
974 
975     E = result.get();
976     return false;
977   }
978 
979   // Nothing to do.
980   return false;
981 }
982 
983 /// checkArgPlaceholdersForOverload - Check a set of call operands for
984 /// placeholders.
985 static bool checkArgPlaceholdersForOverload(Sema &S,
986                                             MultiExprArg Args,
987                                             UnbridgedCastsSet &unbridged) {
988   for (unsigned i = 0, e = Args.size(); i != e; ++i)
989     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
990       return true;
991 
992   return false;
993 }
994 
995 /// Determine whether the given New declaration is an overload of the
996 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
997 /// New and Old cannot be overloaded, e.g., if New has the same signature as
998 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
999 /// functions (or function templates) at all. When it does return Ovl_Match or
1000 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1001 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1002 /// declaration.
1003 ///
1004 /// Example: Given the following input:
1005 ///
1006 ///   void f(int, float); // #1
1007 ///   void f(int, int); // #2
1008 ///   int f(int, int); // #3
1009 ///
1010 /// When we process #1, there is no previous declaration of "f", so IsOverload
1011 /// will not be used.
1012 ///
1013 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1014 /// the parameter types, we see that #1 and #2 are overloaded (since they have
1015 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1016 /// unchanged.
1017 ///
1018 /// When we process #3, Old is an overload set containing #1 and #2. We compare
1019 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1020 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1021 /// functions are not part of the signature), IsOverload returns Ovl_Match and
1022 /// MatchedDecl will be set to point to the FunctionDecl for #2.
1023 ///
1024 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1025 /// by a using declaration. The rules for whether to hide shadow declarations
1026 /// ignore some properties which otherwise figure into a function template's
1027 /// signature.
1028 Sema::OverloadKind
1029 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1030                     NamedDecl *&Match, bool NewIsUsingDecl) {
1031   for (LookupResult::iterator I = Old.begin(), E = Old.end();
1032          I != E; ++I) {
1033     NamedDecl *OldD = *I;
1034 
1035     bool OldIsUsingDecl = false;
1036     if (isa<UsingShadowDecl>(OldD)) {
1037       OldIsUsingDecl = true;
1038 
1039       // We can always introduce two using declarations into the same
1040       // context, even if they have identical signatures.
1041       if (NewIsUsingDecl) continue;
1042 
1043       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1044     }
1045 
1046     // A using-declaration does not conflict with another declaration
1047     // if one of them is hidden.
1048     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1049       continue;
1050 
1051     // If either declaration was introduced by a using declaration,
1052     // we'll need to use slightly different rules for matching.
1053     // Essentially, these rules are the normal rules, except that
1054     // function templates hide function templates with different
1055     // return types or template parameter lists.
1056     bool UseMemberUsingDeclRules =
1057       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1058       !New->getFriendObjectKind();
1059 
1060     if (FunctionDecl *OldF = OldD->getAsFunction()) {
1061       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1062         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1063           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1064           continue;
1065         }
1066 
1067         if (!isa<FunctionTemplateDecl>(OldD) &&
1068             !shouldLinkPossiblyHiddenDecl(*I, New))
1069           continue;
1070 
1071         Match = *I;
1072         return Ovl_Match;
1073       }
1074 
1075       // Builtins that have custom typechecking or have a reference should
1076       // not be overloadable or redeclarable.
1077       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1078         Match = *I;
1079         return Ovl_NonFunction;
1080       }
1081     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1082       // We can overload with these, which can show up when doing
1083       // redeclaration checks for UsingDecls.
1084       assert(Old.getLookupKind() == LookupUsingDeclName);
1085     } else if (isa<TagDecl>(OldD)) {
1086       // We can always overload with tags by hiding them.
1087     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1088       // Optimistically assume that an unresolved using decl will
1089       // overload; if it doesn't, we'll have to diagnose during
1090       // template instantiation.
1091       //
1092       // Exception: if the scope is dependent and this is not a class
1093       // member, the using declaration can only introduce an enumerator.
1094       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1095         Match = *I;
1096         return Ovl_NonFunction;
1097       }
1098     } else {
1099       // (C++ 13p1):
1100       //   Only function declarations can be overloaded; object and type
1101       //   declarations cannot be overloaded.
1102       Match = *I;
1103       return Ovl_NonFunction;
1104     }
1105   }
1106 
1107   // C++ [temp.friend]p1:
1108   //   For a friend function declaration that is not a template declaration:
1109   //    -- if the name of the friend is a qualified or unqualified template-id,
1110   //       [...], otherwise
1111   //    -- if the name of the friend is a qualified-id and a matching
1112   //       non-template function is found in the specified class or namespace,
1113   //       the friend declaration refers to that function, otherwise,
1114   //    -- if the name of the friend is a qualified-id and a matching function
1115   //       template is found in the specified class or namespace, the friend
1116   //       declaration refers to the deduced specialization of that function
1117   //       template, otherwise
1118   //    -- the name shall be an unqualified-id [...]
1119   // If we get here for a qualified friend declaration, we've just reached the
1120   // third bullet. If the type of the friend is dependent, skip this lookup
1121   // until instantiation.
1122   if (New->getFriendObjectKind() && New->getQualifier() &&
1123       !New->getDescribedFunctionTemplate() &&
1124       !New->getDependentSpecializationInfo() &&
1125       !New->getType()->isDependentType()) {
1126     LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1127     TemplateSpecResult.addAllDecls(Old);
1128     if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1129                                             /*QualifiedFriend*/true)) {
1130       New->setInvalidDecl();
1131       return Ovl_Overload;
1132     }
1133 
1134     Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1135     return Ovl_Match;
1136   }
1137 
1138   return Ovl_Overload;
1139 }
1140 
1141 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1142                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs,
1143                       bool ConsiderRequiresClauses) {
1144   // C++ [basic.start.main]p2: This function shall not be overloaded.
1145   if (New->isMain())
1146     return false;
1147 
1148   // MSVCRT user defined entry points cannot be overloaded.
1149   if (New->isMSVCRTEntryPoint())
1150     return false;
1151 
1152   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1153   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1154 
1155   // C++ [temp.fct]p2:
1156   //   A function template can be overloaded with other function templates
1157   //   and with normal (non-template) functions.
1158   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1159     return true;
1160 
1161   // Is the function New an overload of the function Old?
1162   QualType OldQType = Context.getCanonicalType(Old->getType());
1163   QualType NewQType = Context.getCanonicalType(New->getType());
1164 
1165   // Compare the signatures (C++ 1.3.10) of the two functions to
1166   // determine whether they are overloads. If we find any mismatch
1167   // in the signature, they are overloads.
1168 
1169   // If either of these functions is a K&R-style function (no
1170   // prototype), then we consider them to have matching signatures.
1171   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1172       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1173     return false;
1174 
1175   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1176   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1177 
1178   // The signature of a function includes the types of its
1179   // parameters (C++ 1.3.10), which includes the presence or absence
1180   // of the ellipsis; see C++ DR 357).
1181   if (OldQType != NewQType &&
1182       (OldType->getNumParams() != NewType->getNumParams() ||
1183        OldType->isVariadic() != NewType->isVariadic() ||
1184        !FunctionParamTypesAreEqual(OldType, NewType)))
1185     return true;
1186 
1187   // C++ [temp.over.link]p4:
1188   //   The signature of a function template consists of its function
1189   //   signature, its return type and its template parameter list. The names
1190   //   of the template parameters are significant only for establishing the
1191   //   relationship between the template parameters and the rest of the
1192   //   signature.
1193   //
1194   // We check the return type and template parameter lists for function
1195   // templates first; the remaining checks follow.
1196   //
1197   // However, we don't consider either of these when deciding whether
1198   // a member introduced by a shadow declaration is hidden.
1199   if (!UseMemberUsingDeclRules && NewTemplate &&
1200       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1201                                        OldTemplate->getTemplateParameters(),
1202                                        false, TPL_TemplateMatch) ||
1203        !Context.hasSameType(Old->getDeclaredReturnType(),
1204                             New->getDeclaredReturnType())))
1205     return true;
1206 
1207   // If the function is a class member, its signature includes the
1208   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1209   //
1210   // As part of this, also check whether one of the member functions
1211   // is static, in which case they are not overloads (C++
1212   // 13.1p2). While not part of the definition of the signature,
1213   // this check is important to determine whether these functions
1214   // can be overloaded.
1215   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1216   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1217   if (OldMethod && NewMethod &&
1218       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1219     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1220       if (!UseMemberUsingDeclRules &&
1221           (OldMethod->getRefQualifier() == RQ_None ||
1222            NewMethod->getRefQualifier() == RQ_None)) {
1223         // C++0x [over.load]p2:
1224         //   - Member function declarations with the same name and the same
1225         //     parameter-type-list as well as member function template
1226         //     declarations with the same name, the same parameter-type-list, and
1227         //     the same template parameter lists cannot be overloaded if any of
1228         //     them, but not all, have a ref-qualifier (8.3.5).
1229         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1230           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1231         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1232       }
1233       return true;
1234     }
1235 
1236     // We may not have applied the implicit const for a constexpr member
1237     // function yet (because we haven't yet resolved whether this is a static
1238     // or non-static member function). Add it now, on the assumption that this
1239     // is a redeclaration of OldMethod.
1240     auto OldQuals = OldMethod->getMethodQualifiers();
1241     auto NewQuals = NewMethod->getMethodQualifiers();
1242     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1243         !isa<CXXConstructorDecl>(NewMethod))
1244       NewQuals.addConst();
1245     // We do not allow overloading based off of '__restrict'.
1246     OldQuals.removeRestrict();
1247     NewQuals.removeRestrict();
1248     if (OldQuals != NewQuals)
1249       return true;
1250   }
1251 
1252   // Though pass_object_size is placed on parameters and takes an argument, we
1253   // consider it to be a function-level modifier for the sake of function
1254   // identity. Either the function has one or more parameters with
1255   // pass_object_size or it doesn't.
1256   if (functionHasPassObjectSizeParams(New) !=
1257       functionHasPassObjectSizeParams(Old))
1258     return true;
1259 
1260   // enable_if attributes are an order-sensitive part of the signature.
1261   for (specific_attr_iterator<EnableIfAttr>
1262          NewI = New->specific_attr_begin<EnableIfAttr>(),
1263          NewE = New->specific_attr_end<EnableIfAttr>(),
1264          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1265          OldE = Old->specific_attr_end<EnableIfAttr>();
1266        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1267     if (NewI == NewE || OldI == OldE)
1268       return true;
1269     llvm::FoldingSetNodeID NewID, OldID;
1270     NewI->getCond()->Profile(NewID, Context, true);
1271     OldI->getCond()->Profile(OldID, Context, true);
1272     if (NewID != OldID)
1273       return true;
1274   }
1275 
1276   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1277     // Don't allow overloading of destructors.  (In theory we could, but it
1278     // would be a giant change to clang.)
1279     if (!isa<CXXDestructorDecl>(New)) {
1280       CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1281                          OldTarget = IdentifyCUDATarget(Old);
1282       if (NewTarget != CFT_InvalidTarget) {
1283         assert((OldTarget != CFT_InvalidTarget) &&
1284                "Unexpected invalid target.");
1285 
1286         // Allow overloading of functions with same signature and different CUDA
1287         // target attributes.
1288         if (NewTarget != OldTarget)
1289           return true;
1290       }
1291     }
1292   }
1293 
1294   if (ConsiderRequiresClauses) {
1295     Expr *NewRC = New->getTrailingRequiresClause(),
1296          *OldRC = Old->getTrailingRequiresClause();
1297     if ((NewRC != nullptr) != (OldRC != nullptr))
1298       // RC are most certainly different - these are overloads.
1299       return true;
1300 
1301     if (NewRC) {
1302       llvm::FoldingSetNodeID NewID, OldID;
1303       NewRC->Profile(NewID, Context, /*Canonical=*/true);
1304       OldRC->Profile(OldID, Context, /*Canonical=*/true);
1305       if (NewID != OldID)
1306         // RCs are not equivalent - these are overloads.
1307         return true;
1308     }
1309   }
1310 
1311   // The signatures match; this is not an overload.
1312   return false;
1313 }
1314 
1315 /// Tries a user-defined conversion from From to ToType.
1316 ///
1317 /// Produces an implicit conversion sequence for when a standard conversion
1318 /// is not an option. See TryImplicitConversion for more information.
1319 static ImplicitConversionSequence
1320 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1321                          bool SuppressUserConversions,
1322                          AllowedExplicit AllowExplicit,
1323                          bool InOverloadResolution,
1324                          bool CStyle,
1325                          bool AllowObjCWritebackConversion,
1326                          bool AllowObjCConversionOnExplicit) {
1327   ImplicitConversionSequence ICS;
1328 
1329   if (SuppressUserConversions) {
1330     // We're not in the case above, so there is no conversion that
1331     // we can perform.
1332     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1333     return ICS;
1334   }
1335 
1336   // Attempt user-defined conversion.
1337   OverloadCandidateSet Conversions(From->getExprLoc(),
1338                                    OverloadCandidateSet::CSK_Normal);
1339   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1340                                   Conversions, AllowExplicit,
1341                                   AllowObjCConversionOnExplicit)) {
1342   case OR_Success:
1343   case OR_Deleted:
1344     ICS.setUserDefined();
1345     // C++ [over.ics.user]p4:
1346     //   A conversion of an expression of class type to the same class
1347     //   type is given Exact Match rank, and a conversion of an
1348     //   expression of class type to a base class of that type is
1349     //   given Conversion rank, in spite of the fact that a copy
1350     //   constructor (i.e., a user-defined conversion function) is
1351     //   called for those cases.
1352     if (CXXConstructorDecl *Constructor
1353           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1354       QualType FromCanon
1355         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1356       QualType ToCanon
1357         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1358       if (Constructor->isCopyConstructor() &&
1359           (FromCanon == ToCanon ||
1360            S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1361         // Turn this into a "standard" conversion sequence, so that it
1362         // gets ranked with standard conversion sequences.
1363         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1364         ICS.setStandard();
1365         ICS.Standard.setAsIdentityConversion();
1366         ICS.Standard.setFromType(From->getType());
1367         ICS.Standard.setAllToTypes(ToType);
1368         ICS.Standard.CopyConstructor = Constructor;
1369         ICS.Standard.FoundCopyConstructor = Found;
1370         if (ToCanon != FromCanon)
1371           ICS.Standard.Second = ICK_Derived_To_Base;
1372       }
1373     }
1374     break;
1375 
1376   case OR_Ambiguous:
1377     ICS.setAmbiguous();
1378     ICS.Ambiguous.setFromType(From->getType());
1379     ICS.Ambiguous.setToType(ToType);
1380     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1381          Cand != Conversions.end(); ++Cand)
1382       if (Cand->Best)
1383         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1384     break;
1385 
1386     // Fall through.
1387   case OR_No_Viable_Function:
1388     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1389     break;
1390   }
1391 
1392   return ICS;
1393 }
1394 
1395 /// TryImplicitConversion - Attempt to perform an implicit conversion
1396 /// from the given expression (Expr) to the given type (ToType). This
1397 /// function returns an implicit conversion sequence that can be used
1398 /// to perform the initialization. Given
1399 ///
1400 ///   void f(float f);
1401 ///   void g(int i) { f(i); }
1402 ///
1403 /// this routine would produce an implicit conversion sequence to
1404 /// describe the initialization of f from i, which will be a standard
1405 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1406 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1407 //
1408 /// Note that this routine only determines how the conversion can be
1409 /// performed; it does not actually perform the conversion. As such,
1410 /// it will not produce any diagnostics if no conversion is available,
1411 /// but will instead return an implicit conversion sequence of kind
1412 /// "BadConversion".
1413 ///
1414 /// If @p SuppressUserConversions, then user-defined conversions are
1415 /// not permitted.
1416 /// If @p AllowExplicit, then explicit user-defined conversions are
1417 /// permitted.
1418 ///
1419 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1420 /// writeback conversion, which allows __autoreleasing id* parameters to
1421 /// be initialized with __strong id* or __weak id* arguments.
1422 static ImplicitConversionSequence
1423 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1424                       bool SuppressUserConversions,
1425                       AllowedExplicit AllowExplicit,
1426                       bool InOverloadResolution,
1427                       bool CStyle,
1428                       bool AllowObjCWritebackConversion,
1429                       bool AllowObjCConversionOnExplicit) {
1430   ImplicitConversionSequence ICS;
1431   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1432                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1433     ICS.setStandard();
1434     return ICS;
1435   }
1436 
1437   if (!S.getLangOpts().CPlusPlus) {
1438     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1439     return ICS;
1440   }
1441 
1442   // C++ [over.ics.user]p4:
1443   //   A conversion of an expression of class type to the same class
1444   //   type is given Exact Match rank, and a conversion of an
1445   //   expression of class type to a base class of that type is
1446   //   given Conversion rank, in spite of the fact that a copy/move
1447   //   constructor (i.e., a user-defined conversion function) is
1448   //   called for those cases.
1449   QualType FromType = From->getType();
1450   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1451       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1452        S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1453     ICS.setStandard();
1454     ICS.Standard.setAsIdentityConversion();
1455     ICS.Standard.setFromType(FromType);
1456     ICS.Standard.setAllToTypes(ToType);
1457 
1458     // We don't actually check at this point whether there is a valid
1459     // copy/move constructor, since overloading just assumes that it
1460     // exists. When we actually perform initialization, we'll find the
1461     // appropriate constructor to copy the returned object, if needed.
1462     ICS.Standard.CopyConstructor = nullptr;
1463 
1464     // Determine whether this is considered a derived-to-base conversion.
1465     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1466       ICS.Standard.Second = ICK_Derived_To_Base;
1467 
1468     return ICS;
1469   }
1470 
1471   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1472                                   AllowExplicit, InOverloadResolution, CStyle,
1473                                   AllowObjCWritebackConversion,
1474                                   AllowObjCConversionOnExplicit);
1475 }
1476 
1477 ImplicitConversionSequence
1478 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1479                             bool SuppressUserConversions,
1480                             AllowedExplicit AllowExplicit,
1481                             bool InOverloadResolution,
1482                             bool CStyle,
1483                             bool AllowObjCWritebackConversion) {
1484   return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1485                                  AllowExplicit, InOverloadResolution, CStyle,
1486                                  AllowObjCWritebackConversion,
1487                                  /*AllowObjCConversionOnExplicit=*/false);
1488 }
1489 
1490 /// PerformImplicitConversion - Perform an implicit conversion of the
1491 /// expression From to the type ToType. Returns the
1492 /// converted expression. Flavor is the kind of conversion we're
1493 /// performing, used in the error message. If @p AllowExplicit,
1494 /// explicit user-defined conversions are permitted.
1495 ExprResult
1496 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1497                                 AssignmentAction Action, bool AllowExplicit) {
1498   ImplicitConversionSequence ICS;
1499   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1500 }
1501 
1502 ExprResult
1503 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1504                                 AssignmentAction Action, bool AllowExplicit,
1505                                 ImplicitConversionSequence& ICS) {
1506   if (checkPlaceholderForOverload(*this, From))
1507     return ExprError();
1508 
1509   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1510   bool AllowObjCWritebackConversion
1511     = getLangOpts().ObjCAutoRefCount &&
1512       (Action == AA_Passing || Action == AA_Sending);
1513   if (getLangOpts().ObjC)
1514     CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1515                                       From->getType(), From);
1516   ICS = ::TryImplicitConversion(*this, From, ToType,
1517                                 /*SuppressUserConversions=*/false,
1518                                 AllowExplicit ? AllowedExplicit::All
1519                                               : AllowedExplicit::None,
1520                                 /*InOverloadResolution=*/false,
1521                                 /*CStyle=*/false, AllowObjCWritebackConversion,
1522                                 /*AllowObjCConversionOnExplicit=*/false);
1523   return PerformImplicitConversion(From, ToType, ICS, Action);
1524 }
1525 
1526 /// Determine whether the conversion from FromType to ToType is a valid
1527 /// conversion that strips "noexcept" or "noreturn" off the nested function
1528 /// type.
1529 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1530                                 QualType &ResultTy) {
1531   if (Context.hasSameUnqualifiedType(FromType, ToType))
1532     return false;
1533 
1534   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1535   //                    or F(t noexcept) -> F(t)
1536   // where F adds one of the following at most once:
1537   //   - a pointer
1538   //   - a member pointer
1539   //   - a block pointer
1540   // Changes here need matching changes in FindCompositePointerType.
1541   CanQualType CanTo = Context.getCanonicalType(ToType);
1542   CanQualType CanFrom = Context.getCanonicalType(FromType);
1543   Type::TypeClass TyClass = CanTo->getTypeClass();
1544   if (TyClass != CanFrom->getTypeClass()) return false;
1545   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1546     if (TyClass == Type::Pointer) {
1547       CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1548       CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1549     } else if (TyClass == Type::BlockPointer) {
1550       CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1551       CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1552     } else if (TyClass == Type::MemberPointer) {
1553       auto ToMPT = CanTo.castAs<MemberPointerType>();
1554       auto FromMPT = CanFrom.castAs<MemberPointerType>();
1555       // A function pointer conversion cannot change the class of the function.
1556       if (ToMPT->getClass() != FromMPT->getClass())
1557         return false;
1558       CanTo = ToMPT->getPointeeType();
1559       CanFrom = FromMPT->getPointeeType();
1560     } else {
1561       return false;
1562     }
1563 
1564     TyClass = CanTo->getTypeClass();
1565     if (TyClass != CanFrom->getTypeClass()) return false;
1566     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1567       return false;
1568   }
1569 
1570   const auto *FromFn = cast<FunctionType>(CanFrom);
1571   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1572 
1573   const auto *ToFn = cast<FunctionType>(CanTo);
1574   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1575 
1576   bool Changed = false;
1577 
1578   // Drop 'noreturn' if not present in target type.
1579   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1580     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1581     Changed = true;
1582   }
1583 
1584   // Drop 'noexcept' if not present in target type.
1585   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1586     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1587     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1588       FromFn = cast<FunctionType>(
1589           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1590                                                    EST_None)
1591                  .getTypePtr());
1592       Changed = true;
1593     }
1594 
1595     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1596     // only if the ExtParameterInfo lists of the two function prototypes can be
1597     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1598     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1599     bool CanUseToFPT, CanUseFromFPT;
1600     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1601                                       CanUseFromFPT, NewParamInfos) &&
1602         CanUseToFPT && !CanUseFromFPT) {
1603       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1604       ExtInfo.ExtParameterInfos =
1605           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1606       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1607                                             FromFPT->getParamTypes(), ExtInfo);
1608       FromFn = QT->getAs<FunctionType>();
1609       Changed = true;
1610     }
1611   }
1612 
1613   if (!Changed)
1614     return false;
1615 
1616   assert(QualType(FromFn, 0).isCanonical());
1617   if (QualType(FromFn, 0) != CanTo) return false;
1618 
1619   ResultTy = ToType;
1620   return true;
1621 }
1622 
1623 /// Determine whether the conversion from FromType to ToType is a valid
1624 /// vector conversion.
1625 ///
1626 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1627 /// conversion.
1628 static bool IsVectorConversion(Sema &S, QualType FromType,
1629                                QualType ToType, ImplicitConversionKind &ICK) {
1630   // We need at least one of these types to be a vector type to have a vector
1631   // conversion.
1632   if (!ToType->isVectorType() && !FromType->isVectorType())
1633     return false;
1634 
1635   // Identical types require no conversions.
1636   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1637     return false;
1638 
1639   // There are no conversions between extended vector types, only identity.
1640   if (ToType->isExtVectorType()) {
1641     // There are no conversions between extended vector types other than the
1642     // identity conversion.
1643     if (FromType->isExtVectorType())
1644       return false;
1645 
1646     // Vector splat from any arithmetic type to a vector.
1647     if (FromType->isArithmeticType()) {
1648       ICK = ICK_Vector_Splat;
1649       return true;
1650     }
1651   }
1652 
1653   // We can perform the conversion between vector types in the following cases:
1654   // 1)vector types are equivalent AltiVec and GCC vector types
1655   // 2)lax vector conversions are permitted and the vector types are of the
1656   //   same size
1657   // 3)the destination type does not have the ARM MVE strict-polymorphism
1658   //   attribute, which inhibits lax vector conversion for overload resolution
1659   //   only
1660   if (ToType->isVectorType() && FromType->isVectorType()) {
1661     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1662         (S.isLaxVectorConversion(FromType, ToType) &&
1663          !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
1664       ICK = ICK_Vector_Conversion;
1665       return true;
1666     }
1667   }
1668 
1669   return false;
1670 }
1671 
1672 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1673                                 bool InOverloadResolution,
1674                                 StandardConversionSequence &SCS,
1675                                 bool CStyle);
1676 
1677 /// IsStandardConversion - Determines whether there is a standard
1678 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1679 /// expression From to the type ToType. Standard conversion sequences
1680 /// only consider non-class types; for conversions that involve class
1681 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1682 /// contain the standard conversion sequence required to perform this
1683 /// conversion and this routine will return true. Otherwise, this
1684 /// routine will return false and the value of SCS is unspecified.
1685 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1686                                  bool InOverloadResolution,
1687                                  StandardConversionSequence &SCS,
1688                                  bool CStyle,
1689                                  bool AllowObjCWritebackConversion) {
1690   QualType FromType = From->getType();
1691 
1692   // Standard conversions (C++ [conv])
1693   SCS.setAsIdentityConversion();
1694   SCS.IncompatibleObjC = false;
1695   SCS.setFromType(FromType);
1696   SCS.CopyConstructor = nullptr;
1697 
1698   // There are no standard conversions for class types in C++, so
1699   // abort early. When overloading in C, however, we do permit them.
1700   if (S.getLangOpts().CPlusPlus &&
1701       (FromType->isRecordType() || ToType->isRecordType()))
1702     return false;
1703 
1704   // The first conversion can be an lvalue-to-rvalue conversion,
1705   // array-to-pointer conversion, or function-to-pointer conversion
1706   // (C++ 4p1).
1707 
1708   if (FromType == S.Context.OverloadTy) {
1709     DeclAccessPair AccessPair;
1710     if (FunctionDecl *Fn
1711           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1712                                                  AccessPair)) {
1713       // We were able to resolve the address of the overloaded function,
1714       // so we can convert to the type of that function.
1715       FromType = Fn->getType();
1716       SCS.setFromType(FromType);
1717 
1718       // we can sometimes resolve &foo<int> regardless of ToType, so check
1719       // if the type matches (identity) or we are converting to bool
1720       if (!S.Context.hasSameUnqualifiedType(
1721                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1722         QualType resultTy;
1723         // if the function type matches except for [[noreturn]], it's ok
1724         if (!S.IsFunctionConversion(FromType,
1725               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1726           // otherwise, only a boolean conversion is standard
1727           if (!ToType->isBooleanType())
1728             return false;
1729       }
1730 
1731       // Check if the "from" expression is taking the address of an overloaded
1732       // function and recompute the FromType accordingly. Take advantage of the
1733       // fact that non-static member functions *must* have such an address-of
1734       // expression.
1735       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1736       if (Method && !Method->isStatic()) {
1737         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1738                "Non-unary operator on non-static member address");
1739         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1740                == UO_AddrOf &&
1741                "Non-address-of operator on non-static member address");
1742         const Type *ClassType
1743           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1744         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1745       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1746         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1747                UO_AddrOf &&
1748                "Non-address-of operator for overloaded function expression");
1749         FromType = S.Context.getPointerType(FromType);
1750       }
1751 
1752       // Check that we've computed the proper type after overload resolution.
1753       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1754       // be calling it from within an NDEBUG block.
1755       assert(S.Context.hasSameType(
1756         FromType,
1757         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1758     } else {
1759       return false;
1760     }
1761   }
1762   // Lvalue-to-rvalue conversion (C++11 4.1):
1763   //   A glvalue (3.10) of a non-function, non-array type T can
1764   //   be converted to a prvalue.
1765   bool argIsLValue = From->isGLValue();
1766   if (argIsLValue &&
1767       !FromType->isFunctionType() && !FromType->isArrayType() &&
1768       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1769     SCS.First = ICK_Lvalue_To_Rvalue;
1770 
1771     // C11 6.3.2.1p2:
1772     //   ... if the lvalue has atomic type, the value has the non-atomic version
1773     //   of the type of the lvalue ...
1774     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1775       FromType = Atomic->getValueType();
1776 
1777     // If T is a non-class type, the type of the rvalue is the
1778     // cv-unqualified version of T. Otherwise, the type of the rvalue
1779     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1780     // just strip the qualifiers because they don't matter.
1781     FromType = FromType.getUnqualifiedType();
1782   } else if (FromType->isArrayType()) {
1783     // Array-to-pointer conversion (C++ 4.2)
1784     SCS.First = ICK_Array_To_Pointer;
1785 
1786     // An lvalue or rvalue of type "array of N T" or "array of unknown
1787     // bound of T" can be converted to an rvalue of type "pointer to
1788     // T" (C++ 4.2p1).
1789     FromType = S.Context.getArrayDecayedType(FromType);
1790 
1791     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1792       // This conversion is deprecated in C++03 (D.4)
1793       SCS.DeprecatedStringLiteralToCharPtr = true;
1794 
1795       // For the purpose of ranking in overload resolution
1796       // (13.3.3.1.1), this conversion is considered an
1797       // array-to-pointer conversion followed by a qualification
1798       // conversion (4.4). (C++ 4.2p2)
1799       SCS.Second = ICK_Identity;
1800       SCS.Third = ICK_Qualification;
1801       SCS.QualificationIncludesObjCLifetime = false;
1802       SCS.setAllToTypes(FromType);
1803       return true;
1804     }
1805   } else if (FromType->isFunctionType() && argIsLValue) {
1806     // Function-to-pointer conversion (C++ 4.3).
1807     SCS.First = ICK_Function_To_Pointer;
1808 
1809     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1810       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1811         if (!S.checkAddressOfFunctionIsAvailable(FD))
1812           return false;
1813 
1814     // An lvalue of function type T can be converted to an rvalue of
1815     // type "pointer to T." The result is a pointer to the
1816     // function. (C++ 4.3p1).
1817     FromType = S.Context.getPointerType(FromType);
1818   } else {
1819     // We don't require any conversions for the first step.
1820     SCS.First = ICK_Identity;
1821   }
1822   SCS.setToType(0, FromType);
1823 
1824   // The second conversion can be an integral promotion, floating
1825   // point promotion, integral conversion, floating point conversion,
1826   // floating-integral conversion, pointer conversion,
1827   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1828   // For overloading in C, this can also be a "compatible-type"
1829   // conversion.
1830   bool IncompatibleObjC = false;
1831   ImplicitConversionKind SecondICK = ICK_Identity;
1832   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1833     // The unqualified versions of the types are the same: there's no
1834     // conversion to do.
1835     SCS.Second = ICK_Identity;
1836   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1837     // Integral promotion (C++ 4.5).
1838     SCS.Second = ICK_Integral_Promotion;
1839     FromType = ToType.getUnqualifiedType();
1840   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1841     // Floating point promotion (C++ 4.6).
1842     SCS.Second = ICK_Floating_Promotion;
1843     FromType = ToType.getUnqualifiedType();
1844   } else if (S.IsComplexPromotion(FromType, ToType)) {
1845     // Complex promotion (Clang extension)
1846     SCS.Second = ICK_Complex_Promotion;
1847     FromType = ToType.getUnqualifiedType();
1848   } else if (ToType->isBooleanType() &&
1849              (FromType->isArithmeticType() ||
1850               FromType->isAnyPointerType() ||
1851               FromType->isBlockPointerType() ||
1852               FromType->isMemberPointerType())) {
1853     // Boolean conversions (C++ 4.12).
1854     SCS.Second = ICK_Boolean_Conversion;
1855     FromType = S.Context.BoolTy;
1856   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1857              ToType->isIntegralType(S.Context)) {
1858     // Integral conversions (C++ 4.7).
1859     SCS.Second = ICK_Integral_Conversion;
1860     FromType = ToType.getUnqualifiedType();
1861   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1862     // Complex conversions (C99 6.3.1.6)
1863     SCS.Second = ICK_Complex_Conversion;
1864     FromType = ToType.getUnqualifiedType();
1865   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1866              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1867     // Complex-real conversions (C99 6.3.1.7)
1868     SCS.Second = ICK_Complex_Real;
1869     FromType = ToType.getUnqualifiedType();
1870   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1871     // FIXME: disable conversions between long double and __float128 if
1872     // their representation is different until there is back end support
1873     // We of course allow this conversion if long double is really double.
1874 
1875     // Conversions between bfloat and other floats are not permitted.
1876     if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty)
1877       return false;
1878     if (&S.Context.getFloatTypeSemantics(FromType) !=
1879         &S.Context.getFloatTypeSemantics(ToType)) {
1880       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1881                                     ToType == S.Context.LongDoubleTy) ||
1882                                    (FromType == S.Context.LongDoubleTy &&
1883                                     ToType == S.Context.Float128Ty));
1884       if (Float128AndLongDouble &&
1885           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1886            &llvm::APFloat::PPCDoubleDouble()))
1887         return false;
1888     }
1889     // Floating point conversions (C++ 4.8).
1890     SCS.Second = ICK_Floating_Conversion;
1891     FromType = ToType.getUnqualifiedType();
1892   } else if ((FromType->isRealFloatingType() &&
1893               ToType->isIntegralType(S.Context)) ||
1894              (FromType->isIntegralOrUnscopedEnumerationType() &&
1895               ToType->isRealFloatingType())) {
1896     // Conversions between bfloat and int are not permitted.
1897     if (FromType->isBFloat16Type() || ToType->isBFloat16Type())
1898       return false;
1899 
1900     // Floating-integral conversions (C++ 4.9).
1901     SCS.Second = ICK_Floating_Integral;
1902     FromType = ToType.getUnqualifiedType();
1903   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1904     SCS.Second = ICK_Block_Pointer_Conversion;
1905   } else if (AllowObjCWritebackConversion &&
1906              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1907     SCS.Second = ICK_Writeback_Conversion;
1908   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1909                                    FromType, IncompatibleObjC)) {
1910     // Pointer conversions (C++ 4.10).
1911     SCS.Second = ICK_Pointer_Conversion;
1912     SCS.IncompatibleObjC = IncompatibleObjC;
1913     FromType = FromType.getUnqualifiedType();
1914   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1915                                          InOverloadResolution, FromType)) {
1916     // Pointer to member conversions (4.11).
1917     SCS.Second = ICK_Pointer_Member;
1918   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1919     SCS.Second = SecondICK;
1920     FromType = ToType.getUnqualifiedType();
1921   } else if (!S.getLangOpts().CPlusPlus &&
1922              S.Context.typesAreCompatible(ToType, FromType)) {
1923     // Compatible conversions (Clang extension for C function overloading)
1924     SCS.Second = ICK_Compatible_Conversion;
1925     FromType = ToType.getUnqualifiedType();
1926   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1927                                              InOverloadResolution,
1928                                              SCS, CStyle)) {
1929     SCS.Second = ICK_TransparentUnionConversion;
1930     FromType = ToType;
1931   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1932                                  CStyle)) {
1933     // tryAtomicConversion has updated the standard conversion sequence
1934     // appropriately.
1935     return true;
1936   } else if (ToType->isEventT() &&
1937              From->isIntegerConstantExpr(S.getASTContext()) &&
1938              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1939     SCS.Second = ICK_Zero_Event_Conversion;
1940     FromType = ToType;
1941   } else if (ToType->isQueueT() &&
1942              From->isIntegerConstantExpr(S.getASTContext()) &&
1943              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1944     SCS.Second = ICK_Zero_Queue_Conversion;
1945     FromType = ToType;
1946   } else if (ToType->isSamplerT() &&
1947              From->isIntegerConstantExpr(S.getASTContext())) {
1948     SCS.Second = ICK_Compatible_Conversion;
1949     FromType = ToType;
1950   } else {
1951     // No second conversion required.
1952     SCS.Second = ICK_Identity;
1953   }
1954   SCS.setToType(1, FromType);
1955 
1956   // The third conversion can be a function pointer conversion or a
1957   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1958   bool ObjCLifetimeConversion;
1959   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1960     // Function pointer conversions (removing 'noexcept') including removal of
1961     // 'noreturn' (Clang extension).
1962     SCS.Third = ICK_Function_Conversion;
1963   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1964                                          ObjCLifetimeConversion)) {
1965     SCS.Third = ICK_Qualification;
1966     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1967     FromType = ToType;
1968   } else {
1969     // No conversion required
1970     SCS.Third = ICK_Identity;
1971   }
1972 
1973   // C++ [over.best.ics]p6:
1974   //   [...] Any difference in top-level cv-qualification is
1975   //   subsumed by the initialization itself and does not constitute
1976   //   a conversion. [...]
1977   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1978   QualType CanonTo = S.Context.getCanonicalType(ToType);
1979   if (CanonFrom.getLocalUnqualifiedType()
1980                                      == CanonTo.getLocalUnqualifiedType() &&
1981       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1982     FromType = ToType;
1983     CanonFrom = CanonTo;
1984   }
1985 
1986   SCS.setToType(2, FromType);
1987 
1988   if (CanonFrom == CanonTo)
1989     return true;
1990 
1991   // If we have not converted the argument type to the parameter type,
1992   // this is a bad conversion sequence, unless we're resolving an overload in C.
1993   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1994     return false;
1995 
1996   ExprResult ER = ExprResult{From};
1997   Sema::AssignConvertType Conv =
1998       S.CheckSingleAssignmentConstraints(ToType, ER,
1999                                          /*Diagnose=*/false,
2000                                          /*DiagnoseCFAudited=*/false,
2001                                          /*ConvertRHS=*/false);
2002   ImplicitConversionKind SecondConv;
2003   switch (Conv) {
2004   case Sema::Compatible:
2005     SecondConv = ICK_C_Only_Conversion;
2006     break;
2007   // For our purposes, discarding qualifiers is just as bad as using an
2008   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2009   // qualifiers, as well.
2010   case Sema::CompatiblePointerDiscardsQualifiers:
2011   case Sema::IncompatiblePointer:
2012   case Sema::IncompatiblePointerSign:
2013     SecondConv = ICK_Incompatible_Pointer_Conversion;
2014     break;
2015   default:
2016     return false;
2017   }
2018 
2019   // First can only be an lvalue conversion, so we pretend that this was the
2020   // second conversion. First should already be valid from earlier in the
2021   // function.
2022   SCS.Second = SecondConv;
2023   SCS.setToType(1, ToType);
2024 
2025   // Third is Identity, because Second should rank us worse than any other
2026   // conversion. This could also be ICK_Qualification, but it's simpler to just
2027   // lump everything in with the second conversion, and we don't gain anything
2028   // from making this ICK_Qualification.
2029   SCS.Third = ICK_Identity;
2030   SCS.setToType(2, ToType);
2031   return true;
2032 }
2033 
2034 static bool
2035 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2036                                      QualType &ToType,
2037                                      bool InOverloadResolution,
2038                                      StandardConversionSequence &SCS,
2039                                      bool CStyle) {
2040 
2041   const RecordType *UT = ToType->getAsUnionType();
2042   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2043     return false;
2044   // The field to initialize within the transparent union.
2045   RecordDecl *UD = UT->getDecl();
2046   // It's compatible if the expression matches any of the fields.
2047   for (const auto *it : UD->fields()) {
2048     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2049                              CStyle, /*AllowObjCWritebackConversion=*/false)) {
2050       ToType = it->getType();
2051       return true;
2052     }
2053   }
2054   return false;
2055 }
2056 
2057 /// IsIntegralPromotion - Determines whether the conversion from the
2058 /// expression From (whose potentially-adjusted type is FromType) to
2059 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
2060 /// sets PromotedType to the promoted type.
2061 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2062   const BuiltinType *To = ToType->getAs<BuiltinType>();
2063   // All integers are built-in.
2064   if (!To) {
2065     return false;
2066   }
2067 
2068   // An rvalue of type char, signed char, unsigned char, short int, or
2069   // unsigned short int can be converted to an rvalue of type int if
2070   // int can represent all the values of the source type; otherwise,
2071   // the source rvalue can be converted to an rvalue of type unsigned
2072   // int (C++ 4.5p1).
2073   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
2074       !FromType->isEnumeralType()) {
2075     if (// We can promote any signed, promotable integer type to an int
2076         (FromType->isSignedIntegerType() ||
2077          // We can promote any unsigned integer type whose size is
2078          // less than int to an int.
2079          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2080       return To->getKind() == BuiltinType::Int;
2081     }
2082 
2083     return To->getKind() == BuiltinType::UInt;
2084   }
2085 
2086   // C++11 [conv.prom]p3:
2087   //   A prvalue of an unscoped enumeration type whose underlying type is not
2088   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2089   //   following types that can represent all the values of the enumeration
2090   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
2091   //   unsigned int, long int, unsigned long int, long long int, or unsigned
2092   //   long long int. If none of the types in that list can represent all the
2093   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2094   //   type can be converted to an rvalue a prvalue of the extended integer type
2095   //   with lowest integer conversion rank (4.13) greater than the rank of long
2096   //   long in which all the values of the enumeration can be represented. If
2097   //   there are two such extended types, the signed one is chosen.
2098   // C++11 [conv.prom]p4:
2099   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
2100   //   can be converted to a prvalue of its underlying type. Moreover, if
2101   //   integral promotion can be applied to its underlying type, a prvalue of an
2102   //   unscoped enumeration type whose underlying type is fixed can also be
2103   //   converted to a prvalue of the promoted underlying type.
2104   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2105     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2106     // provided for a scoped enumeration.
2107     if (FromEnumType->getDecl()->isScoped())
2108       return false;
2109 
2110     // We can perform an integral promotion to the underlying type of the enum,
2111     // even if that's not the promoted type. Note that the check for promoting
2112     // the underlying type is based on the type alone, and does not consider
2113     // the bitfield-ness of the actual source expression.
2114     if (FromEnumType->getDecl()->isFixed()) {
2115       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2116       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2117              IsIntegralPromotion(nullptr, Underlying, ToType);
2118     }
2119 
2120     // We have already pre-calculated the promotion type, so this is trivial.
2121     if (ToType->isIntegerType() &&
2122         isCompleteType(From->getBeginLoc(), FromType))
2123       return Context.hasSameUnqualifiedType(
2124           ToType, FromEnumType->getDecl()->getPromotionType());
2125 
2126     // C++ [conv.prom]p5:
2127     //   If the bit-field has an enumerated type, it is treated as any other
2128     //   value of that type for promotion purposes.
2129     //
2130     // ... so do not fall through into the bit-field checks below in C++.
2131     if (getLangOpts().CPlusPlus)
2132       return false;
2133   }
2134 
2135   // C++0x [conv.prom]p2:
2136   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2137   //   to an rvalue a prvalue of the first of the following types that can
2138   //   represent all the values of its underlying type: int, unsigned int,
2139   //   long int, unsigned long int, long long int, or unsigned long long int.
2140   //   If none of the types in that list can represent all the values of its
2141   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2142   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2143   //   type.
2144   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2145       ToType->isIntegerType()) {
2146     // Determine whether the type we're converting from is signed or
2147     // unsigned.
2148     bool FromIsSigned = FromType->isSignedIntegerType();
2149     uint64_t FromSize = Context.getTypeSize(FromType);
2150 
2151     // The types we'll try to promote to, in the appropriate
2152     // order. Try each of these types.
2153     QualType PromoteTypes[6] = {
2154       Context.IntTy, Context.UnsignedIntTy,
2155       Context.LongTy, Context.UnsignedLongTy ,
2156       Context.LongLongTy, Context.UnsignedLongLongTy
2157     };
2158     for (int Idx = 0; Idx < 6; ++Idx) {
2159       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2160       if (FromSize < ToSize ||
2161           (FromSize == ToSize &&
2162            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2163         // We found the type that we can promote to. If this is the
2164         // type we wanted, we have a promotion. Otherwise, no
2165         // promotion.
2166         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2167       }
2168     }
2169   }
2170 
2171   // An rvalue for an integral bit-field (9.6) can be converted to an
2172   // rvalue of type int if int can represent all the values of the
2173   // bit-field; otherwise, it can be converted to unsigned int if
2174   // unsigned int can represent all the values of the bit-field. If
2175   // the bit-field is larger yet, no integral promotion applies to
2176   // it. If the bit-field has an enumerated type, it is treated as any
2177   // other value of that type for promotion purposes (C++ 4.5p3).
2178   // FIXME: We should delay checking of bit-fields until we actually perform the
2179   // conversion.
2180   //
2181   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2182   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2183   // bit-fields and those whose underlying type is larger than int) for GCC
2184   // compatibility.
2185   if (From) {
2186     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2187       Optional<llvm::APSInt> BitWidth;
2188       if (FromType->isIntegralType(Context) &&
2189           (BitWidth =
2190                MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2191         llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2192         ToSize = Context.getTypeSize(ToType);
2193 
2194         // Are we promoting to an int from a bitfield that fits in an int?
2195         if (*BitWidth < ToSize ||
2196             (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2197           return To->getKind() == BuiltinType::Int;
2198         }
2199 
2200         // Are we promoting to an unsigned int from an unsigned bitfield
2201         // that fits into an unsigned int?
2202         if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2203           return To->getKind() == BuiltinType::UInt;
2204         }
2205 
2206         return false;
2207       }
2208     }
2209   }
2210 
2211   // An rvalue of type bool can be converted to an rvalue of type int,
2212   // with false becoming zero and true becoming one (C++ 4.5p4).
2213   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2214     return true;
2215   }
2216 
2217   return false;
2218 }
2219 
2220 /// IsFloatingPointPromotion - Determines whether the conversion from
2221 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2222 /// returns true and sets PromotedType to the promoted type.
2223 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2224   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2225     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2226       /// An rvalue of type float can be converted to an rvalue of type
2227       /// double. (C++ 4.6p1).
2228       if (FromBuiltin->getKind() == BuiltinType::Float &&
2229           ToBuiltin->getKind() == BuiltinType::Double)
2230         return true;
2231 
2232       // C99 6.3.1.5p1:
2233       //   When a float is promoted to double or long double, or a
2234       //   double is promoted to long double [...].
2235       if (!getLangOpts().CPlusPlus &&
2236           (FromBuiltin->getKind() == BuiltinType::Float ||
2237            FromBuiltin->getKind() == BuiltinType::Double) &&
2238           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2239            ToBuiltin->getKind() == BuiltinType::Float128))
2240         return true;
2241 
2242       // Half can be promoted to float.
2243       if (!getLangOpts().NativeHalfType &&
2244            FromBuiltin->getKind() == BuiltinType::Half &&
2245           ToBuiltin->getKind() == BuiltinType::Float)
2246         return true;
2247     }
2248 
2249   return false;
2250 }
2251 
2252 /// Determine if a conversion is a complex promotion.
2253 ///
2254 /// A complex promotion is defined as a complex -> complex conversion
2255 /// where the conversion between the underlying real types is a
2256 /// floating-point or integral promotion.
2257 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2258   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2259   if (!FromComplex)
2260     return false;
2261 
2262   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2263   if (!ToComplex)
2264     return false;
2265 
2266   return IsFloatingPointPromotion(FromComplex->getElementType(),
2267                                   ToComplex->getElementType()) ||
2268     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2269                         ToComplex->getElementType());
2270 }
2271 
2272 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2273 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2274 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2275 /// if non-empty, will be a pointer to ToType that may or may not have
2276 /// the right set of qualifiers on its pointee.
2277 ///
2278 static QualType
2279 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2280                                    QualType ToPointee, QualType ToType,
2281                                    ASTContext &Context,
2282                                    bool StripObjCLifetime = false) {
2283   assert((FromPtr->getTypeClass() == Type::Pointer ||
2284           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2285          "Invalid similarly-qualified pointer type");
2286 
2287   /// Conversions to 'id' subsume cv-qualifier conversions.
2288   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2289     return ToType.getUnqualifiedType();
2290 
2291   QualType CanonFromPointee
2292     = Context.getCanonicalType(FromPtr->getPointeeType());
2293   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2294   Qualifiers Quals = CanonFromPointee.getQualifiers();
2295 
2296   if (StripObjCLifetime)
2297     Quals.removeObjCLifetime();
2298 
2299   // Exact qualifier match -> return the pointer type we're converting to.
2300   if (CanonToPointee.getLocalQualifiers() == Quals) {
2301     // ToType is exactly what we need. Return it.
2302     if (!ToType.isNull())
2303       return ToType.getUnqualifiedType();
2304 
2305     // Build a pointer to ToPointee. It has the right qualifiers
2306     // already.
2307     if (isa<ObjCObjectPointerType>(ToType))
2308       return Context.getObjCObjectPointerType(ToPointee);
2309     return Context.getPointerType(ToPointee);
2310   }
2311 
2312   // Just build a canonical type that has the right qualifiers.
2313   QualType QualifiedCanonToPointee
2314     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2315 
2316   if (isa<ObjCObjectPointerType>(ToType))
2317     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2318   return Context.getPointerType(QualifiedCanonToPointee);
2319 }
2320 
2321 static bool isNullPointerConstantForConversion(Expr *Expr,
2322                                                bool InOverloadResolution,
2323                                                ASTContext &Context) {
2324   // Handle value-dependent integral null pointer constants correctly.
2325   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2326   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2327       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2328     return !InOverloadResolution;
2329 
2330   return Expr->isNullPointerConstant(Context,
2331                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2332                                         : Expr::NPC_ValueDependentIsNull);
2333 }
2334 
2335 /// IsPointerConversion - Determines whether the conversion of the
2336 /// expression From, which has the (possibly adjusted) type FromType,
2337 /// can be converted to the type ToType via a pointer conversion (C++
2338 /// 4.10). If so, returns true and places the converted type (that
2339 /// might differ from ToType in its cv-qualifiers at some level) into
2340 /// ConvertedType.
2341 ///
2342 /// This routine also supports conversions to and from block pointers
2343 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2344 /// pointers to interfaces. FIXME: Once we've determined the
2345 /// appropriate overloading rules for Objective-C, we may want to
2346 /// split the Objective-C checks into a different routine; however,
2347 /// GCC seems to consider all of these conversions to be pointer
2348 /// conversions, so for now they live here. IncompatibleObjC will be
2349 /// set if the conversion is an allowed Objective-C conversion that
2350 /// should result in a warning.
2351 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2352                                bool InOverloadResolution,
2353                                QualType& ConvertedType,
2354                                bool &IncompatibleObjC) {
2355   IncompatibleObjC = false;
2356   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2357                               IncompatibleObjC))
2358     return true;
2359 
2360   // Conversion from a null pointer constant to any Objective-C pointer type.
2361   if (ToType->isObjCObjectPointerType() &&
2362       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2363     ConvertedType = ToType;
2364     return true;
2365   }
2366 
2367   // Blocks: Block pointers can be converted to void*.
2368   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2369       ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2370     ConvertedType = ToType;
2371     return true;
2372   }
2373   // Blocks: A null pointer constant can be converted to a block
2374   // pointer type.
2375   if (ToType->isBlockPointerType() &&
2376       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2377     ConvertedType = ToType;
2378     return true;
2379   }
2380 
2381   // If the left-hand-side is nullptr_t, the right side can be a null
2382   // pointer constant.
2383   if (ToType->isNullPtrType() &&
2384       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2385     ConvertedType = ToType;
2386     return true;
2387   }
2388 
2389   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2390   if (!ToTypePtr)
2391     return false;
2392 
2393   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2394   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2395     ConvertedType = ToType;
2396     return true;
2397   }
2398 
2399   // Beyond this point, both types need to be pointers
2400   // , including objective-c pointers.
2401   QualType ToPointeeType = ToTypePtr->getPointeeType();
2402   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2403       !getLangOpts().ObjCAutoRefCount) {
2404     ConvertedType = BuildSimilarlyQualifiedPointerType(
2405                                       FromType->getAs<ObjCObjectPointerType>(),
2406                                                        ToPointeeType,
2407                                                        ToType, Context);
2408     return true;
2409   }
2410   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2411   if (!FromTypePtr)
2412     return false;
2413 
2414   QualType FromPointeeType = FromTypePtr->getPointeeType();
2415 
2416   // If the unqualified pointee types are the same, this can't be a
2417   // pointer conversion, so don't do all of the work below.
2418   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2419     return false;
2420 
2421   // An rvalue of type "pointer to cv T," where T is an object type,
2422   // can be converted to an rvalue of type "pointer to cv void" (C++
2423   // 4.10p2).
2424   if (FromPointeeType->isIncompleteOrObjectType() &&
2425       ToPointeeType->isVoidType()) {
2426     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2427                                                        ToPointeeType,
2428                                                        ToType, Context,
2429                                                    /*StripObjCLifetime=*/true);
2430     return true;
2431   }
2432 
2433   // MSVC allows implicit function to void* type conversion.
2434   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2435       ToPointeeType->isVoidType()) {
2436     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2437                                                        ToPointeeType,
2438                                                        ToType, Context);
2439     return true;
2440   }
2441 
2442   // When we're overloading in C, we allow a special kind of pointer
2443   // conversion for compatible-but-not-identical pointee types.
2444   if (!getLangOpts().CPlusPlus &&
2445       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2446     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2447                                                        ToPointeeType,
2448                                                        ToType, Context);
2449     return true;
2450   }
2451 
2452   // C++ [conv.ptr]p3:
2453   //
2454   //   An rvalue of type "pointer to cv D," where D is a class type,
2455   //   can be converted to an rvalue of type "pointer to cv B," where
2456   //   B is a base class (clause 10) of D. If B is an inaccessible
2457   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2458   //   necessitates this conversion is ill-formed. The result of the
2459   //   conversion is a pointer to the base class sub-object of the
2460   //   derived class object. The null pointer value is converted to
2461   //   the null pointer value of the destination type.
2462   //
2463   // Note that we do not check for ambiguity or inaccessibility
2464   // here. That is handled by CheckPointerConversion.
2465   if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2466       ToPointeeType->isRecordType() &&
2467       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2468       IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2469     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2470                                                        ToPointeeType,
2471                                                        ToType, Context);
2472     return true;
2473   }
2474 
2475   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2476       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2477     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2478                                                        ToPointeeType,
2479                                                        ToType, Context);
2480     return true;
2481   }
2482 
2483   return false;
2484 }
2485 
2486 /// Adopt the given qualifiers for the given type.
2487 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2488   Qualifiers TQs = T.getQualifiers();
2489 
2490   // Check whether qualifiers already match.
2491   if (TQs == Qs)
2492     return T;
2493 
2494   if (Qs.compatiblyIncludes(TQs))
2495     return Context.getQualifiedType(T, Qs);
2496 
2497   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2498 }
2499 
2500 /// isObjCPointerConversion - Determines whether this is an
2501 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2502 /// with the same arguments and return values.
2503 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2504                                    QualType& ConvertedType,
2505                                    bool &IncompatibleObjC) {
2506   if (!getLangOpts().ObjC)
2507     return false;
2508 
2509   // The set of qualifiers on the type we're converting from.
2510   Qualifiers FromQualifiers = FromType.getQualifiers();
2511 
2512   // First, we handle all conversions on ObjC object pointer types.
2513   const ObjCObjectPointerType* ToObjCPtr =
2514     ToType->getAs<ObjCObjectPointerType>();
2515   const ObjCObjectPointerType *FromObjCPtr =
2516     FromType->getAs<ObjCObjectPointerType>();
2517 
2518   if (ToObjCPtr && FromObjCPtr) {
2519     // If the pointee types are the same (ignoring qualifications),
2520     // then this is not a pointer conversion.
2521     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2522                                        FromObjCPtr->getPointeeType()))
2523       return false;
2524 
2525     // Conversion between Objective-C pointers.
2526     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2527       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2528       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2529       if (getLangOpts().CPlusPlus && LHS && RHS &&
2530           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2531                                                 FromObjCPtr->getPointeeType()))
2532         return false;
2533       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2534                                                    ToObjCPtr->getPointeeType(),
2535                                                          ToType, Context);
2536       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2537       return true;
2538     }
2539 
2540     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2541       // Okay: this is some kind of implicit downcast of Objective-C
2542       // interfaces, which is permitted. However, we're going to
2543       // complain about it.
2544       IncompatibleObjC = true;
2545       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2546                                                    ToObjCPtr->getPointeeType(),
2547                                                          ToType, Context);
2548       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2549       return true;
2550     }
2551   }
2552   // Beyond this point, both types need to be C pointers or block pointers.
2553   QualType ToPointeeType;
2554   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2555     ToPointeeType = ToCPtr->getPointeeType();
2556   else if (const BlockPointerType *ToBlockPtr =
2557             ToType->getAs<BlockPointerType>()) {
2558     // Objective C++: We're able to convert from a pointer to any object
2559     // to a block pointer type.
2560     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2561       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2562       return true;
2563     }
2564     ToPointeeType = ToBlockPtr->getPointeeType();
2565   }
2566   else if (FromType->getAs<BlockPointerType>() &&
2567            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2568     // Objective C++: We're able to convert from a block pointer type to a
2569     // pointer to any object.
2570     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2571     return true;
2572   }
2573   else
2574     return false;
2575 
2576   QualType FromPointeeType;
2577   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2578     FromPointeeType = FromCPtr->getPointeeType();
2579   else if (const BlockPointerType *FromBlockPtr =
2580            FromType->getAs<BlockPointerType>())
2581     FromPointeeType = FromBlockPtr->getPointeeType();
2582   else
2583     return false;
2584 
2585   // If we have pointers to pointers, recursively check whether this
2586   // is an Objective-C conversion.
2587   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2588       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2589                               IncompatibleObjC)) {
2590     // We always complain about this conversion.
2591     IncompatibleObjC = true;
2592     ConvertedType = Context.getPointerType(ConvertedType);
2593     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2594     return true;
2595   }
2596   // Allow conversion of pointee being objective-c pointer to another one;
2597   // as in I* to id.
2598   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2599       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2600       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2601                               IncompatibleObjC)) {
2602 
2603     ConvertedType = Context.getPointerType(ConvertedType);
2604     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2605     return true;
2606   }
2607 
2608   // If we have pointers to functions or blocks, check whether the only
2609   // differences in the argument and result types are in Objective-C
2610   // pointer conversions. If so, we permit the conversion (but
2611   // complain about it).
2612   const FunctionProtoType *FromFunctionType
2613     = FromPointeeType->getAs<FunctionProtoType>();
2614   const FunctionProtoType *ToFunctionType
2615     = ToPointeeType->getAs<FunctionProtoType>();
2616   if (FromFunctionType && ToFunctionType) {
2617     // If the function types are exactly the same, this isn't an
2618     // Objective-C pointer conversion.
2619     if (Context.getCanonicalType(FromPointeeType)
2620           == Context.getCanonicalType(ToPointeeType))
2621       return false;
2622 
2623     // Perform the quick checks that will tell us whether these
2624     // function types are obviously different.
2625     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2626         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2627         FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2628       return false;
2629 
2630     bool HasObjCConversion = false;
2631     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2632         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2633       // Okay, the types match exactly. Nothing to do.
2634     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2635                                        ToFunctionType->getReturnType(),
2636                                        ConvertedType, IncompatibleObjC)) {
2637       // Okay, we have an Objective-C pointer conversion.
2638       HasObjCConversion = true;
2639     } else {
2640       // Function types are too different. Abort.
2641       return false;
2642     }
2643 
2644     // Check argument types.
2645     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2646          ArgIdx != NumArgs; ++ArgIdx) {
2647       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2648       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2649       if (Context.getCanonicalType(FromArgType)
2650             == Context.getCanonicalType(ToArgType)) {
2651         // Okay, the types match exactly. Nothing to do.
2652       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2653                                          ConvertedType, IncompatibleObjC)) {
2654         // Okay, we have an Objective-C pointer conversion.
2655         HasObjCConversion = true;
2656       } else {
2657         // Argument types are too different. Abort.
2658         return false;
2659       }
2660     }
2661 
2662     if (HasObjCConversion) {
2663       // We had an Objective-C conversion. Allow this pointer
2664       // conversion, but complain about it.
2665       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2666       IncompatibleObjC = true;
2667       return true;
2668     }
2669   }
2670 
2671   return false;
2672 }
2673 
2674 /// Determine whether this is an Objective-C writeback conversion,
2675 /// used for parameter passing when performing automatic reference counting.
2676 ///
2677 /// \param FromType The type we're converting form.
2678 ///
2679 /// \param ToType The type we're converting to.
2680 ///
2681 /// \param ConvertedType The type that will be produced after applying
2682 /// this conversion.
2683 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2684                                      QualType &ConvertedType) {
2685   if (!getLangOpts().ObjCAutoRefCount ||
2686       Context.hasSameUnqualifiedType(FromType, ToType))
2687     return false;
2688 
2689   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2690   QualType ToPointee;
2691   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2692     ToPointee = ToPointer->getPointeeType();
2693   else
2694     return false;
2695 
2696   Qualifiers ToQuals = ToPointee.getQualifiers();
2697   if (!ToPointee->isObjCLifetimeType() ||
2698       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2699       !ToQuals.withoutObjCLifetime().empty())
2700     return false;
2701 
2702   // Argument must be a pointer to __strong to __weak.
2703   QualType FromPointee;
2704   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2705     FromPointee = FromPointer->getPointeeType();
2706   else
2707     return false;
2708 
2709   Qualifiers FromQuals = FromPointee.getQualifiers();
2710   if (!FromPointee->isObjCLifetimeType() ||
2711       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2712        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2713     return false;
2714 
2715   // Make sure that we have compatible qualifiers.
2716   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2717   if (!ToQuals.compatiblyIncludes(FromQuals))
2718     return false;
2719 
2720   // Remove qualifiers from the pointee type we're converting from; they
2721   // aren't used in the compatibility check belong, and we'll be adding back
2722   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2723   FromPointee = FromPointee.getUnqualifiedType();
2724 
2725   // The unqualified form of the pointee types must be compatible.
2726   ToPointee = ToPointee.getUnqualifiedType();
2727   bool IncompatibleObjC;
2728   if (Context.typesAreCompatible(FromPointee, ToPointee))
2729     FromPointee = ToPointee;
2730   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2731                                     IncompatibleObjC))
2732     return false;
2733 
2734   /// Construct the type we're converting to, which is a pointer to
2735   /// __autoreleasing pointee.
2736   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2737   ConvertedType = Context.getPointerType(FromPointee);
2738   return true;
2739 }
2740 
2741 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2742                                     QualType& ConvertedType) {
2743   QualType ToPointeeType;
2744   if (const BlockPointerType *ToBlockPtr =
2745         ToType->getAs<BlockPointerType>())
2746     ToPointeeType = ToBlockPtr->getPointeeType();
2747   else
2748     return false;
2749 
2750   QualType FromPointeeType;
2751   if (const BlockPointerType *FromBlockPtr =
2752       FromType->getAs<BlockPointerType>())
2753     FromPointeeType = FromBlockPtr->getPointeeType();
2754   else
2755     return false;
2756   // We have pointer to blocks, check whether the only
2757   // differences in the argument and result types are in Objective-C
2758   // pointer conversions. If so, we permit the conversion.
2759 
2760   const FunctionProtoType *FromFunctionType
2761     = FromPointeeType->getAs<FunctionProtoType>();
2762   const FunctionProtoType *ToFunctionType
2763     = ToPointeeType->getAs<FunctionProtoType>();
2764 
2765   if (!FromFunctionType || !ToFunctionType)
2766     return false;
2767 
2768   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2769     return true;
2770 
2771   // Perform the quick checks that will tell us whether these
2772   // function types are obviously different.
2773   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2774       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2775     return false;
2776 
2777   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2778   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2779   if (FromEInfo != ToEInfo)
2780     return false;
2781 
2782   bool IncompatibleObjC = false;
2783   if (Context.hasSameType(FromFunctionType->getReturnType(),
2784                           ToFunctionType->getReturnType())) {
2785     // Okay, the types match exactly. Nothing to do.
2786   } else {
2787     QualType RHS = FromFunctionType->getReturnType();
2788     QualType LHS = ToFunctionType->getReturnType();
2789     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2790         !RHS.hasQualifiers() && LHS.hasQualifiers())
2791        LHS = LHS.getUnqualifiedType();
2792 
2793      if (Context.hasSameType(RHS,LHS)) {
2794        // OK exact match.
2795      } else if (isObjCPointerConversion(RHS, LHS,
2796                                         ConvertedType, IncompatibleObjC)) {
2797      if (IncompatibleObjC)
2798        return false;
2799      // Okay, we have an Objective-C pointer conversion.
2800      }
2801      else
2802        return false;
2803    }
2804 
2805    // Check argument types.
2806    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2807         ArgIdx != NumArgs; ++ArgIdx) {
2808      IncompatibleObjC = false;
2809      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2810      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2811      if (Context.hasSameType(FromArgType, ToArgType)) {
2812        // Okay, the types match exactly. Nothing to do.
2813      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2814                                         ConvertedType, IncompatibleObjC)) {
2815        if (IncompatibleObjC)
2816          return false;
2817        // Okay, we have an Objective-C pointer conversion.
2818      } else
2819        // Argument types are too different. Abort.
2820        return false;
2821    }
2822 
2823    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2824    bool CanUseToFPT, CanUseFromFPT;
2825    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2826                                       CanUseToFPT, CanUseFromFPT,
2827                                       NewParamInfos))
2828      return false;
2829 
2830    ConvertedType = ToType;
2831    return true;
2832 }
2833 
2834 enum {
2835   ft_default,
2836   ft_different_class,
2837   ft_parameter_arity,
2838   ft_parameter_mismatch,
2839   ft_return_type,
2840   ft_qualifer_mismatch,
2841   ft_noexcept
2842 };
2843 
2844 /// Attempts to get the FunctionProtoType from a Type. Handles
2845 /// MemberFunctionPointers properly.
2846 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2847   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2848     return FPT;
2849 
2850   if (auto *MPT = FromType->getAs<MemberPointerType>())
2851     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2852 
2853   return nullptr;
2854 }
2855 
2856 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2857 /// function types.  Catches different number of parameter, mismatch in
2858 /// parameter types, and different return types.
2859 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2860                                       QualType FromType, QualType ToType) {
2861   // If either type is not valid, include no extra info.
2862   if (FromType.isNull() || ToType.isNull()) {
2863     PDiag << ft_default;
2864     return;
2865   }
2866 
2867   // Get the function type from the pointers.
2868   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2869     const auto *FromMember = FromType->castAs<MemberPointerType>(),
2870                *ToMember = ToType->castAs<MemberPointerType>();
2871     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2872       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2873             << QualType(FromMember->getClass(), 0);
2874       return;
2875     }
2876     FromType = FromMember->getPointeeType();
2877     ToType = ToMember->getPointeeType();
2878   }
2879 
2880   if (FromType->isPointerType())
2881     FromType = FromType->getPointeeType();
2882   if (ToType->isPointerType())
2883     ToType = ToType->getPointeeType();
2884 
2885   // Remove references.
2886   FromType = FromType.getNonReferenceType();
2887   ToType = ToType.getNonReferenceType();
2888 
2889   // Don't print extra info for non-specialized template functions.
2890   if (FromType->isInstantiationDependentType() &&
2891       !FromType->getAs<TemplateSpecializationType>()) {
2892     PDiag << ft_default;
2893     return;
2894   }
2895 
2896   // No extra info for same types.
2897   if (Context.hasSameType(FromType, ToType)) {
2898     PDiag << ft_default;
2899     return;
2900   }
2901 
2902   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2903                           *ToFunction = tryGetFunctionProtoType(ToType);
2904 
2905   // Both types need to be function types.
2906   if (!FromFunction || !ToFunction) {
2907     PDiag << ft_default;
2908     return;
2909   }
2910 
2911   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2912     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2913           << FromFunction->getNumParams();
2914     return;
2915   }
2916 
2917   // Handle different parameter types.
2918   unsigned ArgPos;
2919   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2920     PDiag << ft_parameter_mismatch << ArgPos + 1
2921           << ToFunction->getParamType(ArgPos)
2922           << FromFunction->getParamType(ArgPos);
2923     return;
2924   }
2925 
2926   // Handle different return type.
2927   if (!Context.hasSameType(FromFunction->getReturnType(),
2928                            ToFunction->getReturnType())) {
2929     PDiag << ft_return_type << ToFunction->getReturnType()
2930           << FromFunction->getReturnType();
2931     return;
2932   }
2933 
2934   if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2935     PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2936           << FromFunction->getMethodQuals();
2937     return;
2938   }
2939 
2940   // Handle exception specification differences on canonical type (in C++17
2941   // onwards).
2942   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2943           ->isNothrow() !=
2944       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2945           ->isNothrow()) {
2946     PDiag << ft_noexcept;
2947     return;
2948   }
2949 
2950   // Unable to find a difference, so add no extra info.
2951   PDiag << ft_default;
2952 }
2953 
2954 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2955 /// for equality of their argument types. Caller has already checked that
2956 /// they have same number of arguments.  If the parameters are different,
2957 /// ArgPos will have the parameter index of the first different parameter.
2958 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2959                                       const FunctionProtoType *NewType,
2960                                       unsigned *ArgPos) {
2961   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2962                                               N = NewType->param_type_begin(),
2963                                               E = OldType->param_type_end();
2964        O && (O != E); ++O, ++N) {
2965     // Ignore address spaces in pointee type. This is to disallow overloading
2966     // on __ptr32/__ptr64 address spaces.
2967     QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType());
2968     QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType());
2969 
2970     if (!Context.hasSameType(Old, New)) {
2971       if (ArgPos)
2972         *ArgPos = O - OldType->param_type_begin();
2973       return false;
2974     }
2975   }
2976   return true;
2977 }
2978 
2979 /// CheckPointerConversion - Check the pointer conversion from the
2980 /// expression From to the type ToType. This routine checks for
2981 /// ambiguous or inaccessible derived-to-base pointer
2982 /// conversions for which IsPointerConversion has already returned
2983 /// true. It returns true and produces a diagnostic if there was an
2984 /// error, or returns false otherwise.
2985 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2986                                   CastKind &Kind,
2987                                   CXXCastPath& BasePath,
2988                                   bool IgnoreBaseAccess,
2989                                   bool Diagnose) {
2990   QualType FromType = From->getType();
2991   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2992 
2993   Kind = CK_BitCast;
2994 
2995   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2996       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2997           Expr::NPCK_ZeroExpression) {
2998     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2999       DiagRuntimeBehavior(From->getExprLoc(), From,
3000                           PDiag(diag::warn_impcast_bool_to_null_pointer)
3001                             << ToType << From->getSourceRange());
3002     else if (!isUnevaluatedContext())
3003       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3004         << ToType << From->getSourceRange();
3005   }
3006   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3007     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3008       QualType FromPointeeType = FromPtrType->getPointeeType(),
3009                ToPointeeType   = ToPtrType->getPointeeType();
3010 
3011       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3012           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3013         // We must have a derived-to-base conversion. Check an
3014         // ambiguous or inaccessible conversion.
3015         unsigned InaccessibleID = 0;
3016         unsigned AmbiguousID = 0;
3017         if (Diagnose) {
3018           InaccessibleID = diag::err_upcast_to_inaccessible_base;
3019           AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3020         }
3021         if (CheckDerivedToBaseConversion(
3022                 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3023                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3024                 &BasePath, IgnoreBaseAccess))
3025           return true;
3026 
3027         // The conversion was successful.
3028         Kind = CK_DerivedToBase;
3029       }
3030 
3031       if (Diagnose && !IsCStyleOrFunctionalCast &&
3032           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3033         assert(getLangOpts().MSVCCompat &&
3034                "this should only be possible with MSVCCompat!");
3035         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3036             << From->getSourceRange();
3037       }
3038     }
3039   } else if (const ObjCObjectPointerType *ToPtrType =
3040                ToType->getAs<ObjCObjectPointerType>()) {
3041     if (const ObjCObjectPointerType *FromPtrType =
3042           FromType->getAs<ObjCObjectPointerType>()) {
3043       // Objective-C++ conversions are always okay.
3044       // FIXME: We should have a different class of conversions for the
3045       // Objective-C++ implicit conversions.
3046       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3047         return false;
3048     } else if (FromType->isBlockPointerType()) {
3049       Kind = CK_BlockPointerToObjCPointerCast;
3050     } else {
3051       Kind = CK_CPointerToObjCPointerCast;
3052     }
3053   } else if (ToType->isBlockPointerType()) {
3054     if (!FromType->isBlockPointerType())
3055       Kind = CK_AnyPointerToBlockPointerCast;
3056   }
3057 
3058   // We shouldn't fall into this case unless it's valid for other
3059   // reasons.
3060   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3061     Kind = CK_NullToPointer;
3062 
3063   return false;
3064 }
3065 
3066 /// IsMemberPointerConversion - Determines whether the conversion of the
3067 /// expression From, which has the (possibly adjusted) type FromType, can be
3068 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
3069 /// If so, returns true and places the converted type (that might differ from
3070 /// ToType in its cv-qualifiers at some level) into ConvertedType.
3071 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3072                                      QualType ToType,
3073                                      bool InOverloadResolution,
3074                                      QualType &ConvertedType) {
3075   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3076   if (!ToTypePtr)
3077     return false;
3078 
3079   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3080   if (From->isNullPointerConstant(Context,
3081                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3082                                         : Expr::NPC_ValueDependentIsNull)) {
3083     ConvertedType = ToType;
3084     return true;
3085   }
3086 
3087   // Otherwise, both types have to be member pointers.
3088   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3089   if (!FromTypePtr)
3090     return false;
3091 
3092   // A pointer to member of B can be converted to a pointer to member of D,
3093   // where D is derived from B (C++ 4.11p2).
3094   QualType FromClass(FromTypePtr->getClass(), 0);
3095   QualType ToClass(ToTypePtr->getClass(), 0);
3096 
3097   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3098       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3099     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3100                                                  ToClass.getTypePtr());
3101     return true;
3102   }
3103 
3104   return false;
3105 }
3106 
3107 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3108 /// expression From to the type ToType. This routine checks for ambiguous or
3109 /// virtual or inaccessible base-to-derived member pointer conversions
3110 /// for which IsMemberPointerConversion has already returned true. It returns
3111 /// true and produces a diagnostic if there was an error, or returns false
3112 /// otherwise.
3113 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3114                                         CastKind &Kind,
3115                                         CXXCastPath &BasePath,
3116                                         bool IgnoreBaseAccess) {
3117   QualType FromType = From->getType();
3118   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3119   if (!FromPtrType) {
3120     // This must be a null pointer to member pointer conversion
3121     assert(From->isNullPointerConstant(Context,
3122                                        Expr::NPC_ValueDependentIsNull) &&
3123            "Expr must be null pointer constant!");
3124     Kind = CK_NullToMemberPointer;
3125     return false;
3126   }
3127 
3128   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3129   assert(ToPtrType && "No member pointer cast has a target type "
3130                       "that is not a member pointer.");
3131 
3132   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3133   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3134 
3135   // FIXME: What about dependent types?
3136   assert(FromClass->isRecordType() && "Pointer into non-class.");
3137   assert(ToClass->isRecordType() && "Pointer into non-class.");
3138 
3139   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3140                      /*DetectVirtual=*/true);
3141   bool DerivationOkay =
3142       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3143   assert(DerivationOkay &&
3144          "Should not have been called if derivation isn't OK.");
3145   (void)DerivationOkay;
3146 
3147   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3148                                   getUnqualifiedType())) {
3149     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3150     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3151       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3152     return true;
3153   }
3154 
3155   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3156     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3157       << FromClass << ToClass << QualType(VBase, 0)
3158       << From->getSourceRange();
3159     return true;
3160   }
3161 
3162   if (!IgnoreBaseAccess)
3163     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3164                          Paths.front(),
3165                          diag::err_downcast_from_inaccessible_base);
3166 
3167   // Must be a base to derived member conversion.
3168   BuildBasePathArray(Paths, BasePath);
3169   Kind = CK_BaseToDerivedMemberPointer;
3170   return false;
3171 }
3172 
3173 /// Determine whether the lifetime conversion between the two given
3174 /// qualifiers sets is nontrivial.
3175 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3176                                                Qualifiers ToQuals) {
3177   // Converting anything to const __unsafe_unretained is trivial.
3178   if (ToQuals.hasConst() &&
3179       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3180     return false;
3181 
3182   return true;
3183 }
3184 
3185 /// Perform a single iteration of the loop for checking if a qualification
3186 /// conversion is valid.
3187 ///
3188 /// Specifically, check whether any change between the qualifiers of \p
3189 /// FromType and \p ToType is permissible, given knowledge about whether every
3190 /// outer layer is const-qualified.
3191 static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3192                                           bool CStyle, bool IsTopLevel,
3193                                           bool &PreviousToQualsIncludeConst,
3194                                           bool &ObjCLifetimeConversion) {
3195   Qualifiers FromQuals = FromType.getQualifiers();
3196   Qualifiers ToQuals = ToType.getQualifiers();
3197 
3198   // Ignore __unaligned qualifier if this type is void.
3199   if (ToType.getUnqualifiedType()->isVoidType())
3200     FromQuals.removeUnaligned();
3201 
3202   // Objective-C ARC:
3203   //   Check Objective-C lifetime conversions.
3204   if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3205     if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3206       if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3207         ObjCLifetimeConversion = true;
3208       FromQuals.removeObjCLifetime();
3209       ToQuals.removeObjCLifetime();
3210     } else {
3211       // Qualification conversions cannot cast between different
3212       // Objective-C lifetime qualifiers.
3213       return false;
3214     }
3215   }
3216 
3217   // Allow addition/removal of GC attributes but not changing GC attributes.
3218   if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3219       (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3220     FromQuals.removeObjCGCAttr();
3221     ToQuals.removeObjCGCAttr();
3222   }
3223 
3224   //   -- for every j > 0, if const is in cv 1,j then const is in cv
3225   //      2,j, and similarly for volatile.
3226   if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3227     return false;
3228 
3229   // If address spaces mismatch:
3230   //  - in top level it is only valid to convert to addr space that is a
3231   //    superset in all cases apart from C-style casts where we allow
3232   //    conversions between overlapping address spaces.
3233   //  - in non-top levels it is not a valid conversion.
3234   if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3235       (!IsTopLevel ||
3236        !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3237          (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3238     return false;
3239 
3240   //   -- if the cv 1,j and cv 2,j are different, then const is in
3241   //      every cv for 0 < k < j.
3242   if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3243       !PreviousToQualsIncludeConst)
3244     return false;
3245 
3246   // Keep track of whether all prior cv-qualifiers in the "to" type
3247   // include const.
3248   PreviousToQualsIncludeConst =
3249       PreviousToQualsIncludeConst && ToQuals.hasConst();
3250   return true;
3251 }
3252 
3253 /// IsQualificationConversion - Determines whether the conversion from
3254 /// an rvalue of type FromType to ToType is a qualification conversion
3255 /// (C++ 4.4).
3256 ///
3257 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3258 /// when the qualification conversion involves a change in the Objective-C
3259 /// object lifetime.
3260 bool
3261 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3262                                 bool CStyle, bool &ObjCLifetimeConversion) {
3263   FromType = Context.getCanonicalType(FromType);
3264   ToType = Context.getCanonicalType(ToType);
3265   ObjCLifetimeConversion = false;
3266 
3267   // If FromType and ToType are the same type, this is not a
3268   // qualification conversion.
3269   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3270     return false;
3271 
3272   // (C++ 4.4p4):
3273   //   A conversion can add cv-qualifiers at levels other than the first
3274   //   in multi-level pointers, subject to the following rules: [...]
3275   bool PreviousToQualsIncludeConst = true;
3276   bool UnwrappedAnyPointer = false;
3277   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3278     if (!isQualificationConversionStep(
3279             FromType, ToType, CStyle, !UnwrappedAnyPointer,
3280             PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3281       return false;
3282     UnwrappedAnyPointer = true;
3283   }
3284 
3285   // We are left with FromType and ToType being the pointee types
3286   // after unwrapping the original FromType and ToType the same number
3287   // of times. If we unwrapped any pointers, and if FromType and
3288   // ToType have the same unqualified type (since we checked
3289   // qualifiers above), then this is a qualification conversion.
3290   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3291 }
3292 
3293 /// - Determine whether this is a conversion from a scalar type to an
3294 /// atomic type.
3295 ///
3296 /// If successful, updates \c SCS's second and third steps in the conversion
3297 /// sequence to finish the conversion.
3298 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3299                                 bool InOverloadResolution,
3300                                 StandardConversionSequence &SCS,
3301                                 bool CStyle) {
3302   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3303   if (!ToAtomic)
3304     return false;
3305 
3306   StandardConversionSequence InnerSCS;
3307   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3308                             InOverloadResolution, InnerSCS,
3309                             CStyle, /*AllowObjCWritebackConversion=*/false))
3310     return false;
3311 
3312   SCS.Second = InnerSCS.Second;
3313   SCS.setToType(1, InnerSCS.getToType(1));
3314   SCS.Third = InnerSCS.Third;
3315   SCS.QualificationIncludesObjCLifetime
3316     = InnerSCS.QualificationIncludesObjCLifetime;
3317   SCS.setToType(2, InnerSCS.getToType(2));
3318   return true;
3319 }
3320 
3321 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3322                                               CXXConstructorDecl *Constructor,
3323                                               QualType Type) {
3324   const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3325   if (CtorType->getNumParams() > 0) {
3326     QualType FirstArg = CtorType->getParamType(0);
3327     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3328       return true;
3329   }
3330   return false;
3331 }
3332 
3333 static OverloadingResult
3334 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3335                                        CXXRecordDecl *To,
3336                                        UserDefinedConversionSequence &User,
3337                                        OverloadCandidateSet &CandidateSet,
3338                                        bool AllowExplicit) {
3339   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3340   for (auto *D : S.LookupConstructors(To)) {
3341     auto Info = getConstructorInfo(D);
3342     if (!Info)
3343       continue;
3344 
3345     bool Usable = !Info.Constructor->isInvalidDecl() &&
3346                   S.isInitListConstructor(Info.Constructor);
3347     if (Usable) {
3348       // If the first argument is (a reference to) the target type,
3349       // suppress conversions.
3350       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3351           S.Context, Info.Constructor, ToType);
3352       if (Info.ConstructorTmpl)
3353         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3354                                        /*ExplicitArgs*/ nullptr, From,
3355                                        CandidateSet, SuppressUserConversions,
3356                                        /*PartialOverloading*/ false,
3357                                        AllowExplicit);
3358       else
3359         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3360                                CandidateSet, SuppressUserConversions,
3361                                /*PartialOverloading*/ false, AllowExplicit);
3362     }
3363   }
3364 
3365   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3366 
3367   OverloadCandidateSet::iterator Best;
3368   switch (auto Result =
3369               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3370   case OR_Deleted:
3371   case OR_Success: {
3372     // Record the standard conversion we used and the conversion function.
3373     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3374     QualType ThisType = Constructor->getThisType();
3375     // Initializer lists don't have conversions as such.
3376     User.Before.setAsIdentityConversion();
3377     User.HadMultipleCandidates = HadMultipleCandidates;
3378     User.ConversionFunction = Constructor;
3379     User.FoundConversionFunction = Best->FoundDecl;
3380     User.After.setAsIdentityConversion();
3381     User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3382     User.After.setAllToTypes(ToType);
3383     return Result;
3384   }
3385 
3386   case OR_No_Viable_Function:
3387     return OR_No_Viable_Function;
3388   case OR_Ambiguous:
3389     return OR_Ambiguous;
3390   }
3391 
3392   llvm_unreachable("Invalid OverloadResult!");
3393 }
3394 
3395 /// Determines whether there is a user-defined conversion sequence
3396 /// (C++ [over.ics.user]) that converts expression From to the type
3397 /// ToType. If such a conversion exists, User will contain the
3398 /// user-defined conversion sequence that performs such a conversion
3399 /// and this routine will return true. Otherwise, this routine returns
3400 /// false and User is unspecified.
3401 ///
3402 /// \param AllowExplicit  true if the conversion should consider C++0x
3403 /// "explicit" conversion functions as well as non-explicit conversion
3404 /// functions (C++0x [class.conv.fct]p2).
3405 ///
3406 /// \param AllowObjCConversionOnExplicit true if the conversion should
3407 /// allow an extra Objective-C pointer conversion on uses of explicit
3408 /// constructors. Requires \c AllowExplicit to also be set.
3409 static OverloadingResult
3410 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3411                         UserDefinedConversionSequence &User,
3412                         OverloadCandidateSet &CandidateSet,
3413                         AllowedExplicit AllowExplicit,
3414                         bool AllowObjCConversionOnExplicit) {
3415   assert(AllowExplicit != AllowedExplicit::None ||
3416          !AllowObjCConversionOnExplicit);
3417   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3418 
3419   // Whether we will only visit constructors.
3420   bool ConstructorsOnly = false;
3421 
3422   // If the type we are conversion to is a class type, enumerate its
3423   // constructors.
3424   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3425     // C++ [over.match.ctor]p1:
3426     //   When objects of class type are direct-initialized (8.5), or
3427     //   copy-initialized from an expression of the same or a
3428     //   derived class type (8.5), overload resolution selects the
3429     //   constructor. [...] For copy-initialization, the candidate
3430     //   functions are all the converting constructors (12.3.1) of
3431     //   that class. The argument list is the expression-list within
3432     //   the parentheses of the initializer.
3433     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3434         (From->getType()->getAs<RecordType>() &&
3435          S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3436       ConstructorsOnly = true;
3437 
3438     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3439       // We're not going to find any constructors.
3440     } else if (CXXRecordDecl *ToRecordDecl
3441                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3442 
3443       Expr **Args = &From;
3444       unsigned NumArgs = 1;
3445       bool ListInitializing = false;
3446       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3447         // But first, see if there is an init-list-constructor that will work.
3448         OverloadingResult Result = IsInitializerListConstructorConversion(
3449             S, From, ToType, ToRecordDecl, User, CandidateSet,
3450             AllowExplicit == AllowedExplicit::All);
3451         if (Result != OR_No_Viable_Function)
3452           return Result;
3453         // Never mind.
3454         CandidateSet.clear(
3455             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3456 
3457         // If we're list-initializing, we pass the individual elements as
3458         // arguments, not the entire list.
3459         Args = InitList->getInits();
3460         NumArgs = InitList->getNumInits();
3461         ListInitializing = true;
3462       }
3463 
3464       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3465         auto Info = getConstructorInfo(D);
3466         if (!Info)
3467           continue;
3468 
3469         bool Usable = !Info.Constructor->isInvalidDecl();
3470         if (!ListInitializing)
3471           Usable = Usable && Info.Constructor->isConvertingConstructor(
3472                                  /*AllowExplicit*/ true);
3473         if (Usable) {
3474           bool SuppressUserConversions = !ConstructorsOnly;
3475           if (SuppressUserConversions && ListInitializing) {
3476             SuppressUserConversions = false;
3477             if (NumArgs == 1) {
3478               // If the first argument is (a reference to) the target type,
3479               // suppress conversions.
3480               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3481                   S.Context, Info.Constructor, ToType);
3482             }
3483           }
3484           if (Info.ConstructorTmpl)
3485             S.AddTemplateOverloadCandidate(
3486                 Info.ConstructorTmpl, Info.FoundDecl,
3487                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3488                 CandidateSet, SuppressUserConversions,
3489                 /*PartialOverloading*/ false,
3490                 AllowExplicit == AllowedExplicit::All);
3491           else
3492             // Allow one user-defined conversion when user specifies a
3493             // From->ToType conversion via an static cast (c-style, etc).
3494             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3495                                    llvm::makeArrayRef(Args, NumArgs),
3496                                    CandidateSet, SuppressUserConversions,
3497                                    /*PartialOverloading*/ false,
3498                                    AllowExplicit == AllowedExplicit::All);
3499         }
3500       }
3501     }
3502   }
3503 
3504   // Enumerate conversion functions, if we're allowed to.
3505   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3506   } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3507     // No conversion functions from incomplete types.
3508   } else if (const RecordType *FromRecordType =
3509                  From->getType()->getAs<RecordType>()) {
3510     if (CXXRecordDecl *FromRecordDecl
3511          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3512       // Add all of the conversion functions as candidates.
3513       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3514       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3515         DeclAccessPair FoundDecl = I.getPair();
3516         NamedDecl *D = FoundDecl.getDecl();
3517         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3518         if (isa<UsingShadowDecl>(D))
3519           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3520 
3521         CXXConversionDecl *Conv;
3522         FunctionTemplateDecl *ConvTemplate;
3523         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3524           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3525         else
3526           Conv = cast<CXXConversionDecl>(D);
3527 
3528         if (ConvTemplate)
3529           S.AddTemplateConversionCandidate(
3530               ConvTemplate, FoundDecl, ActingContext, From, ToType,
3531               CandidateSet, AllowObjCConversionOnExplicit,
3532               AllowExplicit != AllowedExplicit::None);
3533         else
3534           S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3535                                    CandidateSet, AllowObjCConversionOnExplicit,
3536                                    AllowExplicit != AllowedExplicit::None);
3537       }
3538     }
3539   }
3540 
3541   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3542 
3543   OverloadCandidateSet::iterator Best;
3544   switch (auto Result =
3545               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3546   case OR_Success:
3547   case OR_Deleted:
3548     // Record the standard conversion we used and the conversion function.
3549     if (CXXConstructorDecl *Constructor
3550           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3551       // C++ [over.ics.user]p1:
3552       //   If the user-defined conversion is specified by a
3553       //   constructor (12.3.1), the initial standard conversion
3554       //   sequence converts the source type to the type required by
3555       //   the argument of the constructor.
3556       //
3557       QualType ThisType = Constructor->getThisType();
3558       if (isa<InitListExpr>(From)) {
3559         // Initializer lists don't have conversions as such.
3560         User.Before.setAsIdentityConversion();
3561       } else {
3562         if (Best->Conversions[0].isEllipsis())
3563           User.EllipsisConversion = true;
3564         else {
3565           User.Before = Best->Conversions[0].Standard;
3566           User.EllipsisConversion = false;
3567         }
3568       }
3569       User.HadMultipleCandidates = HadMultipleCandidates;
3570       User.ConversionFunction = Constructor;
3571       User.FoundConversionFunction = Best->FoundDecl;
3572       User.After.setAsIdentityConversion();
3573       User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3574       User.After.setAllToTypes(ToType);
3575       return Result;
3576     }
3577     if (CXXConversionDecl *Conversion
3578                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3579       // C++ [over.ics.user]p1:
3580       //
3581       //   [...] If the user-defined conversion is specified by a
3582       //   conversion function (12.3.2), the initial standard
3583       //   conversion sequence converts the source type to the
3584       //   implicit object parameter of the conversion function.
3585       User.Before = Best->Conversions[0].Standard;
3586       User.HadMultipleCandidates = HadMultipleCandidates;
3587       User.ConversionFunction = Conversion;
3588       User.FoundConversionFunction = Best->FoundDecl;
3589       User.EllipsisConversion = false;
3590 
3591       // C++ [over.ics.user]p2:
3592       //   The second standard conversion sequence converts the
3593       //   result of the user-defined conversion to the target type
3594       //   for the sequence. Since an implicit conversion sequence
3595       //   is an initialization, the special rules for
3596       //   initialization by user-defined conversion apply when
3597       //   selecting the best user-defined conversion for a
3598       //   user-defined conversion sequence (see 13.3.3 and
3599       //   13.3.3.1).
3600       User.After = Best->FinalConversion;
3601       return Result;
3602     }
3603     llvm_unreachable("Not a constructor or conversion function?");
3604 
3605   case OR_No_Viable_Function:
3606     return OR_No_Viable_Function;
3607 
3608   case OR_Ambiguous:
3609     return OR_Ambiguous;
3610   }
3611 
3612   llvm_unreachable("Invalid OverloadResult!");
3613 }
3614 
3615 bool
3616 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3617   ImplicitConversionSequence ICS;
3618   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3619                                     OverloadCandidateSet::CSK_Normal);
3620   OverloadingResult OvResult =
3621     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3622                             CandidateSet, AllowedExplicit::None, false);
3623 
3624   if (!(OvResult == OR_Ambiguous ||
3625         (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3626     return false;
3627 
3628   auto Cands = CandidateSet.CompleteCandidates(
3629       *this,
3630       OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3631       From);
3632   if (OvResult == OR_Ambiguous)
3633     Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3634         << From->getType() << ToType << From->getSourceRange();
3635   else { // OR_No_Viable_Function && !CandidateSet.empty()
3636     if (!RequireCompleteType(From->getBeginLoc(), ToType,
3637                              diag::err_typecheck_nonviable_condition_incomplete,
3638                              From->getType(), From->getSourceRange()))
3639       Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3640           << false << From->getType() << From->getSourceRange() << ToType;
3641   }
3642 
3643   CandidateSet.NoteCandidates(
3644                               *this, From, Cands);
3645   return true;
3646 }
3647 
3648 /// Compare the user-defined conversion functions or constructors
3649 /// of two user-defined conversion sequences to determine whether any ordering
3650 /// is possible.
3651 static ImplicitConversionSequence::CompareKind
3652 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3653                            FunctionDecl *Function2) {
3654   if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11)
3655     return ImplicitConversionSequence::Indistinguishable;
3656 
3657   // Objective-C++:
3658   //   If both conversion functions are implicitly-declared conversions from
3659   //   a lambda closure type to a function pointer and a block pointer,
3660   //   respectively, always prefer the conversion to a function pointer,
3661   //   because the function pointer is more lightweight and is more likely
3662   //   to keep code working.
3663   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3664   if (!Conv1)
3665     return ImplicitConversionSequence::Indistinguishable;
3666 
3667   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3668   if (!Conv2)
3669     return ImplicitConversionSequence::Indistinguishable;
3670 
3671   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3672     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3673     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3674     if (Block1 != Block2)
3675       return Block1 ? ImplicitConversionSequence::Worse
3676                     : ImplicitConversionSequence::Better;
3677   }
3678 
3679   return ImplicitConversionSequence::Indistinguishable;
3680 }
3681 
3682 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3683     const ImplicitConversionSequence &ICS) {
3684   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3685          (ICS.isUserDefined() &&
3686           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3687 }
3688 
3689 /// CompareImplicitConversionSequences - Compare two implicit
3690 /// conversion sequences to determine whether one is better than the
3691 /// other or if they are indistinguishable (C++ 13.3.3.2).
3692 static ImplicitConversionSequence::CompareKind
3693 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3694                                    const ImplicitConversionSequence& ICS1,
3695                                    const ImplicitConversionSequence& ICS2)
3696 {
3697   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3698   // conversion sequences (as defined in 13.3.3.1)
3699   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3700   //      conversion sequence than a user-defined conversion sequence or
3701   //      an ellipsis conversion sequence, and
3702   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3703   //      conversion sequence than an ellipsis conversion sequence
3704   //      (13.3.3.1.3).
3705   //
3706   // C++0x [over.best.ics]p10:
3707   //   For the purpose of ranking implicit conversion sequences as
3708   //   described in 13.3.3.2, the ambiguous conversion sequence is
3709   //   treated as a user-defined sequence that is indistinguishable
3710   //   from any other user-defined conversion sequence.
3711 
3712   // String literal to 'char *' conversion has been deprecated in C++03. It has
3713   // been removed from C++11. We still accept this conversion, if it happens at
3714   // the best viable function. Otherwise, this conversion is considered worse
3715   // than ellipsis conversion. Consider this as an extension; this is not in the
3716   // standard. For example:
3717   //
3718   // int &f(...);    // #1
3719   // void f(char*);  // #2
3720   // void g() { int &r = f("foo"); }
3721   //
3722   // In C++03, we pick #2 as the best viable function.
3723   // In C++11, we pick #1 as the best viable function, because ellipsis
3724   // conversion is better than string-literal to char* conversion (since there
3725   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3726   // convert arguments, #2 would be the best viable function in C++11.
3727   // If the best viable function has this conversion, a warning will be issued
3728   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3729 
3730   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3731       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3732       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3733     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3734                ? ImplicitConversionSequence::Worse
3735                : ImplicitConversionSequence::Better;
3736 
3737   if (ICS1.getKindRank() < ICS2.getKindRank())
3738     return ImplicitConversionSequence::Better;
3739   if (ICS2.getKindRank() < ICS1.getKindRank())
3740     return ImplicitConversionSequence::Worse;
3741 
3742   // The following checks require both conversion sequences to be of
3743   // the same kind.
3744   if (ICS1.getKind() != ICS2.getKind())
3745     return ImplicitConversionSequence::Indistinguishable;
3746 
3747   ImplicitConversionSequence::CompareKind Result =
3748       ImplicitConversionSequence::Indistinguishable;
3749 
3750   // Two implicit conversion sequences of the same form are
3751   // indistinguishable conversion sequences unless one of the
3752   // following rules apply: (C++ 13.3.3.2p3):
3753 
3754   // List-initialization sequence L1 is a better conversion sequence than
3755   // list-initialization sequence L2 if:
3756   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3757   //   if not that,
3758   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3759   //   and N1 is smaller than N2.,
3760   // even if one of the other rules in this paragraph would otherwise apply.
3761   if (!ICS1.isBad()) {
3762     if (ICS1.isStdInitializerListElement() &&
3763         !ICS2.isStdInitializerListElement())
3764       return ImplicitConversionSequence::Better;
3765     if (!ICS1.isStdInitializerListElement() &&
3766         ICS2.isStdInitializerListElement())
3767       return ImplicitConversionSequence::Worse;
3768   }
3769 
3770   if (ICS1.isStandard())
3771     // Standard conversion sequence S1 is a better conversion sequence than
3772     // standard conversion sequence S2 if [...]
3773     Result = CompareStandardConversionSequences(S, Loc,
3774                                                 ICS1.Standard, ICS2.Standard);
3775   else if (ICS1.isUserDefined()) {
3776     // User-defined conversion sequence U1 is a better conversion
3777     // sequence than another user-defined conversion sequence U2 if
3778     // they contain the same user-defined conversion function or
3779     // constructor and if the second standard conversion sequence of
3780     // U1 is better than the second standard conversion sequence of
3781     // U2 (C++ 13.3.3.2p3).
3782     if (ICS1.UserDefined.ConversionFunction ==
3783           ICS2.UserDefined.ConversionFunction)
3784       Result = CompareStandardConversionSequences(S, Loc,
3785                                                   ICS1.UserDefined.After,
3786                                                   ICS2.UserDefined.After);
3787     else
3788       Result = compareConversionFunctions(S,
3789                                           ICS1.UserDefined.ConversionFunction,
3790                                           ICS2.UserDefined.ConversionFunction);
3791   }
3792 
3793   return Result;
3794 }
3795 
3796 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3797 // determine if one is a proper subset of the other.
3798 static ImplicitConversionSequence::CompareKind
3799 compareStandardConversionSubsets(ASTContext &Context,
3800                                  const StandardConversionSequence& SCS1,
3801                                  const StandardConversionSequence& SCS2) {
3802   ImplicitConversionSequence::CompareKind Result
3803     = ImplicitConversionSequence::Indistinguishable;
3804 
3805   // the identity conversion sequence is considered to be a subsequence of
3806   // any non-identity conversion sequence
3807   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3808     return ImplicitConversionSequence::Better;
3809   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3810     return ImplicitConversionSequence::Worse;
3811 
3812   if (SCS1.Second != SCS2.Second) {
3813     if (SCS1.Second == ICK_Identity)
3814       Result = ImplicitConversionSequence::Better;
3815     else if (SCS2.Second == ICK_Identity)
3816       Result = ImplicitConversionSequence::Worse;
3817     else
3818       return ImplicitConversionSequence::Indistinguishable;
3819   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3820     return ImplicitConversionSequence::Indistinguishable;
3821 
3822   if (SCS1.Third == SCS2.Third) {
3823     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3824                              : ImplicitConversionSequence::Indistinguishable;
3825   }
3826 
3827   if (SCS1.Third == ICK_Identity)
3828     return Result == ImplicitConversionSequence::Worse
3829              ? ImplicitConversionSequence::Indistinguishable
3830              : ImplicitConversionSequence::Better;
3831 
3832   if (SCS2.Third == ICK_Identity)
3833     return Result == ImplicitConversionSequence::Better
3834              ? ImplicitConversionSequence::Indistinguishable
3835              : ImplicitConversionSequence::Worse;
3836 
3837   return ImplicitConversionSequence::Indistinguishable;
3838 }
3839 
3840 /// Determine whether one of the given reference bindings is better
3841 /// than the other based on what kind of bindings they are.
3842 static bool
3843 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3844                              const StandardConversionSequence &SCS2) {
3845   // C++0x [over.ics.rank]p3b4:
3846   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3847   //      implicit object parameter of a non-static member function declared
3848   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3849   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3850   //      lvalue reference to a function lvalue and S2 binds an rvalue
3851   //      reference*.
3852   //
3853   // FIXME: Rvalue references. We're going rogue with the above edits,
3854   // because the semantics in the current C++0x working paper (N3225 at the
3855   // time of this writing) break the standard definition of std::forward
3856   // and std::reference_wrapper when dealing with references to functions.
3857   // Proposed wording changes submitted to CWG for consideration.
3858   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3859       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3860     return false;
3861 
3862   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3863           SCS2.IsLvalueReference) ||
3864          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3865           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3866 }
3867 
3868 enum class FixedEnumPromotion {
3869   None,
3870   ToUnderlyingType,
3871   ToPromotedUnderlyingType
3872 };
3873 
3874 /// Returns kind of fixed enum promotion the \a SCS uses.
3875 static FixedEnumPromotion
3876 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
3877 
3878   if (SCS.Second != ICK_Integral_Promotion)
3879     return FixedEnumPromotion::None;
3880 
3881   QualType FromType = SCS.getFromType();
3882   if (!FromType->isEnumeralType())
3883     return FixedEnumPromotion::None;
3884 
3885   EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl();
3886   if (!Enum->isFixed())
3887     return FixedEnumPromotion::None;
3888 
3889   QualType UnderlyingType = Enum->getIntegerType();
3890   if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
3891     return FixedEnumPromotion::ToUnderlyingType;
3892 
3893   return FixedEnumPromotion::ToPromotedUnderlyingType;
3894 }
3895 
3896 /// CompareStandardConversionSequences - Compare two standard
3897 /// conversion sequences to determine whether one is better than the
3898 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3899 static ImplicitConversionSequence::CompareKind
3900 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3901                                    const StandardConversionSequence& SCS1,
3902                                    const StandardConversionSequence& SCS2)
3903 {
3904   // Standard conversion sequence S1 is a better conversion sequence
3905   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3906 
3907   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3908   //     sequences in the canonical form defined by 13.3.3.1.1,
3909   //     excluding any Lvalue Transformation; the identity conversion
3910   //     sequence is considered to be a subsequence of any
3911   //     non-identity conversion sequence) or, if not that,
3912   if (ImplicitConversionSequence::CompareKind CK
3913         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3914     return CK;
3915 
3916   //  -- the rank of S1 is better than the rank of S2 (by the rules
3917   //     defined below), or, if not that,
3918   ImplicitConversionRank Rank1 = SCS1.getRank();
3919   ImplicitConversionRank Rank2 = SCS2.getRank();
3920   if (Rank1 < Rank2)
3921     return ImplicitConversionSequence::Better;
3922   else if (Rank2 < Rank1)
3923     return ImplicitConversionSequence::Worse;
3924 
3925   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3926   // are indistinguishable unless one of the following rules
3927   // applies:
3928 
3929   //   A conversion that is not a conversion of a pointer, or
3930   //   pointer to member, to bool is better than another conversion
3931   //   that is such a conversion.
3932   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3933     return SCS2.isPointerConversionToBool()
3934              ? ImplicitConversionSequence::Better
3935              : ImplicitConversionSequence::Worse;
3936 
3937   // C++14 [over.ics.rank]p4b2:
3938   // This is retroactively applied to C++11 by CWG 1601.
3939   //
3940   //   A conversion that promotes an enumeration whose underlying type is fixed
3941   //   to its underlying type is better than one that promotes to the promoted
3942   //   underlying type, if the two are different.
3943   FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
3944   FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
3945   if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
3946       FEP1 != FEP2)
3947     return FEP1 == FixedEnumPromotion::ToUnderlyingType
3948                ? ImplicitConversionSequence::Better
3949                : ImplicitConversionSequence::Worse;
3950 
3951   // C++ [over.ics.rank]p4b2:
3952   //
3953   //   If class B is derived directly or indirectly from class A,
3954   //   conversion of B* to A* is better than conversion of B* to
3955   //   void*, and conversion of A* to void* is better than conversion
3956   //   of B* to void*.
3957   bool SCS1ConvertsToVoid
3958     = SCS1.isPointerConversionToVoidPointer(S.Context);
3959   bool SCS2ConvertsToVoid
3960     = SCS2.isPointerConversionToVoidPointer(S.Context);
3961   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3962     // Exactly one of the conversion sequences is a conversion to
3963     // a void pointer; it's the worse conversion.
3964     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3965                               : ImplicitConversionSequence::Worse;
3966   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3967     // Neither conversion sequence converts to a void pointer; compare
3968     // their derived-to-base conversions.
3969     if (ImplicitConversionSequence::CompareKind DerivedCK
3970           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3971       return DerivedCK;
3972   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3973              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3974     // Both conversion sequences are conversions to void
3975     // pointers. Compare the source types to determine if there's an
3976     // inheritance relationship in their sources.
3977     QualType FromType1 = SCS1.getFromType();
3978     QualType FromType2 = SCS2.getFromType();
3979 
3980     // Adjust the types we're converting from via the array-to-pointer
3981     // conversion, if we need to.
3982     if (SCS1.First == ICK_Array_To_Pointer)
3983       FromType1 = S.Context.getArrayDecayedType(FromType1);
3984     if (SCS2.First == ICK_Array_To_Pointer)
3985       FromType2 = S.Context.getArrayDecayedType(FromType2);
3986 
3987     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3988     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3989 
3990     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3991       return ImplicitConversionSequence::Better;
3992     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3993       return ImplicitConversionSequence::Worse;
3994 
3995     // Objective-C++: If one interface is more specific than the
3996     // other, it is the better one.
3997     const ObjCObjectPointerType* FromObjCPtr1
3998       = FromType1->getAs<ObjCObjectPointerType>();
3999     const ObjCObjectPointerType* FromObjCPtr2
4000       = FromType2->getAs<ObjCObjectPointerType>();
4001     if (FromObjCPtr1 && FromObjCPtr2) {
4002       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4003                                                           FromObjCPtr2);
4004       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4005                                                            FromObjCPtr1);
4006       if (AssignLeft != AssignRight) {
4007         return AssignLeft? ImplicitConversionSequence::Better
4008                          : ImplicitConversionSequence::Worse;
4009       }
4010     }
4011   }
4012 
4013   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4014     // Check for a better reference binding based on the kind of bindings.
4015     if (isBetterReferenceBindingKind(SCS1, SCS2))
4016       return ImplicitConversionSequence::Better;
4017     else if (isBetterReferenceBindingKind(SCS2, SCS1))
4018       return ImplicitConversionSequence::Worse;
4019   }
4020 
4021   // Compare based on qualification conversions (C++ 13.3.3.2p3,
4022   // bullet 3).
4023   if (ImplicitConversionSequence::CompareKind QualCK
4024         = CompareQualificationConversions(S, SCS1, SCS2))
4025     return QualCK;
4026 
4027   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4028     // C++ [over.ics.rank]p3b4:
4029     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
4030     //      which the references refer are the same type except for
4031     //      top-level cv-qualifiers, and the type to which the reference
4032     //      initialized by S2 refers is more cv-qualified than the type
4033     //      to which the reference initialized by S1 refers.
4034     QualType T1 = SCS1.getToType(2);
4035     QualType T2 = SCS2.getToType(2);
4036     T1 = S.Context.getCanonicalType(T1);
4037     T2 = S.Context.getCanonicalType(T2);
4038     Qualifiers T1Quals, T2Quals;
4039     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4040     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4041     if (UnqualT1 == UnqualT2) {
4042       // Objective-C++ ARC: If the references refer to objects with different
4043       // lifetimes, prefer bindings that don't change lifetime.
4044       if (SCS1.ObjCLifetimeConversionBinding !=
4045                                           SCS2.ObjCLifetimeConversionBinding) {
4046         return SCS1.ObjCLifetimeConversionBinding
4047                                            ? ImplicitConversionSequence::Worse
4048                                            : ImplicitConversionSequence::Better;
4049       }
4050 
4051       // If the type is an array type, promote the element qualifiers to the
4052       // type for comparison.
4053       if (isa<ArrayType>(T1) && T1Quals)
4054         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4055       if (isa<ArrayType>(T2) && T2Quals)
4056         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4057       if (T2.isMoreQualifiedThan(T1))
4058         return ImplicitConversionSequence::Better;
4059       if (T1.isMoreQualifiedThan(T2))
4060         return ImplicitConversionSequence::Worse;
4061     }
4062   }
4063 
4064   // In Microsoft mode, prefer an integral conversion to a
4065   // floating-to-integral conversion if the integral conversion
4066   // is between types of the same size.
4067   // For example:
4068   // void f(float);
4069   // void f(int);
4070   // int main {
4071   //    long a;
4072   //    f(a);
4073   // }
4074   // Here, MSVC will call f(int) instead of generating a compile error
4075   // as clang will do in standard mode.
4076   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
4077       SCS2.Second == ICK_Floating_Integral &&
4078       S.Context.getTypeSize(SCS1.getFromType()) ==
4079           S.Context.getTypeSize(SCS1.getToType(2)))
4080     return ImplicitConversionSequence::Better;
4081 
4082   // Prefer a compatible vector conversion over a lax vector conversion
4083   // For example:
4084   //
4085   // typedef float __v4sf __attribute__((__vector_size__(16)));
4086   // void f(vector float);
4087   // void f(vector signed int);
4088   // int main() {
4089   //   __v4sf a;
4090   //   f(a);
4091   // }
4092   // Here, we'd like to choose f(vector float) and not
4093   // report an ambiguous call error
4094   if (SCS1.Second == ICK_Vector_Conversion &&
4095       SCS2.Second == ICK_Vector_Conversion) {
4096     bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4097         SCS1.getFromType(), SCS1.getToType(2));
4098     bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4099         SCS2.getFromType(), SCS2.getToType(2));
4100 
4101     if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4102       return SCS1IsCompatibleVectorConversion
4103                  ? ImplicitConversionSequence::Better
4104                  : ImplicitConversionSequence::Worse;
4105   }
4106 
4107   return ImplicitConversionSequence::Indistinguishable;
4108 }
4109 
4110 /// CompareQualificationConversions - Compares two standard conversion
4111 /// sequences to determine whether they can be ranked based on their
4112 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4113 static ImplicitConversionSequence::CompareKind
4114 CompareQualificationConversions(Sema &S,
4115                                 const StandardConversionSequence& SCS1,
4116                                 const StandardConversionSequence& SCS2) {
4117   // C++ 13.3.3.2p3:
4118   //  -- S1 and S2 differ only in their qualification conversion and
4119   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
4120   //     cv-qualification signature of type T1 is a proper subset of
4121   //     the cv-qualification signature of type T2, and S1 is not the
4122   //     deprecated string literal array-to-pointer conversion (4.2).
4123   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4124       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4125     return ImplicitConversionSequence::Indistinguishable;
4126 
4127   // FIXME: the example in the standard doesn't use a qualification
4128   // conversion (!)
4129   QualType T1 = SCS1.getToType(2);
4130   QualType T2 = SCS2.getToType(2);
4131   T1 = S.Context.getCanonicalType(T1);
4132   T2 = S.Context.getCanonicalType(T2);
4133   assert(!T1->isReferenceType() && !T2->isReferenceType());
4134   Qualifiers T1Quals, T2Quals;
4135   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4136   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4137 
4138   // If the types are the same, we won't learn anything by unwrapping
4139   // them.
4140   if (UnqualT1 == UnqualT2)
4141     return ImplicitConversionSequence::Indistinguishable;
4142 
4143   ImplicitConversionSequence::CompareKind Result
4144     = ImplicitConversionSequence::Indistinguishable;
4145 
4146   // Objective-C++ ARC:
4147   //   Prefer qualification conversions not involving a change in lifetime
4148   //   to qualification conversions that do not change lifetime.
4149   if (SCS1.QualificationIncludesObjCLifetime !=
4150                                       SCS2.QualificationIncludesObjCLifetime) {
4151     Result = SCS1.QualificationIncludesObjCLifetime
4152                ? ImplicitConversionSequence::Worse
4153                : ImplicitConversionSequence::Better;
4154   }
4155 
4156   while (S.Context.UnwrapSimilarTypes(T1, T2)) {
4157     // Within each iteration of the loop, we check the qualifiers to
4158     // determine if this still looks like a qualification
4159     // conversion. Then, if all is well, we unwrap one more level of
4160     // pointers or pointers-to-members and do it all again
4161     // until there are no more pointers or pointers-to-members left
4162     // to unwrap. This essentially mimics what
4163     // IsQualificationConversion does, but here we're checking for a
4164     // strict subset of qualifiers.
4165     if (T1.getQualifiers().withoutObjCLifetime() ==
4166         T2.getQualifiers().withoutObjCLifetime())
4167       // The qualifiers are the same, so this doesn't tell us anything
4168       // about how the sequences rank.
4169       // ObjC ownership quals are omitted above as they interfere with
4170       // the ARC overload rule.
4171       ;
4172     else if (T2.isMoreQualifiedThan(T1)) {
4173       // T1 has fewer qualifiers, so it could be the better sequence.
4174       if (Result == ImplicitConversionSequence::Worse)
4175         // Neither has qualifiers that are a subset of the other's
4176         // qualifiers.
4177         return ImplicitConversionSequence::Indistinguishable;
4178 
4179       Result = ImplicitConversionSequence::Better;
4180     } else if (T1.isMoreQualifiedThan(T2)) {
4181       // T2 has fewer qualifiers, so it could be the better sequence.
4182       if (Result == ImplicitConversionSequence::Better)
4183         // Neither has qualifiers that are a subset of the other's
4184         // qualifiers.
4185         return ImplicitConversionSequence::Indistinguishable;
4186 
4187       Result = ImplicitConversionSequence::Worse;
4188     } else {
4189       // Qualifiers are disjoint.
4190       return ImplicitConversionSequence::Indistinguishable;
4191     }
4192 
4193     // If the types after this point are equivalent, we're done.
4194     if (S.Context.hasSameUnqualifiedType(T1, T2))
4195       break;
4196   }
4197 
4198   // Check that the winning standard conversion sequence isn't using
4199   // the deprecated string literal array to pointer conversion.
4200   switch (Result) {
4201   case ImplicitConversionSequence::Better:
4202     if (SCS1.DeprecatedStringLiteralToCharPtr)
4203       Result = ImplicitConversionSequence::Indistinguishable;
4204     break;
4205 
4206   case ImplicitConversionSequence::Indistinguishable:
4207     break;
4208 
4209   case ImplicitConversionSequence::Worse:
4210     if (SCS2.DeprecatedStringLiteralToCharPtr)
4211       Result = ImplicitConversionSequence::Indistinguishable;
4212     break;
4213   }
4214 
4215   return Result;
4216 }
4217 
4218 /// CompareDerivedToBaseConversions - Compares two standard conversion
4219 /// sequences to determine whether they can be ranked based on their
4220 /// various kinds of derived-to-base conversions (C++
4221 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4222 /// conversions between Objective-C interface types.
4223 static ImplicitConversionSequence::CompareKind
4224 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4225                                 const StandardConversionSequence& SCS1,
4226                                 const StandardConversionSequence& SCS2) {
4227   QualType FromType1 = SCS1.getFromType();
4228   QualType ToType1 = SCS1.getToType(1);
4229   QualType FromType2 = SCS2.getFromType();
4230   QualType ToType2 = SCS2.getToType(1);
4231 
4232   // Adjust the types we're converting from via the array-to-pointer
4233   // conversion, if we need to.
4234   if (SCS1.First == ICK_Array_To_Pointer)
4235     FromType1 = S.Context.getArrayDecayedType(FromType1);
4236   if (SCS2.First == ICK_Array_To_Pointer)
4237     FromType2 = S.Context.getArrayDecayedType(FromType2);
4238 
4239   // Canonicalize all of the types.
4240   FromType1 = S.Context.getCanonicalType(FromType1);
4241   ToType1 = S.Context.getCanonicalType(ToType1);
4242   FromType2 = S.Context.getCanonicalType(FromType2);
4243   ToType2 = S.Context.getCanonicalType(ToType2);
4244 
4245   // C++ [over.ics.rank]p4b3:
4246   //
4247   //   If class B is derived directly or indirectly from class A and
4248   //   class C is derived directly or indirectly from B,
4249   //
4250   // Compare based on pointer conversions.
4251   if (SCS1.Second == ICK_Pointer_Conversion &&
4252       SCS2.Second == ICK_Pointer_Conversion &&
4253       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4254       FromType1->isPointerType() && FromType2->isPointerType() &&
4255       ToType1->isPointerType() && ToType2->isPointerType()) {
4256     QualType FromPointee1 =
4257         FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4258     QualType ToPointee1 =
4259         ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4260     QualType FromPointee2 =
4261         FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4262     QualType ToPointee2 =
4263         ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4264 
4265     //   -- conversion of C* to B* is better than conversion of C* to A*,
4266     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4267       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4268         return ImplicitConversionSequence::Better;
4269       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4270         return ImplicitConversionSequence::Worse;
4271     }
4272 
4273     //   -- conversion of B* to A* is better than conversion of C* to A*,
4274     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4275       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4276         return ImplicitConversionSequence::Better;
4277       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4278         return ImplicitConversionSequence::Worse;
4279     }
4280   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4281              SCS2.Second == ICK_Pointer_Conversion) {
4282     const ObjCObjectPointerType *FromPtr1
4283       = FromType1->getAs<ObjCObjectPointerType>();
4284     const ObjCObjectPointerType *FromPtr2
4285       = FromType2->getAs<ObjCObjectPointerType>();
4286     const ObjCObjectPointerType *ToPtr1
4287       = ToType1->getAs<ObjCObjectPointerType>();
4288     const ObjCObjectPointerType *ToPtr2
4289       = ToType2->getAs<ObjCObjectPointerType>();
4290 
4291     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4292       // Apply the same conversion ranking rules for Objective-C pointer types
4293       // that we do for C++ pointers to class types. However, we employ the
4294       // Objective-C pseudo-subtyping relationship used for assignment of
4295       // Objective-C pointer types.
4296       bool FromAssignLeft
4297         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4298       bool FromAssignRight
4299         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4300       bool ToAssignLeft
4301         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4302       bool ToAssignRight
4303         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4304 
4305       // A conversion to an a non-id object pointer type or qualified 'id'
4306       // type is better than a conversion to 'id'.
4307       if (ToPtr1->isObjCIdType() &&
4308           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4309         return ImplicitConversionSequence::Worse;
4310       if (ToPtr2->isObjCIdType() &&
4311           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4312         return ImplicitConversionSequence::Better;
4313 
4314       // A conversion to a non-id object pointer type is better than a
4315       // conversion to a qualified 'id' type
4316       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4317         return ImplicitConversionSequence::Worse;
4318       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4319         return ImplicitConversionSequence::Better;
4320 
4321       // A conversion to an a non-Class object pointer type or qualified 'Class'
4322       // type is better than a conversion to 'Class'.
4323       if (ToPtr1->isObjCClassType() &&
4324           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4325         return ImplicitConversionSequence::Worse;
4326       if (ToPtr2->isObjCClassType() &&
4327           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4328         return ImplicitConversionSequence::Better;
4329 
4330       // A conversion to a non-Class object pointer type is better than a
4331       // conversion to a qualified 'Class' type.
4332       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4333         return ImplicitConversionSequence::Worse;
4334       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4335         return ImplicitConversionSequence::Better;
4336 
4337       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4338       if (S.Context.hasSameType(FromType1, FromType2) &&
4339           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4340           (ToAssignLeft != ToAssignRight)) {
4341         if (FromPtr1->isSpecialized()) {
4342           // "conversion of B<A> * to B * is better than conversion of B * to
4343           // C *.
4344           bool IsFirstSame =
4345               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4346           bool IsSecondSame =
4347               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4348           if (IsFirstSame) {
4349             if (!IsSecondSame)
4350               return ImplicitConversionSequence::Better;
4351           } else if (IsSecondSame)
4352             return ImplicitConversionSequence::Worse;
4353         }
4354         return ToAssignLeft? ImplicitConversionSequence::Worse
4355                            : ImplicitConversionSequence::Better;
4356       }
4357 
4358       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4359       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4360           (FromAssignLeft != FromAssignRight))
4361         return FromAssignLeft? ImplicitConversionSequence::Better
4362         : ImplicitConversionSequence::Worse;
4363     }
4364   }
4365 
4366   // Ranking of member-pointer types.
4367   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4368       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4369       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4370     const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4371     const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4372     const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4373     const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4374     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4375     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4376     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4377     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4378     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4379     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4380     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4381     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4382     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4383     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4384       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4385         return ImplicitConversionSequence::Worse;
4386       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4387         return ImplicitConversionSequence::Better;
4388     }
4389     // conversion of B::* to C::* is better than conversion of A::* to C::*
4390     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4391       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4392         return ImplicitConversionSequence::Better;
4393       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4394         return ImplicitConversionSequence::Worse;
4395     }
4396   }
4397 
4398   if (SCS1.Second == ICK_Derived_To_Base) {
4399     //   -- conversion of C to B is better than conversion of C to A,
4400     //   -- binding of an expression of type C to a reference of type
4401     //      B& is better than binding an expression of type C to a
4402     //      reference of type A&,
4403     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4404         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4405       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4406         return ImplicitConversionSequence::Better;
4407       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4408         return ImplicitConversionSequence::Worse;
4409     }
4410 
4411     //   -- conversion of B to A is better than conversion of C to A.
4412     //   -- binding of an expression of type B to a reference of type
4413     //      A& is better than binding an expression of type C to a
4414     //      reference of type A&,
4415     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4416         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4417       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4418         return ImplicitConversionSequence::Better;
4419       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4420         return ImplicitConversionSequence::Worse;
4421     }
4422   }
4423 
4424   return ImplicitConversionSequence::Indistinguishable;
4425 }
4426 
4427 /// Determine whether the given type is valid, e.g., it is not an invalid
4428 /// C++ class.
4429 static bool isTypeValid(QualType T) {
4430   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4431     return !Record->isInvalidDecl();
4432 
4433   return true;
4434 }
4435 
4436 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4437   if (!T.getQualifiers().hasUnaligned())
4438     return T;
4439 
4440   Qualifiers Q;
4441   T = Ctx.getUnqualifiedArrayType(T, Q);
4442   Q.removeUnaligned();
4443   return Ctx.getQualifiedType(T, Q);
4444 }
4445 
4446 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4447 /// determine whether they are reference-compatible,
4448 /// reference-related, or incompatible, for use in C++ initialization by
4449 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4450 /// type, and the first type (T1) is the pointee type of the reference
4451 /// type being initialized.
4452 Sema::ReferenceCompareResult
4453 Sema::CompareReferenceRelationship(SourceLocation Loc,
4454                                    QualType OrigT1, QualType OrigT2,
4455                                    ReferenceConversions *ConvOut) {
4456   assert(!OrigT1->isReferenceType() &&
4457     "T1 must be the pointee type of the reference type");
4458   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4459 
4460   QualType T1 = Context.getCanonicalType(OrigT1);
4461   QualType T2 = Context.getCanonicalType(OrigT2);
4462   Qualifiers T1Quals, T2Quals;
4463   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4464   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4465 
4466   ReferenceConversions ConvTmp;
4467   ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4468   Conv = ReferenceConversions();
4469 
4470   // C++2a [dcl.init.ref]p4:
4471   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4472   //   reference-related to "cv2 T2" if T1 is similar to T2, or
4473   //   T1 is a base class of T2.
4474   //   "cv1 T1" is reference-compatible with "cv2 T2" if
4475   //   a prvalue of type "pointer to cv2 T2" can be converted to the type
4476   //   "pointer to cv1 T1" via a standard conversion sequence.
4477 
4478   // Check for standard conversions we can apply to pointers: derived-to-base
4479   // conversions, ObjC pointer conversions, and function pointer conversions.
4480   // (Qualification conversions are checked last.)
4481   QualType ConvertedT2;
4482   if (UnqualT1 == UnqualT2) {
4483     // Nothing to do.
4484   } else if (isCompleteType(Loc, OrigT2) &&
4485              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4486              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4487     Conv |= ReferenceConversions::DerivedToBase;
4488   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4489            UnqualT2->isObjCObjectOrInterfaceType() &&
4490            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4491     Conv |= ReferenceConversions::ObjC;
4492   else if (UnqualT2->isFunctionType() &&
4493            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4494     Conv |= ReferenceConversions::Function;
4495     // No need to check qualifiers; function types don't have them.
4496     return Ref_Compatible;
4497   }
4498   bool ConvertedReferent = Conv != 0;
4499 
4500   // We can have a qualification conversion. Compute whether the types are
4501   // similar at the same time.
4502   bool PreviousToQualsIncludeConst = true;
4503   bool TopLevel = true;
4504   do {
4505     if (T1 == T2)
4506       break;
4507 
4508     // We will need a qualification conversion.
4509     Conv |= ReferenceConversions::Qualification;
4510 
4511     // Track whether we performed a qualification conversion anywhere other
4512     // than the top level. This matters for ranking reference bindings in
4513     // overload resolution.
4514     if (!TopLevel)
4515       Conv |= ReferenceConversions::NestedQualification;
4516 
4517     // MS compiler ignores __unaligned qualifier for references; do the same.
4518     T1 = withoutUnaligned(Context, T1);
4519     T2 = withoutUnaligned(Context, T2);
4520 
4521     // If we find a qualifier mismatch, the types are not reference-compatible,
4522     // but are still be reference-related if they're similar.
4523     bool ObjCLifetimeConversion = false;
4524     if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4525                                        PreviousToQualsIncludeConst,
4526                                        ObjCLifetimeConversion))
4527       return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4528                  ? Ref_Related
4529                  : Ref_Incompatible;
4530 
4531     // FIXME: Should we track this for any level other than the first?
4532     if (ObjCLifetimeConversion)
4533       Conv |= ReferenceConversions::ObjCLifetime;
4534 
4535     TopLevel = false;
4536   } while (Context.UnwrapSimilarTypes(T1, T2));
4537 
4538   // At this point, if the types are reference-related, we must either have the
4539   // same inner type (ignoring qualifiers), or must have already worked out how
4540   // to convert the referent.
4541   return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4542              ? Ref_Compatible
4543              : Ref_Incompatible;
4544 }
4545 
4546 /// Look for a user-defined conversion to a value reference-compatible
4547 ///        with DeclType. Return true if something definite is found.
4548 static bool
4549 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4550                          QualType DeclType, SourceLocation DeclLoc,
4551                          Expr *Init, QualType T2, bool AllowRvalues,
4552                          bool AllowExplicit) {
4553   assert(T2->isRecordType() && "Can only find conversions of record types.");
4554   auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4555 
4556   OverloadCandidateSet CandidateSet(
4557       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4558   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4559   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4560     NamedDecl *D = *I;
4561     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4562     if (isa<UsingShadowDecl>(D))
4563       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4564 
4565     FunctionTemplateDecl *ConvTemplate
4566       = dyn_cast<FunctionTemplateDecl>(D);
4567     CXXConversionDecl *Conv;
4568     if (ConvTemplate)
4569       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4570     else
4571       Conv = cast<CXXConversionDecl>(D);
4572 
4573     if (AllowRvalues) {
4574       // If we are initializing an rvalue reference, don't permit conversion
4575       // functions that return lvalues.
4576       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4577         const ReferenceType *RefType
4578           = Conv->getConversionType()->getAs<LValueReferenceType>();
4579         if (RefType && !RefType->getPointeeType()->isFunctionType())
4580           continue;
4581       }
4582 
4583       if (!ConvTemplate &&
4584           S.CompareReferenceRelationship(
4585               DeclLoc,
4586               Conv->getConversionType()
4587                   .getNonReferenceType()
4588                   .getUnqualifiedType(),
4589               DeclType.getNonReferenceType().getUnqualifiedType()) ==
4590               Sema::Ref_Incompatible)
4591         continue;
4592     } else {
4593       // If the conversion function doesn't return a reference type,
4594       // it can't be considered for this conversion. An rvalue reference
4595       // is only acceptable if its referencee is a function type.
4596 
4597       const ReferenceType *RefType =
4598         Conv->getConversionType()->getAs<ReferenceType>();
4599       if (!RefType ||
4600           (!RefType->isLValueReferenceType() &&
4601            !RefType->getPointeeType()->isFunctionType()))
4602         continue;
4603     }
4604 
4605     if (ConvTemplate)
4606       S.AddTemplateConversionCandidate(
4607           ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4608           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4609     else
4610       S.AddConversionCandidate(
4611           Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4612           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4613   }
4614 
4615   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4616 
4617   OverloadCandidateSet::iterator Best;
4618   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4619   case OR_Success:
4620     // C++ [over.ics.ref]p1:
4621     //
4622     //   [...] If the parameter binds directly to the result of
4623     //   applying a conversion function to the argument
4624     //   expression, the implicit conversion sequence is a
4625     //   user-defined conversion sequence (13.3.3.1.2), with the
4626     //   second standard conversion sequence either an identity
4627     //   conversion or, if the conversion function returns an
4628     //   entity of a type that is a derived class of the parameter
4629     //   type, a derived-to-base Conversion.
4630     if (!Best->FinalConversion.DirectBinding)
4631       return false;
4632 
4633     ICS.setUserDefined();
4634     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4635     ICS.UserDefined.After = Best->FinalConversion;
4636     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4637     ICS.UserDefined.ConversionFunction = Best->Function;
4638     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4639     ICS.UserDefined.EllipsisConversion = false;
4640     assert(ICS.UserDefined.After.ReferenceBinding &&
4641            ICS.UserDefined.After.DirectBinding &&
4642            "Expected a direct reference binding!");
4643     return true;
4644 
4645   case OR_Ambiguous:
4646     ICS.setAmbiguous();
4647     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4648          Cand != CandidateSet.end(); ++Cand)
4649       if (Cand->Best)
4650         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4651     return true;
4652 
4653   case OR_No_Viable_Function:
4654   case OR_Deleted:
4655     // There was no suitable conversion, or we found a deleted
4656     // conversion; continue with other checks.
4657     return false;
4658   }
4659 
4660   llvm_unreachable("Invalid OverloadResult!");
4661 }
4662 
4663 /// Compute an implicit conversion sequence for reference
4664 /// initialization.
4665 static ImplicitConversionSequence
4666 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4667                  SourceLocation DeclLoc,
4668                  bool SuppressUserConversions,
4669                  bool AllowExplicit) {
4670   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4671 
4672   // Most paths end in a failed conversion.
4673   ImplicitConversionSequence ICS;
4674   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4675 
4676   QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4677   QualType T2 = Init->getType();
4678 
4679   // If the initializer is the address of an overloaded function, try
4680   // to resolve the overloaded function. If all goes well, T2 is the
4681   // type of the resulting function.
4682   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4683     DeclAccessPair Found;
4684     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4685                                                                 false, Found))
4686       T2 = Fn->getType();
4687   }
4688 
4689   // Compute some basic properties of the types and the initializer.
4690   bool isRValRef = DeclType->isRValueReferenceType();
4691   Expr::Classification InitCategory = Init->Classify(S.Context);
4692 
4693   Sema::ReferenceConversions RefConv;
4694   Sema::ReferenceCompareResult RefRelationship =
4695       S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4696 
4697   auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4698     ICS.setStandard();
4699     ICS.Standard.First = ICK_Identity;
4700     // FIXME: A reference binding can be a function conversion too. We should
4701     // consider that when ordering reference-to-function bindings.
4702     ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4703                               ? ICK_Derived_To_Base
4704                               : (RefConv & Sema::ReferenceConversions::ObjC)
4705                                     ? ICK_Compatible_Conversion
4706                                     : ICK_Identity;
4707     // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4708     // a reference binding that performs a non-top-level qualification
4709     // conversion as a qualification conversion, not as an identity conversion.
4710     ICS.Standard.Third = (RefConv &
4711                               Sema::ReferenceConversions::NestedQualification)
4712                              ? ICK_Qualification
4713                              : ICK_Identity;
4714     ICS.Standard.setFromType(T2);
4715     ICS.Standard.setToType(0, T2);
4716     ICS.Standard.setToType(1, T1);
4717     ICS.Standard.setToType(2, T1);
4718     ICS.Standard.ReferenceBinding = true;
4719     ICS.Standard.DirectBinding = BindsDirectly;
4720     ICS.Standard.IsLvalueReference = !isRValRef;
4721     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4722     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4723     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4724     ICS.Standard.ObjCLifetimeConversionBinding =
4725         (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4726     ICS.Standard.CopyConstructor = nullptr;
4727     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4728   };
4729 
4730   // C++0x [dcl.init.ref]p5:
4731   //   A reference to type "cv1 T1" is initialized by an expression
4732   //   of type "cv2 T2" as follows:
4733 
4734   //     -- If reference is an lvalue reference and the initializer expression
4735   if (!isRValRef) {
4736     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4737     //        reference-compatible with "cv2 T2," or
4738     //
4739     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4740     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4741       // C++ [over.ics.ref]p1:
4742       //   When a parameter of reference type binds directly (8.5.3)
4743       //   to an argument expression, the implicit conversion sequence
4744       //   is the identity conversion, unless the argument expression
4745       //   has a type that is a derived class of the parameter type,
4746       //   in which case the implicit conversion sequence is a
4747       //   derived-to-base Conversion (13.3.3.1).
4748       SetAsReferenceBinding(/*BindsDirectly=*/true);
4749 
4750       // Nothing more to do: the inaccessibility/ambiguity check for
4751       // derived-to-base conversions is suppressed when we're
4752       // computing the implicit conversion sequence (C++
4753       // [over.best.ics]p2).
4754       return ICS;
4755     }
4756 
4757     //       -- has a class type (i.e., T2 is a class type), where T1 is
4758     //          not reference-related to T2, and can be implicitly
4759     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4760     //          is reference-compatible with "cv3 T3" 92) (this
4761     //          conversion is selected by enumerating the applicable
4762     //          conversion functions (13.3.1.6) and choosing the best
4763     //          one through overload resolution (13.3)),
4764     if (!SuppressUserConversions && T2->isRecordType() &&
4765         S.isCompleteType(DeclLoc, T2) &&
4766         RefRelationship == Sema::Ref_Incompatible) {
4767       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4768                                    Init, T2, /*AllowRvalues=*/false,
4769                                    AllowExplicit))
4770         return ICS;
4771     }
4772   }
4773 
4774   //     -- Otherwise, the reference shall be an lvalue reference to a
4775   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4776   //        shall be an rvalue reference.
4777   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4778     return ICS;
4779 
4780   //       -- If the initializer expression
4781   //
4782   //            -- is an xvalue, class prvalue, array prvalue or function
4783   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4784   if (RefRelationship == Sema::Ref_Compatible &&
4785       (InitCategory.isXValue() ||
4786        (InitCategory.isPRValue() &&
4787           (T2->isRecordType() || T2->isArrayType())) ||
4788        (InitCategory.isLValue() && T2->isFunctionType()))) {
4789     // In C++11, this is always a direct binding. In C++98/03, it's a direct
4790     // binding unless we're binding to a class prvalue.
4791     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4792     // allow the use of rvalue references in C++98/03 for the benefit of
4793     // standard library implementors; therefore, we need the xvalue check here.
4794     SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4795                           !(InitCategory.isPRValue() || T2->isRecordType()));
4796     return ICS;
4797   }
4798 
4799   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4800   //               reference-related to T2, and can be implicitly converted to
4801   //               an xvalue, class prvalue, or function lvalue of type
4802   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4803   //               "cv3 T3",
4804   //
4805   //          then the reference is bound to the value of the initializer
4806   //          expression in the first case and to the result of the conversion
4807   //          in the second case (or, in either case, to an appropriate base
4808   //          class subobject).
4809   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4810       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4811       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4812                                Init, T2, /*AllowRvalues=*/true,
4813                                AllowExplicit)) {
4814     // In the second case, if the reference is an rvalue reference
4815     // and the second standard conversion sequence of the
4816     // user-defined conversion sequence includes an lvalue-to-rvalue
4817     // conversion, the program is ill-formed.
4818     if (ICS.isUserDefined() && isRValRef &&
4819         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4820       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4821 
4822     return ICS;
4823   }
4824 
4825   // A temporary of function type cannot be created; don't even try.
4826   if (T1->isFunctionType())
4827     return ICS;
4828 
4829   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4830   //          initialized from the initializer expression using the
4831   //          rules for a non-reference copy initialization (8.5). The
4832   //          reference is then bound to the temporary. If T1 is
4833   //          reference-related to T2, cv1 must be the same
4834   //          cv-qualification as, or greater cv-qualification than,
4835   //          cv2; otherwise, the program is ill-formed.
4836   if (RefRelationship == Sema::Ref_Related) {
4837     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4838     // we would be reference-compatible or reference-compatible with
4839     // added qualification. But that wasn't the case, so the reference
4840     // initialization fails.
4841     //
4842     // Note that we only want to check address spaces and cvr-qualifiers here.
4843     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4844     Qualifiers T1Quals = T1.getQualifiers();
4845     Qualifiers T2Quals = T2.getQualifiers();
4846     T1Quals.removeObjCGCAttr();
4847     T1Quals.removeObjCLifetime();
4848     T2Quals.removeObjCGCAttr();
4849     T2Quals.removeObjCLifetime();
4850     // MS compiler ignores __unaligned qualifier for references; do the same.
4851     T1Quals.removeUnaligned();
4852     T2Quals.removeUnaligned();
4853     if (!T1Quals.compatiblyIncludes(T2Quals))
4854       return ICS;
4855   }
4856 
4857   // If at least one of the types is a class type, the types are not
4858   // related, and we aren't allowed any user conversions, the
4859   // reference binding fails. This case is important for breaking
4860   // recursion, since TryImplicitConversion below will attempt to
4861   // create a temporary through the use of a copy constructor.
4862   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4863       (T1->isRecordType() || T2->isRecordType()))
4864     return ICS;
4865 
4866   // If T1 is reference-related to T2 and the reference is an rvalue
4867   // reference, the initializer expression shall not be an lvalue.
4868   if (RefRelationship >= Sema::Ref_Related &&
4869       isRValRef && Init->Classify(S.Context).isLValue())
4870     return ICS;
4871 
4872   // C++ [over.ics.ref]p2:
4873   //   When a parameter of reference type is not bound directly to
4874   //   an argument expression, the conversion sequence is the one
4875   //   required to convert the argument expression to the
4876   //   underlying type of the reference according to
4877   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4878   //   to copy-initializing a temporary of the underlying type with
4879   //   the argument expression. Any difference in top-level
4880   //   cv-qualification is subsumed by the initialization itself
4881   //   and does not constitute a conversion.
4882   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4883                               AllowedExplicit::None,
4884                               /*InOverloadResolution=*/false,
4885                               /*CStyle=*/false,
4886                               /*AllowObjCWritebackConversion=*/false,
4887                               /*AllowObjCConversionOnExplicit=*/false);
4888 
4889   // Of course, that's still a reference binding.
4890   if (ICS.isStandard()) {
4891     ICS.Standard.ReferenceBinding = true;
4892     ICS.Standard.IsLvalueReference = !isRValRef;
4893     ICS.Standard.BindsToFunctionLvalue = false;
4894     ICS.Standard.BindsToRvalue = true;
4895     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4896     ICS.Standard.ObjCLifetimeConversionBinding = false;
4897   } else if (ICS.isUserDefined()) {
4898     const ReferenceType *LValRefType =
4899         ICS.UserDefined.ConversionFunction->getReturnType()
4900             ->getAs<LValueReferenceType>();
4901 
4902     // C++ [over.ics.ref]p3:
4903     //   Except for an implicit object parameter, for which see 13.3.1, a
4904     //   standard conversion sequence cannot be formed if it requires [...]
4905     //   binding an rvalue reference to an lvalue other than a function
4906     //   lvalue.
4907     // Note that the function case is not possible here.
4908     if (DeclType->isRValueReferenceType() && LValRefType) {
4909       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4910       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4911       // reference to an rvalue!
4912       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4913       return ICS;
4914     }
4915 
4916     ICS.UserDefined.After.ReferenceBinding = true;
4917     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4918     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4919     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4920     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4921     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4922   }
4923 
4924   return ICS;
4925 }
4926 
4927 static ImplicitConversionSequence
4928 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4929                       bool SuppressUserConversions,
4930                       bool InOverloadResolution,
4931                       bool AllowObjCWritebackConversion,
4932                       bool AllowExplicit = false);
4933 
4934 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4935 /// initializer list From.
4936 static ImplicitConversionSequence
4937 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4938                   bool SuppressUserConversions,
4939                   bool InOverloadResolution,
4940                   bool AllowObjCWritebackConversion) {
4941   // C++11 [over.ics.list]p1:
4942   //   When an argument is an initializer list, it is not an expression and
4943   //   special rules apply for converting it to a parameter type.
4944 
4945   ImplicitConversionSequence Result;
4946   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4947 
4948   // We need a complete type for what follows. Incomplete types can never be
4949   // initialized from init lists.
4950   if (!S.isCompleteType(From->getBeginLoc(), ToType))
4951     return Result;
4952 
4953   // Per DR1467:
4954   //   If the parameter type is a class X and the initializer list has a single
4955   //   element of type cv U, where U is X or a class derived from X, the
4956   //   implicit conversion sequence is the one required to convert the element
4957   //   to the parameter type.
4958   //
4959   //   Otherwise, if the parameter type is a character array [... ]
4960   //   and the initializer list has a single element that is an
4961   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4962   //   implicit conversion sequence is the identity conversion.
4963   if (From->getNumInits() == 1) {
4964     if (ToType->isRecordType()) {
4965       QualType InitType = From->getInit(0)->getType();
4966       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4967           S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
4968         return TryCopyInitialization(S, From->getInit(0), ToType,
4969                                      SuppressUserConversions,
4970                                      InOverloadResolution,
4971                                      AllowObjCWritebackConversion);
4972     }
4973     // FIXME: Check the other conditions here: array of character type,
4974     // initializer is a string literal.
4975     if (ToType->isArrayType()) {
4976       InitializedEntity Entity =
4977         InitializedEntity::InitializeParameter(S.Context, ToType,
4978                                                /*Consumed=*/false);
4979       if (S.CanPerformCopyInitialization(Entity, From)) {
4980         Result.setStandard();
4981         Result.Standard.setAsIdentityConversion();
4982         Result.Standard.setFromType(ToType);
4983         Result.Standard.setAllToTypes(ToType);
4984         return Result;
4985       }
4986     }
4987   }
4988 
4989   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4990   // C++11 [over.ics.list]p2:
4991   //   If the parameter type is std::initializer_list<X> or "array of X" and
4992   //   all the elements can be implicitly converted to X, the implicit
4993   //   conversion sequence is the worst conversion necessary to convert an
4994   //   element of the list to X.
4995   //
4996   // C++14 [over.ics.list]p3:
4997   //   Otherwise, if the parameter type is "array of N X", if the initializer
4998   //   list has exactly N elements or if it has fewer than N elements and X is
4999   //   default-constructible, and if all the elements of the initializer list
5000   //   can be implicitly converted to X, the implicit conversion sequence is
5001   //   the worst conversion necessary to convert an element of the list to X.
5002   //
5003   // FIXME: We're missing a lot of these checks.
5004   bool toStdInitializerList = false;
5005   QualType X;
5006   if (ToType->isArrayType())
5007     X = S.Context.getAsArrayType(ToType)->getElementType();
5008   else
5009     toStdInitializerList = S.isStdInitializerList(ToType, &X);
5010   if (!X.isNull()) {
5011     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
5012       Expr *Init = From->getInit(i);
5013       ImplicitConversionSequence ICS =
5014           TryCopyInitialization(S, Init, X, SuppressUserConversions,
5015                                 InOverloadResolution,
5016                                 AllowObjCWritebackConversion);
5017       // If a single element isn't convertible, fail.
5018       if (ICS.isBad()) {
5019         Result = ICS;
5020         break;
5021       }
5022       // Otherwise, look for the worst conversion.
5023       if (Result.isBad() || CompareImplicitConversionSequences(
5024                                 S, From->getBeginLoc(), ICS, Result) ==
5025                                 ImplicitConversionSequence::Worse)
5026         Result = ICS;
5027     }
5028 
5029     // For an empty list, we won't have computed any conversion sequence.
5030     // Introduce the identity conversion sequence.
5031     if (From->getNumInits() == 0) {
5032       Result.setStandard();
5033       Result.Standard.setAsIdentityConversion();
5034       Result.Standard.setFromType(ToType);
5035       Result.Standard.setAllToTypes(ToType);
5036     }
5037 
5038     Result.setStdInitializerListElement(toStdInitializerList);
5039     return Result;
5040   }
5041 
5042   // C++14 [over.ics.list]p4:
5043   // C++11 [over.ics.list]p3:
5044   //   Otherwise, if the parameter is a non-aggregate class X and overload
5045   //   resolution chooses a single best constructor [...] the implicit
5046   //   conversion sequence is a user-defined conversion sequence. If multiple
5047   //   constructors are viable but none is better than the others, the
5048   //   implicit conversion sequence is a user-defined conversion sequence.
5049   if (ToType->isRecordType() && !ToType->isAggregateType()) {
5050     // This function can deal with initializer lists.
5051     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5052                                     AllowedExplicit::None,
5053                                     InOverloadResolution, /*CStyle=*/false,
5054                                     AllowObjCWritebackConversion,
5055                                     /*AllowObjCConversionOnExplicit=*/false);
5056   }
5057 
5058   // C++14 [over.ics.list]p5:
5059   // C++11 [over.ics.list]p4:
5060   //   Otherwise, if the parameter has an aggregate type which can be
5061   //   initialized from the initializer list [...] the implicit conversion
5062   //   sequence is a user-defined conversion sequence.
5063   if (ToType->isAggregateType()) {
5064     // Type is an aggregate, argument is an init list. At this point it comes
5065     // down to checking whether the initialization works.
5066     // FIXME: Find out whether this parameter is consumed or not.
5067     InitializedEntity Entity =
5068         InitializedEntity::InitializeParameter(S.Context, ToType,
5069                                                /*Consumed=*/false);
5070     if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5071                                                                  From)) {
5072       Result.setUserDefined();
5073       Result.UserDefined.Before.setAsIdentityConversion();
5074       // Initializer lists don't have a type.
5075       Result.UserDefined.Before.setFromType(QualType());
5076       Result.UserDefined.Before.setAllToTypes(QualType());
5077 
5078       Result.UserDefined.After.setAsIdentityConversion();
5079       Result.UserDefined.After.setFromType(ToType);
5080       Result.UserDefined.After.setAllToTypes(ToType);
5081       Result.UserDefined.ConversionFunction = nullptr;
5082     }
5083     return Result;
5084   }
5085 
5086   // C++14 [over.ics.list]p6:
5087   // C++11 [over.ics.list]p5:
5088   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5089   if (ToType->isReferenceType()) {
5090     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5091     // mention initializer lists in any way. So we go by what list-
5092     // initialization would do and try to extrapolate from that.
5093 
5094     QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5095 
5096     // If the initializer list has a single element that is reference-related
5097     // to the parameter type, we initialize the reference from that.
5098     if (From->getNumInits() == 1) {
5099       Expr *Init = From->getInit(0);
5100 
5101       QualType T2 = Init->getType();
5102 
5103       // If the initializer is the address of an overloaded function, try
5104       // to resolve the overloaded function. If all goes well, T2 is the
5105       // type of the resulting function.
5106       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5107         DeclAccessPair Found;
5108         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5109                                    Init, ToType, false, Found))
5110           T2 = Fn->getType();
5111       }
5112 
5113       // Compute some basic properties of the types and the initializer.
5114       Sema::ReferenceCompareResult RefRelationship =
5115           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5116 
5117       if (RefRelationship >= Sema::Ref_Related) {
5118         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5119                                 SuppressUserConversions,
5120                                 /*AllowExplicit=*/false);
5121       }
5122     }
5123 
5124     // Otherwise, we bind the reference to a temporary created from the
5125     // initializer list.
5126     Result = TryListConversion(S, From, T1, SuppressUserConversions,
5127                                InOverloadResolution,
5128                                AllowObjCWritebackConversion);
5129     if (Result.isFailure())
5130       return Result;
5131     assert(!Result.isEllipsis() &&
5132            "Sub-initialization cannot result in ellipsis conversion.");
5133 
5134     // Can we even bind to a temporary?
5135     if (ToType->isRValueReferenceType() ||
5136         (T1.isConstQualified() && !T1.isVolatileQualified())) {
5137       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5138                                             Result.UserDefined.After;
5139       SCS.ReferenceBinding = true;
5140       SCS.IsLvalueReference = ToType->isLValueReferenceType();
5141       SCS.BindsToRvalue = true;
5142       SCS.BindsToFunctionLvalue = false;
5143       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5144       SCS.ObjCLifetimeConversionBinding = false;
5145     } else
5146       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5147                     From, ToType);
5148     return Result;
5149   }
5150 
5151   // C++14 [over.ics.list]p7:
5152   // C++11 [over.ics.list]p6:
5153   //   Otherwise, if the parameter type is not a class:
5154   if (!ToType->isRecordType()) {
5155     //    - if the initializer list has one element that is not itself an
5156     //      initializer list, the implicit conversion sequence is the one
5157     //      required to convert the element to the parameter type.
5158     unsigned NumInits = From->getNumInits();
5159     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5160       Result = TryCopyInitialization(S, From->getInit(0), ToType,
5161                                      SuppressUserConversions,
5162                                      InOverloadResolution,
5163                                      AllowObjCWritebackConversion);
5164     //    - if the initializer list has no elements, the implicit conversion
5165     //      sequence is the identity conversion.
5166     else if (NumInits == 0) {
5167       Result.setStandard();
5168       Result.Standard.setAsIdentityConversion();
5169       Result.Standard.setFromType(ToType);
5170       Result.Standard.setAllToTypes(ToType);
5171     }
5172     return Result;
5173   }
5174 
5175   // C++14 [over.ics.list]p8:
5176   // C++11 [over.ics.list]p7:
5177   //   In all cases other than those enumerated above, no conversion is possible
5178   return Result;
5179 }
5180 
5181 /// TryCopyInitialization - Try to copy-initialize a value of type
5182 /// ToType from the expression From. Return the implicit conversion
5183 /// sequence required to pass this argument, which may be a bad
5184 /// conversion sequence (meaning that the argument cannot be passed to
5185 /// a parameter of this type). If @p SuppressUserConversions, then we
5186 /// do not permit any user-defined conversion sequences.
5187 static ImplicitConversionSequence
5188 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5189                       bool SuppressUserConversions,
5190                       bool InOverloadResolution,
5191                       bool AllowObjCWritebackConversion,
5192                       bool AllowExplicit) {
5193   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5194     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5195                              InOverloadResolution,AllowObjCWritebackConversion);
5196 
5197   if (ToType->isReferenceType())
5198     return TryReferenceInit(S, From, ToType,
5199                             /*FIXME:*/ From->getBeginLoc(),
5200                             SuppressUserConversions, AllowExplicit);
5201 
5202   return TryImplicitConversion(S, From, ToType,
5203                                SuppressUserConversions,
5204                                AllowedExplicit::None,
5205                                InOverloadResolution,
5206                                /*CStyle=*/false,
5207                                AllowObjCWritebackConversion,
5208                                /*AllowObjCConversionOnExplicit=*/false);
5209 }
5210 
5211 static bool TryCopyInitialization(const CanQualType FromQTy,
5212                                   const CanQualType ToQTy,
5213                                   Sema &S,
5214                                   SourceLocation Loc,
5215                                   ExprValueKind FromVK) {
5216   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5217   ImplicitConversionSequence ICS =
5218     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5219 
5220   return !ICS.isBad();
5221 }
5222 
5223 /// TryObjectArgumentInitialization - Try to initialize the object
5224 /// parameter of the given member function (@c Method) from the
5225 /// expression @p From.
5226 static ImplicitConversionSequence
5227 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5228                                 Expr::Classification FromClassification,
5229                                 CXXMethodDecl *Method,
5230                                 CXXRecordDecl *ActingContext) {
5231   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5232   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5233   //                 const volatile object.
5234   Qualifiers Quals = Method->getMethodQualifiers();
5235   if (isa<CXXDestructorDecl>(Method)) {
5236     Quals.addConst();
5237     Quals.addVolatile();
5238   }
5239 
5240   QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5241 
5242   // Set up the conversion sequence as a "bad" conversion, to allow us
5243   // to exit early.
5244   ImplicitConversionSequence ICS;
5245 
5246   // We need to have an object of class type.
5247   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5248     FromType = PT->getPointeeType();
5249 
5250     // When we had a pointer, it's implicitly dereferenced, so we
5251     // better have an lvalue.
5252     assert(FromClassification.isLValue());
5253   }
5254 
5255   assert(FromType->isRecordType());
5256 
5257   // C++0x [over.match.funcs]p4:
5258   //   For non-static member functions, the type of the implicit object
5259   //   parameter is
5260   //
5261   //     - "lvalue reference to cv X" for functions declared without a
5262   //        ref-qualifier or with the & ref-qualifier
5263   //     - "rvalue reference to cv X" for functions declared with the &&
5264   //        ref-qualifier
5265   //
5266   // where X is the class of which the function is a member and cv is the
5267   // cv-qualification on the member function declaration.
5268   //
5269   // However, when finding an implicit conversion sequence for the argument, we
5270   // are not allowed to perform user-defined conversions
5271   // (C++ [over.match.funcs]p5). We perform a simplified version of
5272   // reference binding here, that allows class rvalues to bind to
5273   // non-constant references.
5274 
5275   // First check the qualifiers.
5276   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5277   if (ImplicitParamType.getCVRQualifiers()
5278                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5279       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5280     ICS.setBad(BadConversionSequence::bad_qualifiers,
5281                FromType, ImplicitParamType);
5282     return ICS;
5283   }
5284 
5285   if (FromTypeCanon.hasAddressSpace()) {
5286     Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5287     Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5288     if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5289       ICS.setBad(BadConversionSequence::bad_qualifiers,
5290                  FromType, ImplicitParamType);
5291       return ICS;
5292     }
5293   }
5294 
5295   // Check that we have either the same type or a derived type. It
5296   // affects the conversion rank.
5297   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5298   ImplicitConversionKind SecondKind;
5299   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5300     SecondKind = ICK_Identity;
5301   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5302     SecondKind = ICK_Derived_To_Base;
5303   else {
5304     ICS.setBad(BadConversionSequence::unrelated_class,
5305                FromType, ImplicitParamType);
5306     return ICS;
5307   }
5308 
5309   // Check the ref-qualifier.
5310   switch (Method->getRefQualifier()) {
5311   case RQ_None:
5312     // Do nothing; we don't care about lvalueness or rvalueness.
5313     break;
5314 
5315   case RQ_LValue:
5316     if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5317       // non-const lvalue reference cannot bind to an rvalue
5318       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5319                  ImplicitParamType);
5320       return ICS;
5321     }
5322     break;
5323 
5324   case RQ_RValue:
5325     if (!FromClassification.isRValue()) {
5326       // rvalue reference cannot bind to an lvalue
5327       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5328                  ImplicitParamType);
5329       return ICS;
5330     }
5331     break;
5332   }
5333 
5334   // Success. Mark this as a reference binding.
5335   ICS.setStandard();
5336   ICS.Standard.setAsIdentityConversion();
5337   ICS.Standard.Second = SecondKind;
5338   ICS.Standard.setFromType(FromType);
5339   ICS.Standard.setAllToTypes(ImplicitParamType);
5340   ICS.Standard.ReferenceBinding = true;
5341   ICS.Standard.DirectBinding = true;
5342   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5343   ICS.Standard.BindsToFunctionLvalue = false;
5344   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5345   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5346     = (Method->getRefQualifier() == RQ_None);
5347   return ICS;
5348 }
5349 
5350 /// PerformObjectArgumentInitialization - Perform initialization of
5351 /// the implicit object parameter for the given Method with the given
5352 /// expression.
5353 ExprResult
5354 Sema::PerformObjectArgumentInitialization(Expr *From,
5355                                           NestedNameSpecifier *Qualifier,
5356                                           NamedDecl *FoundDecl,
5357                                           CXXMethodDecl *Method) {
5358   QualType FromRecordType, DestType;
5359   QualType ImplicitParamRecordType  =
5360     Method->getThisType()->castAs<PointerType>()->getPointeeType();
5361 
5362   Expr::Classification FromClassification;
5363   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5364     FromRecordType = PT->getPointeeType();
5365     DestType = Method->getThisType();
5366     FromClassification = Expr::Classification::makeSimpleLValue();
5367   } else {
5368     FromRecordType = From->getType();
5369     DestType = ImplicitParamRecordType;
5370     FromClassification = From->Classify(Context);
5371 
5372     // When performing member access on an rvalue, materialize a temporary.
5373     if (From->isRValue()) {
5374       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5375                                             Method->getRefQualifier() !=
5376                                                 RefQualifierKind::RQ_RValue);
5377     }
5378   }
5379 
5380   // Note that we always use the true parent context when performing
5381   // the actual argument initialization.
5382   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5383       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5384       Method->getParent());
5385   if (ICS.isBad()) {
5386     switch (ICS.Bad.Kind) {
5387     case BadConversionSequence::bad_qualifiers: {
5388       Qualifiers FromQs = FromRecordType.getQualifiers();
5389       Qualifiers ToQs = DestType.getQualifiers();
5390       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5391       if (CVR) {
5392         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5393             << Method->getDeclName() << FromRecordType << (CVR - 1)
5394             << From->getSourceRange();
5395         Diag(Method->getLocation(), diag::note_previous_decl)
5396           << Method->getDeclName();
5397         return ExprError();
5398       }
5399       break;
5400     }
5401 
5402     case BadConversionSequence::lvalue_ref_to_rvalue:
5403     case BadConversionSequence::rvalue_ref_to_lvalue: {
5404       bool IsRValueQualified =
5405         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5406       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5407           << Method->getDeclName() << FromClassification.isRValue()
5408           << IsRValueQualified;
5409       Diag(Method->getLocation(), diag::note_previous_decl)
5410         << Method->getDeclName();
5411       return ExprError();
5412     }
5413 
5414     case BadConversionSequence::no_conversion:
5415     case BadConversionSequence::unrelated_class:
5416       break;
5417     }
5418 
5419     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5420            << ImplicitParamRecordType << FromRecordType
5421            << From->getSourceRange();
5422   }
5423 
5424   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5425     ExprResult FromRes =
5426       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5427     if (FromRes.isInvalid())
5428       return ExprError();
5429     From = FromRes.get();
5430   }
5431 
5432   if (!Context.hasSameType(From->getType(), DestType)) {
5433     CastKind CK;
5434     QualType PteeTy = DestType->getPointeeType();
5435     LangAS DestAS =
5436         PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5437     if (FromRecordType.getAddressSpace() != DestAS)
5438       CK = CK_AddressSpaceConversion;
5439     else
5440       CK = CK_NoOp;
5441     From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5442   }
5443   return From;
5444 }
5445 
5446 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5447 /// expression From to bool (C++0x [conv]p3).
5448 static ImplicitConversionSequence
5449 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5450   // C++ [dcl.init]/17.8:
5451   //   - Otherwise, if the initialization is direct-initialization, the source
5452   //     type is std::nullptr_t, and the destination type is bool, the initial
5453   //     value of the object being initialized is false.
5454   if (From->getType()->isNullPtrType())
5455     return ImplicitConversionSequence::getNullptrToBool(From->getType(),
5456                                                         S.Context.BoolTy,
5457                                                         From->isGLValue());
5458 
5459   // All other direct-initialization of bool is equivalent to an implicit
5460   // conversion to bool in which explicit conversions are permitted.
5461   return TryImplicitConversion(S, From, S.Context.BoolTy,
5462                                /*SuppressUserConversions=*/false,
5463                                AllowedExplicit::Conversions,
5464                                /*InOverloadResolution=*/false,
5465                                /*CStyle=*/false,
5466                                /*AllowObjCWritebackConversion=*/false,
5467                                /*AllowObjCConversionOnExplicit=*/false);
5468 }
5469 
5470 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5471 /// of the expression From to bool (C++0x [conv]p3).
5472 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5473   if (checkPlaceholderForOverload(*this, From))
5474     return ExprError();
5475 
5476   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5477   if (!ICS.isBad())
5478     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5479 
5480   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5481     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5482            << From->getType() << From->getSourceRange();
5483   return ExprError();
5484 }
5485 
5486 /// Check that the specified conversion is permitted in a converted constant
5487 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5488 /// is acceptable.
5489 static bool CheckConvertedConstantConversions(Sema &S,
5490                                               StandardConversionSequence &SCS) {
5491   // Since we know that the target type is an integral or unscoped enumeration
5492   // type, most conversion kinds are impossible. All possible First and Third
5493   // conversions are fine.
5494   switch (SCS.Second) {
5495   case ICK_Identity:
5496   case ICK_Function_Conversion:
5497   case ICK_Integral_Promotion:
5498   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5499   case ICK_Zero_Queue_Conversion:
5500     return true;
5501 
5502   case ICK_Boolean_Conversion:
5503     // Conversion from an integral or unscoped enumeration type to bool is
5504     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5505     // conversion, so we allow it in a converted constant expression.
5506     //
5507     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5508     // a lot of popular code. We should at least add a warning for this
5509     // (non-conforming) extension.
5510     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5511            SCS.getToType(2)->isBooleanType();
5512 
5513   case ICK_Pointer_Conversion:
5514   case ICK_Pointer_Member:
5515     // C++1z: null pointer conversions and null member pointer conversions are
5516     // only permitted if the source type is std::nullptr_t.
5517     return SCS.getFromType()->isNullPtrType();
5518 
5519   case ICK_Floating_Promotion:
5520   case ICK_Complex_Promotion:
5521   case ICK_Floating_Conversion:
5522   case ICK_Complex_Conversion:
5523   case ICK_Floating_Integral:
5524   case ICK_Compatible_Conversion:
5525   case ICK_Derived_To_Base:
5526   case ICK_Vector_Conversion:
5527   case ICK_Vector_Splat:
5528   case ICK_Complex_Real:
5529   case ICK_Block_Pointer_Conversion:
5530   case ICK_TransparentUnionConversion:
5531   case ICK_Writeback_Conversion:
5532   case ICK_Zero_Event_Conversion:
5533   case ICK_C_Only_Conversion:
5534   case ICK_Incompatible_Pointer_Conversion:
5535     return false;
5536 
5537   case ICK_Lvalue_To_Rvalue:
5538   case ICK_Array_To_Pointer:
5539   case ICK_Function_To_Pointer:
5540     llvm_unreachable("found a first conversion kind in Second");
5541 
5542   case ICK_Qualification:
5543     llvm_unreachable("found a third conversion kind in Second");
5544 
5545   case ICK_Num_Conversion_Kinds:
5546     break;
5547   }
5548 
5549   llvm_unreachable("unknown conversion kind");
5550 }
5551 
5552 /// CheckConvertedConstantExpression - Check that the expression From is a
5553 /// converted constant expression of type T, perform the conversion and produce
5554 /// the converted expression, per C++11 [expr.const]p3.
5555 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5556                                                    QualType T, APValue &Value,
5557                                                    Sema::CCEKind CCE,
5558                                                    bool RequireInt) {
5559   assert(S.getLangOpts().CPlusPlus11 &&
5560          "converted constant expression outside C++11");
5561 
5562   if (checkPlaceholderForOverload(S, From))
5563     return ExprError();
5564 
5565   // C++1z [expr.const]p3:
5566   //  A converted constant expression of type T is an expression,
5567   //  implicitly converted to type T, where the converted
5568   //  expression is a constant expression and the implicit conversion
5569   //  sequence contains only [... list of conversions ...].
5570   // C++1z [stmt.if]p2:
5571   //  If the if statement is of the form if constexpr, the value of the
5572   //  condition shall be a contextually converted constant expression of type
5573   //  bool.
5574   ImplicitConversionSequence ICS =
5575       CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool
5576           ? TryContextuallyConvertToBool(S, From)
5577           : TryCopyInitialization(S, From, T,
5578                                   /*SuppressUserConversions=*/false,
5579                                   /*InOverloadResolution=*/false,
5580                                   /*AllowObjCWritebackConversion=*/false,
5581                                   /*AllowExplicit=*/false);
5582   StandardConversionSequence *SCS = nullptr;
5583   switch (ICS.getKind()) {
5584   case ImplicitConversionSequence::StandardConversion:
5585     SCS = &ICS.Standard;
5586     break;
5587   case ImplicitConversionSequence::UserDefinedConversion:
5588     // We are converting to a non-class type, so the Before sequence
5589     // must be trivial.
5590     SCS = &ICS.UserDefined.After;
5591     break;
5592   case ImplicitConversionSequence::AmbiguousConversion:
5593   case ImplicitConversionSequence::BadConversion:
5594     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5595       return S.Diag(From->getBeginLoc(),
5596                     diag::err_typecheck_converted_constant_expression)
5597              << From->getType() << From->getSourceRange() << T;
5598     return ExprError();
5599 
5600   case ImplicitConversionSequence::EllipsisConversion:
5601     llvm_unreachable("ellipsis conversion in converted constant expression");
5602   }
5603 
5604   // Check that we would only use permitted conversions.
5605   if (!CheckConvertedConstantConversions(S, *SCS)) {
5606     return S.Diag(From->getBeginLoc(),
5607                   diag::err_typecheck_converted_constant_expression_disallowed)
5608            << From->getType() << From->getSourceRange() << T;
5609   }
5610   // [...] and where the reference binding (if any) binds directly.
5611   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5612     return S.Diag(From->getBeginLoc(),
5613                   diag::err_typecheck_converted_constant_expression_indirect)
5614            << From->getType() << From->getSourceRange() << T;
5615   }
5616 
5617   ExprResult Result =
5618       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5619   if (Result.isInvalid())
5620     return Result;
5621 
5622   // C++2a [intro.execution]p5:
5623   //   A full-expression is [...] a constant-expression [...]
5624   Result =
5625       S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5626                             /*DiscardedValue=*/false, /*IsConstexpr=*/true);
5627   if (Result.isInvalid())
5628     return Result;
5629 
5630   // Check for a narrowing implicit conversion.
5631   APValue PreNarrowingValue;
5632   QualType PreNarrowingType;
5633   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5634                                 PreNarrowingType)) {
5635   case NK_Dependent_Narrowing:
5636     // Implicit conversion to a narrower type, but the expression is
5637     // value-dependent so we can't tell whether it's actually narrowing.
5638   case NK_Variable_Narrowing:
5639     // Implicit conversion to a narrower type, and the value is not a constant
5640     // expression. We'll diagnose this in a moment.
5641   case NK_Not_Narrowing:
5642     break;
5643 
5644   case NK_Constant_Narrowing:
5645     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5646         << CCE << /*Constant*/ 1
5647         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5648     break;
5649 
5650   case NK_Type_Narrowing:
5651     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5652         << CCE << /*Constant*/ 0 << From->getType() << T;
5653     break;
5654   }
5655 
5656   if (Result.get()->isValueDependent()) {
5657     Value = APValue();
5658     return Result;
5659   }
5660 
5661   // Check the expression is a constant expression.
5662   SmallVector<PartialDiagnosticAt, 8> Notes;
5663   Expr::EvalResult Eval;
5664   Eval.Diag = &Notes;
5665   Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5666                                    ? Expr::EvaluateForMangling
5667                                    : Expr::EvaluateForCodeGen;
5668 
5669   if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5670       (RequireInt && !Eval.Val.isInt())) {
5671     // The expression can't be folded, so we can't keep it at this position in
5672     // the AST.
5673     Result = ExprError();
5674   } else {
5675     Value = Eval.Val;
5676 
5677     if (Notes.empty()) {
5678       // It's a constant expression.
5679       return ConstantExpr::Create(S.Context, Result.get(), Value);
5680     }
5681   }
5682 
5683   // It's not a constant expression. Produce an appropriate diagnostic.
5684   if (Notes.size() == 1 &&
5685       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5686     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5687   else {
5688     S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5689         << CCE << From->getSourceRange();
5690     for (unsigned I = 0; I < Notes.size(); ++I)
5691       S.Diag(Notes[I].first, Notes[I].second);
5692   }
5693   return ExprError();
5694 }
5695 
5696 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5697                                                   APValue &Value, CCEKind CCE) {
5698   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5699 }
5700 
5701 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5702                                                   llvm::APSInt &Value,
5703                                                   CCEKind CCE) {
5704   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5705 
5706   APValue V;
5707   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5708   if (!R.isInvalid() && !R.get()->isValueDependent())
5709     Value = V.getInt();
5710   return R;
5711 }
5712 
5713 
5714 /// dropPointerConversions - If the given standard conversion sequence
5715 /// involves any pointer conversions, remove them.  This may change
5716 /// the result type of the conversion sequence.
5717 static void dropPointerConversion(StandardConversionSequence &SCS) {
5718   if (SCS.Second == ICK_Pointer_Conversion) {
5719     SCS.Second = ICK_Identity;
5720     SCS.Third = ICK_Identity;
5721     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5722   }
5723 }
5724 
5725 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5726 /// convert the expression From to an Objective-C pointer type.
5727 static ImplicitConversionSequence
5728 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5729   // Do an implicit conversion to 'id'.
5730   QualType Ty = S.Context.getObjCIdType();
5731   ImplicitConversionSequence ICS
5732     = TryImplicitConversion(S, From, Ty,
5733                             // FIXME: Are these flags correct?
5734                             /*SuppressUserConversions=*/false,
5735                             AllowedExplicit::Conversions,
5736                             /*InOverloadResolution=*/false,
5737                             /*CStyle=*/false,
5738                             /*AllowObjCWritebackConversion=*/false,
5739                             /*AllowObjCConversionOnExplicit=*/true);
5740 
5741   // Strip off any final conversions to 'id'.
5742   switch (ICS.getKind()) {
5743   case ImplicitConversionSequence::BadConversion:
5744   case ImplicitConversionSequence::AmbiguousConversion:
5745   case ImplicitConversionSequence::EllipsisConversion:
5746     break;
5747 
5748   case ImplicitConversionSequence::UserDefinedConversion:
5749     dropPointerConversion(ICS.UserDefined.After);
5750     break;
5751 
5752   case ImplicitConversionSequence::StandardConversion:
5753     dropPointerConversion(ICS.Standard);
5754     break;
5755   }
5756 
5757   return ICS;
5758 }
5759 
5760 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5761 /// conversion of the expression From to an Objective-C pointer type.
5762 /// Returns a valid but null ExprResult if no conversion sequence exists.
5763 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5764   if (checkPlaceholderForOverload(*this, From))
5765     return ExprError();
5766 
5767   QualType Ty = Context.getObjCIdType();
5768   ImplicitConversionSequence ICS =
5769     TryContextuallyConvertToObjCPointer(*this, From);
5770   if (!ICS.isBad())
5771     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5772   return ExprResult();
5773 }
5774 
5775 /// Determine whether the provided type is an integral type, or an enumeration
5776 /// type of a permitted flavor.
5777 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5778   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5779                                  : T->isIntegralOrUnscopedEnumerationType();
5780 }
5781 
5782 static ExprResult
5783 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5784                             Sema::ContextualImplicitConverter &Converter,
5785                             QualType T, UnresolvedSetImpl &ViableConversions) {
5786 
5787   if (Converter.Suppress)
5788     return ExprError();
5789 
5790   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5791   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5792     CXXConversionDecl *Conv =
5793         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5794     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5795     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5796   }
5797   return From;
5798 }
5799 
5800 static bool
5801 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5802                            Sema::ContextualImplicitConverter &Converter,
5803                            QualType T, bool HadMultipleCandidates,
5804                            UnresolvedSetImpl &ExplicitConversions) {
5805   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5806     DeclAccessPair Found = ExplicitConversions[0];
5807     CXXConversionDecl *Conversion =
5808         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5809 
5810     // The user probably meant to invoke the given explicit
5811     // conversion; use it.
5812     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5813     std::string TypeStr;
5814     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5815 
5816     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5817         << FixItHint::CreateInsertion(From->getBeginLoc(),
5818                                       "static_cast<" + TypeStr + ">(")
5819         << FixItHint::CreateInsertion(
5820                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5821     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5822 
5823     // If we aren't in a SFINAE context, build a call to the
5824     // explicit conversion function.
5825     if (SemaRef.isSFINAEContext())
5826       return true;
5827 
5828     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5829     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5830                                                        HadMultipleCandidates);
5831     if (Result.isInvalid())
5832       return true;
5833     // Record usage of conversion in an implicit cast.
5834     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5835                                     CK_UserDefinedConversion, Result.get(),
5836                                     nullptr, Result.get()->getValueKind());
5837   }
5838   return false;
5839 }
5840 
5841 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5842                              Sema::ContextualImplicitConverter &Converter,
5843                              QualType T, bool HadMultipleCandidates,
5844                              DeclAccessPair &Found) {
5845   CXXConversionDecl *Conversion =
5846       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5847   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5848 
5849   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5850   if (!Converter.SuppressConversion) {
5851     if (SemaRef.isSFINAEContext())
5852       return true;
5853 
5854     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5855         << From->getSourceRange();
5856   }
5857 
5858   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5859                                                      HadMultipleCandidates);
5860   if (Result.isInvalid())
5861     return true;
5862   // Record usage of conversion in an implicit cast.
5863   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5864                                   CK_UserDefinedConversion, Result.get(),
5865                                   nullptr, Result.get()->getValueKind());
5866   return false;
5867 }
5868 
5869 static ExprResult finishContextualImplicitConversion(
5870     Sema &SemaRef, SourceLocation Loc, Expr *From,
5871     Sema::ContextualImplicitConverter &Converter) {
5872   if (!Converter.match(From->getType()) && !Converter.Suppress)
5873     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5874         << From->getSourceRange();
5875 
5876   return SemaRef.DefaultLvalueConversion(From);
5877 }
5878 
5879 static void
5880 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5881                                   UnresolvedSetImpl &ViableConversions,
5882                                   OverloadCandidateSet &CandidateSet) {
5883   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5884     DeclAccessPair FoundDecl = ViableConversions[I];
5885     NamedDecl *D = FoundDecl.getDecl();
5886     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5887     if (isa<UsingShadowDecl>(D))
5888       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5889 
5890     CXXConversionDecl *Conv;
5891     FunctionTemplateDecl *ConvTemplate;
5892     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5893       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5894     else
5895       Conv = cast<CXXConversionDecl>(D);
5896 
5897     if (ConvTemplate)
5898       SemaRef.AddTemplateConversionCandidate(
5899           ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5900           /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
5901     else
5902       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5903                                      ToType, CandidateSet,
5904                                      /*AllowObjCConversionOnExplicit=*/false,
5905                                      /*AllowExplicit*/ true);
5906   }
5907 }
5908 
5909 /// Attempt to convert the given expression to a type which is accepted
5910 /// by the given converter.
5911 ///
5912 /// This routine will attempt to convert an expression of class type to a
5913 /// type accepted by the specified converter. In C++11 and before, the class
5914 /// must have a single non-explicit conversion function converting to a matching
5915 /// type. In C++1y, there can be multiple such conversion functions, but only
5916 /// one target type.
5917 ///
5918 /// \param Loc The source location of the construct that requires the
5919 /// conversion.
5920 ///
5921 /// \param From The expression we're converting from.
5922 ///
5923 /// \param Converter Used to control and diagnose the conversion process.
5924 ///
5925 /// \returns The expression, converted to an integral or enumeration type if
5926 /// successful.
5927 ExprResult Sema::PerformContextualImplicitConversion(
5928     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5929   // We can't perform any more checking for type-dependent expressions.
5930   if (From->isTypeDependent())
5931     return From;
5932 
5933   // Process placeholders immediately.
5934   if (From->hasPlaceholderType()) {
5935     ExprResult result = CheckPlaceholderExpr(From);
5936     if (result.isInvalid())
5937       return result;
5938     From = result.get();
5939   }
5940 
5941   // If the expression already has a matching type, we're golden.
5942   QualType T = From->getType();
5943   if (Converter.match(T))
5944     return DefaultLvalueConversion(From);
5945 
5946   // FIXME: Check for missing '()' if T is a function type?
5947 
5948   // We can only perform contextual implicit conversions on objects of class
5949   // type.
5950   const RecordType *RecordTy = T->getAs<RecordType>();
5951   if (!RecordTy || !getLangOpts().CPlusPlus) {
5952     if (!Converter.Suppress)
5953       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5954     return From;
5955   }
5956 
5957   // We must have a complete class type.
5958   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5959     ContextualImplicitConverter &Converter;
5960     Expr *From;
5961 
5962     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5963         : Converter(Converter), From(From) {}
5964 
5965     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5966       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5967     }
5968   } IncompleteDiagnoser(Converter, From);
5969 
5970   if (Converter.Suppress ? !isCompleteType(Loc, T)
5971                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5972     return From;
5973 
5974   // Look for a conversion to an integral or enumeration type.
5975   UnresolvedSet<4>
5976       ViableConversions; // These are *potentially* viable in C++1y.
5977   UnresolvedSet<4> ExplicitConversions;
5978   const auto &Conversions =
5979       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5980 
5981   bool HadMultipleCandidates =
5982       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5983 
5984   // To check that there is only one target type, in C++1y:
5985   QualType ToType;
5986   bool HasUniqueTargetType = true;
5987 
5988   // Collect explicit or viable (potentially in C++1y) conversions.
5989   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5990     NamedDecl *D = (*I)->getUnderlyingDecl();
5991     CXXConversionDecl *Conversion;
5992     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5993     if (ConvTemplate) {
5994       if (getLangOpts().CPlusPlus14)
5995         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5996       else
5997         continue; // C++11 does not consider conversion operator templates(?).
5998     } else
5999       Conversion = cast<CXXConversionDecl>(D);
6000 
6001     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6002            "Conversion operator templates are considered potentially "
6003            "viable in C++1y");
6004 
6005     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6006     if (Converter.match(CurToType) || ConvTemplate) {
6007 
6008       if (Conversion->isExplicit()) {
6009         // FIXME: For C++1y, do we need this restriction?
6010         // cf. diagnoseNoViableConversion()
6011         if (!ConvTemplate)
6012           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6013       } else {
6014         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6015           if (ToType.isNull())
6016             ToType = CurToType.getUnqualifiedType();
6017           else if (HasUniqueTargetType &&
6018                    (CurToType.getUnqualifiedType() != ToType))
6019             HasUniqueTargetType = false;
6020         }
6021         ViableConversions.addDecl(I.getDecl(), I.getAccess());
6022       }
6023     }
6024   }
6025 
6026   if (getLangOpts().CPlusPlus14) {
6027     // C++1y [conv]p6:
6028     // ... An expression e of class type E appearing in such a context
6029     // is said to be contextually implicitly converted to a specified
6030     // type T and is well-formed if and only if e can be implicitly
6031     // converted to a type T that is determined as follows: E is searched
6032     // for conversion functions whose return type is cv T or reference to
6033     // cv T such that T is allowed by the context. There shall be
6034     // exactly one such T.
6035 
6036     // If no unique T is found:
6037     if (ToType.isNull()) {
6038       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6039                                      HadMultipleCandidates,
6040                                      ExplicitConversions))
6041         return ExprError();
6042       return finishContextualImplicitConversion(*this, Loc, From, Converter);
6043     }
6044 
6045     // If more than one unique Ts are found:
6046     if (!HasUniqueTargetType)
6047       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6048                                          ViableConversions);
6049 
6050     // If one unique T is found:
6051     // First, build a candidate set from the previously recorded
6052     // potentially viable conversions.
6053     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6054     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6055                                       CandidateSet);
6056 
6057     // Then, perform overload resolution over the candidate set.
6058     OverloadCandidateSet::iterator Best;
6059     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6060     case OR_Success: {
6061       // Apply this conversion.
6062       DeclAccessPair Found =
6063           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6064       if (recordConversion(*this, Loc, From, Converter, T,
6065                            HadMultipleCandidates, Found))
6066         return ExprError();
6067       break;
6068     }
6069     case OR_Ambiguous:
6070       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6071                                          ViableConversions);
6072     case OR_No_Viable_Function:
6073       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6074                                      HadMultipleCandidates,
6075                                      ExplicitConversions))
6076         return ExprError();
6077       LLVM_FALLTHROUGH;
6078     case OR_Deleted:
6079       // We'll complain below about a non-integral condition type.
6080       break;
6081     }
6082   } else {
6083     switch (ViableConversions.size()) {
6084     case 0: {
6085       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6086                                      HadMultipleCandidates,
6087                                      ExplicitConversions))
6088         return ExprError();
6089 
6090       // We'll complain below about a non-integral condition type.
6091       break;
6092     }
6093     case 1: {
6094       // Apply this conversion.
6095       DeclAccessPair Found = ViableConversions[0];
6096       if (recordConversion(*this, Loc, From, Converter, T,
6097                            HadMultipleCandidates, Found))
6098         return ExprError();
6099       break;
6100     }
6101     default:
6102       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6103                                          ViableConversions);
6104     }
6105   }
6106 
6107   return finishContextualImplicitConversion(*this, Loc, From, Converter);
6108 }
6109 
6110 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6111 /// an acceptable non-member overloaded operator for a call whose
6112 /// arguments have types T1 (and, if non-empty, T2). This routine
6113 /// implements the check in C++ [over.match.oper]p3b2 concerning
6114 /// enumeration types.
6115 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6116                                                    FunctionDecl *Fn,
6117                                                    ArrayRef<Expr *> Args) {
6118   QualType T1 = Args[0]->getType();
6119   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6120 
6121   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6122     return true;
6123 
6124   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6125     return true;
6126 
6127   const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6128   if (Proto->getNumParams() < 1)
6129     return false;
6130 
6131   if (T1->isEnumeralType()) {
6132     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6133     if (Context.hasSameUnqualifiedType(T1, ArgType))
6134       return true;
6135   }
6136 
6137   if (Proto->getNumParams() < 2)
6138     return false;
6139 
6140   if (!T2.isNull() && T2->isEnumeralType()) {
6141     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6142     if (Context.hasSameUnqualifiedType(T2, ArgType))
6143       return true;
6144   }
6145 
6146   return false;
6147 }
6148 
6149 /// AddOverloadCandidate - Adds the given function to the set of
6150 /// candidate functions, using the given function call arguments.  If
6151 /// @p SuppressUserConversions, then don't allow user-defined
6152 /// conversions via constructors or conversion operators.
6153 ///
6154 /// \param PartialOverloading true if we are performing "partial" overloading
6155 /// based on an incomplete set of function arguments. This feature is used by
6156 /// code completion.
6157 void Sema::AddOverloadCandidate(
6158     FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6159     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6160     bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6161     ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6162     OverloadCandidateParamOrder PO) {
6163   const FunctionProtoType *Proto
6164     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6165   assert(Proto && "Functions without a prototype cannot be overloaded");
6166   assert(!Function->getDescribedFunctionTemplate() &&
6167          "Use AddTemplateOverloadCandidate for function templates");
6168 
6169   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6170     if (!isa<CXXConstructorDecl>(Method)) {
6171       // If we get here, it's because we're calling a member function
6172       // that is named without a member access expression (e.g.,
6173       // "this->f") that was either written explicitly or created
6174       // implicitly. This can happen with a qualified call to a member
6175       // function, e.g., X::f(). We use an empty type for the implied
6176       // object argument (C++ [over.call.func]p3), and the acting context
6177       // is irrelevant.
6178       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6179                          Expr::Classification::makeSimpleLValue(), Args,
6180                          CandidateSet, SuppressUserConversions,
6181                          PartialOverloading, EarlyConversions, PO);
6182       return;
6183     }
6184     // We treat a constructor like a non-member function, since its object
6185     // argument doesn't participate in overload resolution.
6186   }
6187 
6188   if (!CandidateSet.isNewCandidate(Function, PO))
6189     return;
6190 
6191   // C++11 [class.copy]p11: [DR1402]
6192   //   A defaulted move constructor that is defined as deleted is ignored by
6193   //   overload resolution.
6194   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6195   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6196       Constructor->isMoveConstructor())
6197     return;
6198 
6199   // Overload resolution is always an unevaluated context.
6200   EnterExpressionEvaluationContext Unevaluated(
6201       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6202 
6203   // C++ [over.match.oper]p3:
6204   //   if no operand has a class type, only those non-member functions in the
6205   //   lookup set that have a first parameter of type T1 or "reference to
6206   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6207   //   is a right operand) a second parameter of type T2 or "reference to
6208   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
6209   //   candidate functions.
6210   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6211       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6212     return;
6213 
6214   // Add this candidate
6215   OverloadCandidate &Candidate =
6216       CandidateSet.addCandidate(Args.size(), EarlyConversions);
6217   Candidate.FoundDecl = FoundDecl;
6218   Candidate.Function = Function;
6219   Candidate.Viable = true;
6220   Candidate.RewriteKind =
6221       CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6222   Candidate.IsSurrogate = false;
6223   Candidate.IsADLCandidate = IsADLCandidate;
6224   Candidate.IgnoreObjectArgument = false;
6225   Candidate.ExplicitCallArguments = Args.size();
6226 
6227   // Explicit functions are not actually candidates at all if we're not
6228   // allowing them in this context, but keep them around so we can point
6229   // to them in diagnostics.
6230   if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6231     Candidate.Viable = false;
6232     Candidate.FailureKind = ovl_fail_explicit;
6233     return;
6234   }
6235 
6236   if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6237       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6238     Candidate.Viable = false;
6239     Candidate.FailureKind = ovl_non_default_multiversion_function;
6240     return;
6241   }
6242 
6243   if (Constructor) {
6244     // C++ [class.copy]p3:
6245     //   A member function template is never instantiated to perform the copy
6246     //   of a class object to an object of its class type.
6247     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6248     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6249         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6250          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6251                        ClassType))) {
6252       Candidate.Viable = false;
6253       Candidate.FailureKind = ovl_fail_illegal_constructor;
6254       return;
6255     }
6256 
6257     // C++ [over.match.funcs]p8: (proposed DR resolution)
6258     //   A constructor inherited from class type C that has a first parameter
6259     //   of type "reference to P" (including such a constructor instantiated
6260     //   from a template) is excluded from the set of candidate functions when
6261     //   constructing an object of type cv D if the argument list has exactly
6262     //   one argument and D is reference-related to P and P is reference-related
6263     //   to C.
6264     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6265     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6266         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6267       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6268       QualType C = Context.getRecordType(Constructor->getParent());
6269       QualType D = Context.getRecordType(Shadow->getParent());
6270       SourceLocation Loc = Args.front()->getExprLoc();
6271       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6272           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6273         Candidate.Viable = false;
6274         Candidate.FailureKind = ovl_fail_inhctor_slice;
6275         return;
6276       }
6277     }
6278 
6279     // Check that the constructor is capable of constructing an object in the
6280     // destination address space.
6281     if (!Qualifiers::isAddressSpaceSupersetOf(
6282             Constructor->getMethodQualifiers().getAddressSpace(),
6283             CandidateSet.getDestAS())) {
6284       Candidate.Viable = false;
6285       Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6286     }
6287   }
6288 
6289   unsigned NumParams = Proto->getNumParams();
6290 
6291   // (C++ 13.3.2p2): A candidate function having fewer than m
6292   // parameters is viable only if it has an ellipsis in its parameter
6293   // list (8.3.5).
6294   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6295       !Proto->isVariadic()) {
6296     Candidate.Viable = false;
6297     Candidate.FailureKind = ovl_fail_too_many_arguments;
6298     return;
6299   }
6300 
6301   // (C++ 13.3.2p2): A candidate function having more than m parameters
6302   // is viable only if the (m+1)st parameter has a default argument
6303   // (8.3.6). For the purposes of overload resolution, the
6304   // parameter list is truncated on the right, so that there are
6305   // exactly m parameters.
6306   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6307   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6308     // Not enough arguments.
6309     Candidate.Viable = false;
6310     Candidate.FailureKind = ovl_fail_too_few_arguments;
6311     return;
6312   }
6313 
6314   // (CUDA B.1): Check for invalid calls between targets.
6315   if (getLangOpts().CUDA)
6316     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6317       // Skip the check for callers that are implicit members, because in this
6318       // case we may not yet know what the member's target is; the target is
6319       // inferred for the member automatically, based on the bases and fields of
6320       // the class.
6321       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6322         Candidate.Viable = false;
6323         Candidate.FailureKind = ovl_fail_bad_target;
6324         return;
6325       }
6326 
6327   if (Function->getTrailingRequiresClause()) {
6328     ConstraintSatisfaction Satisfaction;
6329     if (CheckFunctionConstraints(Function, Satisfaction) ||
6330         !Satisfaction.IsSatisfied) {
6331       Candidate.Viable = false;
6332       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6333       return;
6334     }
6335   }
6336 
6337   // Determine the implicit conversion sequences for each of the
6338   // arguments.
6339   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6340     unsigned ConvIdx =
6341         PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6342     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6343       // We already formed a conversion sequence for this parameter during
6344       // template argument deduction.
6345     } else if (ArgIdx < NumParams) {
6346       // (C++ 13.3.2p3): for F to be a viable function, there shall
6347       // exist for each argument an implicit conversion sequence
6348       // (13.3.3.1) that converts that argument to the corresponding
6349       // parameter of F.
6350       QualType ParamType = Proto->getParamType(ArgIdx);
6351       Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6352           *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6353           /*InOverloadResolution=*/true,
6354           /*AllowObjCWritebackConversion=*/
6355           getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6356       if (Candidate.Conversions[ConvIdx].isBad()) {
6357         Candidate.Viable = false;
6358         Candidate.FailureKind = ovl_fail_bad_conversion;
6359         return;
6360       }
6361     } else {
6362       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6363       // argument for which there is no corresponding parameter is
6364       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6365       Candidate.Conversions[ConvIdx].setEllipsis();
6366     }
6367   }
6368 
6369   if (EnableIfAttr *FailedAttr =
6370           CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
6371     Candidate.Viable = false;
6372     Candidate.FailureKind = ovl_fail_enable_if;
6373     Candidate.DeductionFailure.Data = FailedAttr;
6374     return;
6375   }
6376 
6377   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6378     Candidate.Viable = false;
6379     Candidate.FailureKind = ovl_fail_ext_disabled;
6380     return;
6381   }
6382 }
6383 
6384 ObjCMethodDecl *
6385 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6386                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6387   if (Methods.size() <= 1)
6388     return nullptr;
6389 
6390   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6391     bool Match = true;
6392     ObjCMethodDecl *Method = Methods[b];
6393     unsigned NumNamedArgs = Sel.getNumArgs();
6394     // Method might have more arguments than selector indicates. This is due
6395     // to addition of c-style arguments in method.
6396     if (Method->param_size() > NumNamedArgs)
6397       NumNamedArgs = Method->param_size();
6398     if (Args.size() < NumNamedArgs)
6399       continue;
6400 
6401     for (unsigned i = 0; i < NumNamedArgs; i++) {
6402       // We can't do any type-checking on a type-dependent argument.
6403       if (Args[i]->isTypeDependent()) {
6404         Match = false;
6405         break;
6406       }
6407 
6408       ParmVarDecl *param = Method->parameters()[i];
6409       Expr *argExpr = Args[i];
6410       assert(argExpr && "SelectBestMethod(): missing expression");
6411 
6412       // Strip the unbridged-cast placeholder expression off unless it's
6413       // a consumed argument.
6414       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6415           !param->hasAttr<CFConsumedAttr>())
6416         argExpr = stripARCUnbridgedCast(argExpr);
6417 
6418       // If the parameter is __unknown_anytype, move on to the next method.
6419       if (param->getType() == Context.UnknownAnyTy) {
6420         Match = false;
6421         break;
6422       }
6423 
6424       ImplicitConversionSequence ConversionState
6425         = TryCopyInitialization(*this, argExpr, param->getType(),
6426                                 /*SuppressUserConversions*/false,
6427                                 /*InOverloadResolution=*/true,
6428                                 /*AllowObjCWritebackConversion=*/
6429                                 getLangOpts().ObjCAutoRefCount,
6430                                 /*AllowExplicit*/false);
6431       // This function looks for a reasonably-exact match, so we consider
6432       // incompatible pointer conversions to be a failure here.
6433       if (ConversionState.isBad() ||
6434           (ConversionState.isStandard() &&
6435            ConversionState.Standard.Second ==
6436                ICK_Incompatible_Pointer_Conversion)) {
6437         Match = false;
6438         break;
6439       }
6440     }
6441     // Promote additional arguments to variadic methods.
6442     if (Match && Method->isVariadic()) {
6443       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6444         if (Args[i]->isTypeDependent()) {
6445           Match = false;
6446           break;
6447         }
6448         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6449                                                           nullptr);
6450         if (Arg.isInvalid()) {
6451           Match = false;
6452           break;
6453         }
6454       }
6455     } else {
6456       // Check for extra arguments to non-variadic methods.
6457       if (Args.size() != NumNamedArgs)
6458         Match = false;
6459       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6460         // Special case when selectors have no argument. In this case, select
6461         // one with the most general result type of 'id'.
6462         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6463           QualType ReturnT = Methods[b]->getReturnType();
6464           if (ReturnT->isObjCIdType())
6465             return Methods[b];
6466         }
6467       }
6468     }
6469 
6470     if (Match)
6471       return Method;
6472   }
6473   return nullptr;
6474 }
6475 
6476 static bool convertArgsForAvailabilityChecks(
6477     Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
6478     ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
6479     Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
6480   if (ThisArg) {
6481     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6482     assert(!isa<CXXConstructorDecl>(Method) &&
6483            "Shouldn't have `this` for ctors!");
6484     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6485     ExprResult R = S.PerformObjectArgumentInitialization(
6486         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6487     if (R.isInvalid())
6488       return false;
6489     ConvertedThis = R.get();
6490   } else {
6491     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6492       (void)MD;
6493       assert((MissingImplicitThis || MD->isStatic() ||
6494               isa<CXXConstructorDecl>(MD)) &&
6495              "Expected `this` for non-ctor instance methods");
6496     }
6497     ConvertedThis = nullptr;
6498   }
6499 
6500   // Ignore any variadic arguments. Converting them is pointless, since the
6501   // user can't refer to them in the function condition.
6502   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6503 
6504   // Convert the arguments.
6505   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6506     ExprResult R;
6507     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6508                                         S.Context, Function->getParamDecl(I)),
6509                                     SourceLocation(), Args[I]);
6510 
6511     if (R.isInvalid())
6512       return false;
6513 
6514     ConvertedArgs.push_back(R.get());
6515   }
6516 
6517   if (Trap.hasErrorOccurred())
6518     return false;
6519 
6520   // Push default arguments if needed.
6521   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6522     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6523       ParmVarDecl *P = Function->getParamDecl(i);
6524       if (!P->hasDefaultArg())
6525         return false;
6526       ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
6527       if (R.isInvalid())
6528         return false;
6529       ConvertedArgs.push_back(R.get());
6530     }
6531 
6532     if (Trap.hasErrorOccurred())
6533       return false;
6534   }
6535   return true;
6536 }
6537 
6538 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
6539                                   SourceLocation CallLoc,
6540                                   ArrayRef<Expr *> Args,
6541                                   bool MissingImplicitThis) {
6542   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6543   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6544     return nullptr;
6545 
6546   SFINAETrap Trap(*this);
6547   SmallVector<Expr *, 16> ConvertedArgs;
6548   // FIXME: We should look into making enable_if late-parsed.
6549   Expr *DiscardedThis;
6550   if (!convertArgsForAvailabilityChecks(
6551           *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
6552           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6553     return *EnableIfAttrs.begin();
6554 
6555   for (auto *EIA : EnableIfAttrs) {
6556     APValue Result;
6557     // FIXME: This doesn't consider value-dependent cases, because doing so is
6558     // very difficult. Ideally, we should handle them more gracefully.
6559     if (EIA->getCond()->isValueDependent() ||
6560         !EIA->getCond()->EvaluateWithSubstitution(
6561             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6562       return EIA;
6563 
6564     if (!Result.isInt() || !Result.getInt().getBoolValue())
6565       return EIA;
6566   }
6567   return nullptr;
6568 }
6569 
6570 template <typename CheckFn>
6571 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6572                                         bool ArgDependent, SourceLocation Loc,
6573                                         CheckFn &&IsSuccessful) {
6574   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6575   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6576     if (ArgDependent == DIA->getArgDependent())
6577       Attrs.push_back(DIA);
6578   }
6579 
6580   // Common case: No diagnose_if attributes, so we can quit early.
6581   if (Attrs.empty())
6582     return false;
6583 
6584   auto WarningBegin = std::stable_partition(
6585       Attrs.begin(), Attrs.end(),
6586       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6587 
6588   // Note that diagnose_if attributes are late-parsed, so they appear in the
6589   // correct order (unlike enable_if attributes).
6590   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6591                                IsSuccessful);
6592   if (ErrAttr != WarningBegin) {
6593     const DiagnoseIfAttr *DIA = *ErrAttr;
6594     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6595     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6596         << DIA->getParent() << DIA->getCond()->getSourceRange();
6597     return true;
6598   }
6599 
6600   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6601     if (IsSuccessful(DIA)) {
6602       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6603       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6604           << DIA->getParent() << DIA->getCond()->getSourceRange();
6605     }
6606 
6607   return false;
6608 }
6609 
6610 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6611                                                const Expr *ThisArg,
6612                                                ArrayRef<const Expr *> Args,
6613                                                SourceLocation Loc) {
6614   return diagnoseDiagnoseIfAttrsWith(
6615       *this, Function, /*ArgDependent=*/true, Loc,
6616       [&](const DiagnoseIfAttr *DIA) {
6617         APValue Result;
6618         // It's sane to use the same Args for any redecl of this function, since
6619         // EvaluateWithSubstitution only cares about the position of each
6620         // argument in the arg list, not the ParmVarDecl* it maps to.
6621         if (!DIA->getCond()->EvaluateWithSubstitution(
6622                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6623           return false;
6624         return Result.isInt() && Result.getInt().getBoolValue();
6625       });
6626 }
6627 
6628 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6629                                                  SourceLocation Loc) {
6630   return diagnoseDiagnoseIfAttrsWith(
6631       *this, ND, /*ArgDependent=*/false, Loc,
6632       [&](const DiagnoseIfAttr *DIA) {
6633         bool Result;
6634         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6635                Result;
6636       });
6637 }
6638 
6639 /// Add all of the function declarations in the given function set to
6640 /// the overload candidate set.
6641 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6642                                  ArrayRef<Expr *> Args,
6643                                  OverloadCandidateSet &CandidateSet,
6644                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6645                                  bool SuppressUserConversions,
6646                                  bool PartialOverloading,
6647                                  bool FirstArgumentIsBase) {
6648   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6649     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6650     ArrayRef<Expr *> FunctionArgs = Args;
6651 
6652     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6653     FunctionDecl *FD =
6654         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6655 
6656     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6657       QualType ObjectType;
6658       Expr::Classification ObjectClassification;
6659       if (Args.size() > 0) {
6660         if (Expr *E = Args[0]) {
6661           // Use the explicit base to restrict the lookup:
6662           ObjectType = E->getType();
6663           // Pointers in the object arguments are implicitly dereferenced, so we
6664           // always classify them as l-values.
6665           if (!ObjectType.isNull() && ObjectType->isPointerType())
6666             ObjectClassification = Expr::Classification::makeSimpleLValue();
6667           else
6668             ObjectClassification = E->Classify(Context);
6669         } // .. else there is an implicit base.
6670         FunctionArgs = Args.slice(1);
6671       }
6672       if (FunTmpl) {
6673         AddMethodTemplateCandidate(
6674             FunTmpl, F.getPair(),
6675             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6676             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6677             FunctionArgs, CandidateSet, SuppressUserConversions,
6678             PartialOverloading);
6679       } else {
6680         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6681                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6682                            ObjectClassification, FunctionArgs, CandidateSet,
6683                            SuppressUserConversions, PartialOverloading);
6684       }
6685     } else {
6686       // This branch handles both standalone functions and static methods.
6687 
6688       // Slice the first argument (which is the base) when we access
6689       // static method as non-static.
6690       if (Args.size() > 0 &&
6691           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6692                         !isa<CXXConstructorDecl>(FD)))) {
6693         assert(cast<CXXMethodDecl>(FD)->isStatic());
6694         FunctionArgs = Args.slice(1);
6695       }
6696       if (FunTmpl) {
6697         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6698                                      ExplicitTemplateArgs, FunctionArgs,
6699                                      CandidateSet, SuppressUserConversions,
6700                                      PartialOverloading);
6701       } else {
6702         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6703                              SuppressUserConversions, PartialOverloading);
6704       }
6705     }
6706   }
6707 }
6708 
6709 /// AddMethodCandidate - Adds a named decl (which is some kind of
6710 /// method) as a method candidate to the given overload set.
6711 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
6712                               Expr::Classification ObjectClassification,
6713                               ArrayRef<Expr *> Args,
6714                               OverloadCandidateSet &CandidateSet,
6715                               bool SuppressUserConversions,
6716                               OverloadCandidateParamOrder PO) {
6717   NamedDecl *Decl = FoundDecl.getDecl();
6718   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6719 
6720   if (isa<UsingShadowDecl>(Decl))
6721     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6722 
6723   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6724     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6725            "Expected a member function template");
6726     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6727                                /*ExplicitArgs*/ nullptr, ObjectType,
6728                                ObjectClassification, Args, CandidateSet,
6729                                SuppressUserConversions, false, PO);
6730   } else {
6731     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6732                        ObjectType, ObjectClassification, Args, CandidateSet,
6733                        SuppressUserConversions, false, None, PO);
6734   }
6735 }
6736 
6737 /// AddMethodCandidate - Adds the given C++ member function to the set
6738 /// of candidate functions, using the given function call arguments
6739 /// and the object argument (@c Object). For example, in a call
6740 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6741 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6742 /// allow user-defined conversions via constructors or conversion
6743 /// operators.
6744 void
6745 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6746                          CXXRecordDecl *ActingContext, QualType ObjectType,
6747                          Expr::Classification ObjectClassification,
6748                          ArrayRef<Expr *> Args,
6749                          OverloadCandidateSet &CandidateSet,
6750                          bool SuppressUserConversions,
6751                          bool PartialOverloading,
6752                          ConversionSequenceList EarlyConversions,
6753                          OverloadCandidateParamOrder PO) {
6754   const FunctionProtoType *Proto
6755     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6756   assert(Proto && "Methods without a prototype cannot be overloaded");
6757   assert(!isa<CXXConstructorDecl>(Method) &&
6758          "Use AddOverloadCandidate for constructors");
6759 
6760   if (!CandidateSet.isNewCandidate(Method, PO))
6761     return;
6762 
6763   // C++11 [class.copy]p23: [DR1402]
6764   //   A defaulted move assignment operator that is defined as deleted is
6765   //   ignored by overload resolution.
6766   if (Method->isDefaulted() && Method->isDeleted() &&
6767       Method->isMoveAssignmentOperator())
6768     return;
6769 
6770   // Overload resolution is always an unevaluated context.
6771   EnterExpressionEvaluationContext Unevaluated(
6772       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6773 
6774   // Add this candidate
6775   OverloadCandidate &Candidate =
6776       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6777   Candidate.FoundDecl = FoundDecl;
6778   Candidate.Function = Method;
6779   Candidate.RewriteKind =
6780       CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
6781   Candidate.IsSurrogate = false;
6782   Candidate.IgnoreObjectArgument = false;
6783   Candidate.ExplicitCallArguments = Args.size();
6784 
6785   unsigned NumParams = Proto->getNumParams();
6786 
6787   // (C++ 13.3.2p2): A candidate function having fewer than m
6788   // parameters is viable only if it has an ellipsis in its parameter
6789   // list (8.3.5).
6790   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6791       !Proto->isVariadic()) {
6792     Candidate.Viable = false;
6793     Candidate.FailureKind = ovl_fail_too_many_arguments;
6794     return;
6795   }
6796 
6797   // (C++ 13.3.2p2): A candidate function having more than m parameters
6798   // is viable only if the (m+1)st parameter has a default argument
6799   // (8.3.6). For the purposes of overload resolution, the
6800   // parameter list is truncated on the right, so that there are
6801   // exactly m parameters.
6802   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6803   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6804     // Not enough arguments.
6805     Candidate.Viable = false;
6806     Candidate.FailureKind = ovl_fail_too_few_arguments;
6807     return;
6808   }
6809 
6810   Candidate.Viable = true;
6811 
6812   if (Method->isStatic() || ObjectType.isNull())
6813     // The implicit object argument is ignored.
6814     Candidate.IgnoreObjectArgument = true;
6815   else {
6816     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
6817     // Determine the implicit conversion sequence for the object
6818     // parameter.
6819     Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization(
6820         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6821         Method, ActingContext);
6822     if (Candidate.Conversions[ConvIdx].isBad()) {
6823       Candidate.Viable = false;
6824       Candidate.FailureKind = ovl_fail_bad_conversion;
6825       return;
6826     }
6827   }
6828 
6829   // (CUDA B.1): Check for invalid calls between targets.
6830   if (getLangOpts().CUDA)
6831     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6832       if (!IsAllowedCUDACall(Caller, Method)) {
6833         Candidate.Viable = false;
6834         Candidate.FailureKind = ovl_fail_bad_target;
6835         return;
6836       }
6837 
6838   if (Method->getTrailingRequiresClause()) {
6839     ConstraintSatisfaction Satisfaction;
6840     if (CheckFunctionConstraints(Method, Satisfaction) ||
6841         !Satisfaction.IsSatisfied) {
6842       Candidate.Viable = false;
6843       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6844       return;
6845     }
6846   }
6847 
6848   // Determine the implicit conversion sequences for each of the
6849   // arguments.
6850   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6851     unsigned ConvIdx =
6852         PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
6853     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6854       // We already formed a conversion sequence for this parameter during
6855       // template argument deduction.
6856     } else if (ArgIdx < NumParams) {
6857       // (C++ 13.3.2p3): for F to be a viable function, there shall
6858       // exist for each argument an implicit conversion sequence
6859       // (13.3.3.1) that converts that argument to the corresponding
6860       // parameter of F.
6861       QualType ParamType = Proto->getParamType(ArgIdx);
6862       Candidate.Conversions[ConvIdx]
6863         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6864                                 SuppressUserConversions,
6865                                 /*InOverloadResolution=*/true,
6866                                 /*AllowObjCWritebackConversion=*/
6867                                   getLangOpts().ObjCAutoRefCount);
6868       if (Candidate.Conversions[ConvIdx].isBad()) {
6869         Candidate.Viable = false;
6870         Candidate.FailureKind = ovl_fail_bad_conversion;
6871         return;
6872       }
6873     } else {
6874       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6875       // argument for which there is no corresponding parameter is
6876       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6877       Candidate.Conversions[ConvIdx].setEllipsis();
6878     }
6879   }
6880 
6881   if (EnableIfAttr *FailedAttr =
6882           CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
6883     Candidate.Viable = false;
6884     Candidate.FailureKind = ovl_fail_enable_if;
6885     Candidate.DeductionFailure.Data = FailedAttr;
6886     return;
6887   }
6888 
6889   if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6890       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6891     Candidate.Viable = false;
6892     Candidate.FailureKind = ovl_non_default_multiversion_function;
6893   }
6894 }
6895 
6896 /// Add a C++ member function template as a candidate to the candidate
6897 /// set, using template argument deduction to produce an appropriate member
6898 /// function template specialization.
6899 void Sema::AddMethodTemplateCandidate(
6900     FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
6901     CXXRecordDecl *ActingContext,
6902     TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
6903     Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
6904     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6905     bool PartialOverloading, OverloadCandidateParamOrder PO) {
6906   if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
6907     return;
6908 
6909   // C++ [over.match.funcs]p7:
6910   //   In each case where a candidate is a function template, candidate
6911   //   function template specializations are generated using template argument
6912   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6913   //   candidate functions in the usual way.113) A given name can refer to one
6914   //   or more function templates and also to a set of overloaded non-template
6915   //   functions. In such a case, the candidate functions generated from each
6916   //   function template are combined with the set of non-template candidate
6917   //   functions.
6918   TemplateDeductionInfo Info(CandidateSet.getLocation());
6919   FunctionDecl *Specialization = nullptr;
6920   ConversionSequenceList Conversions;
6921   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6922           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6923           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6924             return CheckNonDependentConversions(
6925                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6926                 SuppressUserConversions, ActingContext, ObjectType,
6927                 ObjectClassification, PO);
6928           })) {
6929     OverloadCandidate &Candidate =
6930         CandidateSet.addCandidate(Conversions.size(), Conversions);
6931     Candidate.FoundDecl = FoundDecl;
6932     Candidate.Function = MethodTmpl->getTemplatedDecl();
6933     Candidate.Viable = false;
6934     Candidate.RewriteKind =
6935       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
6936     Candidate.IsSurrogate = false;
6937     Candidate.IgnoreObjectArgument =
6938         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6939         ObjectType.isNull();
6940     Candidate.ExplicitCallArguments = Args.size();
6941     if (Result == TDK_NonDependentConversionFailure)
6942       Candidate.FailureKind = ovl_fail_bad_conversion;
6943     else {
6944       Candidate.FailureKind = ovl_fail_bad_deduction;
6945       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6946                                                             Info);
6947     }
6948     return;
6949   }
6950 
6951   // Add the function template specialization produced by template argument
6952   // deduction as a candidate.
6953   assert(Specialization && "Missing member function template specialization?");
6954   assert(isa<CXXMethodDecl>(Specialization) &&
6955          "Specialization is not a member function?");
6956   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6957                      ActingContext, ObjectType, ObjectClassification, Args,
6958                      CandidateSet, SuppressUserConversions, PartialOverloading,
6959                      Conversions, PO);
6960 }
6961 
6962 /// Determine whether a given function template has a simple explicit specifier
6963 /// or a non-value-dependent explicit-specification that evaluates to true.
6964 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
6965   return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
6966 }
6967 
6968 /// Add a C++ function template specialization as a candidate
6969 /// in the candidate set, using template argument deduction to produce
6970 /// an appropriate function template specialization.
6971 void Sema::AddTemplateOverloadCandidate(
6972     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
6973     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6974     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6975     bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
6976     OverloadCandidateParamOrder PO) {
6977   if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
6978     return;
6979 
6980   // If the function template has a non-dependent explicit specification,
6981   // exclude it now if appropriate; we are not permitted to perform deduction
6982   // and substitution in this case.
6983   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
6984     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6985     Candidate.FoundDecl = FoundDecl;
6986     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6987     Candidate.Viable = false;
6988     Candidate.FailureKind = ovl_fail_explicit;
6989     return;
6990   }
6991 
6992   // C++ [over.match.funcs]p7:
6993   //   In each case where a candidate is a function template, candidate
6994   //   function template specializations are generated using template argument
6995   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6996   //   candidate functions in the usual way.113) A given name can refer to one
6997   //   or more function templates and also to a set of overloaded non-template
6998   //   functions. In such a case, the candidate functions generated from each
6999   //   function template are combined with the set of non-template candidate
7000   //   functions.
7001   TemplateDeductionInfo Info(CandidateSet.getLocation());
7002   FunctionDecl *Specialization = nullptr;
7003   ConversionSequenceList Conversions;
7004   if (TemplateDeductionResult Result = DeduceTemplateArguments(
7005           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7006           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7007             return CheckNonDependentConversions(
7008                 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7009                 SuppressUserConversions, nullptr, QualType(), {}, PO);
7010           })) {
7011     OverloadCandidate &Candidate =
7012         CandidateSet.addCandidate(Conversions.size(), Conversions);
7013     Candidate.FoundDecl = FoundDecl;
7014     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7015     Candidate.Viable = false;
7016     Candidate.RewriteKind =
7017       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7018     Candidate.IsSurrogate = false;
7019     Candidate.IsADLCandidate = IsADLCandidate;
7020     // Ignore the object argument if there is one, since we don't have an object
7021     // type.
7022     Candidate.IgnoreObjectArgument =
7023         isa<CXXMethodDecl>(Candidate.Function) &&
7024         !isa<CXXConstructorDecl>(Candidate.Function);
7025     Candidate.ExplicitCallArguments = Args.size();
7026     if (Result == TDK_NonDependentConversionFailure)
7027       Candidate.FailureKind = ovl_fail_bad_conversion;
7028     else {
7029       Candidate.FailureKind = ovl_fail_bad_deduction;
7030       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7031                                                             Info);
7032     }
7033     return;
7034   }
7035 
7036   // Add the function template specialization produced by template argument
7037   // deduction as a candidate.
7038   assert(Specialization && "Missing function template specialization?");
7039   AddOverloadCandidate(
7040       Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7041       PartialOverloading, AllowExplicit,
7042       /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO);
7043 }
7044 
7045 /// Check that implicit conversion sequences can be formed for each argument
7046 /// whose corresponding parameter has a non-dependent type, per DR1391's
7047 /// [temp.deduct.call]p10.
7048 bool Sema::CheckNonDependentConversions(
7049     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7050     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7051     ConversionSequenceList &Conversions, bool SuppressUserConversions,
7052     CXXRecordDecl *ActingContext, QualType ObjectType,
7053     Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7054   // FIXME: The cases in which we allow explicit conversions for constructor
7055   // arguments never consider calling a constructor template. It's not clear
7056   // that is correct.
7057   const bool AllowExplicit = false;
7058 
7059   auto *FD = FunctionTemplate->getTemplatedDecl();
7060   auto *Method = dyn_cast<CXXMethodDecl>(FD);
7061   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7062   unsigned ThisConversions = HasThisConversion ? 1 : 0;
7063 
7064   Conversions =
7065       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7066 
7067   // Overload resolution is always an unevaluated context.
7068   EnterExpressionEvaluationContext Unevaluated(
7069       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7070 
7071   // For a method call, check the 'this' conversion here too. DR1391 doesn't
7072   // require that, but this check should never result in a hard error, and
7073   // overload resolution is permitted to sidestep instantiations.
7074   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7075       !ObjectType.isNull()) {
7076     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7077     Conversions[ConvIdx] = TryObjectArgumentInitialization(
7078         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7079         Method, ActingContext);
7080     if (Conversions[ConvIdx].isBad())
7081       return true;
7082   }
7083 
7084   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
7085        ++I) {
7086     QualType ParamType = ParamTypes[I];
7087     if (!ParamType->isDependentType()) {
7088       unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
7089                              ? 0
7090                              : (ThisConversions + I);
7091       Conversions[ConvIdx]
7092         = TryCopyInitialization(*this, Args[I], ParamType,
7093                                 SuppressUserConversions,
7094                                 /*InOverloadResolution=*/true,
7095                                 /*AllowObjCWritebackConversion=*/
7096                                   getLangOpts().ObjCAutoRefCount,
7097                                 AllowExplicit);
7098       if (Conversions[ConvIdx].isBad())
7099         return true;
7100     }
7101   }
7102 
7103   return false;
7104 }
7105 
7106 /// Determine whether this is an allowable conversion from the result
7107 /// of an explicit conversion operator to the expected type, per C++
7108 /// [over.match.conv]p1 and [over.match.ref]p1.
7109 ///
7110 /// \param ConvType The return type of the conversion function.
7111 ///
7112 /// \param ToType The type we are converting to.
7113 ///
7114 /// \param AllowObjCPointerConversion Allow a conversion from one
7115 /// Objective-C pointer to another.
7116 ///
7117 /// \returns true if the conversion is allowable, false otherwise.
7118 static bool isAllowableExplicitConversion(Sema &S,
7119                                           QualType ConvType, QualType ToType,
7120                                           bool AllowObjCPointerConversion) {
7121   QualType ToNonRefType = ToType.getNonReferenceType();
7122 
7123   // Easy case: the types are the same.
7124   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7125     return true;
7126 
7127   // Allow qualification conversions.
7128   bool ObjCLifetimeConversion;
7129   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7130                                   ObjCLifetimeConversion))
7131     return true;
7132 
7133   // If we're not allowed to consider Objective-C pointer conversions,
7134   // we're done.
7135   if (!AllowObjCPointerConversion)
7136     return false;
7137 
7138   // Is this an Objective-C pointer conversion?
7139   bool IncompatibleObjC = false;
7140   QualType ConvertedType;
7141   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7142                                    IncompatibleObjC);
7143 }
7144 
7145 /// AddConversionCandidate - Add a C++ conversion function as a
7146 /// candidate in the candidate set (C++ [over.match.conv],
7147 /// C++ [over.match.copy]). From is the expression we're converting from,
7148 /// and ToType is the type that we're eventually trying to convert to
7149 /// (which may or may not be the same type as the type that the
7150 /// conversion function produces).
7151 void Sema::AddConversionCandidate(
7152     CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7153     CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7154     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7155     bool AllowExplicit, bool AllowResultConversion) {
7156   assert(!Conversion->getDescribedFunctionTemplate() &&
7157          "Conversion function templates use AddTemplateConversionCandidate");
7158   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7159   if (!CandidateSet.isNewCandidate(Conversion))
7160     return;
7161 
7162   // If the conversion function has an undeduced return type, trigger its
7163   // deduction now.
7164   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7165     if (DeduceReturnType(Conversion, From->getExprLoc()))
7166       return;
7167     ConvType = Conversion->getConversionType().getNonReferenceType();
7168   }
7169 
7170   // If we don't allow any conversion of the result type, ignore conversion
7171   // functions that don't convert to exactly (possibly cv-qualified) T.
7172   if (!AllowResultConversion &&
7173       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7174     return;
7175 
7176   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7177   // operator is only a candidate if its return type is the target type or
7178   // can be converted to the target type with a qualification conversion.
7179   //
7180   // FIXME: Include such functions in the candidate list and explain why we
7181   // can't select them.
7182   if (Conversion->isExplicit() &&
7183       !isAllowableExplicitConversion(*this, ConvType, ToType,
7184                                      AllowObjCConversionOnExplicit))
7185     return;
7186 
7187   // Overload resolution is always an unevaluated context.
7188   EnterExpressionEvaluationContext Unevaluated(
7189       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7190 
7191   // Add this candidate
7192   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7193   Candidate.FoundDecl = FoundDecl;
7194   Candidate.Function = Conversion;
7195   Candidate.IsSurrogate = false;
7196   Candidate.IgnoreObjectArgument = false;
7197   Candidate.FinalConversion.setAsIdentityConversion();
7198   Candidate.FinalConversion.setFromType(ConvType);
7199   Candidate.FinalConversion.setAllToTypes(ToType);
7200   Candidate.Viable = true;
7201   Candidate.ExplicitCallArguments = 1;
7202 
7203   // Explicit functions are not actually candidates at all if we're not
7204   // allowing them in this context, but keep them around so we can point
7205   // to them in diagnostics.
7206   if (!AllowExplicit && Conversion->isExplicit()) {
7207     Candidate.Viable = false;
7208     Candidate.FailureKind = ovl_fail_explicit;
7209     return;
7210   }
7211 
7212   // C++ [over.match.funcs]p4:
7213   //   For conversion functions, the function is considered to be a member of
7214   //   the class of the implicit implied object argument for the purpose of
7215   //   defining the type of the implicit object parameter.
7216   //
7217   // Determine the implicit conversion sequence for the implicit
7218   // object parameter.
7219   QualType ImplicitParamType = From->getType();
7220   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7221     ImplicitParamType = FromPtrType->getPointeeType();
7222   CXXRecordDecl *ConversionContext
7223     = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
7224 
7225   Candidate.Conversions[0] = TryObjectArgumentInitialization(
7226       *this, CandidateSet.getLocation(), From->getType(),
7227       From->Classify(Context), Conversion, ConversionContext);
7228 
7229   if (Candidate.Conversions[0].isBad()) {
7230     Candidate.Viable = false;
7231     Candidate.FailureKind = ovl_fail_bad_conversion;
7232     return;
7233   }
7234 
7235   if (Conversion->getTrailingRequiresClause()) {
7236     ConstraintSatisfaction Satisfaction;
7237     if (CheckFunctionConstraints(Conversion, Satisfaction) ||
7238         !Satisfaction.IsSatisfied) {
7239       Candidate.Viable = false;
7240       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7241       return;
7242     }
7243   }
7244 
7245   // We won't go through a user-defined type conversion function to convert a
7246   // derived to base as such conversions are given Conversion Rank. They only
7247   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7248   QualType FromCanon
7249     = Context.getCanonicalType(From->getType().getUnqualifiedType());
7250   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7251   if (FromCanon == ToCanon ||
7252       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7253     Candidate.Viable = false;
7254     Candidate.FailureKind = ovl_fail_trivial_conversion;
7255     return;
7256   }
7257 
7258   // To determine what the conversion from the result of calling the
7259   // conversion function to the type we're eventually trying to
7260   // convert to (ToType), we need to synthesize a call to the
7261   // conversion function and attempt copy initialization from it. This
7262   // makes sure that we get the right semantics with respect to
7263   // lvalues/rvalues and the type. Fortunately, we can allocate this
7264   // call on the stack and we don't need its arguments to be
7265   // well-formed.
7266   DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7267                             VK_LValue, From->getBeginLoc());
7268   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7269                                 Context.getPointerType(Conversion->getType()),
7270                                 CK_FunctionToPointerDecay,
7271                                 &ConversionRef, VK_RValue);
7272 
7273   QualType ConversionType = Conversion->getConversionType();
7274   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7275     Candidate.Viable = false;
7276     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7277     return;
7278   }
7279 
7280   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7281 
7282   // Note that it is safe to allocate CallExpr on the stack here because
7283   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7284   // allocator).
7285   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7286 
7287   alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7288   CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7289       Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7290 
7291   ImplicitConversionSequence ICS =
7292       TryCopyInitialization(*this, TheTemporaryCall, ToType,
7293                             /*SuppressUserConversions=*/true,
7294                             /*InOverloadResolution=*/false,
7295                             /*AllowObjCWritebackConversion=*/false);
7296 
7297   switch (ICS.getKind()) {
7298   case ImplicitConversionSequence::StandardConversion:
7299     Candidate.FinalConversion = ICS.Standard;
7300 
7301     // C++ [over.ics.user]p3:
7302     //   If the user-defined conversion is specified by a specialization of a
7303     //   conversion function template, the second standard conversion sequence
7304     //   shall have exact match rank.
7305     if (Conversion->getPrimaryTemplate() &&
7306         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7307       Candidate.Viable = false;
7308       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7309       return;
7310     }
7311 
7312     // C++0x [dcl.init.ref]p5:
7313     //    In the second case, if the reference is an rvalue reference and
7314     //    the second standard conversion sequence of the user-defined
7315     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7316     //    program is ill-formed.
7317     if (ToType->isRValueReferenceType() &&
7318         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7319       Candidate.Viable = false;
7320       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7321       return;
7322     }
7323     break;
7324 
7325   case ImplicitConversionSequence::BadConversion:
7326     Candidate.Viable = false;
7327     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7328     return;
7329 
7330   default:
7331     llvm_unreachable(
7332            "Can only end up with a standard conversion sequence or failure");
7333   }
7334 
7335   if (EnableIfAttr *FailedAttr =
7336           CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7337     Candidate.Viable = false;
7338     Candidate.FailureKind = ovl_fail_enable_if;
7339     Candidate.DeductionFailure.Data = FailedAttr;
7340     return;
7341   }
7342 
7343   if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7344       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7345     Candidate.Viable = false;
7346     Candidate.FailureKind = ovl_non_default_multiversion_function;
7347   }
7348 }
7349 
7350 /// Adds a conversion function template specialization
7351 /// candidate to the overload set, using template argument deduction
7352 /// to deduce the template arguments of the conversion function
7353 /// template from the type that we are converting to (C++
7354 /// [temp.deduct.conv]).
7355 void Sema::AddTemplateConversionCandidate(
7356     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7357     CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7358     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7359     bool AllowExplicit, bool AllowResultConversion) {
7360   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7361          "Only conversion function templates permitted here");
7362 
7363   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7364     return;
7365 
7366   // If the function template has a non-dependent explicit specification,
7367   // exclude it now if appropriate; we are not permitted to perform deduction
7368   // and substitution in this case.
7369   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7370     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7371     Candidate.FoundDecl = FoundDecl;
7372     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7373     Candidate.Viable = false;
7374     Candidate.FailureKind = ovl_fail_explicit;
7375     return;
7376   }
7377 
7378   TemplateDeductionInfo Info(CandidateSet.getLocation());
7379   CXXConversionDecl *Specialization = nullptr;
7380   if (TemplateDeductionResult Result
7381         = DeduceTemplateArguments(FunctionTemplate, ToType,
7382                                   Specialization, Info)) {
7383     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7384     Candidate.FoundDecl = FoundDecl;
7385     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7386     Candidate.Viable = false;
7387     Candidate.FailureKind = ovl_fail_bad_deduction;
7388     Candidate.IsSurrogate = false;
7389     Candidate.IgnoreObjectArgument = false;
7390     Candidate.ExplicitCallArguments = 1;
7391     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7392                                                           Info);
7393     return;
7394   }
7395 
7396   // Add the conversion function template specialization produced by
7397   // template argument deduction as a candidate.
7398   assert(Specialization && "Missing function template specialization?");
7399   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7400                          CandidateSet, AllowObjCConversionOnExplicit,
7401                          AllowExplicit, AllowResultConversion);
7402 }
7403 
7404 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7405 /// converts the given @c Object to a function pointer via the
7406 /// conversion function @c Conversion, and then attempts to call it
7407 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7408 /// the type of function that we'll eventually be calling.
7409 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7410                                  DeclAccessPair FoundDecl,
7411                                  CXXRecordDecl *ActingContext,
7412                                  const FunctionProtoType *Proto,
7413                                  Expr *Object,
7414                                  ArrayRef<Expr *> Args,
7415                                  OverloadCandidateSet& CandidateSet) {
7416   if (!CandidateSet.isNewCandidate(Conversion))
7417     return;
7418 
7419   // Overload resolution is always an unevaluated context.
7420   EnterExpressionEvaluationContext Unevaluated(
7421       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7422 
7423   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7424   Candidate.FoundDecl = FoundDecl;
7425   Candidate.Function = nullptr;
7426   Candidate.Surrogate = Conversion;
7427   Candidate.Viable = true;
7428   Candidate.IsSurrogate = true;
7429   Candidate.IgnoreObjectArgument = false;
7430   Candidate.ExplicitCallArguments = Args.size();
7431 
7432   // Determine the implicit conversion sequence for the implicit
7433   // object parameter.
7434   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7435       *this, CandidateSet.getLocation(), Object->getType(),
7436       Object->Classify(Context), Conversion, ActingContext);
7437   if (ObjectInit.isBad()) {
7438     Candidate.Viable = false;
7439     Candidate.FailureKind = ovl_fail_bad_conversion;
7440     Candidate.Conversions[0] = ObjectInit;
7441     return;
7442   }
7443 
7444   // The first conversion is actually a user-defined conversion whose
7445   // first conversion is ObjectInit's standard conversion (which is
7446   // effectively a reference binding). Record it as such.
7447   Candidate.Conversions[0].setUserDefined();
7448   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7449   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7450   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7451   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7452   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7453   Candidate.Conversions[0].UserDefined.After
7454     = Candidate.Conversions[0].UserDefined.Before;
7455   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7456 
7457   // Find the
7458   unsigned NumParams = Proto->getNumParams();
7459 
7460   // (C++ 13.3.2p2): A candidate function having fewer than m
7461   // parameters is viable only if it has an ellipsis in its parameter
7462   // list (8.3.5).
7463   if (Args.size() > NumParams && !Proto->isVariadic()) {
7464     Candidate.Viable = false;
7465     Candidate.FailureKind = ovl_fail_too_many_arguments;
7466     return;
7467   }
7468 
7469   // Function types don't have any default arguments, so just check if
7470   // we have enough arguments.
7471   if (Args.size() < NumParams) {
7472     // Not enough arguments.
7473     Candidate.Viable = false;
7474     Candidate.FailureKind = ovl_fail_too_few_arguments;
7475     return;
7476   }
7477 
7478   // Determine the implicit conversion sequences for each of the
7479   // arguments.
7480   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7481     if (ArgIdx < NumParams) {
7482       // (C++ 13.3.2p3): for F to be a viable function, there shall
7483       // exist for each argument an implicit conversion sequence
7484       // (13.3.3.1) that converts that argument to the corresponding
7485       // parameter of F.
7486       QualType ParamType = Proto->getParamType(ArgIdx);
7487       Candidate.Conversions[ArgIdx + 1]
7488         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7489                                 /*SuppressUserConversions=*/false,
7490                                 /*InOverloadResolution=*/false,
7491                                 /*AllowObjCWritebackConversion=*/
7492                                   getLangOpts().ObjCAutoRefCount);
7493       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7494         Candidate.Viable = false;
7495         Candidate.FailureKind = ovl_fail_bad_conversion;
7496         return;
7497       }
7498     } else {
7499       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7500       // argument for which there is no corresponding parameter is
7501       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7502       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7503     }
7504   }
7505 
7506   if (EnableIfAttr *FailedAttr =
7507           CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7508     Candidate.Viable = false;
7509     Candidate.FailureKind = ovl_fail_enable_if;
7510     Candidate.DeductionFailure.Data = FailedAttr;
7511     return;
7512   }
7513 }
7514 
7515 /// Add all of the non-member operator function declarations in the given
7516 /// function set to the overload candidate set.
7517 void Sema::AddNonMemberOperatorCandidates(
7518     const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
7519     OverloadCandidateSet &CandidateSet,
7520     TemplateArgumentListInfo *ExplicitTemplateArgs) {
7521   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7522     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7523     ArrayRef<Expr *> FunctionArgs = Args;
7524 
7525     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7526     FunctionDecl *FD =
7527         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7528 
7529     // Don't consider rewritten functions if we're not rewriting.
7530     if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
7531       continue;
7532 
7533     assert(!isa<CXXMethodDecl>(FD) &&
7534            "unqualified operator lookup found a member function");
7535 
7536     if (FunTmpl) {
7537       AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
7538                                    FunctionArgs, CandidateSet);
7539       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7540         AddTemplateOverloadCandidate(
7541             FunTmpl, F.getPair(), ExplicitTemplateArgs,
7542             {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
7543             true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
7544     } else {
7545       if (ExplicitTemplateArgs)
7546         continue;
7547       AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
7548       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7549         AddOverloadCandidate(FD, F.getPair(),
7550                              {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
7551                              false, false, true, false, ADLCallKind::NotADL,
7552                              None, OverloadCandidateParamOrder::Reversed);
7553     }
7554   }
7555 }
7556 
7557 /// Add overload candidates for overloaded operators that are
7558 /// member functions.
7559 ///
7560 /// Add the overloaded operator candidates that are member functions
7561 /// for the operator Op that was used in an operator expression such
7562 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7563 /// CandidateSet will store the added overload candidates. (C++
7564 /// [over.match.oper]).
7565 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7566                                        SourceLocation OpLoc,
7567                                        ArrayRef<Expr *> Args,
7568                                        OverloadCandidateSet &CandidateSet,
7569                                        OverloadCandidateParamOrder PO) {
7570   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7571 
7572   // C++ [over.match.oper]p3:
7573   //   For a unary operator @ with an operand of a type whose
7574   //   cv-unqualified version is T1, and for a binary operator @ with
7575   //   a left operand of a type whose cv-unqualified version is T1 and
7576   //   a right operand of a type whose cv-unqualified version is T2,
7577   //   three sets of candidate functions, designated member
7578   //   candidates, non-member candidates and built-in candidates, are
7579   //   constructed as follows:
7580   QualType T1 = Args[0]->getType();
7581 
7582   //     -- If T1 is a complete class type or a class currently being
7583   //        defined, the set of member candidates is the result of the
7584   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7585   //        the set of member candidates is empty.
7586   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7587     // Complete the type if it can be completed.
7588     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7589       return;
7590     // If the type is neither complete nor being defined, bail out now.
7591     if (!T1Rec->getDecl()->getDefinition())
7592       return;
7593 
7594     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7595     LookupQualifiedName(Operators, T1Rec->getDecl());
7596     Operators.suppressDiagnostics();
7597 
7598     for (LookupResult::iterator Oper = Operators.begin(),
7599                              OperEnd = Operators.end();
7600          Oper != OperEnd;
7601          ++Oper)
7602       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7603                          Args[0]->Classify(Context), Args.slice(1),
7604                          CandidateSet, /*SuppressUserConversion=*/false, PO);
7605   }
7606 }
7607 
7608 /// AddBuiltinCandidate - Add a candidate for a built-in
7609 /// operator. ResultTy and ParamTys are the result and parameter types
7610 /// of the built-in candidate, respectively. Args and NumArgs are the
7611 /// arguments being passed to the candidate. IsAssignmentOperator
7612 /// should be true when this built-in candidate is an assignment
7613 /// operator. NumContextualBoolArguments is the number of arguments
7614 /// (at the beginning of the argument list) that will be contextually
7615 /// converted to bool.
7616 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7617                                OverloadCandidateSet& CandidateSet,
7618                                bool IsAssignmentOperator,
7619                                unsigned NumContextualBoolArguments) {
7620   // Overload resolution is always an unevaluated context.
7621   EnterExpressionEvaluationContext Unevaluated(
7622       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7623 
7624   // Add this candidate
7625   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7626   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7627   Candidate.Function = nullptr;
7628   Candidate.IsSurrogate = false;
7629   Candidate.IgnoreObjectArgument = false;
7630   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7631 
7632   // Determine the implicit conversion sequences for each of the
7633   // arguments.
7634   Candidate.Viable = true;
7635   Candidate.ExplicitCallArguments = Args.size();
7636   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7637     // C++ [over.match.oper]p4:
7638     //   For the built-in assignment operators, conversions of the
7639     //   left operand are restricted as follows:
7640     //     -- no temporaries are introduced to hold the left operand, and
7641     //     -- no user-defined conversions are applied to the left
7642     //        operand to achieve a type match with the left-most
7643     //        parameter of a built-in candidate.
7644     //
7645     // We block these conversions by turning off user-defined
7646     // conversions, since that is the only way that initialization of
7647     // a reference to a non-class type can occur from something that
7648     // is not of the same type.
7649     if (ArgIdx < NumContextualBoolArguments) {
7650       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7651              "Contextual conversion to bool requires bool type");
7652       Candidate.Conversions[ArgIdx]
7653         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7654     } else {
7655       Candidate.Conversions[ArgIdx]
7656         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7657                                 ArgIdx == 0 && IsAssignmentOperator,
7658                                 /*InOverloadResolution=*/false,
7659                                 /*AllowObjCWritebackConversion=*/
7660                                   getLangOpts().ObjCAutoRefCount);
7661     }
7662     if (Candidate.Conversions[ArgIdx].isBad()) {
7663       Candidate.Viable = false;
7664       Candidate.FailureKind = ovl_fail_bad_conversion;
7665       break;
7666     }
7667   }
7668 }
7669 
7670 namespace {
7671 
7672 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7673 /// candidate operator functions for built-in operators (C++
7674 /// [over.built]). The types are separated into pointer types and
7675 /// enumeration types.
7676 class BuiltinCandidateTypeSet  {
7677   /// TypeSet - A set of types.
7678   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7679                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7680 
7681   /// PointerTypes - The set of pointer types that will be used in the
7682   /// built-in candidates.
7683   TypeSet PointerTypes;
7684 
7685   /// MemberPointerTypes - The set of member pointer types that will be
7686   /// used in the built-in candidates.
7687   TypeSet MemberPointerTypes;
7688 
7689   /// EnumerationTypes - The set of enumeration types that will be
7690   /// used in the built-in candidates.
7691   TypeSet EnumerationTypes;
7692 
7693   /// The set of vector types that will be used in the built-in
7694   /// candidates.
7695   TypeSet VectorTypes;
7696 
7697   /// The set of matrix types that will be used in the built-in
7698   /// candidates.
7699   TypeSet MatrixTypes;
7700 
7701   /// A flag indicating non-record types are viable candidates
7702   bool HasNonRecordTypes;
7703 
7704   /// A flag indicating whether either arithmetic or enumeration types
7705   /// were present in the candidate set.
7706   bool HasArithmeticOrEnumeralTypes;
7707 
7708   /// A flag indicating whether the nullptr type was present in the
7709   /// candidate set.
7710   bool HasNullPtrType;
7711 
7712   /// Sema - The semantic analysis instance where we are building the
7713   /// candidate type set.
7714   Sema &SemaRef;
7715 
7716   /// Context - The AST context in which we will build the type sets.
7717   ASTContext &Context;
7718 
7719   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7720                                                const Qualifiers &VisibleQuals);
7721   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7722 
7723 public:
7724   /// iterator - Iterates through the types that are part of the set.
7725   typedef TypeSet::iterator iterator;
7726 
7727   BuiltinCandidateTypeSet(Sema &SemaRef)
7728     : HasNonRecordTypes(false),
7729       HasArithmeticOrEnumeralTypes(false),
7730       HasNullPtrType(false),
7731       SemaRef(SemaRef),
7732       Context(SemaRef.Context) { }
7733 
7734   void AddTypesConvertedFrom(QualType Ty,
7735                              SourceLocation Loc,
7736                              bool AllowUserConversions,
7737                              bool AllowExplicitConversions,
7738                              const Qualifiers &VisibleTypeConversionsQuals);
7739 
7740   /// pointer_begin - First pointer type found;
7741   iterator pointer_begin() { return PointerTypes.begin(); }
7742 
7743   /// pointer_end - Past the last pointer type found;
7744   iterator pointer_end() { return PointerTypes.end(); }
7745 
7746   /// member_pointer_begin - First member pointer type found;
7747   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7748 
7749   /// member_pointer_end - Past the last member pointer type found;
7750   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7751 
7752   /// enumeration_begin - First enumeration type found;
7753   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7754 
7755   /// enumeration_end - Past the last enumeration type found;
7756   iterator enumeration_end() { return EnumerationTypes.end(); }
7757 
7758   llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
7759 
7760   llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
7761 
7762   bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
7763   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7764   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7765   bool hasNullPtrType() const { return HasNullPtrType; }
7766 };
7767 
7768 } // end anonymous namespace
7769 
7770 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7771 /// the set of pointer types along with any more-qualified variants of
7772 /// that type. For example, if @p Ty is "int const *", this routine
7773 /// will add "int const *", "int const volatile *", "int const
7774 /// restrict *", and "int const volatile restrict *" to the set of
7775 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7776 /// false otherwise.
7777 ///
7778 /// FIXME: what to do about extended qualifiers?
7779 bool
7780 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7781                                              const Qualifiers &VisibleQuals) {
7782 
7783   // Insert this type.
7784   if (!PointerTypes.insert(Ty))
7785     return false;
7786 
7787   QualType PointeeTy;
7788   const PointerType *PointerTy = Ty->getAs<PointerType>();
7789   bool buildObjCPtr = false;
7790   if (!PointerTy) {
7791     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7792     PointeeTy = PTy->getPointeeType();
7793     buildObjCPtr = true;
7794   } else {
7795     PointeeTy = PointerTy->getPointeeType();
7796   }
7797 
7798   // Don't add qualified variants of arrays. For one, they're not allowed
7799   // (the qualifier would sink to the element type), and for another, the
7800   // only overload situation where it matters is subscript or pointer +- int,
7801   // and those shouldn't have qualifier variants anyway.
7802   if (PointeeTy->isArrayType())
7803     return true;
7804 
7805   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7806   bool hasVolatile = VisibleQuals.hasVolatile();
7807   bool hasRestrict = VisibleQuals.hasRestrict();
7808 
7809   // Iterate through all strict supersets of BaseCVR.
7810   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7811     if ((CVR | BaseCVR) != CVR) continue;
7812     // Skip over volatile if no volatile found anywhere in the types.
7813     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7814 
7815     // Skip over restrict if no restrict found anywhere in the types, or if
7816     // the type cannot be restrict-qualified.
7817     if ((CVR & Qualifiers::Restrict) &&
7818         (!hasRestrict ||
7819          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7820       continue;
7821 
7822     // Build qualified pointee type.
7823     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7824 
7825     // Build qualified pointer type.
7826     QualType QPointerTy;
7827     if (!buildObjCPtr)
7828       QPointerTy = Context.getPointerType(QPointeeTy);
7829     else
7830       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7831 
7832     // Insert qualified pointer type.
7833     PointerTypes.insert(QPointerTy);
7834   }
7835 
7836   return true;
7837 }
7838 
7839 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7840 /// to the set of pointer types along with any more-qualified variants of
7841 /// that type. For example, if @p Ty is "int const *", this routine
7842 /// will add "int const *", "int const volatile *", "int const
7843 /// restrict *", and "int const volatile restrict *" to the set of
7844 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7845 /// false otherwise.
7846 ///
7847 /// FIXME: what to do about extended qualifiers?
7848 bool
7849 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7850     QualType Ty) {
7851   // Insert this type.
7852   if (!MemberPointerTypes.insert(Ty))
7853     return false;
7854 
7855   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7856   assert(PointerTy && "type was not a member pointer type!");
7857 
7858   QualType PointeeTy = PointerTy->getPointeeType();
7859   // Don't add qualified variants of arrays. For one, they're not allowed
7860   // (the qualifier would sink to the element type), and for another, the
7861   // only overload situation where it matters is subscript or pointer +- int,
7862   // and those shouldn't have qualifier variants anyway.
7863   if (PointeeTy->isArrayType())
7864     return true;
7865   const Type *ClassTy = PointerTy->getClass();
7866 
7867   // Iterate through all strict supersets of the pointee type's CVR
7868   // qualifiers.
7869   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7870   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7871     if ((CVR | BaseCVR) != CVR) continue;
7872 
7873     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7874     MemberPointerTypes.insert(
7875       Context.getMemberPointerType(QPointeeTy, ClassTy));
7876   }
7877 
7878   return true;
7879 }
7880 
7881 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7882 /// Ty can be implicit converted to the given set of @p Types. We're
7883 /// primarily interested in pointer types and enumeration types. We also
7884 /// take member pointer types, for the conditional operator.
7885 /// AllowUserConversions is true if we should look at the conversion
7886 /// functions of a class type, and AllowExplicitConversions if we
7887 /// should also include the explicit conversion functions of a class
7888 /// type.
7889 void
7890 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7891                                                SourceLocation Loc,
7892                                                bool AllowUserConversions,
7893                                                bool AllowExplicitConversions,
7894                                                const Qualifiers &VisibleQuals) {
7895   // Only deal with canonical types.
7896   Ty = Context.getCanonicalType(Ty);
7897 
7898   // Look through reference types; they aren't part of the type of an
7899   // expression for the purposes of conversions.
7900   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7901     Ty = RefTy->getPointeeType();
7902 
7903   // If we're dealing with an array type, decay to the pointer.
7904   if (Ty->isArrayType())
7905     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7906 
7907   // Otherwise, we don't care about qualifiers on the type.
7908   Ty = Ty.getLocalUnqualifiedType();
7909 
7910   // Flag if we ever add a non-record type.
7911   const RecordType *TyRec = Ty->getAs<RecordType>();
7912   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7913 
7914   // Flag if we encounter an arithmetic type.
7915   HasArithmeticOrEnumeralTypes =
7916     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7917 
7918   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7919     PointerTypes.insert(Ty);
7920   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7921     // Insert our type, and its more-qualified variants, into the set
7922     // of types.
7923     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7924       return;
7925   } else if (Ty->isMemberPointerType()) {
7926     // Member pointers are far easier, since the pointee can't be converted.
7927     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7928       return;
7929   } else if (Ty->isEnumeralType()) {
7930     HasArithmeticOrEnumeralTypes = true;
7931     EnumerationTypes.insert(Ty);
7932   } else if (Ty->isVectorType()) {
7933     // We treat vector types as arithmetic types in many contexts as an
7934     // extension.
7935     HasArithmeticOrEnumeralTypes = true;
7936     VectorTypes.insert(Ty);
7937   } else if (Ty->isMatrixType()) {
7938     // Similar to vector types, we treat vector types as arithmetic types in
7939     // many contexts as an extension.
7940     HasArithmeticOrEnumeralTypes = true;
7941     MatrixTypes.insert(Ty);
7942   } else if (Ty->isNullPtrType()) {
7943     HasNullPtrType = true;
7944   } else if (AllowUserConversions && TyRec) {
7945     // No conversion functions in incomplete types.
7946     if (!SemaRef.isCompleteType(Loc, Ty))
7947       return;
7948 
7949     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7950     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7951       if (isa<UsingShadowDecl>(D))
7952         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7953 
7954       // Skip conversion function templates; they don't tell us anything
7955       // about which builtin types we can convert to.
7956       if (isa<FunctionTemplateDecl>(D))
7957         continue;
7958 
7959       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7960       if (AllowExplicitConversions || !Conv->isExplicit()) {
7961         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7962                               VisibleQuals);
7963       }
7964     }
7965   }
7966 }
7967 /// Helper function for adjusting address spaces for the pointer or reference
7968 /// operands of builtin operators depending on the argument.
7969 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
7970                                                         Expr *Arg) {
7971   return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
7972 }
7973 
7974 /// Helper function for AddBuiltinOperatorCandidates() that adds
7975 /// the volatile- and non-volatile-qualified assignment operators for the
7976 /// given type to the candidate set.
7977 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7978                                                    QualType T,
7979                                                    ArrayRef<Expr *> Args,
7980                                     OverloadCandidateSet &CandidateSet) {
7981   QualType ParamTypes[2];
7982 
7983   // T& operator=(T&, T)
7984   ParamTypes[0] = S.Context.getLValueReferenceType(
7985       AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
7986   ParamTypes[1] = T;
7987   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7988                         /*IsAssignmentOperator=*/true);
7989 
7990   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7991     // volatile T& operator=(volatile T&, T)
7992     ParamTypes[0] = S.Context.getLValueReferenceType(
7993         AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
7994                                                 Args[0]));
7995     ParamTypes[1] = T;
7996     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7997                           /*IsAssignmentOperator=*/true);
7998   }
7999 }
8000 
8001 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8002 /// if any, found in visible type conversion functions found in ArgExpr's type.
8003 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8004     Qualifiers VRQuals;
8005     const RecordType *TyRec;
8006     if (const MemberPointerType *RHSMPType =
8007         ArgExpr->getType()->getAs<MemberPointerType>())
8008       TyRec = RHSMPType->getClass()->getAs<RecordType>();
8009     else
8010       TyRec = ArgExpr->getType()->getAs<RecordType>();
8011     if (!TyRec) {
8012       // Just to be safe, assume the worst case.
8013       VRQuals.addVolatile();
8014       VRQuals.addRestrict();
8015       return VRQuals;
8016     }
8017 
8018     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8019     if (!ClassDecl->hasDefinition())
8020       return VRQuals;
8021 
8022     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8023       if (isa<UsingShadowDecl>(D))
8024         D = cast<UsingShadowDecl>(D)->getTargetDecl();
8025       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8026         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8027         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8028           CanTy = ResTypeRef->getPointeeType();
8029         // Need to go down the pointer/mempointer chain and add qualifiers
8030         // as see them.
8031         bool done = false;
8032         while (!done) {
8033           if (CanTy.isRestrictQualified())
8034             VRQuals.addRestrict();
8035           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8036             CanTy = ResTypePtr->getPointeeType();
8037           else if (const MemberPointerType *ResTypeMPtr =
8038                 CanTy->getAs<MemberPointerType>())
8039             CanTy = ResTypeMPtr->getPointeeType();
8040           else
8041             done = true;
8042           if (CanTy.isVolatileQualified())
8043             VRQuals.addVolatile();
8044           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8045             return VRQuals;
8046         }
8047       }
8048     }
8049     return VRQuals;
8050 }
8051 
8052 namespace {
8053 
8054 /// Helper class to manage the addition of builtin operator overload
8055 /// candidates. It provides shared state and utility methods used throughout
8056 /// the process, as well as a helper method to add each group of builtin
8057 /// operator overloads from the standard to a candidate set.
8058 class BuiltinOperatorOverloadBuilder {
8059   // Common instance state available to all overload candidate addition methods.
8060   Sema &S;
8061   ArrayRef<Expr *> Args;
8062   Qualifiers VisibleTypeConversionsQuals;
8063   bool HasArithmeticOrEnumeralCandidateType;
8064   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8065   OverloadCandidateSet &CandidateSet;
8066 
8067   static constexpr int ArithmeticTypesCap = 24;
8068   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8069 
8070   // Define some indices used to iterate over the arithmetic types in
8071   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
8072   // types are that preserved by promotion (C++ [over.built]p2).
8073   unsigned FirstIntegralType,
8074            LastIntegralType;
8075   unsigned FirstPromotedIntegralType,
8076            LastPromotedIntegralType;
8077   unsigned FirstPromotedArithmeticType,
8078            LastPromotedArithmeticType;
8079   unsigned NumArithmeticTypes;
8080 
8081   void InitArithmeticTypes() {
8082     // Start of promoted types.
8083     FirstPromotedArithmeticType = 0;
8084     ArithmeticTypes.push_back(S.Context.FloatTy);
8085     ArithmeticTypes.push_back(S.Context.DoubleTy);
8086     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8087     if (S.Context.getTargetInfo().hasFloat128Type())
8088       ArithmeticTypes.push_back(S.Context.Float128Ty);
8089 
8090     // Start of integral types.
8091     FirstIntegralType = ArithmeticTypes.size();
8092     FirstPromotedIntegralType = ArithmeticTypes.size();
8093     ArithmeticTypes.push_back(S.Context.IntTy);
8094     ArithmeticTypes.push_back(S.Context.LongTy);
8095     ArithmeticTypes.push_back(S.Context.LongLongTy);
8096     if (S.Context.getTargetInfo().hasInt128Type())
8097       ArithmeticTypes.push_back(S.Context.Int128Ty);
8098     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8099     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8100     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8101     if (S.Context.getTargetInfo().hasInt128Type())
8102       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8103     LastPromotedIntegralType = ArithmeticTypes.size();
8104     LastPromotedArithmeticType = ArithmeticTypes.size();
8105     // End of promoted types.
8106 
8107     ArithmeticTypes.push_back(S.Context.BoolTy);
8108     ArithmeticTypes.push_back(S.Context.CharTy);
8109     ArithmeticTypes.push_back(S.Context.WCharTy);
8110     if (S.Context.getLangOpts().Char8)
8111       ArithmeticTypes.push_back(S.Context.Char8Ty);
8112     ArithmeticTypes.push_back(S.Context.Char16Ty);
8113     ArithmeticTypes.push_back(S.Context.Char32Ty);
8114     ArithmeticTypes.push_back(S.Context.SignedCharTy);
8115     ArithmeticTypes.push_back(S.Context.ShortTy);
8116     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8117     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8118     LastIntegralType = ArithmeticTypes.size();
8119     NumArithmeticTypes = ArithmeticTypes.size();
8120     // End of integral types.
8121     // FIXME: What about complex? What about half?
8122 
8123     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
8124            "Enough inline storage for all arithmetic types.");
8125   }
8126 
8127   /// Helper method to factor out the common pattern of adding overloads
8128   /// for '++' and '--' builtin operators.
8129   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8130                                            bool HasVolatile,
8131                                            bool HasRestrict) {
8132     QualType ParamTypes[2] = {
8133       S.Context.getLValueReferenceType(CandidateTy),
8134       S.Context.IntTy
8135     };
8136 
8137     // Non-volatile version.
8138     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8139 
8140     // Use a heuristic to reduce number of builtin candidates in the set:
8141     // add volatile version only if there are conversions to a volatile type.
8142     if (HasVolatile) {
8143       ParamTypes[0] =
8144         S.Context.getLValueReferenceType(
8145           S.Context.getVolatileType(CandidateTy));
8146       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8147     }
8148 
8149     // Add restrict version only if there are conversions to a restrict type
8150     // and our candidate type is a non-restrict-qualified pointer.
8151     if (HasRestrict && CandidateTy->isAnyPointerType() &&
8152         !CandidateTy.isRestrictQualified()) {
8153       ParamTypes[0]
8154         = S.Context.getLValueReferenceType(
8155             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8156       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8157 
8158       if (HasVolatile) {
8159         ParamTypes[0]
8160           = S.Context.getLValueReferenceType(
8161               S.Context.getCVRQualifiedType(CandidateTy,
8162                                             (Qualifiers::Volatile |
8163                                              Qualifiers::Restrict)));
8164         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8165       }
8166     }
8167 
8168   }
8169 
8170   /// Helper to add an overload candidate for a binary builtin with types \p L
8171   /// and \p R.
8172   void AddCandidate(QualType L, QualType R) {
8173     QualType LandR[2] = {L, R};
8174     S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8175   }
8176 
8177 public:
8178   BuiltinOperatorOverloadBuilder(
8179     Sema &S, ArrayRef<Expr *> Args,
8180     Qualifiers VisibleTypeConversionsQuals,
8181     bool HasArithmeticOrEnumeralCandidateType,
8182     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8183     OverloadCandidateSet &CandidateSet)
8184     : S(S), Args(Args),
8185       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8186       HasArithmeticOrEnumeralCandidateType(
8187         HasArithmeticOrEnumeralCandidateType),
8188       CandidateTypes(CandidateTypes),
8189       CandidateSet(CandidateSet) {
8190 
8191     InitArithmeticTypes();
8192   }
8193 
8194   // Increment is deprecated for bool since C++17.
8195   //
8196   // C++ [over.built]p3:
8197   //
8198   //   For every pair (T, VQ), where T is an arithmetic type other
8199   //   than bool, and VQ is either volatile or empty, there exist
8200   //   candidate operator functions of the form
8201   //
8202   //       VQ T&      operator++(VQ T&);
8203   //       T          operator++(VQ T&, int);
8204   //
8205   // C++ [over.built]p4:
8206   //
8207   //   For every pair (T, VQ), where T is an arithmetic type other
8208   //   than bool, and VQ is either volatile or empty, there exist
8209   //   candidate operator functions of the form
8210   //
8211   //       VQ T&      operator--(VQ T&);
8212   //       T          operator--(VQ T&, int);
8213   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8214     if (!HasArithmeticOrEnumeralCandidateType)
8215       return;
8216 
8217     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8218       const auto TypeOfT = ArithmeticTypes[Arith];
8219       if (TypeOfT == S.Context.BoolTy) {
8220         if (Op == OO_MinusMinus)
8221           continue;
8222         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8223           continue;
8224       }
8225       addPlusPlusMinusMinusStyleOverloads(
8226         TypeOfT,
8227         VisibleTypeConversionsQuals.hasVolatile(),
8228         VisibleTypeConversionsQuals.hasRestrict());
8229     }
8230   }
8231 
8232   // C++ [over.built]p5:
8233   //
8234   //   For every pair (T, VQ), where T is a cv-qualified or
8235   //   cv-unqualified object type, and VQ is either volatile or
8236   //   empty, there exist candidate operator functions of the form
8237   //
8238   //       T*VQ&      operator++(T*VQ&);
8239   //       T*VQ&      operator--(T*VQ&);
8240   //       T*         operator++(T*VQ&, int);
8241   //       T*         operator--(T*VQ&, int);
8242   void addPlusPlusMinusMinusPointerOverloads() {
8243     for (BuiltinCandidateTypeSet::iterator
8244               Ptr = CandidateTypes[0].pointer_begin(),
8245            PtrEnd = CandidateTypes[0].pointer_end();
8246          Ptr != PtrEnd; ++Ptr) {
8247       // Skip pointer types that aren't pointers to object types.
8248       if (!(*Ptr)->getPointeeType()->isObjectType())
8249         continue;
8250 
8251       addPlusPlusMinusMinusStyleOverloads(*Ptr,
8252         (!(*Ptr).isVolatileQualified() &&
8253          VisibleTypeConversionsQuals.hasVolatile()),
8254         (!(*Ptr).isRestrictQualified() &&
8255          VisibleTypeConversionsQuals.hasRestrict()));
8256     }
8257   }
8258 
8259   // C++ [over.built]p6:
8260   //   For every cv-qualified or cv-unqualified object type T, there
8261   //   exist candidate operator functions of the form
8262   //
8263   //       T&         operator*(T*);
8264   //
8265   // C++ [over.built]p7:
8266   //   For every function type T that does not have cv-qualifiers or a
8267   //   ref-qualifier, there exist candidate operator functions of the form
8268   //       T&         operator*(T*);
8269   void addUnaryStarPointerOverloads() {
8270     for (BuiltinCandidateTypeSet::iterator
8271               Ptr = CandidateTypes[0].pointer_begin(),
8272            PtrEnd = CandidateTypes[0].pointer_end();
8273          Ptr != PtrEnd; ++Ptr) {
8274       QualType ParamTy = *Ptr;
8275       QualType PointeeTy = ParamTy->getPointeeType();
8276       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8277         continue;
8278 
8279       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8280         if (Proto->getMethodQuals() || Proto->getRefQualifier())
8281           continue;
8282 
8283       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8284     }
8285   }
8286 
8287   // C++ [over.built]p9:
8288   //  For every promoted arithmetic type T, there exist candidate
8289   //  operator functions of the form
8290   //
8291   //       T         operator+(T);
8292   //       T         operator-(T);
8293   void addUnaryPlusOrMinusArithmeticOverloads() {
8294     if (!HasArithmeticOrEnumeralCandidateType)
8295       return;
8296 
8297     for (unsigned Arith = FirstPromotedArithmeticType;
8298          Arith < LastPromotedArithmeticType; ++Arith) {
8299       QualType ArithTy = ArithmeticTypes[Arith];
8300       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8301     }
8302 
8303     // Extension: We also add these operators for vector types.
8304     for (QualType VecTy : CandidateTypes[0].vector_types())
8305       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8306   }
8307 
8308   // C++ [over.built]p8:
8309   //   For every type T, there exist candidate operator functions of
8310   //   the form
8311   //
8312   //       T*         operator+(T*);
8313   void addUnaryPlusPointerOverloads() {
8314     for (BuiltinCandidateTypeSet::iterator
8315               Ptr = CandidateTypes[0].pointer_begin(),
8316            PtrEnd = CandidateTypes[0].pointer_end();
8317          Ptr != PtrEnd; ++Ptr) {
8318       QualType ParamTy = *Ptr;
8319       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8320     }
8321   }
8322 
8323   // C++ [over.built]p10:
8324   //   For every promoted integral type T, there exist candidate
8325   //   operator functions of the form
8326   //
8327   //        T         operator~(T);
8328   void addUnaryTildePromotedIntegralOverloads() {
8329     if (!HasArithmeticOrEnumeralCandidateType)
8330       return;
8331 
8332     for (unsigned Int = FirstPromotedIntegralType;
8333          Int < LastPromotedIntegralType; ++Int) {
8334       QualType IntTy = ArithmeticTypes[Int];
8335       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8336     }
8337 
8338     // Extension: We also add this operator for vector types.
8339     for (QualType VecTy : CandidateTypes[0].vector_types())
8340       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8341   }
8342 
8343   // C++ [over.match.oper]p16:
8344   //   For every pointer to member type T or type std::nullptr_t, there
8345   //   exist candidate operator functions of the form
8346   //
8347   //        bool operator==(T,T);
8348   //        bool operator!=(T,T);
8349   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8350     /// Set of (canonical) types that we've already handled.
8351     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8352 
8353     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8354       for (BuiltinCandidateTypeSet::iterator
8355                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8356              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8357            MemPtr != MemPtrEnd;
8358            ++MemPtr) {
8359         // Don't add the same builtin candidate twice.
8360         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8361           continue;
8362 
8363         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8364         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8365       }
8366 
8367       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8368         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8369         if (AddedTypes.insert(NullPtrTy).second) {
8370           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8371           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8372         }
8373       }
8374     }
8375   }
8376 
8377   // C++ [over.built]p15:
8378   //
8379   //   For every T, where T is an enumeration type or a pointer type,
8380   //   there exist candidate operator functions of the form
8381   //
8382   //        bool       operator<(T, T);
8383   //        bool       operator>(T, T);
8384   //        bool       operator<=(T, T);
8385   //        bool       operator>=(T, T);
8386   //        bool       operator==(T, T);
8387   //        bool       operator!=(T, T);
8388   //           R       operator<=>(T, T)
8389   void addGenericBinaryPointerOrEnumeralOverloads() {
8390     // C++ [over.match.oper]p3:
8391     //   [...]the built-in candidates include all of the candidate operator
8392     //   functions defined in 13.6 that, compared to the given operator, [...]
8393     //   do not have the same parameter-type-list as any non-template non-member
8394     //   candidate.
8395     //
8396     // Note that in practice, this only affects enumeration types because there
8397     // aren't any built-in candidates of record type, and a user-defined operator
8398     // must have an operand of record or enumeration type. Also, the only other
8399     // overloaded operator with enumeration arguments, operator=,
8400     // cannot be overloaded for enumeration types, so this is the only place
8401     // where we must suppress candidates like this.
8402     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8403       UserDefinedBinaryOperators;
8404 
8405     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8406       if (CandidateTypes[ArgIdx].enumeration_begin() !=
8407           CandidateTypes[ArgIdx].enumeration_end()) {
8408         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8409                                          CEnd = CandidateSet.end();
8410              C != CEnd; ++C) {
8411           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8412             continue;
8413 
8414           if (C->Function->isFunctionTemplateSpecialization())
8415             continue;
8416 
8417           // We interpret "same parameter-type-list" as applying to the
8418           // "synthesized candidate, with the order of the two parameters
8419           // reversed", not to the original function.
8420           bool Reversed = C->isReversed();
8421           QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
8422                                         ->getType()
8423                                         .getUnqualifiedType();
8424           QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
8425                                          ->getType()
8426                                          .getUnqualifiedType();
8427 
8428           // Skip if either parameter isn't of enumeral type.
8429           if (!FirstParamType->isEnumeralType() ||
8430               !SecondParamType->isEnumeralType())
8431             continue;
8432 
8433           // Add this operator to the set of known user-defined operators.
8434           UserDefinedBinaryOperators.insert(
8435             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8436                            S.Context.getCanonicalType(SecondParamType)));
8437         }
8438       }
8439     }
8440 
8441     /// Set of (canonical) types that we've already handled.
8442     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8443 
8444     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8445       for (BuiltinCandidateTypeSet::iterator
8446                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8447              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8448            Ptr != PtrEnd; ++Ptr) {
8449         // Don't add the same builtin candidate twice.
8450         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8451           continue;
8452 
8453         QualType ParamTypes[2] = { *Ptr, *Ptr };
8454         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8455       }
8456       for (BuiltinCandidateTypeSet::iterator
8457                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8458              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8459            Enum != EnumEnd; ++Enum) {
8460         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8461 
8462         // Don't add the same builtin candidate twice, or if a user defined
8463         // candidate exists.
8464         if (!AddedTypes.insert(CanonType).second ||
8465             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8466                                                             CanonType)))
8467           continue;
8468         QualType ParamTypes[2] = { *Enum, *Enum };
8469         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8470       }
8471     }
8472   }
8473 
8474   // C++ [over.built]p13:
8475   //
8476   //   For every cv-qualified or cv-unqualified object type T
8477   //   there exist candidate operator functions of the form
8478   //
8479   //      T*         operator+(T*, ptrdiff_t);
8480   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8481   //      T*         operator-(T*, ptrdiff_t);
8482   //      T*         operator+(ptrdiff_t, T*);
8483   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8484   //
8485   // C++ [over.built]p14:
8486   //
8487   //   For every T, where T is a pointer to object type, there
8488   //   exist candidate operator functions of the form
8489   //
8490   //      ptrdiff_t  operator-(T, T);
8491   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8492     /// Set of (canonical) types that we've already handled.
8493     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8494 
8495     for (int Arg = 0; Arg < 2; ++Arg) {
8496       QualType AsymmetricParamTypes[2] = {
8497         S.Context.getPointerDiffType(),
8498         S.Context.getPointerDiffType(),
8499       };
8500       for (BuiltinCandidateTypeSet::iterator
8501                 Ptr = CandidateTypes[Arg].pointer_begin(),
8502              PtrEnd = CandidateTypes[Arg].pointer_end();
8503            Ptr != PtrEnd; ++Ptr) {
8504         QualType PointeeTy = (*Ptr)->getPointeeType();
8505         if (!PointeeTy->isObjectType())
8506           continue;
8507 
8508         AsymmetricParamTypes[Arg] = *Ptr;
8509         if (Arg == 0 || Op == OO_Plus) {
8510           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8511           // T* operator+(ptrdiff_t, T*);
8512           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8513         }
8514         if (Op == OO_Minus) {
8515           // ptrdiff_t operator-(T, T);
8516           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8517             continue;
8518 
8519           QualType ParamTypes[2] = { *Ptr, *Ptr };
8520           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8521         }
8522       }
8523     }
8524   }
8525 
8526   // C++ [over.built]p12:
8527   //
8528   //   For every pair of promoted arithmetic types L and R, there
8529   //   exist candidate operator functions of the form
8530   //
8531   //        LR         operator*(L, R);
8532   //        LR         operator/(L, R);
8533   //        LR         operator+(L, R);
8534   //        LR         operator-(L, R);
8535   //        bool       operator<(L, R);
8536   //        bool       operator>(L, R);
8537   //        bool       operator<=(L, R);
8538   //        bool       operator>=(L, R);
8539   //        bool       operator==(L, R);
8540   //        bool       operator!=(L, R);
8541   //
8542   //   where LR is the result of the usual arithmetic conversions
8543   //   between types L and R.
8544   //
8545   // C++ [over.built]p24:
8546   //
8547   //   For every pair of promoted arithmetic types L and R, there exist
8548   //   candidate operator functions of the form
8549   //
8550   //        LR       operator?(bool, L, R);
8551   //
8552   //   where LR is the result of the usual arithmetic conversions
8553   //   between types L and R.
8554   // Our candidates ignore the first parameter.
8555   void addGenericBinaryArithmeticOverloads() {
8556     if (!HasArithmeticOrEnumeralCandidateType)
8557       return;
8558 
8559     for (unsigned Left = FirstPromotedArithmeticType;
8560          Left < LastPromotedArithmeticType; ++Left) {
8561       for (unsigned Right = FirstPromotedArithmeticType;
8562            Right < LastPromotedArithmeticType; ++Right) {
8563         QualType LandR[2] = { ArithmeticTypes[Left],
8564                               ArithmeticTypes[Right] };
8565         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8566       }
8567     }
8568 
8569     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8570     // conditional operator for vector types.
8571     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8572       for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
8573         QualType LandR[2] = {Vec1Ty, Vec2Ty};
8574         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8575       }
8576   }
8577 
8578   /// Add binary operator overloads for each candidate matrix type M1, M2:
8579   ///  * (M1, M1) -> M1
8580   ///  * (M1, M1.getElementType()) -> M1
8581   ///  * (M2.getElementType(), M2) -> M2
8582   ///  * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
8583   void addMatrixBinaryArithmeticOverloads() {
8584     if (!HasArithmeticOrEnumeralCandidateType)
8585       return;
8586 
8587     for (QualType M1 : CandidateTypes[0].matrix_types()) {
8588       AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
8589       AddCandidate(M1, M1);
8590     }
8591 
8592     for (QualType M2 : CandidateTypes[1].matrix_types()) {
8593       AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
8594       if (!CandidateTypes[0].containsMatrixType(M2))
8595         AddCandidate(M2, M2);
8596     }
8597   }
8598 
8599   // C++2a [over.built]p14:
8600   //
8601   //   For every integral type T there exists a candidate operator function
8602   //   of the form
8603   //
8604   //        std::strong_ordering operator<=>(T, T)
8605   //
8606   // C++2a [over.built]p15:
8607   //
8608   //   For every pair of floating-point types L and R, there exists a candidate
8609   //   operator function of the form
8610   //
8611   //       std::partial_ordering operator<=>(L, R);
8612   //
8613   // FIXME: The current specification for integral types doesn't play nice with
8614   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8615   // comparisons. Under the current spec this can lead to ambiguity during
8616   // overload resolution. For example:
8617   //
8618   //   enum A : int {a};
8619   //   auto x = (a <=> (long)42);
8620   //
8621   //   error: call is ambiguous for arguments 'A' and 'long'.
8622   //   note: candidate operator<=>(int, int)
8623   //   note: candidate operator<=>(long, long)
8624   //
8625   // To avoid this error, this function deviates from the specification and adds
8626   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8627   // arithmetic types (the same as the generic relational overloads).
8628   //
8629   // For now this function acts as a placeholder.
8630   void addThreeWayArithmeticOverloads() {
8631     addGenericBinaryArithmeticOverloads();
8632   }
8633 
8634   // C++ [over.built]p17:
8635   //
8636   //   For every pair of promoted integral types L and R, there
8637   //   exist candidate operator functions of the form
8638   //
8639   //      LR         operator%(L, R);
8640   //      LR         operator&(L, R);
8641   //      LR         operator^(L, R);
8642   //      LR         operator|(L, R);
8643   //      L          operator<<(L, R);
8644   //      L          operator>>(L, R);
8645   //
8646   //   where LR is the result of the usual arithmetic conversions
8647   //   between types L and R.
8648   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8649     if (!HasArithmeticOrEnumeralCandidateType)
8650       return;
8651 
8652     for (unsigned Left = FirstPromotedIntegralType;
8653          Left < LastPromotedIntegralType; ++Left) {
8654       for (unsigned Right = FirstPromotedIntegralType;
8655            Right < LastPromotedIntegralType; ++Right) {
8656         QualType LandR[2] = { ArithmeticTypes[Left],
8657                               ArithmeticTypes[Right] };
8658         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8659       }
8660     }
8661   }
8662 
8663   // C++ [over.built]p20:
8664   //
8665   //   For every pair (T, VQ), where T is an enumeration or
8666   //   pointer to member type and VQ is either volatile or
8667   //   empty, there exist candidate operator functions of the form
8668   //
8669   //        VQ T&      operator=(VQ T&, T);
8670   void addAssignmentMemberPointerOrEnumeralOverloads() {
8671     /// Set of (canonical) types that we've already handled.
8672     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8673 
8674     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8675       for (BuiltinCandidateTypeSet::iterator
8676                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8677              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8678            Enum != EnumEnd; ++Enum) {
8679         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8680           continue;
8681 
8682         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8683       }
8684 
8685       for (BuiltinCandidateTypeSet::iterator
8686                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8687              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8688            MemPtr != MemPtrEnd; ++MemPtr) {
8689         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8690           continue;
8691 
8692         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8693       }
8694     }
8695   }
8696 
8697   // C++ [over.built]p19:
8698   //
8699   //   For every pair (T, VQ), where T is any type and VQ is either
8700   //   volatile or empty, there exist candidate operator functions
8701   //   of the form
8702   //
8703   //        T*VQ&      operator=(T*VQ&, T*);
8704   //
8705   // C++ [over.built]p21:
8706   //
8707   //   For every pair (T, VQ), where T is a cv-qualified or
8708   //   cv-unqualified object type and VQ is either volatile or
8709   //   empty, there exist candidate operator functions of the form
8710   //
8711   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8712   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8713   void addAssignmentPointerOverloads(bool isEqualOp) {
8714     /// Set of (canonical) types that we've already handled.
8715     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8716 
8717     for (BuiltinCandidateTypeSet::iterator
8718               Ptr = CandidateTypes[0].pointer_begin(),
8719            PtrEnd = CandidateTypes[0].pointer_end();
8720          Ptr != PtrEnd; ++Ptr) {
8721       // If this is operator=, keep track of the builtin candidates we added.
8722       if (isEqualOp)
8723         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8724       else if (!(*Ptr)->getPointeeType()->isObjectType())
8725         continue;
8726 
8727       // non-volatile version
8728       QualType ParamTypes[2] = {
8729         S.Context.getLValueReferenceType(*Ptr),
8730         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8731       };
8732       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8733                             /*IsAssignmentOperator=*/ isEqualOp);
8734 
8735       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8736                           VisibleTypeConversionsQuals.hasVolatile();
8737       if (NeedVolatile) {
8738         // volatile version
8739         ParamTypes[0] =
8740           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8741         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8742                               /*IsAssignmentOperator=*/isEqualOp);
8743       }
8744 
8745       if (!(*Ptr).isRestrictQualified() &&
8746           VisibleTypeConversionsQuals.hasRestrict()) {
8747         // restrict version
8748         ParamTypes[0]
8749           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8750         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8751                               /*IsAssignmentOperator=*/isEqualOp);
8752 
8753         if (NeedVolatile) {
8754           // volatile restrict version
8755           ParamTypes[0]
8756             = S.Context.getLValueReferenceType(
8757                 S.Context.getCVRQualifiedType(*Ptr,
8758                                               (Qualifiers::Volatile |
8759                                                Qualifiers::Restrict)));
8760           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8761                                 /*IsAssignmentOperator=*/isEqualOp);
8762         }
8763       }
8764     }
8765 
8766     if (isEqualOp) {
8767       for (BuiltinCandidateTypeSet::iterator
8768                 Ptr = CandidateTypes[1].pointer_begin(),
8769              PtrEnd = CandidateTypes[1].pointer_end();
8770            Ptr != PtrEnd; ++Ptr) {
8771         // Make sure we don't add the same candidate twice.
8772         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8773           continue;
8774 
8775         QualType ParamTypes[2] = {
8776           S.Context.getLValueReferenceType(*Ptr),
8777           *Ptr,
8778         };
8779 
8780         // non-volatile version
8781         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8782                               /*IsAssignmentOperator=*/true);
8783 
8784         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8785                            VisibleTypeConversionsQuals.hasVolatile();
8786         if (NeedVolatile) {
8787           // volatile version
8788           ParamTypes[0] =
8789             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8790           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8791                                 /*IsAssignmentOperator=*/true);
8792         }
8793 
8794         if (!(*Ptr).isRestrictQualified() &&
8795             VisibleTypeConversionsQuals.hasRestrict()) {
8796           // restrict version
8797           ParamTypes[0]
8798             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8799           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8800                                 /*IsAssignmentOperator=*/true);
8801 
8802           if (NeedVolatile) {
8803             // volatile restrict version
8804             ParamTypes[0]
8805               = S.Context.getLValueReferenceType(
8806                   S.Context.getCVRQualifiedType(*Ptr,
8807                                                 (Qualifiers::Volatile |
8808                                                  Qualifiers::Restrict)));
8809             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8810                                   /*IsAssignmentOperator=*/true);
8811           }
8812         }
8813       }
8814     }
8815   }
8816 
8817   // C++ [over.built]p18:
8818   //
8819   //   For every triple (L, VQ, R), where L is an arithmetic type,
8820   //   VQ is either volatile or empty, and R is a promoted
8821   //   arithmetic type, there exist candidate operator functions of
8822   //   the form
8823   //
8824   //        VQ L&      operator=(VQ L&, R);
8825   //        VQ L&      operator*=(VQ L&, R);
8826   //        VQ L&      operator/=(VQ L&, R);
8827   //        VQ L&      operator+=(VQ L&, R);
8828   //        VQ L&      operator-=(VQ L&, R);
8829   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8830     if (!HasArithmeticOrEnumeralCandidateType)
8831       return;
8832 
8833     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8834       for (unsigned Right = FirstPromotedArithmeticType;
8835            Right < LastPromotedArithmeticType; ++Right) {
8836         QualType ParamTypes[2];
8837         ParamTypes[1] = ArithmeticTypes[Right];
8838         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8839             S, ArithmeticTypes[Left], Args[0]);
8840         // Add this built-in operator as a candidate (VQ is empty).
8841         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8842         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8843                               /*IsAssignmentOperator=*/isEqualOp);
8844 
8845         // Add this built-in operator as a candidate (VQ is 'volatile').
8846         if (VisibleTypeConversionsQuals.hasVolatile()) {
8847           ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy);
8848           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8849           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8850                                 /*IsAssignmentOperator=*/isEqualOp);
8851         }
8852       }
8853     }
8854 
8855     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8856     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8857       for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
8858         QualType ParamTypes[2];
8859         ParamTypes[1] = Vec2Ty;
8860         // Add this built-in operator as a candidate (VQ is empty).
8861         ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
8862         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8863                               /*IsAssignmentOperator=*/isEqualOp);
8864 
8865         // Add this built-in operator as a candidate (VQ is 'volatile').
8866         if (VisibleTypeConversionsQuals.hasVolatile()) {
8867           ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
8868           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8869           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8870                                 /*IsAssignmentOperator=*/isEqualOp);
8871         }
8872       }
8873   }
8874 
8875   // C++ [over.built]p22:
8876   //
8877   //   For every triple (L, VQ, R), where L is an integral type, VQ
8878   //   is either volatile or empty, and R is a promoted integral
8879   //   type, there exist candidate operator functions of the form
8880   //
8881   //        VQ L&       operator%=(VQ L&, R);
8882   //        VQ L&       operator<<=(VQ L&, R);
8883   //        VQ L&       operator>>=(VQ L&, R);
8884   //        VQ L&       operator&=(VQ L&, R);
8885   //        VQ L&       operator^=(VQ L&, R);
8886   //        VQ L&       operator|=(VQ L&, R);
8887   void addAssignmentIntegralOverloads() {
8888     if (!HasArithmeticOrEnumeralCandidateType)
8889       return;
8890 
8891     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8892       for (unsigned Right = FirstPromotedIntegralType;
8893            Right < LastPromotedIntegralType; ++Right) {
8894         QualType ParamTypes[2];
8895         ParamTypes[1] = ArithmeticTypes[Right];
8896         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8897             S, ArithmeticTypes[Left], Args[0]);
8898         // Add this built-in operator as a candidate (VQ is empty).
8899         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8900         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8901         if (VisibleTypeConversionsQuals.hasVolatile()) {
8902           // Add this built-in operator as a candidate (VQ is 'volatile').
8903           ParamTypes[0] = LeftBaseTy;
8904           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8905           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8906           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8907         }
8908       }
8909     }
8910   }
8911 
8912   // C++ [over.operator]p23:
8913   //
8914   //   There also exist candidate operator functions of the form
8915   //
8916   //        bool        operator!(bool);
8917   //        bool        operator&&(bool, bool);
8918   //        bool        operator||(bool, bool);
8919   void addExclaimOverload() {
8920     QualType ParamTy = S.Context.BoolTy;
8921     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8922                           /*IsAssignmentOperator=*/false,
8923                           /*NumContextualBoolArguments=*/1);
8924   }
8925   void addAmpAmpOrPipePipeOverload() {
8926     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8927     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8928                           /*IsAssignmentOperator=*/false,
8929                           /*NumContextualBoolArguments=*/2);
8930   }
8931 
8932   // C++ [over.built]p13:
8933   //
8934   //   For every cv-qualified or cv-unqualified object type T there
8935   //   exist candidate operator functions of the form
8936   //
8937   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8938   //        T&         operator[](T*, ptrdiff_t);
8939   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8940   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8941   //        T&         operator[](ptrdiff_t, T*);
8942   void addSubscriptOverloads() {
8943     for (BuiltinCandidateTypeSet::iterator
8944               Ptr = CandidateTypes[0].pointer_begin(),
8945            PtrEnd = CandidateTypes[0].pointer_end();
8946          Ptr != PtrEnd; ++Ptr) {
8947       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8948       QualType PointeeType = (*Ptr)->getPointeeType();
8949       if (!PointeeType->isObjectType())
8950         continue;
8951 
8952       // T& operator[](T*, ptrdiff_t)
8953       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8954     }
8955 
8956     for (BuiltinCandidateTypeSet::iterator
8957               Ptr = CandidateTypes[1].pointer_begin(),
8958            PtrEnd = CandidateTypes[1].pointer_end();
8959          Ptr != PtrEnd; ++Ptr) {
8960       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8961       QualType PointeeType = (*Ptr)->getPointeeType();
8962       if (!PointeeType->isObjectType())
8963         continue;
8964 
8965       // T& operator[](ptrdiff_t, T*)
8966       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8967     }
8968   }
8969 
8970   // C++ [over.built]p11:
8971   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8972   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8973   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8974   //    there exist candidate operator functions of the form
8975   //
8976   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8977   //
8978   //    where CV12 is the union of CV1 and CV2.
8979   void addArrowStarOverloads() {
8980     for (BuiltinCandidateTypeSet::iterator
8981              Ptr = CandidateTypes[0].pointer_begin(),
8982            PtrEnd = CandidateTypes[0].pointer_end();
8983          Ptr != PtrEnd; ++Ptr) {
8984       QualType C1Ty = (*Ptr);
8985       QualType C1;
8986       QualifierCollector Q1;
8987       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8988       if (!isa<RecordType>(C1))
8989         continue;
8990       // heuristic to reduce number of builtin candidates in the set.
8991       // Add volatile/restrict version only if there are conversions to a
8992       // volatile/restrict type.
8993       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8994         continue;
8995       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8996         continue;
8997       for (BuiltinCandidateTypeSet::iterator
8998                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8999              MemPtrEnd = CandidateTypes[1].member_pointer_end();
9000            MemPtr != MemPtrEnd; ++MemPtr) {
9001         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
9002         QualType C2 = QualType(mptr->getClass(), 0);
9003         C2 = C2.getUnqualifiedType();
9004         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9005           break;
9006         QualType ParamTypes[2] = { *Ptr, *MemPtr };
9007         // build CV12 T&
9008         QualType T = mptr->getPointeeType();
9009         if (!VisibleTypeConversionsQuals.hasVolatile() &&
9010             T.isVolatileQualified())
9011           continue;
9012         if (!VisibleTypeConversionsQuals.hasRestrict() &&
9013             T.isRestrictQualified())
9014           continue;
9015         T = Q1.apply(S.Context, T);
9016         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9017       }
9018     }
9019   }
9020 
9021   // Note that we don't consider the first argument, since it has been
9022   // contextually converted to bool long ago. The candidates below are
9023   // therefore added as binary.
9024   //
9025   // C++ [over.built]p25:
9026   //   For every type T, where T is a pointer, pointer-to-member, or scoped
9027   //   enumeration type, there exist candidate operator functions of the form
9028   //
9029   //        T        operator?(bool, T, T);
9030   //
9031   void addConditionalOperatorOverloads() {
9032     /// Set of (canonical) types that we've already handled.
9033     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9034 
9035     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9036       for (BuiltinCandidateTypeSet::iterator
9037                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
9038              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
9039            Ptr != PtrEnd; ++Ptr) {
9040         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
9041           continue;
9042 
9043         QualType ParamTypes[2] = { *Ptr, *Ptr };
9044         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9045       }
9046 
9047       for (BuiltinCandidateTypeSet::iterator
9048                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
9049              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
9050            MemPtr != MemPtrEnd; ++MemPtr) {
9051         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
9052           continue;
9053 
9054         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
9055         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9056       }
9057 
9058       if (S.getLangOpts().CPlusPlus11) {
9059         for (BuiltinCandidateTypeSet::iterator
9060                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
9061                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
9062              Enum != EnumEnd; ++Enum) {
9063           if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped())
9064             continue;
9065 
9066           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
9067             continue;
9068 
9069           QualType ParamTypes[2] = { *Enum, *Enum };
9070           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9071         }
9072       }
9073     }
9074   }
9075 };
9076 
9077 } // end anonymous namespace
9078 
9079 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
9080 /// operator overloads to the candidate set (C++ [over.built]), based
9081 /// on the operator @p Op and the arguments given. For example, if the
9082 /// operator is a binary '+', this routine might add "int
9083 /// operator+(int, int)" to cover integer addition.
9084 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9085                                         SourceLocation OpLoc,
9086                                         ArrayRef<Expr *> Args,
9087                                         OverloadCandidateSet &CandidateSet) {
9088   // Find all of the types that the arguments can convert to, but only
9089   // if the operator we're looking at has built-in operator candidates
9090   // that make use of these types. Also record whether we encounter non-record
9091   // candidate types or either arithmetic or enumeral candidate types.
9092   Qualifiers VisibleTypeConversionsQuals;
9093   VisibleTypeConversionsQuals.addConst();
9094   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
9095     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9096 
9097   bool HasNonRecordCandidateType = false;
9098   bool HasArithmeticOrEnumeralCandidateType = false;
9099   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9100   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9101     CandidateTypes.emplace_back(*this);
9102     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9103                                                  OpLoc,
9104                                                  true,
9105                                                  (Op == OO_Exclaim ||
9106                                                   Op == OO_AmpAmp ||
9107                                                   Op == OO_PipePipe),
9108                                                  VisibleTypeConversionsQuals);
9109     HasNonRecordCandidateType = HasNonRecordCandidateType ||
9110         CandidateTypes[ArgIdx].hasNonRecordTypes();
9111     HasArithmeticOrEnumeralCandidateType =
9112         HasArithmeticOrEnumeralCandidateType ||
9113         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9114   }
9115 
9116   // Exit early when no non-record types have been added to the candidate set
9117   // for any of the arguments to the operator.
9118   //
9119   // We can't exit early for !, ||, or &&, since there we have always have
9120   // 'bool' overloads.
9121   if (!HasNonRecordCandidateType &&
9122       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9123     return;
9124 
9125   // Setup an object to manage the common state for building overloads.
9126   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9127                                            VisibleTypeConversionsQuals,
9128                                            HasArithmeticOrEnumeralCandidateType,
9129                                            CandidateTypes, CandidateSet);
9130 
9131   // Dispatch over the operation to add in only those overloads which apply.
9132   switch (Op) {
9133   case OO_None:
9134   case NUM_OVERLOADED_OPERATORS:
9135     llvm_unreachable("Expected an overloaded operator");
9136 
9137   case OO_New:
9138   case OO_Delete:
9139   case OO_Array_New:
9140   case OO_Array_Delete:
9141   case OO_Call:
9142     llvm_unreachable(
9143                     "Special operators don't use AddBuiltinOperatorCandidates");
9144 
9145   case OO_Comma:
9146   case OO_Arrow:
9147   case OO_Coawait:
9148     // C++ [over.match.oper]p3:
9149     //   -- For the operator ',', the unary operator '&', the
9150     //      operator '->', or the operator 'co_await', the
9151     //      built-in candidates set is empty.
9152     break;
9153 
9154   case OO_Plus: // '+' is either unary or binary
9155     if (Args.size() == 1)
9156       OpBuilder.addUnaryPlusPointerOverloads();
9157     LLVM_FALLTHROUGH;
9158 
9159   case OO_Minus: // '-' is either unary or binary
9160     if (Args.size() == 1) {
9161       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9162     } else {
9163       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9164       OpBuilder.addGenericBinaryArithmeticOverloads();
9165       OpBuilder.addMatrixBinaryArithmeticOverloads();
9166     }
9167     break;
9168 
9169   case OO_Star: // '*' is either unary or binary
9170     if (Args.size() == 1)
9171       OpBuilder.addUnaryStarPointerOverloads();
9172     else {
9173       OpBuilder.addGenericBinaryArithmeticOverloads();
9174       OpBuilder.addMatrixBinaryArithmeticOverloads();
9175     }
9176     break;
9177 
9178   case OO_Slash:
9179     OpBuilder.addGenericBinaryArithmeticOverloads();
9180     break;
9181 
9182   case OO_PlusPlus:
9183   case OO_MinusMinus:
9184     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9185     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9186     break;
9187 
9188   case OO_EqualEqual:
9189   case OO_ExclaimEqual:
9190     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9191     LLVM_FALLTHROUGH;
9192 
9193   case OO_Less:
9194   case OO_Greater:
9195   case OO_LessEqual:
9196   case OO_GreaterEqual:
9197     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9198     OpBuilder.addGenericBinaryArithmeticOverloads();
9199     break;
9200 
9201   case OO_Spaceship:
9202     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9203     OpBuilder.addThreeWayArithmeticOverloads();
9204     break;
9205 
9206   case OO_Percent:
9207   case OO_Caret:
9208   case OO_Pipe:
9209   case OO_LessLess:
9210   case OO_GreaterGreater:
9211     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9212     break;
9213 
9214   case OO_Amp: // '&' is either unary or binary
9215     if (Args.size() == 1)
9216       // C++ [over.match.oper]p3:
9217       //   -- For the operator ',', the unary operator '&', or the
9218       //      operator '->', the built-in candidates set is empty.
9219       break;
9220 
9221     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9222     break;
9223 
9224   case OO_Tilde:
9225     OpBuilder.addUnaryTildePromotedIntegralOverloads();
9226     break;
9227 
9228   case OO_Equal:
9229     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9230     LLVM_FALLTHROUGH;
9231 
9232   case OO_PlusEqual:
9233   case OO_MinusEqual:
9234     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9235     LLVM_FALLTHROUGH;
9236 
9237   case OO_StarEqual:
9238   case OO_SlashEqual:
9239     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9240     break;
9241 
9242   case OO_PercentEqual:
9243   case OO_LessLessEqual:
9244   case OO_GreaterGreaterEqual:
9245   case OO_AmpEqual:
9246   case OO_CaretEqual:
9247   case OO_PipeEqual:
9248     OpBuilder.addAssignmentIntegralOverloads();
9249     break;
9250 
9251   case OO_Exclaim:
9252     OpBuilder.addExclaimOverload();
9253     break;
9254 
9255   case OO_AmpAmp:
9256   case OO_PipePipe:
9257     OpBuilder.addAmpAmpOrPipePipeOverload();
9258     break;
9259 
9260   case OO_Subscript:
9261     OpBuilder.addSubscriptOverloads();
9262     break;
9263 
9264   case OO_ArrowStar:
9265     OpBuilder.addArrowStarOverloads();
9266     break;
9267 
9268   case OO_Conditional:
9269     OpBuilder.addConditionalOperatorOverloads();
9270     OpBuilder.addGenericBinaryArithmeticOverloads();
9271     break;
9272   }
9273 }
9274 
9275 /// Add function candidates found via argument-dependent lookup
9276 /// to the set of overloading candidates.
9277 ///
9278 /// This routine performs argument-dependent name lookup based on the
9279 /// given function name (which may also be an operator name) and adds
9280 /// all of the overload candidates found by ADL to the overload
9281 /// candidate set (C++ [basic.lookup.argdep]).
9282 void
9283 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9284                                            SourceLocation Loc,
9285                                            ArrayRef<Expr *> Args,
9286                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
9287                                            OverloadCandidateSet& CandidateSet,
9288                                            bool PartialOverloading) {
9289   ADLResult Fns;
9290 
9291   // FIXME: This approach for uniquing ADL results (and removing
9292   // redundant candidates from the set) relies on pointer-equality,
9293   // which means we need to key off the canonical decl.  However,
9294   // always going back to the canonical decl might not get us the
9295   // right set of default arguments.  What default arguments are
9296   // we supposed to consider on ADL candidates, anyway?
9297 
9298   // FIXME: Pass in the explicit template arguments?
9299   ArgumentDependentLookup(Name, Loc, Args, Fns);
9300 
9301   // Erase all of the candidates we already knew about.
9302   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9303                                    CandEnd = CandidateSet.end();
9304        Cand != CandEnd; ++Cand)
9305     if (Cand->Function) {
9306       Fns.erase(Cand->Function);
9307       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9308         Fns.erase(FunTmpl);
9309     }
9310 
9311   // For each of the ADL candidates we found, add it to the overload
9312   // set.
9313   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9314     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9315 
9316     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9317       if (ExplicitTemplateArgs)
9318         continue;
9319 
9320       AddOverloadCandidate(
9321           FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
9322           PartialOverloading, /*AllowExplicit=*/true,
9323           /*AllowExplicitConversions=*/false, ADLCallKind::UsesADL);
9324       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) {
9325         AddOverloadCandidate(
9326             FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
9327             /*SuppressUserConversions=*/false, PartialOverloading,
9328             /*AllowExplicit=*/true, /*AllowExplicitConversions=*/false,
9329             ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed);
9330       }
9331     } else {
9332       auto *FTD = cast<FunctionTemplateDecl>(*I);
9333       AddTemplateOverloadCandidate(
9334           FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
9335           /*SuppressUserConversions=*/false, PartialOverloading,
9336           /*AllowExplicit=*/true, ADLCallKind::UsesADL);
9337       if (CandidateSet.getRewriteInfo().shouldAddReversed(
9338               Context, FTD->getTemplatedDecl())) {
9339         AddTemplateOverloadCandidate(
9340             FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
9341             CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
9342             /*AllowExplicit=*/true, ADLCallKind::UsesADL,
9343             OverloadCandidateParamOrder::Reversed);
9344       }
9345     }
9346   }
9347 }
9348 
9349 namespace {
9350 enum class Comparison { Equal, Better, Worse };
9351 }
9352 
9353 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9354 /// overload resolution.
9355 ///
9356 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9357 /// Cand1's first N enable_if attributes have precisely the same conditions as
9358 /// Cand2's first N enable_if attributes (where N = the number of enable_if
9359 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9360 ///
9361 /// Note that you can have a pair of candidates such that Cand1's enable_if
9362 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9363 /// worse than Cand1's.
9364 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9365                                        const FunctionDecl *Cand2) {
9366   // Common case: One (or both) decls don't have enable_if attrs.
9367   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9368   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9369   if (!Cand1Attr || !Cand2Attr) {
9370     if (Cand1Attr == Cand2Attr)
9371       return Comparison::Equal;
9372     return Cand1Attr ? Comparison::Better : Comparison::Worse;
9373   }
9374 
9375   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9376   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9377 
9378   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9379   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9380     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9381     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9382 
9383     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9384     // has fewer enable_if attributes than Cand2, and vice versa.
9385     if (!Cand1A)
9386       return Comparison::Worse;
9387     if (!Cand2A)
9388       return Comparison::Better;
9389 
9390     Cand1ID.clear();
9391     Cand2ID.clear();
9392 
9393     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9394     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9395     if (Cand1ID != Cand2ID)
9396       return Comparison::Worse;
9397   }
9398 
9399   return Comparison::Equal;
9400 }
9401 
9402 static Comparison
9403 isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9404                               const OverloadCandidate &Cand2) {
9405   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9406       !Cand2.Function->isMultiVersion())
9407     return Comparison::Equal;
9408 
9409   // If both are invalid, they are equal. If one of them is invalid, the other
9410   // is better.
9411   if (Cand1.Function->isInvalidDecl()) {
9412     if (Cand2.Function->isInvalidDecl())
9413       return Comparison::Equal;
9414     return Comparison::Worse;
9415   }
9416   if (Cand2.Function->isInvalidDecl())
9417     return Comparison::Better;
9418 
9419   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9420   // cpu_dispatch, else arbitrarily based on the identifiers.
9421   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9422   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9423   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9424   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9425 
9426   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9427     return Comparison::Equal;
9428 
9429   if (Cand1CPUDisp && !Cand2CPUDisp)
9430     return Comparison::Better;
9431   if (Cand2CPUDisp && !Cand1CPUDisp)
9432     return Comparison::Worse;
9433 
9434   if (Cand1CPUSpec && Cand2CPUSpec) {
9435     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9436       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
9437                  ? Comparison::Better
9438                  : Comparison::Worse;
9439 
9440     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9441         FirstDiff = std::mismatch(
9442             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9443             Cand2CPUSpec->cpus_begin(),
9444             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9445               return LHS->getName() == RHS->getName();
9446             });
9447 
9448     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9449            "Two different cpu-specific versions should not have the same "
9450            "identifier list, otherwise they'd be the same decl!");
9451     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
9452                ? Comparison::Better
9453                : Comparison::Worse;
9454   }
9455   llvm_unreachable("No way to get here unless both had cpu_dispatch");
9456 }
9457 
9458 /// Compute the type of the implicit object parameter for the given function,
9459 /// if any. Returns None if there is no implicit object parameter, and a null
9460 /// QualType if there is a 'matches anything' implicit object parameter.
9461 static Optional<QualType> getImplicitObjectParamType(ASTContext &Context,
9462                                                      const FunctionDecl *F) {
9463   if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
9464     return llvm::None;
9465 
9466   auto *M = cast<CXXMethodDecl>(F);
9467   // Static member functions' object parameters match all types.
9468   if (M->isStatic())
9469     return QualType();
9470 
9471   QualType T = M->getThisObjectType();
9472   if (M->getRefQualifier() == RQ_RValue)
9473     return Context.getRValueReferenceType(T);
9474   return Context.getLValueReferenceType(T);
9475 }
9476 
9477 static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1,
9478                                    const FunctionDecl *F2, unsigned NumParams) {
9479   if (declaresSameEntity(F1, F2))
9480     return true;
9481 
9482   auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
9483     if (First) {
9484       if (Optional<QualType> T = getImplicitObjectParamType(Context, F))
9485         return *T;
9486     }
9487     assert(I < F->getNumParams());
9488     return F->getParamDecl(I++)->getType();
9489   };
9490 
9491   unsigned I1 = 0, I2 = 0;
9492   for (unsigned I = 0; I != NumParams; ++I) {
9493     QualType T1 = NextParam(F1, I1, I == 0);
9494     QualType T2 = NextParam(F2, I2, I == 0);
9495     if (!T1.isNull() && !T1.isNull() && !Context.hasSameUnqualifiedType(T1, T2))
9496       return false;
9497   }
9498   return true;
9499 }
9500 
9501 /// isBetterOverloadCandidate - Determines whether the first overload
9502 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9503 bool clang::isBetterOverloadCandidate(
9504     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9505     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9506   // Define viable functions to be better candidates than non-viable
9507   // functions.
9508   if (!Cand2.Viable)
9509     return Cand1.Viable;
9510   else if (!Cand1.Viable)
9511     return false;
9512 
9513   // C++ [over.match.best]p1:
9514   //
9515   //   -- if F is a static member function, ICS1(F) is defined such
9516   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9517   //      any function G, and, symmetrically, ICS1(G) is neither
9518   //      better nor worse than ICS1(F).
9519   unsigned StartArg = 0;
9520   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9521     StartArg = 1;
9522 
9523   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9524     // We don't allow incompatible pointer conversions in C++.
9525     if (!S.getLangOpts().CPlusPlus)
9526       return ICS.isStandard() &&
9527              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9528 
9529     // The only ill-formed conversion we allow in C++ is the string literal to
9530     // char* conversion, which is only considered ill-formed after C++11.
9531     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9532            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9533   };
9534 
9535   // Define functions that don't require ill-formed conversions for a given
9536   // argument to be better candidates than functions that do.
9537   unsigned NumArgs = Cand1.Conversions.size();
9538   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9539   bool HasBetterConversion = false;
9540   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9541     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9542     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9543     if (Cand1Bad != Cand2Bad) {
9544       if (Cand1Bad)
9545         return false;
9546       HasBetterConversion = true;
9547     }
9548   }
9549 
9550   if (HasBetterConversion)
9551     return true;
9552 
9553   // C++ [over.match.best]p1:
9554   //   A viable function F1 is defined to be a better function than another
9555   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9556   //   conversion sequence than ICSi(F2), and then...
9557   bool HasWorseConversion = false;
9558   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9559     switch (CompareImplicitConversionSequences(S, Loc,
9560                                                Cand1.Conversions[ArgIdx],
9561                                                Cand2.Conversions[ArgIdx])) {
9562     case ImplicitConversionSequence::Better:
9563       // Cand1 has a better conversion sequence.
9564       HasBetterConversion = true;
9565       break;
9566 
9567     case ImplicitConversionSequence::Worse:
9568       if (Cand1.Function && Cand2.Function &&
9569           Cand1.isReversed() != Cand2.isReversed() &&
9570           haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function,
9571                                  NumArgs)) {
9572         // Work around large-scale breakage caused by considering reversed
9573         // forms of operator== in C++20:
9574         //
9575         // When comparing a function against a reversed function with the same
9576         // parameter types, if we have a better conversion for one argument and
9577         // a worse conversion for the other, the implicit conversion sequences
9578         // are treated as being equally good.
9579         //
9580         // This prevents a comparison function from being considered ambiguous
9581         // with a reversed form that is written in the same way.
9582         //
9583         // We diagnose this as an extension from CreateOverloadedBinOp.
9584         HasWorseConversion = true;
9585         break;
9586       }
9587 
9588       // Cand1 can't be better than Cand2.
9589       return false;
9590 
9591     case ImplicitConversionSequence::Indistinguishable:
9592       // Do nothing.
9593       break;
9594     }
9595   }
9596 
9597   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9598   //       ICSj(F2), or, if not that,
9599   if (HasBetterConversion && !HasWorseConversion)
9600     return true;
9601 
9602   //   -- the context is an initialization by user-defined conversion
9603   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9604   //      from the return type of F1 to the destination type (i.e.,
9605   //      the type of the entity being initialized) is a better
9606   //      conversion sequence than the standard conversion sequence
9607   //      from the return type of F2 to the destination type.
9608   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9609       Cand1.Function && Cand2.Function &&
9610       isa<CXXConversionDecl>(Cand1.Function) &&
9611       isa<CXXConversionDecl>(Cand2.Function)) {
9612     // First check whether we prefer one of the conversion functions over the
9613     // other. This only distinguishes the results in non-standard, extension
9614     // cases such as the conversion from a lambda closure type to a function
9615     // pointer or block.
9616     ImplicitConversionSequence::CompareKind Result =
9617         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9618     if (Result == ImplicitConversionSequence::Indistinguishable)
9619       Result = CompareStandardConversionSequences(S, Loc,
9620                                                   Cand1.FinalConversion,
9621                                                   Cand2.FinalConversion);
9622 
9623     if (Result != ImplicitConversionSequence::Indistinguishable)
9624       return Result == ImplicitConversionSequence::Better;
9625 
9626     // FIXME: Compare kind of reference binding if conversion functions
9627     // convert to a reference type used in direct reference binding, per
9628     // C++14 [over.match.best]p1 section 2 bullet 3.
9629   }
9630 
9631   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9632   // as combined with the resolution to CWG issue 243.
9633   //
9634   // When the context is initialization by constructor ([over.match.ctor] or
9635   // either phase of [over.match.list]), a constructor is preferred over
9636   // a conversion function.
9637   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9638       Cand1.Function && Cand2.Function &&
9639       isa<CXXConstructorDecl>(Cand1.Function) !=
9640           isa<CXXConstructorDecl>(Cand2.Function))
9641     return isa<CXXConstructorDecl>(Cand1.Function);
9642 
9643   //    -- F1 is a non-template function and F2 is a function template
9644   //       specialization, or, if not that,
9645   bool Cand1IsSpecialization = Cand1.Function &&
9646                                Cand1.Function->getPrimaryTemplate();
9647   bool Cand2IsSpecialization = Cand2.Function &&
9648                                Cand2.Function->getPrimaryTemplate();
9649   if (Cand1IsSpecialization != Cand2IsSpecialization)
9650     return Cand2IsSpecialization;
9651 
9652   //   -- F1 and F2 are function template specializations, and the function
9653   //      template for F1 is more specialized than the template for F2
9654   //      according to the partial ordering rules described in 14.5.5.2, or,
9655   //      if not that,
9656   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9657     if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
9658             Cand1.Function->getPrimaryTemplate(),
9659             Cand2.Function->getPrimaryTemplate(), Loc,
9660             isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
9661                                                    : TPOC_Call,
9662             Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments,
9663             Cand1.isReversed() ^ Cand2.isReversed()))
9664       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9665   }
9666 
9667   //   -— F1 and F2 are non-template functions with the same
9668   //      parameter-type-lists, and F1 is more constrained than F2 [...],
9669   if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization &&
9670       !Cand2IsSpecialization && Cand1.Function->hasPrototype() &&
9671       Cand2.Function->hasPrototype()) {
9672     auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType());
9673     auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType());
9674     if (PT1->getNumParams() == PT2->getNumParams() &&
9675         PT1->isVariadic() == PT2->isVariadic() &&
9676         S.FunctionParamTypesAreEqual(PT1, PT2)) {
9677       Expr *RC1 = Cand1.Function->getTrailingRequiresClause();
9678       Expr *RC2 = Cand2.Function->getTrailingRequiresClause();
9679       if (RC1 && RC2) {
9680         bool AtLeastAsConstrained1, AtLeastAsConstrained2;
9681         if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function,
9682                                      {RC2}, AtLeastAsConstrained1) ||
9683             S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function,
9684                                      {RC1}, AtLeastAsConstrained2))
9685           return false;
9686         if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
9687           return AtLeastAsConstrained1;
9688       } else if (RC1 || RC2) {
9689         return RC1 != nullptr;
9690       }
9691     }
9692   }
9693 
9694   //   -- F1 is a constructor for a class D, F2 is a constructor for a base
9695   //      class B of D, and for all arguments the corresponding parameters of
9696   //      F1 and F2 have the same type.
9697   // FIXME: Implement the "all parameters have the same type" check.
9698   bool Cand1IsInherited =
9699       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9700   bool Cand2IsInherited =
9701       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9702   if (Cand1IsInherited != Cand2IsInherited)
9703     return Cand2IsInherited;
9704   else if (Cand1IsInherited) {
9705     assert(Cand2IsInherited);
9706     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9707     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9708     if (Cand1Class->isDerivedFrom(Cand2Class))
9709       return true;
9710     if (Cand2Class->isDerivedFrom(Cand1Class))
9711       return false;
9712     // Inherited from sibling base classes: still ambiguous.
9713   }
9714 
9715   //   -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
9716   //   -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
9717   //      with reversed order of parameters and F1 is not
9718   //
9719   // We rank reversed + different operator as worse than just reversed, but
9720   // that comparison can never happen, because we only consider reversing for
9721   // the maximally-rewritten operator (== or <=>).
9722   if (Cand1.RewriteKind != Cand2.RewriteKind)
9723     return Cand1.RewriteKind < Cand2.RewriteKind;
9724 
9725   // Check C++17 tie-breakers for deduction guides.
9726   {
9727     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9728     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9729     if (Guide1 && Guide2) {
9730       //  -- F1 is generated from a deduction-guide and F2 is not
9731       if (Guide1->isImplicit() != Guide2->isImplicit())
9732         return Guide2->isImplicit();
9733 
9734       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9735       if (Guide1->isCopyDeductionCandidate())
9736         return true;
9737     }
9738   }
9739 
9740   // Check for enable_if value-based overload resolution.
9741   if (Cand1.Function && Cand2.Function) {
9742     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9743     if (Cmp != Comparison::Equal)
9744       return Cmp == Comparison::Better;
9745   }
9746 
9747   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9748     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9749     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9750            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9751   }
9752 
9753   bool HasPS1 = Cand1.Function != nullptr &&
9754                 functionHasPassObjectSizeParams(Cand1.Function);
9755   bool HasPS2 = Cand2.Function != nullptr &&
9756                 functionHasPassObjectSizeParams(Cand2.Function);
9757   if (HasPS1 != HasPS2 && HasPS1)
9758     return true;
9759 
9760   Comparison MV = isBetterMultiversionCandidate(Cand1, Cand2);
9761   return MV == Comparison::Better;
9762 }
9763 
9764 /// Determine whether two declarations are "equivalent" for the purposes of
9765 /// name lookup and overload resolution. This applies when the same internal/no
9766 /// linkage entity is defined by two modules (probably by textually including
9767 /// the same header). In such a case, we don't consider the declarations to
9768 /// declare the same entity, but we also don't want lookups with both
9769 /// declarations visible to be ambiguous in some cases (this happens when using
9770 /// a modularized libstdc++).
9771 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9772                                                   const NamedDecl *B) {
9773   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9774   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9775   if (!VA || !VB)
9776     return false;
9777 
9778   // The declarations must be declaring the same name as an internal linkage
9779   // entity in different modules.
9780   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9781           VB->getDeclContext()->getRedeclContext()) ||
9782       getOwningModule(VA) == getOwningModule(VB) ||
9783       VA->isExternallyVisible() || VB->isExternallyVisible())
9784     return false;
9785 
9786   // Check that the declarations appear to be equivalent.
9787   //
9788   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9789   // For constants and functions, we should check the initializer or body is
9790   // the same. For non-constant variables, we shouldn't allow it at all.
9791   if (Context.hasSameType(VA->getType(), VB->getType()))
9792     return true;
9793 
9794   // Enum constants within unnamed enumerations will have different types, but
9795   // may still be similar enough to be interchangeable for our purposes.
9796   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9797     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9798       // Only handle anonymous enums. If the enumerations were named and
9799       // equivalent, they would have been merged to the same type.
9800       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9801       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9802       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9803           !Context.hasSameType(EnumA->getIntegerType(),
9804                                EnumB->getIntegerType()))
9805         return false;
9806       // Allow this only if the value is the same for both enumerators.
9807       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9808     }
9809   }
9810 
9811   // Nothing else is sufficiently similar.
9812   return false;
9813 }
9814 
9815 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9816     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9817   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9818 
9819   Module *M = getOwningModule(D);
9820   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9821       << !M << (M ? M->getFullModuleName() : "");
9822 
9823   for (auto *E : Equiv) {
9824     Module *M = getOwningModule(E);
9825     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9826         << !M << (M ? M->getFullModuleName() : "");
9827   }
9828 }
9829 
9830 /// Computes the best viable function (C++ 13.3.3)
9831 /// within an overload candidate set.
9832 ///
9833 /// \param Loc The location of the function name (or operator symbol) for
9834 /// which overload resolution occurs.
9835 ///
9836 /// \param Best If overload resolution was successful or found a deleted
9837 /// function, \p Best points to the candidate function found.
9838 ///
9839 /// \returns The result of overload resolution.
9840 OverloadingResult
9841 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9842                                          iterator &Best) {
9843   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9844   std::transform(begin(), end(), std::back_inserter(Candidates),
9845                  [](OverloadCandidate &Cand) { return &Cand; });
9846 
9847   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9848   // are accepted by both clang and NVCC. However, during a particular
9849   // compilation mode only one call variant is viable. We need to
9850   // exclude non-viable overload candidates from consideration based
9851   // only on their host/device attributes. Specifically, if one
9852   // candidate call is WrongSide and the other is SameSide, we ignore
9853   // the WrongSide candidate.
9854   if (S.getLangOpts().CUDA) {
9855     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9856     bool ContainsSameSideCandidate =
9857         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9858           // Check viable function only.
9859           return Cand->Viable && Cand->Function &&
9860                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9861                      Sema::CFP_SameSide;
9862         });
9863     if (ContainsSameSideCandidate) {
9864       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9865         // Check viable function only to avoid unnecessary data copying/moving.
9866         return Cand->Viable && Cand->Function &&
9867                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9868                    Sema::CFP_WrongSide;
9869       };
9870       llvm::erase_if(Candidates, IsWrongSideCandidate);
9871     }
9872   }
9873 
9874   // Find the best viable function.
9875   Best = end();
9876   for (auto *Cand : Candidates) {
9877     Cand->Best = false;
9878     if (Cand->Viable)
9879       if (Best == end() ||
9880           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9881         Best = Cand;
9882   }
9883 
9884   // If we didn't find any viable functions, abort.
9885   if (Best == end())
9886     return OR_No_Viable_Function;
9887 
9888   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9889 
9890   llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
9891   PendingBest.push_back(&*Best);
9892   Best->Best = true;
9893 
9894   // Make sure that this function is better than every other viable
9895   // function. If not, we have an ambiguity.
9896   while (!PendingBest.empty()) {
9897     auto *Curr = PendingBest.pop_back_val();
9898     for (auto *Cand : Candidates) {
9899       if (Cand->Viable && !Cand->Best &&
9900           !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
9901         PendingBest.push_back(Cand);
9902         Cand->Best = true;
9903 
9904         if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
9905                                                      Curr->Function))
9906           EquivalentCands.push_back(Cand->Function);
9907         else
9908           Best = end();
9909       }
9910     }
9911   }
9912 
9913   // If we found more than one best candidate, this is ambiguous.
9914   if (Best == end())
9915     return OR_Ambiguous;
9916 
9917   // Best is the best viable function.
9918   if (Best->Function && Best->Function->isDeleted())
9919     return OR_Deleted;
9920 
9921   if (!EquivalentCands.empty())
9922     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9923                                                     EquivalentCands);
9924 
9925   return OR_Success;
9926 }
9927 
9928 namespace {
9929 
9930 enum OverloadCandidateKind {
9931   oc_function,
9932   oc_method,
9933   oc_reversed_binary_operator,
9934   oc_constructor,
9935   oc_implicit_default_constructor,
9936   oc_implicit_copy_constructor,
9937   oc_implicit_move_constructor,
9938   oc_implicit_copy_assignment,
9939   oc_implicit_move_assignment,
9940   oc_implicit_equality_comparison,
9941   oc_inherited_constructor
9942 };
9943 
9944 enum OverloadCandidateSelect {
9945   ocs_non_template,
9946   ocs_template,
9947   ocs_described_template,
9948 };
9949 
9950 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
9951 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9952                           OverloadCandidateRewriteKind CRK,
9953                           std::string &Description) {
9954 
9955   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9956   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9957     isTemplate = true;
9958     Description = S.getTemplateArgumentBindingsText(
9959         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9960   }
9961 
9962   OverloadCandidateSelect Select = [&]() {
9963     if (!Description.empty())
9964       return ocs_described_template;
9965     return isTemplate ? ocs_template : ocs_non_template;
9966   }();
9967 
9968   OverloadCandidateKind Kind = [&]() {
9969     if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
9970       return oc_implicit_equality_comparison;
9971 
9972     if (CRK & CRK_Reversed)
9973       return oc_reversed_binary_operator;
9974 
9975     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9976       if (!Ctor->isImplicit()) {
9977         if (isa<ConstructorUsingShadowDecl>(Found))
9978           return oc_inherited_constructor;
9979         else
9980           return oc_constructor;
9981       }
9982 
9983       if (Ctor->isDefaultConstructor())
9984         return oc_implicit_default_constructor;
9985 
9986       if (Ctor->isMoveConstructor())
9987         return oc_implicit_move_constructor;
9988 
9989       assert(Ctor->isCopyConstructor() &&
9990              "unexpected sort of implicit constructor");
9991       return oc_implicit_copy_constructor;
9992     }
9993 
9994     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9995       // This actually gets spelled 'candidate function' for now, but
9996       // it doesn't hurt to split it out.
9997       if (!Meth->isImplicit())
9998         return oc_method;
9999 
10000       if (Meth->isMoveAssignmentOperator())
10001         return oc_implicit_move_assignment;
10002 
10003       if (Meth->isCopyAssignmentOperator())
10004         return oc_implicit_copy_assignment;
10005 
10006       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
10007       return oc_method;
10008     }
10009 
10010     return oc_function;
10011   }();
10012 
10013   return std::make_pair(Kind, Select);
10014 }
10015 
10016 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
10017   // FIXME: It'd be nice to only emit a note once per using-decl per overload
10018   // set.
10019   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
10020     S.Diag(FoundDecl->getLocation(),
10021            diag::note_ovl_candidate_inherited_constructor)
10022       << Shadow->getNominatedBaseClass();
10023 }
10024 
10025 } // end anonymous namespace
10026 
10027 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
10028                                     const FunctionDecl *FD) {
10029   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
10030     bool AlwaysTrue;
10031     if (EnableIf->getCond()->isValueDependent() ||
10032         !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
10033       return false;
10034     if (!AlwaysTrue)
10035       return false;
10036   }
10037   return true;
10038 }
10039 
10040 /// Returns true if we can take the address of the function.
10041 ///
10042 /// \param Complain - If true, we'll emit a diagnostic
10043 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
10044 ///   we in overload resolution?
10045 /// \param Loc - The location of the statement we're complaining about. Ignored
10046 ///   if we're not complaining, or if we're in overload resolution.
10047 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
10048                                               bool Complain,
10049                                               bool InOverloadResolution,
10050                                               SourceLocation Loc) {
10051   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
10052     if (Complain) {
10053       if (InOverloadResolution)
10054         S.Diag(FD->getBeginLoc(),
10055                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
10056       else
10057         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
10058     }
10059     return false;
10060   }
10061 
10062   if (FD->getTrailingRequiresClause()) {
10063     ConstraintSatisfaction Satisfaction;
10064     if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
10065       return false;
10066     if (!Satisfaction.IsSatisfied) {
10067       if (Complain) {
10068         if (InOverloadResolution)
10069           S.Diag(FD->getBeginLoc(),
10070                  diag::note_ovl_candidate_unsatisfied_constraints);
10071         else
10072           S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
10073               << FD;
10074         S.DiagnoseUnsatisfiedConstraint(Satisfaction);
10075       }
10076       return false;
10077     }
10078   }
10079 
10080   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
10081     return P->hasAttr<PassObjectSizeAttr>();
10082   });
10083   if (I == FD->param_end())
10084     return true;
10085 
10086   if (Complain) {
10087     // Add one to ParamNo because it's user-facing
10088     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
10089     if (InOverloadResolution)
10090       S.Diag(FD->getLocation(),
10091              diag::note_ovl_candidate_has_pass_object_size_params)
10092           << ParamNo;
10093     else
10094       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
10095           << FD << ParamNo;
10096   }
10097   return false;
10098 }
10099 
10100 static bool checkAddressOfCandidateIsAvailable(Sema &S,
10101                                                const FunctionDecl *FD) {
10102   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
10103                                            /*InOverloadResolution=*/true,
10104                                            /*Loc=*/SourceLocation());
10105 }
10106 
10107 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10108                                              bool Complain,
10109                                              SourceLocation Loc) {
10110   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
10111                                              /*InOverloadResolution=*/false,
10112                                              Loc);
10113 }
10114 
10115 // Notes the location of an overload candidate.
10116 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
10117                                  OverloadCandidateRewriteKind RewriteKind,
10118                                  QualType DestType, bool TakingAddress) {
10119   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
10120     return;
10121   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
10122       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
10123     return;
10124 
10125   std::string FnDesc;
10126   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
10127       ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
10128   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
10129                          << (unsigned)KSPair.first << (unsigned)KSPair.second
10130                          << Fn << FnDesc;
10131 
10132   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
10133   Diag(Fn->getLocation(), PD);
10134   MaybeEmitInheritedConstructorNote(*this, Found);
10135 }
10136 
10137 static void
10138 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
10139   // Perhaps the ambiguity was caused by two atomic constraints that are
10140   // 'identical' but not equivalent:
10141   //
10142   // void foo() requires (sizeof(T) > 4) { } // #1
10143   // void foo() requires (sizeof(T) > 4) && T::value { } // #2
10144   //
10145   // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
10146   // #2 to subsume #1, but these constraint are not considered equivalent
10147   // according to the subsumption rules because they are not the same
10148   // source-level construct. This behavior is quite confusing and we should try
10149   // to help the user figure out what happened.
10150 
10151   SmallVector<const Expr *, 3> FirstAC, SecondAC;
10152   FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
10153   for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10154     if (!I->Function)
10155       continue;
10156     SmallVector<const Expr *, 3> AC;
10157     if (auto *Template = I->Function->getPrimaryTemplate())
10158       Template->getAssociatedConstraints(AC);
10159     else
10160       I->Function->getAssociatedConstraints(AC);
10161     if (AC.empty())
10162       continue;
10163     if (FirstCand == nullptr) {
10164       FirstCand = I->Function;
10165       FirstAC = AC;
10166     } else if (SecondCand == nullptr) {
10167       SecondCand = I->Function;
10168       SecondAC = AC;
10169     } else {
10170       // We have more than one pair of constrained functions - this check is
10171       // expensive and we'd rather not try to diagnose it.
10172       return;
10173     }
10174   }
10175   if (!SecondCand)
10176     return;
10177   // The diagnostic can only happen if there are associated constraints on
10178   // both sides (there needs to be some identical atomic constraint).
10179   if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
10180                                                       SecondCand, SecondAC))
10181     // Just show the user one diagnostic, they'll probably figure it out
10182     // from here.
10183     return;
10184 }
10185 
10186 // Notes the location of all overload candidates designated through
10187 // OverloadedExpr
10188 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
10189                                      bool TakingAddress) {
10190   assert(OverloadedExpr->getType() == Context.OverloadTy);
10191 
10192   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
10193   OverloadExpr *OvlExpr = Ovl.Expression;
10194 
10195   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10196                             IEnd = OvlExpr->decls_end();
10197        I != IEnd; ++I) {
10198     if (FunctionTemplateDecl *FunTmpl =
10199                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
10200       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
10201                             TakingAddress);
10202     } else if (FunctionDecl *Fun
10203                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
10204       NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
10205     }
10206   }
10207 }
10208 
10209 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
10210 /// "lead" diagnostic; it will be given two arguments, the source and
10211 /// target types of the conversion.
10212 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
10213                                  Sema &S,
10214                                  SourceLocation CaretLoc,
10215                                  const PartialDiagnostic &PDiag) const {
10216   S.Diag(CaretLoc, PDiag)
10217     << Ambiguous.getFromType() << Ambiguous.getToType();
10218   // FIXME: The note limiting machinery is borrowed from
10219   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
10220   // refactoring here.
10221   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10222   unsigned CandsShown = 0;
10223   AmbiguousConversionSequence::const_iterator I, E;
10224   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
10225     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10226       break;
10227     ++CandsShown;
10228     S.NoteOverloadCandidate(I->first, I->second);
10229   }
10230   if (I != E)
10231     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
10232 }
10233 
10234 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
10235                                   unsigned I, bool TakingCandidateAddress) {
10236   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
10237   assert(Conv.isBad());
10238   assert(Cand->Function && "for now, candidate must be a function");
10239   FunctionDecl *Fn = Cand->Function;
10240 
10241   // There's a conversion slot for the object argument if this is a
10242   // non-constructor method.  Note that 'I' corresponds the
10243   // conversion-slot index.
10244   bool isObjectArgument = false;
10245   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
10246     if (I == 0)
10247       isObjectArgument = true;
10248     else
10249       I--;
10250   }
10251 
10252   std::string FnDesc;
10253   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10254       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
10255                                 FnDesc);
10256 
10257   Expr *FromExpr = Conv.Bad.FromExpr;
10258   QualType FromTy = Conv.Bad.getFromType();
10259   QualType ToTy = Conv.Bad.getToType();
10260 
10261   if (FromTy == S.Context.OverloadTy) {
10262     assert(FromExpr && "overload set argument came from implicit argument?");
10263     Expr *E = FromExpr->IgnoreParens();
10264     if (isa<UnaryOperator>(E))
10265       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
10266     DeclarationName Name = cast<OverloadExpr>(E)->getName();
10267 
10268     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
10269         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10270         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
10271         << Name << I + 1;
10272     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10273     return;
10274   }
10275 
10276   // Do some hand-waving analysis to see if the non-viability is due
10277   // to a qualifier mismatch.
10278   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
10279   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
10280   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
10281     CToTy = RT->getPointeeType();
10282   else {
10283     // TODO: detect and diagnose the full richness of const mismatches.
10284     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
10285       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
10286         CFromTy = FromPT->getPointeeType();
10287         CToTy = ToPT->getPointeeType();
10288       }
10289   }
10290 
10291   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
10292       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
10293     Qualifiers FromQs = CFromTy.getQualifiers();
10294     Qualifiers ToQs = CToTy.getQualifiers();
10295 
10296     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
10297       if (isObjectArgument)
10298         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
10299             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10300             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10301             << FromQs.getAddressSpace() << ToQs.getAddressSpace();
10302       else
10303         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
10304             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10305             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10306             << FromQs.getAddressSpace() << ToQs.getAddressSpace()
10307             << ToTy->isReferenceType() << I + 1;
10308       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10309       return;
10310     }
10311 
10312     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10313       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
10314           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10315           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10316           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
10317           << (unsigned)isObjectArgument << I + 1;
10318       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10319       return;
10320     }
10321 
10322     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
10323       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
10324           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10325           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10326           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
10327           << (unsigned)isObjectArgument << I + 1;
10328       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10329       return;
10330     }
10331 
10332     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
10333       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
10334           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10335           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10336           << FromQs.hasUnaligned() << I + 1;
10337       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10338       return;
10339     }
10340 
10341     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
10342     assert(CVR && "unexpected qualifiers mismatch");
10343 
10344     if (isObjectArgument) {
10345       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
10346           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10347           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10348           << (CVR - 1);
10349     } else {
10350       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
10351           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10352           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10353           << (CVR - 1) << I + 1;
10354     }
10355     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10356     return;
10357   }
10358 
10359   // Special diagnostic for failure to convert an initializer list, since
10360   // telling the user that it has type void is not useful.
10361   if (FromExpr && isa<InitListExpr>(FromExpr)) {
10362     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
10363         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10364         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10365         << ToTy << (unsigned)isObjectArgument << I + 1;
10366     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10367     return;
10368   }
10369 
10370   // Diagnose references or pointers to incomplete types differently,
10371   // since it's far from impossible that the incompleteness triggered
10372   // the failure.
10373   QualType TempFromTy = FromTy.getNonReferenceType();
10374   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
10375     TempFromTy = PTy->getPointeeType();
10376   if (TempFromTy->isIncompleteType()) {
10377     // Emit the generic diagnostic and, optionally, add the hints to it.
10378     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
10379         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10380         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10381         << ToTy << (unsigned)isObjectArgument << I + 1
10382         << (unsigned)(Cand->Fix.Kind);
10383 
10384     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10385     return;
10386   }
10387 
10388   // Diagnose base -> derived pointer conversions.
10389   unsigned BaseToDerivedConversion = 0;
10390   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
10391     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
10392       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10393                                                FromPtrTy->getPointeeType()) &&
10394           !FromPtrTy->getPointeeType()->isIncompleteType() &&
10395           !ToPtrTy->getPointeeType()->isIncompleteType() &&
10396           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
10397                           FromPtrTy->getPointeeType()))
10398         BaseToDerivedConversion = 1;
10399     }
10400   } else if (const ObjCObjectPointerType *FromPtrTy
10401                                     = FromTy->getAs<ObjCObjectPointerType>()) {
10402     if (const ObjCObjectPointerType *ToPtrTy
10403                                         = ToTy->getAs<ObjCObjectPointerType>())
10404       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
10405         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
10406           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10407                                                 FromPtrTy->getPointeeType()) &&
10408               FromIface->isSuperClassOf(ToIface))
10409             BaseToDerivedConversion = 2;
10410   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
10411     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
10412         !FromTy->isIncompleteType() &&
10413         !ToRefTy->getPointeeType()->isIncompleteType() &&
10414         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
10415       BaseToDerivedConversion = 3;
10416     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
10417                ToTy.getNonReferenceType().getCanonicalType() ==
10418                FromTy.getNonReferenceType().getCanonicalType()) {
10419       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
10420           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10421           << (unsigned)isObjectArgument << I + 1
10422           << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
10423       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10424       return;
10425     }
10426   }
10427 
10428   if (BaseToDerivedConversion) {
10429     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
10430         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10431         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10432         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
10433     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10434     return;
10435   }
10436 
10437   if (isa<ObjCObjectPointerType>(CFromTy) &&
10438       isa<PointerType>(CToTy)) {
10439       Qualifiers FromQs = CFromTy.getQualifiers();
10440       Qualifiers ToQs = CToTy.getQualifiers();
10441       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10442         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
10443             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10444             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10445             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
10446         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10447         return;
10448       }
10449   }
10450 
10451   if (TakingCandidateAddress &&
10452       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
10453     return;
10454 
10455   // Emit the generic diagnostic and, optionally, add the hints to it.
10456   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
10457   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10458         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10459         << ToTy << (unsigned)isObjectArgument << I + 1
10460         << (unsigned)(Cand->Fix.Kind);
10461 
10462   // If we can fix the conversion, suggest the FixIts.
10463   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
10464        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
10465     FDiag << *HI;
10466   S.Diag(Fn->getLocation(), FDiag);
10467 
10468   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10469 }
10470 
10471 /// Additional arity mismatch diagnosis specific to a function overload
10472 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
10473 /// over a candidate in any candidate set.
10474 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
10475                                unsigned NumArgs) {
10476   FunctionDecl *Fn = Cand->Function;
10477   unsigned MinParams = Fn->getMinRequiredArguments();
10478 
10479   // With invalid overloaded operators, it's possible that we think we
10480   // have an arity mismatch when in fact it looks like we have the
10481   // right number of arguments, because only overloaded operators have
10482   // the weird behavior of overloading member and non-member functions.
10483   // Just don't report anything.
10484   if (Fn->isInvalidDecl() &&
10485       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
10486     return true;
10487 
10488   if (NumArgs < MinParams) {
10489     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
10490            (Cand->FailureKind == ovl_fail_bad_deduction &&
10491             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
10492   } else {
10493     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
10494            (Cand->FailureKind == ovl_fail_bad_deduction &&
10495             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
10496   }
10497 
10498   return false;
10499 }
10500 
10501 /// General arity mismatch diagnosis over a candidate in a candidate set.
10502 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
10503                                   unsigned NumFormalArgs) {
10504   assert(isa<FunctionDecl>(D) &&
10505       "The templated declaration should at least be a function"
10506       " when diagnosing bad template argument deduction due to too many"
10507       " or too few arguments");
10508 
10509   FunctionDecl *Fn = cast<FunctionDecl>(D);
10510 
10511   // TODO: treat calls to a missing default constructor as a special case
10512   const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
10513   unsigned MinParams = Fn->getMinRequiredArguments();
10514 
10515   // at least / at most / exactly
10516   unsigned mode, modeCount;
10517   if (NumFormalArgs < MinParams) {
10518     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
10519         FnTy->isTemplateVariadic())
10520       mode = 0; // "at least"
10521     else
10522       mode = 2; // "exactly"
10523     modeCount = MinParams;
10524   } else {
10525     if (MinParams != FnTy->getNumParams())
10526       mode = 1; // "at most"
10527     else
10528       mode = 2; // "exactly"
10529     modeCount = FnTy->getNumParams();
10530   }
10531 
10532   std::string Description;
10533   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10534       ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
10535 
10536   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10537     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10538         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10539         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
10540   else
10541     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
10542         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10543         << Description << mode << modeCount << NumFormalArgs;
10544 
10545   MaybeEmitInheritedConstructorNote(S, Found);
10546 }
10547 
10548 /// Arity mismatch diagnosis specific to a function overload candidate.
10549 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
10550                                   unsigned NumFormalArgs) {
10551   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
10552     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10553 }
10554 
10555 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10556   if (TemplateDecl *TD = Templated->getDescribedTemplate())
10557     return TD;
10558   llvm_unreachable("Unsupported: Getting the described template declaration"
10559                    " for bad deduction diagnosis");
10560 }
10561 
10562 /// Diagnose a failed template-argument deduction.
10563 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10564                                  DeductionFailureInfo &DeductionFailure,
10565                                  unsigned NumArgs,
10566                                  bool TakingCandidateAddress) {
10567   TemplateParameter Param = DeductionFailure.getTemplateParameter();
10568   NamedDecl *ParamD;
10569   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10570   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10571   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10572   switch (DeductionFailure.Result) {
10573   case Sema::TDK_Success:
10574     llvm_unreachable("TDK_success while diagnosing bad deduction");
10575 
10576   case Sema::TDK_Incomplete: {
10577     assert(ParamD && "no parameter found for incomplete deduction result");
10578     S.Diag(Templated->getLocation(),
10579            diag::note_ovl_candidate_incomplete_deduction)
10580         << ParamD->getDeclName();
10581     MaybeEmitInheritedConstructorNote(S, Found);
10582     return;
10583   }
10584 
10585   case Sema::TDK_IncompletePack: {
10586     assert(ParamD && "no parameter found for incomplete deduction result");
10587     S.Diag(Templated->getLocation(),
10588            diag::note_ovl_candidate_incomplete_deduction_pack)
10589         << ParamD->getDeclName()
10590         << (DeductionFailure.getFirstArg()->pack_size() + 1)
10591         << *DeductionFailure.getFirstArg();
10592     MaybeEmitInheritedConstructorNote(S, Found);
10593     return;
10594   }
10595 
10596   case Sema::TDK_Underqualified: {
10597     assert(ParamD && "no parameter found for bad qualifiers deduction result");
10598     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10599 
10600     QualType Param = DeductionFailure.getFirstArg()->getAsType();
10601 
10602     // Param will have been canonicalized, but it should just be a
10603     // qualified version of ParamD, so move the qualifiers to that.
10604     QualifierCollector Qs;
10605     Qs.strip(Param);
10606     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10607     assert(S.Context.hasSameType(Param, NonCanonParam));
10608 
10609     // Arg has also been canonicalized, but there's nothing we can do
10610     // about that.  It also doesn't matter as much, because it won't
10611     // have any template parameters in it (because deduction isn't
10612     // done on dependent types).
10613     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10614 
10615     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10616         << ParamD->getDeclName() << Arg << NonCanonParam;
10617     MaybeEmitInheritedConstructorNote(S, Found);
10618     return;
10619   }
10620 
10621   case Sema::TDK_Inconsistent: {
10622     assert(ParamD && "no parameter found for inconsistent deduction result");
10623     int which = 0;
10624     if (isa<TemplateTypeParmDecl>(ParamD))
10625       which = 0;
10626     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10627       // Deduction might have failed because we deduced arguments of two
10628       // different types for a non-type template parameter.
10629       // FIXME: Use a different TDK value for this.
10630       QualType T1 =
10631           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10632       QualType T2 =
10633           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10634       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10635         S.Diag(Templated->getLocation(),
10636                diag::note_ovl_candidate_inconsistent_deduction_types)
10637           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10638           << *DeductionFailure.getSecondArg() << T2;
10639         MaybeEmitInheritedConstructorNote(S, Found);
10640         return;
10641       }
10642 
10643       which = 1;
10644     } else {
10645       which = 2;
10646     }
10647 
10648     // Tweak the diagnostic if the problem is that we deduced packs of
10649     // different arities. We'll print the actual packs anyway in case that
10650     // includes additional useful information.
10651     if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
10652         DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
10653         DeductionFailure.getFirstArg()->pack_size() !=
10654             DeductionFailure.getSecondArg()->pack_size()) {
10655       which = 3;
10656     }
10657 
10658     S.Diag(Templated->getLocation(),
10659            diag::note_ovl_candidate_inconsistent_deduction)
10660         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10661         << *DeductionFailure.getSecondArg();
10662     MaybeEmitInheritedConstructorNote(S, Found);
10663     return;
10664   }
10665 
10666   case Sema::TDK_InvalidExplicitArguments:
10667     assert(ParamD && "no parameter found for invalid explicit arguments");
10668     if (ParamD->getDeclName())
10669       S.Diag(Templated->getLocation(),
10670              diag::note_ovl_candidate_explicit_arg_mismatch_named)
10671           << ParamD->getDeclName();
10672     else {
10673       int index = 0;
10674       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10675         index = TTP->getIndex();
10676       else if (NonTypeTemplateParmDecl *NTTP
10677                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10678         index = NTTP->getIndex();
10679       else
10680         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10681       S.Diag(Templated->getLocation(),
10682              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10683           << (index + 1);
10684     }
10685     MaybeEmitInheritedConstructorNote(S, Found);
10686     return;
10687 
10688   case Sema::TDK_ConstraintsNotSatisfied: {
10689     // Format the template argument list into the argument string.
10690     SmallString<128> TemplateArgString;
10691     TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
10692     TemplateArgString = " ";
10693     TemplateArgString += S.getTemplateArgumentBindingsText(
10694         getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10695     if (TemplateArgString.size() == 1)
10696       TemplateArgString.clear();
10697     S.Diag(Templated->getLocation(),
10698            diag::note_ovl_candidate_unsatisfied_constraints)
10699         << TemplateArgString;
10700 
10701     S.DiagnoseUnsatisfiedConstraint(
10702         static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
10703     return;
10704   }
10705   case Sema::TDK_TooManyArguments:
10706   case Sema::TDK_TooFewArguments:
10707     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10708     return;
10709 
10710   case Sema::TDK_InstantiationDepth:
10711     S.Diag(Templated->getLocation(),
10712            diag::note_ovl_candidate_instantiation_depth);
10713     MaybeEmitInheritedConstructorNote(S, Found);
10714     return;
10715 
10716   case Sema::TDK_SubstitutionFailure: {
10717     // Format the template argument list into the argument string.
10718     SmallString<128> TemplateArgString;
10719     if (TemplateArgumentList *Args =
10720             DeductionFailure.getTemplateArgumentList()) {
10721       TemplateArgString = " ";
10722       TemplateArgString += S.getTemplateArgumentBindingsText(
10723           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10724       if (TemplateArgString.size() == 1)
10725         TemplateArgString.clear();
10726     }
10727 
10728     // If this candidate was disabled by enable_if, say so.
10729     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10730     if (PDiag && PDiag->second.getDiagID() ==
10731           diag::err_typename_nested_not_found_enable_if) {
10732       // FIXME: Use the source range of the condition, and the fully-qualified
10733       //        name of the enable_if template. These are both present in PDiag.
10734       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10735         << "'enable_if'" << TemplateArgString;
10736       return;
10737     }
10738 
10739     // We found a specific requirement that disabled the enable_if.
10740     if (PDiag && PDiag->second.getDiagID() ==
10741         diag::err_typename_nested_not_found_requirement) {
10742       S.Diag(Templated->getLocation(),
10743              diag::note_ovl_candidate_disabled_by_requirement)
10744         << PDiag->second.getStringArg(0) << TemplateArgString;
10745       return;
10746     }
10747 
10748     // Format the SFINAE diagnostic into the argument string.
10749     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10750     //        formatted message in another diagnostic.
10751     SmallString<128> SFINAEArgString;
10752     SourceRange R;
10753     if (PDiag) {
10754       SFINAEArgString = ": ";
10755       R = SourceRange(PDiag->first, PDiag->first);
10756       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10757     }
10758 
10759     S.Diag(Templated->getLocation(),
10760            diag::note_ovl_candidate_substitution_failure)
10761         << TemplateArgString << SFINAEArgString << R;
10762     MaybeEmitInheritedConstructorNote(S, Found);
10763     return;
10764   }
10765 
10766   case Sema::TDK_DeducedMismatch:
10767   case Sema::TDK_DeducedMismatchNested: {
10768     // Format the template argument list into the argument string.
10769     SmallString<128> TemplateArgString;
10770     if (TemplateArgumentList *Args =
10771             DeductionFailure.getTemplateArgumentList()) {
10772       TemplateArgString = " ";
10773       TemplateArgString += S.getTemplateArgumentBindingsText(
10774           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10775       if (TemplateArgString.size() == 1)
10776         TemplateArgString.clear();
10777     }
10778 
10779     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10780         << (*DeductionFailure.getCallArgIndex() + 1)
10781         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10782         << TemplateArgString
10783         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10784     break;
10785   }
10786 
10787   case Sema::TDK_NonDeducedMismatch: {
10788     // FIXME: Provide a source location to indicate what we couldn't match.
10789     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10790     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10791     if (FirstTA.getKind() == TemplateArgument::Template &&
10792         SecondTA.getKind() == TemplateArgument::Template) {
10793       TemplateName FirstTN = FirstTA.getAsTemplate();
10794       TemplateName SecondTN = SecondTA.getAsTemplate();
10795       if (FirstTN.getKind() == TemplateName::Template &&
10796           SecondTN.getKind() == TemplateName::Template) {
10797         if (FirstTN.getAsTemplateDecl()->getName() ==
10798             SecondTN.getAsTemplateDecl()->getName()) {
10799           // FIXME: This fixes a bad diagnostic where both templates are named
10800           // the same.  This particular case is a bit difficult since:
10801           // 1) It is passed as a string to the diagnostic printer.
10802           // 2) The diagnostic printer only attempts to find a better
10803           //    name for types, not decls.
10804           // Ideally, this should folded into the diagnostic printer.
10805           S.Diag(Templated->getLocation(),
10806                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10807               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10808           return;
10809         }
10810       }
10811     }
10812 
10813     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10814         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10815       return;
10816 
10817     // FIXME: For generic lambda parameters, check if the function is a lambda
10818     // call operator, and if so, emit a prettier and more informative
10819     // diagnostic that mentions 'auto' and lambda in addition to
10820     // (or instead of?) the canonical template type parameters.
10821     S.Diag(Templated->getLocation(),
10822            diag::note_ovl_candidate_non_deduced_mismatch)
10823         << FirstTA << SecondTA;
10824     return;
10825   }
10826   // TODO: diagnose these individually, then kill off
10827   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10828   case Sema::TDK_MiscellaneousDeductionFailure:
10829     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10830     MaybeEmitInheritedConstructorNote(S, Found);
10831     return;
10832   case Sema::TDK_CUDATargetMismatch:
10833     S.Diag(Templated->getLocation(),
10834            diag::note_cuda_ovl_candidate_target_mismatch);
10835     return;
10836   }
10837 }
10838 
10839 /// Diagnose a failed template-argument deduction, for function calls.
10840 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10841                                  unsigned NumArgs,
10842                                  bool TakingCandidateAddress) {
10843   unsigned TDK = Cand->DeductionFailure.Result;
10844   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10845     if (CheckArityMismatch(S, Cand, NumArgs))
10846       return;
10847   }
10848   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10849                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10850 }
10851 
10852 /// CUDA: diagnose an invalid call across targets.
10853 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10854   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10855   FunctionDecl *Callee = Cand->Function;
10856 
10857   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10858                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10859 
10860   std::string FnDesc;
10861   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10862       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
10863                                 Cand->getRewriteKind(), FnDesc);
10864 
10865   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10866       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10867       << FnDesc /* Ignored */
10868       << CalleeTarget << CallerTarget;
10869 
10870   // This could be an implicit constructor for which we could not infer the
10871   // target due to a collsion. Diagnose that case.
10872   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10873   if (Meth != nullptr && Meth->isImplicit()) {
10874     CXXRecordDecl *ParentClass = Meth->getParent();
10875     Sema::CXXSpecialMember CSM;
10876 
10877     switch (FnKindPair.first) {
10878     default:
10879       return;
10880     case oc_implicit_default_constructor:
10881       CSM = Sema::CXXDefaultConstructor;
10882       break;
10883     case oc_implicit_copy_constructor:
10884       CSM = Sema::CXXCopyConstructor;
10885       break;
10886     case oc_implicit_move_constructor:
10887       CSM = Sema::CXXMoveConstructor;
10888       break;
10889     case oc_implicit_copy_assignment:
10890       CSM = Sema::CXXCopyAssignment;
10891       break;
10892     case oc_implicit_move_assignment:
10893       CSM = Sema::CXXMoveAssignment;
10894       break;
10895     };
10896 
10897     bool ConstRHS = false;
10898     if (Meth->getNumParams()) {
10899       if (const ReferenceType *RT =
10900               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10901         ConstRHS = RT->getPointeeType().isConstQualified();
10902       }
10903     }
10904 
10905     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10906                                               /* ConstRHS */ ConstRHS,
10907                                               /* Diagnose */ true);
10908   }
10909 }
10910 
10911 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10912   FunctionDecl *Callee = Cand->Function;
10913   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10914 
10915   S.Diag(Callee->getLocation(),
10916          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10917       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10918 }
10919 
10920 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
10921   ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function);
10922   assert(ES.isExplicit() && "not an explicit candidate");
10923 
10924   unsigned Kind;
10925   switch (Cand->Function->getDeclKind()) {
10926   case Decl::Kind::CXXConstructor:
10927     Kind = 0;
10928     break;
10929   case Decl::Kind::CXXConversion:
10930     Kind = 1;
10931     break;
10932   case Decl::Kind::CXXDeductionGuide:
10933     Kind = Cand->Function->isImplicit() ? 0 : 2;
10934     break;
10935   default:
10936     llvm_unreachable("invalid Decl");
10937   }
10938 
10939   // Note the location of the first (in-class) declaration; a redeclaration
10940   // (particularly an out-of-class definition) will typically lack the
10941   // 'explicit' specifier.
10942   // FIXME: This is probably a good thing to do for all 'candidate' notes.
10943   FunctionDecl *First = Cand->Function->getFirstDecl();
10944   if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
10945     First = Pattern->getFirstDecl();
10946 
10947   S.Diag(First->getLocation(),
10948          diag::note_ovl_candidate_explicit)
10949       << Kind << (ES.getExpr() ? 1 : 0)
10950       << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
10951 }
10952 
10953 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10954   FunctionDecl *Callee = Cand->Function;
10955 
10956   S.Diag(Callee->getLocation(),
10957          diag::note_ovl_candidate_disabled_by_extension)
10958     << S.getOpenCLExtensionsFromDeclExtMap(Callee);
10959 }
10960 
10961 /// Generates a 'note' diagnostic for an overload candidate.  We've
10962 /// already generated a primary error at the call site.
10963 ///
10964 /// It really does need to be a single diagnostic with its caret
10965 /// pointed at the candidate declaration.  Yes, this creates some
10966 /// major challenges of technical writing.  Yes, this makes pointing
10967 /// out problems with specific arguments quite awkward.  It's still
10968 /// better than generating twenty screens of text for every failed
10969 /// overload.
10970 ///
10971 /// It would be great to be able to express per-candidate problems
10972 /// more richly for those diagnostic clients that cared, but we'd
10973 /// still have to be just as careful with the default diagnostics.
10974 /// \param CtorDestAS Addr space of object being constructed (for ctor
10975 /// candidates only).
10976 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10977                                   unsigned NumArgs,
10978                                   bool TakingCandidateAddress,
10979                                   LangAS CtorDestAS = LangAS::Default) {
10980   FunctionDecl *Fn = Cand->Function;
10981 
10982   // Note deleted candidates, but only if they're viable.
10983   if (Cand->Viable) {
10984     if (Fn->isDeleted()) {
10985       std::string FnDesc;
10986       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10987           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
10988                                     Cand->getRewriteKind(), FnDesc);
10989 
10990       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10991           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10992           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10993       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10994       return;
10995     }
10996 
10997     // We don't really have anything else to say about viable candidates.
10998     S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10999     return;
11000   }
11001 
11002   switch (Cand->FailureKind) {
11003   case ovl_fail_too_many_arguments:
11004   case ovl_fail_too_few_arguments:
11005     return DiagnoseArityMismatch(S, Cand, NumArgs);
11006 
11007   case ovl_fail_bad_deduction:
11008     return DiagnoseBadDeduction(S, Cand, NumArgs,
11009                                 TakingCandidateAddress);
11010 
11011   case ovl_fail_illegal_constructor: {
11012     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
11013       << (Fn->getPrimaryTemplate() ? 1 : 0);
11014     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11015     return;
11016   }
11017 
11018   case ovl_fail_object_addrspace_mismatch: {
11019     Qualifiers QualsForPrinting;
11020     QualsForPrinting.setAddressSpace(CtorDestAS);
11021     S.Diag(Fn->getLocation(),
11022            diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
11023         << QualsForPrinting;
11024     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11025     return;
11026   }
11027 
11028   case ovl_fail_trivial_conversion:
11029   case ovl_fail_bad_final_conversion:
11030   case ovl_fail_final_conversion_not_exact:
11031     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11032 
11033   case ovl_fail_bad_conversion: {
11034     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
11035     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
11036       if (Cand->Conversions[I].isBad())
11037         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
11038 
11039     // FIXME: this currently happens when we're called from SemaInit
11040     // when user-conversion overload fails.  Figure out how to handle
11041     // those conditions and diagnose them well.
11042     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11043   }
11044 
11045   case ovl_fail_bad_target:
11046     return DiagnoseBadTarget(S, Cand);
11047 
11048   case ovl_fail_enable_if:
11049     return DiagnoseFailedEnableIfAttr(S, Cand);
11050 
11051   case ovl_fail_explicit:
11052     return DiagnoseFailedExplicitSpec(S, Cand);
11053 
11054   case ovl_fail_ext_disabled:
11055     return DiagnoseOpenCLExtensionDisabled(S, Cand);
11056 
11057   case ovl_fail_inhctor_slice:
11058     // It's generally not interesting to note copy/move constructors here.
11059     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
11060       return;
11061     S.Diag(Fn->getLocation(),
11062            diag::note_ovl_candidate_inherited_constructor_slice)
11063       << (Fn->getPrimaryTemplate() ? 1 : 0)
11064       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
11065     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11066     return;
11067 
11068   case ovl_fail_addr_not_available: {
11069     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
11070     (void)Available;
11071     assert(!Available);
11072     break;
11073   }
11074   case ovl_non_default_multiversion_function:
11075     // Do nothing, these should simply be ignored.
11076     break;
11077 
11078   case ovl_fail_constraints_not_satisfied: {
11079     std::string FnDesc;
11080     std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11081         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11082                                   Cand->getRewriteKind(), FnDesc);
11083 
11084     S.Diag(Fn->getLocation(),
11085            diag::note_ovl_candidate_constraints_not_satisfied)
11086         << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11087         << FnDesc /* Ignored */;
11088     ConstraintSatisfaction Satisfaction;
11089     if (S.CheckFunctionConstraints(Fn, Satisfaction))
11090       break;
11091     S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11092   }
11093   }
11094 }
11095 
11096 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
11097   // Desugar the type of the surrogate down to a function type,
11098   // retaining as many typedefs as possible while still showing
11099   // the function type (and, therefore, its parameter types).
11100   QualType FnType = Cand->Surrogate->getConversionType();
11101   bool isLValueReference = false;
11102   bool isRValueReference = false;
11103   bool isPointer = false;
11104   if (const LValueReferenceType *FnTypeRef =
11105         FnType->getAs<LValueReferenceType>()) {
11106     FnType = FnTypeRef->getPointeeType();
11107     isLValueReference = true;
11108   } else if (const RValueReferenceType *FnTypeRef =
11109                FnType->getAs<RValueReferenceType>()) {
11110     FnType = FnTypeRef->getPointeeType();
11111     isRValueReference = true;
11112   }
11113   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
11114     FnType = FnTypePtr->getPointeeType();
11115     isPointer = true;
11116   }
11117   // Desugar down to a function type.
11118   FnType = QualType(FnType->getAs<FunctionType>(), 0);
11119   // Reconstruct the pointer/reference as appropriate.
11120   if (isPointer) FnType = S.Context.getPointerType(FnType);
11121   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
11122   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
11123 
11124   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
11125     << FnType;
11126 }
11127 
11128 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
11129                                          SourceLocation OpLoc,
11130                                          OverloadCandidate *Cand) {
11131   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
11132   std::string TypeStr("operator");
11133   TypeStr += Opc;
11134   TypeStr += "(";
11135   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
11136   if (Cand->Conversions.size() == 1) {
11137     TypeStr += ")";
11138     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11139   } else {
11140     TypeStr += ", ";
11141     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
11142     TypeStr += ")";
11143     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11144   }
11145 }
11146 
11147 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
11148                                          OverloadCandidate *Cand) {
11149   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
11150     if (ICS.isBad()) break; // all meaningless after first invalid
11151     if (!ICS.isAmbiguous()) continue;
11152 
11153     ICS.DiagnoseAmbiguousConversion(
11154         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
11155   }
11156 }
11157 
11158 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
11159   if (Cand->Function)
11160     return Cand->Function->getLocation();
11161   if (Cand->IsSurrogate)
11162     return Cand->Surrogate->getLocation();
11163   return SourceLocation();
11164 }
11165 
11166 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
11167   switch ((Sema::TemplateDeductionResult)DFI.Result) {
11168   case Sema::TDK_Success:
11169   case Sema::TDK_NonDependentConversionFailure:
11170     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
11171 
11172   case Sema::TDK_Invalid:
11173   case Sema::TDK_Incomplete:
11174   case Sema::TDK_IncompletePack:
11175     return 1;
11176 
11177   case Sema::TDK_Underqualified:
11178   case Sema::TDK_Inconsistent:
11179     return 2;
11180 
11181   case Sema::TDK_SubstitutionFailure:
11182   case Sema::TDK_DeducedMismatch:
11183   case Sema::TDK_ConstraintsNotSatisfied:
11184   case Sema::TDK_DeducedMismatchNested:
11185   case Sema::TDK_NonDeducedMismatch:
11186   case Sema::TDK_MiscellaneousDeductionFailure:
11187   case Sema::TDK_CUDATargetMismatch:
11188     return 3;
11189 
11190   case Sema::TDK_InstantiationDepth:
11191     return 4;
11192 
11193   case Sema::TDK_InvalidExplicitArguments:
11194     return 5;
11195 
11196   case Sema::TDK_TooManyArguments:
11197   case Sema::TDK_TooFewArguments:
11198     return 6;
11199   }
11200   llvm_unreachable("Unhandled deduction result");
11201 }
11202 
11203 namespace {
11204 struct CompareOverloadCandidatesForDisplay {
11205   Sema &S;
11206   SourceLocation Loc;
11207   size_t NumArgs;
11208   OverloadCandidateSet::CandidateSetKind CSK;
11209 
11210   CompareOverloadCandidatesForDisplay(
11211       Sema &S, SourceLocation Loc, size_t NArgs,
11212       OverloadCandidateSet::CandidateSetKind CSK)
11213       : S(S), NumArgs(NArgs), CSK(CSK) {}
11214 
11215   OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
11216     // If there are too many or too few arguments, that's the high-order bit we
11217     // want to sort by, even if the immediate failure kind was something else.
11218     if (C->FailureKind == ovl_fail_too_many_arguments ||
11219         C->FailureKind == ovl_fail_too_few_arguments)
11220       return static_cast<OverloadFailureKind>(C->FailureKind);
11221 
11222     if (C->Function) {
11223       if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
11224         return ovl_fail_too_many_arguments;
11225       if (NumArgs < C->Function->getMinRequiredArguments())
11226         return ovl_fail_too_few_arguments;
11227     }
11228 
11229     return static_cast<OverloadFailureKind>(C->FailureKind);
11230   }
11231 
11232   bool operator()(const OverloadCandidate *L,
11233                   const OverloadCandidate *R) {
11234     // Fast-path this check.
11235     if (L == R) return false;
11236 
11237     // Order first by viability.
11238     if (L->Viable) {
11239       if (!R->Viable) return true;
11240 
11241       // TODO: introduce a tri-valued comparison for overload
11242       // candidates.  Would be more worthwhile if we had a sort
11243       // that could exploit it.
11244       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
11245         return true;
11246       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
11247         return false;
11248     } else if (R->Viable)
11249       return false;
11250 
11251     assert(L->Viable == R->Viable);
11252 
11253     // Criteria by which we can sort non-viable candidates:
11254     if (!L->Viable) {
11255       OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
11256       OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
11257 
11258       // 1. Arity mismatches come after other candidates.
11259       if (LFailureKind == ovl_fail_too_many_arguments ||
11260           LFailureKind == ovl_fail_too_few_arguments) {
11261         if (RFailureKind == ovl_fail_too_many_arguments ||
11262             RFailureKind == ovl_fail_too_few_arguments) {
11263           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
11264           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
11265           if (LDist == RDist) {
11266             if (LFailureKind == RFailureKind)
11267               // Sort non-surrogates before surrogates.
11268               return !L->IsSurrogate && R->IsSurrogate;
11269             // Sort candidates requiring fewer parameters than there were
11270             // arguments given after candidates requiring more parameters
11271             // than there were arguments given.
11272             return LFailureKind == ovl_fail_too_many_arguments;
11273           }
11274           return LDist < RDist;
11275         }
11276         return false;
11277       }
11278       if (RFailureKind == ovl_fail_too_many_arguments ||
11279           RFailureKind == ovl_fail_too_few_arguments)
11280         return true;
11281 
11282       // 2. Bad conversions come first and are ordered by the number
11283       // of bad conversions and quality of good conversions.
11284       if (LFailureKind == ovl_fail_bad_conversion) {
11285         if (RFailureKind != ovl_fail_bad_conversion)
11286           return true;
11287 
11288         // The conversion that can be fixed with a smaller number of changes,
11289         // comes first.
11290         unsigned numLFixes = L->Fix.NumConversionsFixed;
11291         unsigned numRFixes = R->Fix.NumConversionsFixed;
11292         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
11293         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
11294         if (numLFixes != numRFixes) {
11295           return numLFixes < numRFixes;
11296         }
11297 
11298         // If there's any ordering between the defined conversions...
11299         // FIXME: this might not be transitive.
11300         assert(L->Conversions.size() == R->Conversions.size());
11301 
11302         int leftBetter = 0;
11303         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
11304         for (unsigned E = L->Conversions.size(); I != E; ++I) {
11305           switch (CompareImplicitConversionSequences(S, Loc,
11306                                                      L->Conversions[I],
11307                                                      R->Conversions[I])) {
11308           case ImplicitConversionSequence::Better:
11309             leftBetter++;
11310             break;
11311 
11312           case ImplicitConversionSequence::Worse:
11313             leftBetter--;
11314             break;
11315 
11316           case ImplicitConversionSequence::Indistinguishable:
11317             break;
11318           }
11319         }
11320         if (leftBetter > 0) return true;
11321         if (leftBetter < 0) return false;
11322 
11323       } else if (RFailureKind == ovl_fail_bad_conversion)
11324         return false;
11325 
11326       if (LFailureKind == ovl_fail_bad_deduction) {
11327         if (RFailureKind != ovl_fail_bad_deduction)
11328           return true;
11329 
11330         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11331           return RankDeductionFailure(L->DeductionFailure)
11332                < RankDeductionFailure(R->DeductionFailure);
11333       } else if (RFailureKind == ovl_fail_bad_deduction)
11334         return false;
11335 
11336       // TODO: others?
11337     }
11338 
11339     // Sort everything else by location.
11340     SourceLocation LLoc = GetLocationForCandidate(L);
11341     SourceLocation RLoc = GetLocationForCandidate(R);
11342 
11343     // Put candidates without locations (e.g. builtins) at the end.
11344     if (LLoc.isInvalid()) return false;
11345     if (RLoc.isInvalid()) return true;
11346 
11347     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11348   }
11349 };
11350 }
11351 
11352 /// CompleteNonViableCandidate - Normally, overload resolution only
11353 /// computes up to the first bad conversion. Produces the FixIt set if
11354 /// possible.
11355 static void
11356 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
11357                            ArrayRef<Expr *> Args,
11358                            OverloadCandidateSet::CandidateSetKind CSK) {
11359   assert(!Cand->Viable);
11360 
11361   // Don't do anything on failures other than bad conversion.
11362   if (Cand->FailureKind != ovl_fail_bad_conversion)
11363     return;
11364 
11365   // We only want the FixIts if all the arguments can be corrected.
11366   bool Unfixable = false;
11367   // Use a implicit copy initialization to check conversion fixes.
11368   Cand->Fix.setConversionChecker(TryCopyInitialization);
11369 
11370   // Attempt to fix the bad conversion.
11371   unsigned ConvCount = Cand->Conversions.size();
11372   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
11373        ++ConvIdx) {
11374     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
11375     if (Cand->Conversions[ConvIdx].isInitialized() &&
11376         Cand->Conversions[ConvIdx].isBad()) {
11377       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11378       break;
11379     }
11380   }
11381 
11382   // FIXME: this should probably be preserved from the overload
11383   // operation somehow.
11384   bool SuppressUserConversions = false;
11385 
11386   unsigned ConvIdx = 0;
11387   unsigned ArgIdx = 0;
11388   ArrayRef<QualType> ParamTypes;
11389   bool Reversed = Cand->isReversed();
11390 
11391   if (Cand->IsSurrogate) {
11392     QualType ConvType
11393       = Cand->Surrogate->getConversionType().getNonReferenceType();
11394     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11395       ConvType = ConvPtrType->getPointeeType();
11396     ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
11397     // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11398     ConvIdx = 1;
11399   } else if (Cand->Function) {
11400     ParamTypes =
11401         Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
11402     if (isa<CXXMethodDecl>(Cand->Function) &&
11403         !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
11404       // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11405       ConvIdx = 1;
11406       if (CSK == OverloadCandidateSet::CSK_Operator &&
11407           Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call)
11408         // Argument 0 is 'this', which doesn't have a corresponding parameter.
11409         ArgIdx = 1;
11410     }
11411   } else {
11412     // Builtin operator.
11413     assert(ConvCount <= 3);
11414     ParamTypes = Cand->BuiltinParamTypes;
11415   }
11416 
11417   // Fill in the rest of the conversions.
11418   for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
11419        ConvIdx != ConvCount;
11420        ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
11421     assert(ArgIdx < Args.size() && "no argument for this arg conversion");
11422     if (Cand->Conversions[ConvIdx].isInitialized()) {
11423       // We've already checked this conversion.
11424     } else if (ParamIdx < ParamTypes.size()) {
11425       if (ParamTypes[ParamIdx]->isDependentType())
11426         Cand->Conversions[ConvIdx].setAsIdentityConversion(
11427             Args[ArgIdx]->getType());
11428       else {
11429         Cand->Conversions[ConvIdx] =
11430             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
11431                                   SuppressUserConversions,
11432                                   /*InOverloadResolution=*/true,
11433                                   /*AllowObjCWritebackConversion=*/
11434                                   S.getLangOpts().ObjCAutoRefCount);
11435         // Store the FixIt in the candidate if it exists.
11436         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
11437           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11438       }
11439     } else
11440       Cand->Conversions[ConvIdx].setEllipsis();
11441   }
11442 }
11443 
11444 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
11445     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11446     SourceLocation OpLoc,
11447     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11448   // Sort the candidates by viability and position.  Sorting directly would
11449   // be prohibitive, so we make a set of pointers and sort those.
11450   SmallVector<OverloadCandidate*, 32> Cands;
11451   if (OCD == OCD_AllCandidates) Cands.reserve(size());
11452   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11453     if (!Filter(*Cand))
11454       continue;
11455     switch (OCD) {
11456     case OCD_AllCandidates:
11457       if (!Cand->Viable) {
11458         if (!Cand->Function && !Cand->IsSurrogate) {
11459           // This a non-viable builtin candidate.  We do not, in general,
11460           // want to list every possible builtin candidate.
11461           continue;
11462         }
11463         CompleteNonViableCandidate(S, Cand, Args, Kind);
11464       }
11465       break;
11466 
11467     case OCD_ViableCandidates:
11468       if (!Cand->Viable)
11469         continue;
11470       break;
11471 
11472     case OCD_AmbiguousCandidates:
11473       if (!Cand->Best)
11474         continue;
11475       break;
11476     }
11477 
11478     Cands.push_back(Cand);
11479   }
11480 
11481   llvm::stable_sort(
11482       Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
11483 
11484   return Cands;
11485 }
11486 
11487 /// When overload resolution fails, prints diagnostic messages containing the
11488 /// candidates in the candidate set.
11489 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD,
11490     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11491     StringRef Opc, SourceLocation OpLoc,
11492     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11493 
11494   auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
11495 
11496   S.Diag(PD.first, PD.second);
11497 
11498   NoteCandidates(S, Args, Cands, Opc, OpLoc);
11499 
11500   if (OCD == OCD_AmbiguousCandidates)
11501     MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
11502 }
11503 
11504 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
11505                                           ArrayRef<OverloadCandidate *> Cands,
11506                                           StringRef Opc, SourceLocation OpLoc) {
11507   bool ReportedAmbiguousConversions = false;
11508 
11509   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11510   unsigned CandsShown = 0;
11511   auto I = Cands.begin(), E = Cands.end();
11512   for (; I != E; ++I) {
11513     OverloadCandidate *Cand = *I;
11514 
11515     // Set an arbitrary limit on the number of candidate functions we'll spam
11516     // the user with.  FIXME: This limit should depend on details of the
11517     // candidate list.
11518     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
11519       break;
11520     }
11521     ++CandsShown;
11522 
11523     if (Cand->Function)
11524       NoteFunctionCandidate(S, Cand, Args.size(),
11525                             /*TakingCandidateAddress=*/false, DestAS);
11526     else if (Cand->IsSurrogate)
11527       NoteSurrogateCandidate(S, Cand);
11528     else {
11529       assert(Cand->Viable &&
11530              "Non-viable built-in candidates are not added to Cands.");
11531       // Generally we only see ambiguities including viable builtin
11532       // operators if overload resolution got screwed up by an
11533       // ambiguous user-defined conversion.
11534       //
11535       // FIXME: It's quite possible for different conversions to see
11536       // different ambiguities, though.
11537       if (!ReportedAmbiguousConversions) {
11538         NoteAmbiguousUserConversions(S, OpLoc, Cand);
11539         ReportedAmbiguousConversions = true;
11540       }
11541 
11542       // If this is a viable builtin, print it.
11543       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
11544     }
11545   }
11546 
11547   if (I != E)
11548     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
11549 }
11550 
11551 static SourceLocation
11552 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
11553   return Cand->Specialization ? Cand->Specialization->getLocation()
11554                               : SourceLocation();
11555 }
11556 
11557 namespace {
11558 struct CompareTemplateSpecCandidatesForDisplay {
11559   Sema &S;
11560   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
11561 
11562   bool operator()(const TemplateSpecCandidate *L,
11563                   const TemplateSpecCandidate *R) {
11564     // Fast-path this check.
11565     if (L == R)
11566       return false;
11567 
11568     // Assuming that both candidates are not matches...
11569 
11570     // Sort by the ranking of deduction failures.
11571     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11572       return RankDeductionFailure(L->DeductionFailure) <
11573              RankDeductionFailure(R->DeductionFailure);
11574 
11575     // Sort everything else by location.
11576     SourceLocation LLoc = GetLocationForCandidate(L);
11577     SourceLocation RLoc = GetLocationForCandidate(R);
11578 
11579     // Put candidates without locations (e.g. builtins) at the end.
11580     if (LLoc.isInvalid())
11581       return false;
11582     if (RLoc.isInvalid())
11583       return true;
11584 
11585     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11586   }
11587 };
11588 }
11589 
11590 /// Diagnose a template argument deduction failure.
11591 /// We are treating these failures as overload failures due to bad
11592 /// deductions.
11593 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
11594                                                  bool ForTakingAddress) {
11595   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
11596                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
11597 }
11598 
11599 void TemplateSpecCandidateSet::destroyCandidates() {
11600   for (iterator i = begin(), e = end(); i != e; ++i) {
11601     i->DeductionFailure.Destroy();
11602   }
11603 }
11604 
11605 void TemplateSpecCandidateSet::clear() {
11606   destroyCandidates();
11607   Candidates.clear();
11608 }
11609 
11610 /// NoteCandidates - When no template specialization match is found, prints
11611 /// diagnostic messages containing the non-matching specializations that form
11612 /// the candidate set.
11613 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
11614 /// OCD == OCD_AllCandidates and Cand->Viable == false.
11615 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
11616   // Sort the candidates by position (assuming no candidate is a match).
11617   // Sorting directly would be prohibitive, so we make a set of pointers
11618   // and sort those.
11619   SmallVector<TemplateSpecCandidate *, 32> Cands;
11620   Cands.reserve(size());
11621   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11622     if (Cand->Specialization)
11623       Cands.push_back(Cand);
11624     // Otherwise, this is a non-matching builtin candidate.  We do not,
11625     // in general, want to list every possible builtin candidate.
11626   }
11627 
11628   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
11629 
11630   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
11631   // for generalization purposes (?).
11632   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11633 
11634   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
11635   unsigned CandsShown = 0;
11636   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11637     TemplateSpecCandidate *Cand = *I;
11638 
11639     // Set an arbitrary limit on the number of candidates we'll spam
11640     // the user with.  FIXME: This limit should depend on details of the
11641     // candidate list.
11642     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
11643       break;
11644     ++CandsShown;
11645 
11646     assert(Cand->Specialization &&
11647            "Non-matching built-in candidates are not added to Cands.");
11648     Cand->NoteDeductionFailure(S, ForTakingAddress);
11649   }
11650 
11651   if (I != E)
11652     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
11653 }
11654 
11655 // [PossiblyAFunctionType]  -->   [Return]
11656 // NonFunctionType --> NonFunctionType
11657 // R (A) --> R(A)
11658 // R (*)(A) --> R (A)
11659 // R (&)(A) --> R (A)
11660 // R (S::*)(A) --> R (A)
11661 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
11662   QualType Ret = PossiblyAFunctionType;
11663   if (const PointerType *ToTypePtr =
11664     PossiblyAFunctionType->getAs<PointerType>())
11665     Ret = ToTypePtr->getPointeeType();
11666   else if (const ReferenceType *ToTypeRef =
11667     PossiblyAFunctionType->getAs<ReferenceType>())
11668     Ret = ToTypeRef->getPointeeType();
11669   else if (const MemberPointerType *MemTypePtr =
11670     PossiblyAFunctionType->getAs<MemberPointerType>())
11671     Ret = MemTypePtr->getPointeeType();
11672   Ret =
11673     Context.getCanonicalType(Ret).getUnqualifiedType();
11674   return Ret;
11675 }
11676 
11677 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
11678                                  bool Complain = true) {
11679   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
11680       S.DeduceReturnType(FD, Loc, Complain))
11681     return true;
11682 
11683   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
11684   if (S.getLangOpts().CPlusPlus17 &&
11685       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
11686       !S.ResolveExceptionSpec(Loc, FPT))
11687     return true;
11688 
11689   return false;
11690 }
11691 
11692 namespace {
11693 // A helper class to help with address of function resolution
11694 // - allows us to avoid passing around all those ugly parameters
11695 class AddressOfFunctionResolver {
11696   Sema& S;
11697   Expr* SourceExpr;
11698   const QualType& TargetType;
11699   QualType TargetFunctionType; // Extracted function type from target type
11700 
11701   bool Complain;
11702   //DeclAccessPair& ResultFunctionAccessPair;
11703   ASTContext& Context;
11704 
11705   bool TargetTypeIsNonStaticMemberFunction;
11706   bool FoundNonTemplateFunction;
11707   bool StaticMemberFunctionFromBoundPointer;
11708   bool HasComplained;
11709 
11710   OverloadExpr::FindResult OvlExprInfo;
11711   OverloadExpr *OvlExpr;
11712   TemplateArgumentListInfo OvlExplicitTemplateArgs;
11713   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
11714   TemplateSpecCandidateSet FailedCandidates;
11715 
11716 public:
11717   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
11718                             const QualType &TargetType, bool Complain)
11719       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
11720         Complain(Complain), Context(S.getASTContext()),
11721         TargetTypeIsNonStaticMemberFunction(
11722             !!TargetType->getAs<MemberPointerType>()),
11723         FoundNonTemplateFunction(false),
11724         StaticMemberFunctionFromBoundPointer(false),
11725         HasComplained(false),
11726         OvlExprInfo(OverloadExpr::find(SourceExpr)),
11727         OvlExpr(OvlExprInfo.Expression),
11728         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
11729     ExtractUnqualifiedFunctionTypeFromTargetType();
11730 
11731     if (TargetFunctionType->isFunctionType()) {
11732       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
11733         if (!UME->isImplicitAccess() &&
11734             !S.ResolveSingleFunctionTemplateSpecialization(UME))
11735           StaticMemberFunctionFromBoundPointer = true;
11736     } else if (OvlExpr->hasExplicitTemplateArgs()) {
11737       DeclAccessPair dap;
11738       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
11739               OvlExpr, false, &dap)) {
11740         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
11741           if (!Method->isStatic()) {
11742             // If the target type is a non-function type and the function found
11743             // is a non-static member function, pretend as if that was the
11744             // target, it's the only possible type to end up with.
11745             TargetTypeIsNonStaticMemberFunction = true;
11746 
11747             // And skip adding the function if its not in the proper form.
11748             // We'll diagnose this due to an empty set of functions.
11749             if (!OvlExprInfo.HasFormOfMemberPointer)
11750               return;
11751           }
11752 
11753         Matches.push_back(std::make_pair(dap, Fn));
11754       }
11755       return;
11756     }
11757 
11758     if (OvlExpr->hasExplicitTemplateArgs())
11759       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
11760 
11761     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
11762       // C++ [over.over]p4:
11763       //   If more than one function is selected, [...]
11764       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
11765         if (FoundNonTemplateFunction)
11766           EliminateAllTemplateMatches();
11767         else
11768           EliminateAllExceptMostSpecializedTemplate();
11769       }
11770     }
11771 
11772     if (S.getLangOpts().CUDA && Matches.size() > 1)
11773       EliminateSuboptimalCudaMatches();
11774   }
11775 
11776   bool hasComplained() const { return HasComplained; }
11777 
11778 private:
11779   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
11780     QualType Discard;
11781     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
11782            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
11783   }
11784 
11785   /// \return true if A is considered a better overload candidate for the
11786   /// desired type than B.
11787   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
11788     // If A doesn't have exactly the correct type, we don't want to classify it
11789     // as "better" than anything else. This way, the user is required to
11790     // disambiguate for us if there are multiple candidates and no exact match.
11791     return candidateHasExactlyCorrectType(A) &&
11792            (!candidateHasExactlyCorrectType(B) ||
11793             compareEnableIfAttrs(S, A, B) == Comparison::Better);
11794   }
11795 
11796   /// \return true if we were able to eliminate all but one overload candidate,
11797   /// false otherwise.
11798   bool eliminiateSuboptimalOverloadCandidates() {
11799     // Same algorithm as overload resolution -- one pass to pick the "best",
11800     // another pass to be sure that nothing is better than the best.
11801     auto Best = Matches.begin();
11802     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11803       if (isBetterCandidate(I->second, Best->second))
11804         Best = I;
11805 
11806     const FunctionDecl *BestFn = Best->second;
11807     auto IsBestOrInferiorToBest = [this, BestFn](
11808         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11809       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11810     };
11811 
11812     // Note: We explicitly leave Matches unmodified if there isn't a clear best
11813     // option, so we can potentially give the user a better error
11814     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
11815       return false;
11816     Matches[0] = *Best;
11817     Matches.resize(1);
11818     return true;
11819   }
11820 
11821   bool isTargetTypeAFunction() const {
11822     return TargetFunctionType->isFunctionType();
11823   }
11824 
11825   // [ToType]     [Return]
11826 
11827   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11828   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11829   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11830   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11831     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11832   }
11833 
11834   // return true if any matching specializations were found
11835   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
11836                                    const DeclAccessPair& CurAccessFunPair) {
11837     if (CXXMethodDecl *Method
11838               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11839       // Skip non-static function templates when converting to pointer, and
11840       // static when converting to member pointer.
11841       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11842         return false;
11843     }
11844     else if (TargetTypeIsNonStaticMemberFunction)
11845       return false;
11846 
11847     // C++ [over.over]p2:
11848     //   If the name is a function template, template argument deduction is
11849     //   done (14.8.2.2), and if the argument deduction succeeds, the
11850     //   resulting template argument list is used to generate a single
11851     //   function template specialization, which is added to the set of
11852     //   overloaded functions considered.
11853     FunctionDecl *Specialization = nullptr;
11854     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11855     if (Sema::TemplateDeductionResult Result
11856           = S.DeduceTemplateArguments(FunctionTemplate,
11857                                       &OvlExplicitTemplateArgs,
11858                                       TargetFunctionType, Specialization,
11859                                       Info, /*IsAddressOfFunction*/true)) {
11860       // Make a note of the failed deduction for diagnostics.
11861       FailedCandidates.addCandidate()
11862           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
11863                MakeDeductionFailureInfo(Context, Result, Info));
11864       return false;
11865     }
11866 
11867     // Template argument deduction ensures that we have an exact match or
11868     // compatible pointer-to-function arguments that would be adjusted by ICS.
11869     // This function template specicalization works.
11870     assert(S.isSameOrCompatibleFunctionType(
11871               Context.getCanonicalType(Specialization->getType()),
11872               Context.getCanonicalType(TargetFunctionType)));
11873 
11874     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11875       return false;
11876 
11877     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11878     return true;
11879   }
11880 
11881   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11882                                       const DeclAccessPair& CurAccessFunPair) {
11883     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11884       // Skip non-static functions when converting to pointer, and static
11885       // when converting to member pointer.
11886       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11887         return false;
11888     }
11889     else if (TargetTypeIsNonStaticMemberFunction)
11890       return false;
11891 
11892     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11893       if (S.getLangOpts().CUDA)
11894         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11895           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11896             return false;
11897       if (FunDecl->isMultiVersion()) {
11898         const auto *TA = FunDecl->getAttr<TargetAttr>();
11899         if (TA && !TA->isDefaultVersion())
11900           return false;
11901       }
11902 
11903       // If any candidate has a placeholder return type, trigger its deduction
11904       // now.
11905       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
11906                                Complain)) {
11907         HasComplained |= Complain;
11908         return false;
11909       }
11910 
11911       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11912         return false;
11913 
11914       // If we're in C, we need to support types that aren't exactly identical.
11915       if (!S.getLangOpts().CPlusPlus ||
11916           candidateHasExactlyCorrectType(FunDecl)) {
11917         Matches.push_back(std::make_pair(
11918             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11919         FoundNonTemplateFunction = true;
11920         return true;
11921       }
11922     }
11923 
11924     return false;
11925   }
11926 
11927   bool FindAllFunctionsThatMatchTargetTypeExactly() {
11928     bool Ret = false;
11929 
11930     // If the overload expression doesn't have the form of a pointer to
11931     // member, don't try to convert it to a pointer-to-member type.
11932     if (IsInvalidFormOfPointerToMemberFunction())
11933       return false;
11934 
11935     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11936                                E = OvlExpr->decls_end();
11937          I != E; ++I) {
11938       // Look through any using declarations to find the underlying function.
11939       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11940 
11941       // C++ [over.over]p3:
11942       //   Non-member functions and static member functions match
11943       //   targets of type "pointer-to-function" or "reference-to-function."
11944       //   Nonstatic member functions match targets of
11945       //   type "pointer-to-member-function."
11946       // Note that according to DR 247, the containing class does not matter.
11947       if (FunctionTemplateDecl *FunctionTemplate
11948                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11949         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11950           Ret = true;
11951       }
11952       // If we have explicit template arguments supplied, skip non-templates.
11953       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11954                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11955         Ret = true;
11956     }
11957     assert(Ret || Matches.empty());
11958     return Ret;
11959   }
11960 
11961   void EliminateAllExceptMostSpecializedTemplate() {
11962     //   [...] and any given function template specialization F1 is
11963     //   eliminated if the set contains a second function template
11964     //   specialization whose function template is more specialized
11965     //   than the function template of F1 according to the partial
11966     //   ordering rules of 14.5.5.2.
11967 
11968     // The algorithm specified above is quadratic. We instead use a
11969     // two-pass algorithm (similar to the one used to identify the
11970     // best viable function in an overload set) that identifies the
11971     // best function template (if it exists).
11972 
11973     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11974     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11975       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11976 
11977     // TODO: It looks like FailedCandidates does not serve much purpose
11978     // here, since the no_viable diagnostic has index 0.
11979     UnresolvedSetIterator Result = S.getMostSpecialized(
11980         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11981         SourceExpr->getBeginLoc(), S.PDiag(),
11982         S.PDiag(diag::err_addr_ovl_ambiguous)
11983             << Matches[0].second->getDeclName(),
11984         S.PDiag(diag::note_ovl_candidate)
11985             << (unsigned)oc_function << (unsigned)ocs_described_template,
11986         Complain, TargetFunctionType);
11987 
11988     if (Result != MatchesCopy.end()) {
11989       // Make it the first and only element
11990       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11991       Matches[0].second = cast<FunctionDecl>(*Result);
11992       Matches.resize(1);
11993     } else
11994       HasComplained |= Complain;
11995   }
11996 
11997   void EliminateAllTemplateMatches() {
11998     //   [...] any function template specializations in the set are
11999     //   eliminated if the set also contains a non-template function, [...]
12000     for (unsigned I = 0, N = Matches.size(); I != N; ) {
12001       if (Matches[I].second->getPrimaryTemplate() == nullptr)
12002         ++I;
12003       else {
12004         Matches[I] = Matches[--N];
12005         Matches.resize(N);
12006       }
12007     }
12008   }
12009 
12010   void EliminateSuboptimalCudaMatches() {
12011     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
12012   }
12013 
12014 public:
12015   void ComplainNoMatchesFound() const {
12016     assert(Matches.empty());
12017     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
12018         << OvlExpr->getName() << TargetFunctionType
12019         << OvlExpr->getSourceRange();
12020     if (FailedCandidates.empty())
12021       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12022                                   /*TakingAddress=*/true);
12023     else {
12024       // We have some deduction failure messages. Use them to diagnose
12025       // the function templates, and diagnose the non-template candidates
12026       // normally.
12027       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12028                                  IEnd = OvlExpr->decls_end();
12029            I != IEnd; ++I)
12030         if (FunctionDecl *Fun =
12031                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
12032           if (!functionHasPassObjectSizeParams(Fun))
12033             S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
12034                                     /*TakingAddress=*/true);
12035       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
12036     }
12037   }
12038 
12039   bool IsInvalidFormOfPointerToMemberFunction() const {
12040     return TargetTypeIsNonStaticMemberFunction &&
12041       !OvlExprInfo.HasFormOfMemberPointer;
12042   }
12043 
12044   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
12045       // TODO: Should we condition this on whether any functions might
12046       // have matched, or is it more appropriate to do that in callers?
12047       // TODO: a fixit wouldn't hurt.
12048       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
12049         << TargetType << OvlExpr->getSourceRange();
12050   }
12051 
12052   bool IsStaticMemberFunctionFromBoundPointer() const {
12053     return StaticMemberFunctionFromBoundPointer;
12054   }
12055 
12056   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
12057     S.Diag(OvlExpr->getBeginLoc(),
12058            diag::err_invalid_form_pointer_member_function)
12059         << OvlExpr->getSourceRange();
12060   }
12061 
12062   void ComplainOfInvalidConversion() const {
12063     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
12064         << OvlExpr->getName() << TargetType;
12065   }
12066 
12067   void ComplainMultipleMatchesFound() const {
12068     assert(Matches.size() > 1);
12069     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
12070         << OvlExpr->getName() << OvlExpr->getSourceRange();
12071     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12072                                 /*TakingAddress=*/true);
12073   }
12074 
12075   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
12076 
12077   int getNumMatches() const { return Matches.size(); }
12078 
12079   FunctionDecl* getMatchingFunctionDecl() const {
12080     if (Matches.size() != 1) return nullptr;
12081     return Matches[0].second;
12082   }
12083 
12084   const DeclAccessPair* getMatchingFunctionAccessPair() const {
12085     if (Matches.size() != 1) return nullptr;
12086     return &Matches[0].first;
12087   }
12088 };
12089 }
12090 
12091 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
12092 /// an overloaded function (C++ [over.over]), where @p From is an
12093 /// expression with overloaded function type and @p ToType is the type
12094 /// we're trying to resolve to. For example:
12095 ///
12096 /// @code
12097 /// int f(double);
12098 /// int f(int);
12099 ///
12100 /// int (*pfd)(double) = f; // selects f(double)
12101 /// @endcode
12102 ///
12103 /// This routine returns the resulting FunctionDecl if it could be
12104 /// resolved, and NULL otherwise. When @p Complain is true, this
12105 /// routine will emit diagnostics if there is an error.
12106 FunctionDecl *
12107 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
12108                                          QualType TargetType,
12109                                          bool Complain,
12110                                          DeclAccessPair &FoundResult,
12111                                          bool *pHadMultipleCandidates) {
12112   assert(AddressOfExpr->getType() == Context.OverloadTy);
12113 
12114   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
12115                                      Complain);
12116   int NumMatches = Resolver.getNumMatches();
12117   FunctionDecl *Fn = nullptr;
12118   bool ShouldComplain = Complain && !Resolver.hasComplained();
12119   if (NumMatches == 0 && ShouldComplain) {
12120     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
12121       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
12122     else
12123       Resolver.ComplainNoMatchesFound();
12124   }
12125   else if (NumMatches > 1 && ShouldComplain)
12126     Resolver.ComplainMultipleMatchesFound();
12127   else if (NumMatches == 1) {
12128     Fn = Resolver.getMatchingFunctionDecl();
12129     assert(Fn);
12130     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
12131       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
12132     FoundResult = *Resolver.getMatchingFunctionAccessPair();
12133     if (Complain) {
12134       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
12135         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
12136       else
12137         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
12138     }
12139   }
12140 
12141   if (pHadMultipleCandidates)
12142     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
12143   return Fn;
12144 }
12145 
12146 /// Given an expression that refers to an overloaded function, try to
12147 /// resolve that function to a single function that can have its address taken.
12148 /// This will modify `Pair` iff it returns non-null.
12149 ///
12150 /// This routine can only succeed if from all of the candidates in the overload
12151 /// set for SrcExpr that can have their addresses taken, there is one candidate
12152 /// that is more constrained than the rest.
12153 FunctionDecl *
12154 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
12155   OverloadExpr::FindResult R = OverloadExpr::find(E);
12156   OverloadExpr *Ovl = R.Expression;
12157   bool IsResultAmbiguous = false;
12158   FunctionDecl *Result = nullptr;
12159   DeclAccessPair DAP;
12160   SmallVector<FunctionDecl *, 2> AmbiguousDecls;
12161 
12162   auto CheckMoreConstrained =
12163       [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> {
12164         SmallVector<const Expr *, 1> AC1, AC2;
12165         FD1->getAssociatedConstraints(AC1);
12166         FD2->getAssociatedConstraints(AC2);
12167         bool AtLeastAsConstrained1, AtLeastAsConstrained2;
12168         if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
12169           return None;
12170         if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
12171           return None;
12172         if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
12173           return None;
12174         return AtLeastAsConstrained1;
12175       };
12176 
12177   // Don't use the AddressOfResolver because we're specifically looking for
12178   // cases where we have one overload candidate that lacks
12179   // enable_if/pass_object_size/...
12180   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
12181     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
12182     if (!FD)
12183       return nullptr;
12184 
12185     if (!checkAddressOfFunctionIsAvailable(FD))
12186       continue;
12187 
12188     // We have more than one result - see if it is more constrained than the
12189     // previous one.
12190     if (Result) {
12191       Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD,
12192                                                                         Result);
12193       if (!MoreConstrainedThanPrevious) {
12194         IsResultAmbiguous = true;
12195         AmbiguousDecls.push_back(FD);
12196         continue;
12197       }
12198       if (!*MoreConstrainedThanPrevious)
12199         continue;
12200       // FD is more constrained - replace Result with it.
12201     }
12202     IsResultAmbiguous = false;
12203     DAP = I.getPair();
12204     Result = FD;
12205   }
12206 
12207   if (IsResultAmbiguous)
12208     return nullptr;
12209 
12210   if (Result) {
12211     SmallVector<const Expr *, 1> ResultAC;
12212     // We skipped over some ambiguous declarations which might be ambiguous with
12213     // the selected result.
12214     for (FunctionDecl *Skipped : AmbiguousDecls)
12215       if (!CheckMoreConstrained(Skipped, Result).hasValue())
12216         return nullptr;
12217     Pair = DAP;
12218   }
12219   return Result;
12220 }
12221 
12222 /// Given an overloaded function, tries to turn it into a non-overloaded
12223 /// function reference using resolveAddressOfSingleOverloadCandidate. This
12224 /// will perform access checks, diagnose the use of the resultant decl, and, if
12225 /// requested, potentially perform a function-to-pointer decay.
12226 ///
12227 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
12228 /// Otherwise, returns true. This may emit diagnostics and return true.
12229 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
12230     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
12231   Expr *E = SrcExpr.get();
12232   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
12233 
12234   DeclAccessPair DAP;
12235   FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
12236   if (!Found || Found->isCPUDispatchMultiVersion() ||
12237       Found->isCPUSpecificMultiVersion())
12238     return false;
12239 
12240   // Emitting multiple diagnostics for a function that is both inaccessible and
12241   // unavailable is consistent with our behavior elsewhere. So, always check
12242   // for both.
12243   DiagnoseUseOfDecl(Found, E->getExprLoc());
12244   CheckAddressOfMemberAccess(E, DAP);
12245   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
12246   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
12247     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
12248   else
12249     SrcExpr = Fixed;
12250   return true;
12251 }
12252 
12253 /// Given an expression that refers to an overloaded function, try to
12254 /// resolve that overloaded function expression down to a single function.
12255 ///
12256 /// This routine can only resolve template-ids that refer to a single function
12257 /// template, where that template-id refers to a single template whose template
12258 /// arguments are either provided by the template-id or have defaults,
12259 /// as described in C++0x [temp.arg.explicit]p3.
12260 ///
12261 /// If no template-ids are found, no diagnostics are emitted and NULL is
12262 /// returned.
12263 FunctionDecl *
12264 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
12265                                                   bool Complain,
12266                                                   DeclAccessPair *FoundResult) {
12267   // C++ [over.over]p1:
12268   //   [...] [Note: any redundant set of parentheses surrounding the
12269   //   overloaded function name is ignored (5.1). ]
12270   // C++ [over.over]p1:
12271   //   [...] The overloaded function name can be preceded by the &
12272   //   operator.
12273 
12274   // If we didn't actually find any template-ids, we're done.
12275   if (!ovl->hasExplicitTemplateArgs())
12276     return nullptr;
12277 
12278   TemplateArgumentListInfo ExplicitTemplateArgs;
12279   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
12280   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
12281 
12282   // Look through all of the overloaded functions, searching for one
12283   // whose type matches exactly.
12284   FunctionDecl *Matched = nullptr;
12285   for (UnresolvedSetIterator I = ovl->decls_begin(),
12286          E = ovl->decls_end(); I != E; ++I) {
12287     // C++0x [temp.arg.explicit]p3:
12288     //   [...] In contexts where deduction is done and fails, or in contexts
12289     //   where deduction is not done, if a template argument list is
12290     //   specified and it, along with any default template arguments,
12291     //   identifies a single function template specialization, then the
12292     //   template-id is an lvalue for the function template specialization.
12293     FunctionTemplateDecl *FunctionTemplate
12294       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
12295 
12296     // C++ [over.over]p2:
12297     //   If the name is a function template, template argument deduction is
12298     //   done (14.8.2.2), and if the argument deduction succeeds, the
12299     //   resulting template argument list is used to generate a single
12300     //   function template specialization, which is added to the set of
12301     //   overloaded functions considered.
12302     FunctionDecl *Specialization = nullptr;
12303     TemplateDeductionInfo Info(FailedCandidates.getLocation());
12304     if (TemplateDeductionResult Result
12305           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
12306                                     Specialization, Info,
12307                                     /*IsAddressOfFunction*/true)) {
12308       // Make a note of the failed deduction for diagnostics.
12309       // TODO: Actually use the failed-deduction info?
12310       FailedCandidates.addCandidate()
12311           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
12312                MakeDeductionFailureInfo(Context, Result, Info));
12313       continue;
12314     }
12315 
12316     assert(Specialization && "no specialization and no error?");
12317 
12318     // Multiple matches; we can't resolve to a single declaration.
12319     if (Matched) {
12320       if (Complain) {
12321         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
12322           << ovl->getName();
12323         NoteAllOverloadCandidates(ovl);
12324       }
12325       return nullptr;
12326     }
12327 
12328     Matched = Specialization;
12329     if (FoundResult) *FoundResult = I.getPair();
12330   }
12331 
12332   if (Matched &&
12333       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
12334     return nullptr;
12335 
12336   return Matched;
12337 }
12338 
12339 // Resolve and fix an overloaded expression that can be resolved
12340 // because it identifies a single function template specialization.
12341 //
12342 // Last three arguments should only be supplied if Complain = true
12343 //
12344 // Return true if it was logically possible to so resolve the
12345 // expression, regardless of whether or not it succeeded.  Always
12346 // returns true if 'complain' is set.
12347 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
12348                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
12349                       bool complain, SourceRange OpRangeForComplaining,
12350                                            QualType DestTypeForComplaining,
12351                                             unsigned DiagIDForComplaining) {
12352   assert(SrcExpr.get()->getType() == Context.OverloadTy);
12353 
12354   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
12355 
12356   DeclAccessPair found;
12357   ExprResult SingleFunctionExpression;
12358   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
12359                            ovl.Expression, /*complain*/ false, &found)) {
12360     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
12361       SrcExpr = ExprError();
12362       return true;
12363     }
12364 
12365     // It is only correct to resolve to an instance method if we're
12366     // resolving a form that's permitted to be a pointer to member.
12367     // Otherwise we'll end up making a bound member expression, which
12368     // is illegal in all the contexts we resolve like this.
12369     if (!ovl.HasFormOfMemberPointer &&
12370         isa<CXXMethodDecl>(fn) &&
12371         cast<CXXMethodDecl>(fn)->isInstance()) {
12372       if (!complain) return false;
12373 
12374       Diag(ovl.Expression->getExprLoc(),
12375            diag::err_bound_member_function)
12376         << 0 << ovl.Expression->getSourceRange();
12377 
12378       // TODO: I believe we only end up here if there's a mix of
12379       // static and non-static candidates (otherwise the expression
12380       // would have 'bound member' type, not 'overload' type).
12381       // Ideally we would note which candidate was chosen and why
12382       // the static candidates were rejected.
12383       SrcExpr = ExprError();
12384       return true;
12385     }
12386 
12387     // Fix the expression to refer to 'fn'.
12388     SingleFunctionExpression =
12389         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
12390 
12391     // If desired, do function-to-pointer decay.
12392     if (doFunctionPointerConverion) {
12393       SingleFunctionExpression =
12394         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
12395       if (SingleFunctionExpression.isInvalid()) {
12396         SrcExpr = ExprError();
12397         return true;
12398       }
12399     }
12400   }
12401 
12402   if (!SingleFunctionExpression.isUsable()) {
12403     if (complain) {
12404       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
12405         << ovl.Expression->getName()
12406         << DestTypeForComplaining
12407         << OpRangeForComplaining
12408         << ovl.Expression->getQualifierLoc().getSourceRange();
12409       NoteAllOverloadCandidates(SrcExpr.get());
12410 
12411       SrcExpr = ExprError();
12412       return true;
12413     }
12414 
12415     return false;
12416   }
12417 
12418   SrcExpr = SingleFunctionExpression;
12419   return true;
12420 }
12421 
12422 /// Add a single candidate to the overload set.
12423 static void AddOverloadedCallCandidate(Sema &S,
12424                                        DeclAccessPair FoundDecl,
12425                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
12426                                        ArrayRef<Expr *> Args,
12427                                        OverloadCandidateSet &CandidateSet,
12428                                        bool PartialOverloading,
12429                                        bool KnownValid) {
12430   NamedDecl *Callee = FoundDecl.getDecl();
12431   if (isa<UsingShadowDecl>(Callee))
12432     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
12433 
12434   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
12435     if (ExplicitTemplateArgs) {
12436       assert(!KnownValid && "Explicit template arguments?");
12437       return;
12438     }
12439     // Prevent ill-formed function decls to be added as overload candidates.
12440     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
12441       return;
12442 
12443     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
12444                            /*SuppressUserConversions=*/false,
12445                            PartialOverloading);
12446     return;
12447   }
12448 
12449   if (FunctionTemplateDecl *FuncTemplate
12450       = dyn_cast<FunctionTemplateDecl>(Callee)) {
12451     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
12452                                    ExplicitTemplateArgs, Args, CandidateSet,
12453                                    /*SuppressUserConversions=*/false,
12454                                    PartialOverloading);
12455     return;
12456   }
12457 
12458   assert(!KnownValid && "unhandled case in overloaded call candidate");
12459 }
12460 
12461 /// Add the overload candidates named by callee and/or found by argument
12462 /// dependent lookup to the given overload set.
12463 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
12464                                        ArrayRef<Expr *> Args,
12465                                        OverloadCandidateSet &CandidateSet,
12466                                        bool PartialOverloading) {
12467 
12468 #ifndef NDEBUG
12469   // Verify that ArgumentDependentLookup is consistent with the rules
12470   // in C++0x [basic.lookup.argdep]p3:
12471   //
12472   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
12473   //   and let Y be the lookup set produced by argument dependent
12474   //   lookup (defined as follows). If X contains
12475   //
12476   //     -- a declaration of a class member, or
12477   //
12478   //     -- a block-scope function declaration that is not a
12479   //        using-declaration, or
12480   //
12481   //     -- a declaration that is neither a function or a function
12482   //        template
12483   //
12484   //   then Y is empty.
12485 
12486   if (ULE->requiresADL()) {
12487     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12488            E = ULE->decls_end(); I != E; ++I) {
12489       assert(!(*I)->getDeclContext()->isRecord());
12490       assert(isa<UsingShadowDecl>(*I) ||
12491              !(*I)->getDeclContext()->isFunctionOrMethod());
12492       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
12493     }
12494   }
12495 #endif
12496 
12497   // It would be nice to avoid this copy.
12498   TemplateArgumentListInfo TABuffer;
12499   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12500   if (ULE->hasExplicitTemplateArgs()) {
12501     ULE->copyTemplateArgumentsInto(TABuffer);
12502     ExplicitTemplateArgs = &TABuffer;
12503   }
12504 
12505   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12506          E = ULE->decls_end(); I != E; ++I)
12507     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12508                                CandidateSet, PartialOverloading,
12509                                /*KnownValid*/ true);
12510 
12511   if (ULE->requiresADL())
12512     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
12513                                          Args, ExplicitTemplateArgs,
12514                                          CandidateSet, PartialOverloading);
12515 }
12516 
12517 /// Determine whether a declaration with the specified name could be moved into
12518 /// a different namespace.
12519 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
12520   switch (Name.getCXXOverloadedOperator()) {
12521   case OO_New: case OO_Array_New:
12522   case OO_Delete: case OO_Array_Delete:
12523     return false;
12524 
12525   default:
12526     return true;
12527   }
12528 }
12529 
12530 /// Attempt to recover from an ill-formed use of a non-dependent name in a
12531 /// template, where the non-dependent name was declared after the template
12532 /// was defined. This is common in code written for a compilers which do not
12533 /// correctly implement two-stage name lookup.
12534 ///
12535 /// Returns true if a viable candidate was found and a diagnostic was issued.
12536 static bool
12537 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
12538                        const CXXScopeSpec &SS, LookupResult &R,
12539                        OverloadCandidateSet::CandidateSetKind CSK,
12540                        TemplateArgumentListInfo *ExplicitTemplateArgs,
12541                        ArrayRef<Expr *> Args,
12542                        bool *DoDiagnoseEmptyLookup = nullptr) {
12543   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
12544     return false;
12545 
12546   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
12547     if (DC->isTransparentContext())
12548       continue;
12549 
12550     SemaRef.LookupQualifiedName(R, DC);
12551 
12552     if (!R.empty()) {
12553       R.suppressDiagnostics();
12554 
12555       if (isa<CXXRecordDecl>(DC)) {
12556         // Don't diagnose names we find in classes; we get much better
12557         // diagnostics for these from DiagnoseEmptyLookup.
12558         R.clear();
12559         if (DoDiagnoseEmptyLookup)
12560           *DoDiagnoseEmptyLookup = true;
12561         return false;
12562       }
12563 
12564       OverloadCandidateSet Candidates(FnLoc, CSK);
12565       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12566         AddOverloadedCallCandidate(SemaRef, I.getPair(),
12567                                    ExplicitTemplateArgs, Args,
12568                                    Candidates, false, /*KnownValid*/ false);
12569 
12570       OverloadCandidateSet::iterator Best;
12571       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
12572         // No viable functions. Don't bother the user with notes for functions
12573         // which don't work and shouldn't be found anyway.
12574         R.clear();
12575         return false;
12576       }
12577 
12578       // Find the namespaces where ADL would have looked, and suggest
12579       // declaring the function there instead.
12580       Sema::AssociatedNamespaceSet AssociatedNamespaces;
12581       Sema::AssociatedClassSet AssociatedClasses;
12582       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
12583                                                  AssociatedNamespaces,
12584                                                  AssociatedClasses);
12585       Sema::AssociatedNamespaceSet SuggestedNamespaces;
12586       if (canBeDeclaredInNamespace(R.getLookupName())) {
12587         DeclContext *Std = SemaRef.getStdNamespace();
12588         for (Sema::AssociatedNamespaceSet::iterator
12589                it = AssociatedNamespaces.begin(),
12590                end = AssociatedNamespaces.end(); it != end; ++it) {
12591           // Never suggest declaring a function within namespace 'std'.
12592           if (Std && Std->Encloses(*it))
12593             continue;
12594 
12595           // Never suggest declaring a function within a namespace with a
12596           // reserved name, like __gnu_cxx.
12597           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
12598           if (NS &&
12599               NS->getQualifiedNameAsString().find("__") != std::string::npos)
12600             continue;
12601 
12602           SuggestedNamespaces.insert(*it);
12603         }
12604       }
12605 
12606       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
12607         << R.getLookupName();
12608       if (SuggestedNamespaces.empty()) {
12609         SemaRef.Diag(Best->Function->getLocation(),
12610                      diag::note_not_found_by_two_phase_lookup)
12611           << R.getLookupName() << 0;
12612       } else if (SuggestedNamespaces.size() == 1) {
12613         SemaRef.Diag(Best->Function->getLocation(),
12614                      diag::note_not_found_by_two_phase_lookup)
12615           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
12616       } else {
12617         // FIXME: It would be useful to list the associated namespaces here,
12618         // but the diagnostics infrastructure doesn't provide a way to produce
12619         // a localized representation of a list of items.
12620         SemaRef.Diag(Best->Function->getLocation(),
12621                      diag::note_not_found_by_two_phase_lookup)
12622           << R.getLookupName() << 2;
12623       }
12624 
12625       // Try to recover by calling this function.
12626       return true;
12627     }
12628 
12629     R.clear();
12630   }
12631 
12632   return false;
12633 }
12634 
12635 /// Attempt to recover from ill-formed use of a non-dependent operator in a
12636 /// template, where the non-dependent operator was declared after the template
12637 /// was defined.
12638 ///
12639 /// Returns true if a viable candidate was found and a diagnostic was issued.
12640 static bool
12641 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
12642                                SourceLocation OpLoc,
12643                                ArrayRef<Expr *> Args) {
12644   DeclarationName OpName =
12645     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
12646   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
12647   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
12648                                 OverloadCandidateSet::CSK_Operator,
12649                                 /*ExplicitTemplateArgs=*/nullptr, Args);
12650 }
12651 
12652 namespace {
12653 class BuildRecoveryCallExprRAII {
12654   Sema &SemaRef;
12655 public:
12656   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
12657     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
12658     SemaRef.IsBuildingRecoveryCallExpr = true;
12659   }
12660 
12661   ~BuildRecoveryCallExprRAII() {
12662     SemaRef.IsBuildingRecoveryCallExpr = false;
12663   }
12664 };
12665 
12666 }
12667 
12668 /// Attempts to recover from a call where no functions were found.
12669 ///
12670 /// Returns true if new candidates were found.
12671 static ExprResult
12672 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12673                       UnresolvedLookupExpr *ULE,
12674                       SourceLocation LParenLoc,
12675                       MutableArrayRef<Expr *> Args,
12676                       SourceLocation RParenLoc,
12677                       bool EmptyLookup, bool AllowTypoCorrection) {
12678   // Do not try to recover if it is already building a recovery call.
12679   // This stops infinite loops for template instantiations like
12680   //
12681   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
12682   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
12683   //
12684   if (SemaRef.IsBuildingRecoveryCallExpr)
12685     return ExprError();
12686   BuildRecoveryCallExprRAII RCE(SemaRef);
12687 
12688   CXXScopeSpec SS;
12689   SS.Adopt(ULE->getQualifierLoc());
12690   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
12691 
12692   TemplateArgumentListInfo TABuffer;
12693   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12694   if (ULE->hasExplicitTemplateArgs()) {
12695     ULE->copyTemplateArgumentsInto(TABuffer);
12696     ExplicitTemplateArgs = &TABuffer;
12697   }
12698 
12699   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
12700                  Sema::LookupOrdinaryName);
12701   bool DoDiagnoseEmptyLookup = EmptyLookup;
12702   if (!DiagnoseTwoPhaseLookup(
12703           SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal,
12704           ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) {
12705     NoTypoCorrectionCCC NoTypoValidator{};
12706     FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
12707                                                 ExplicitTemplateArgs != nullptr,
12708                                                 dyn_cast<MemberExpr>(Fn));
12709     CorrectionCandidateCallback &Validator =
12710         AllowTypoCorrection
12711             ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
12712             : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
12713     if (!DoDiagnoseEmptyLookup ||
12714         SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
12715                                     Args))
12716       return ExprError();
12717   }
12718 
12719   assert(!R.empty() && "lookup results empty despite recovery");
12720 
12721   // If recovery created an ambiguity, just bail out.
12722   if (R.isAmbiguous()) {
12723     R.suppressDiagnostics();
12724     return ExprError();
12725   }
12726 
12727   // Build an implicit member call if appropriate.  Just drop the
12728   // casts and such from the call, we don't really care.
12729   ExprResult NewFn = ExprError();
12730   if ((*R.begin())->isCXXClassMember())
12731     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12732                                                     ExplicitTemplateArgs, S);
12733   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
12734     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
12735                                         ExplicitTemplateArgs);
12736   else
12737     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
12738 
12739   if (NewFn.isInvalid())
12740     return ExprError();
12741 
12742   // This shouldn't cause an infinite loop because we're giving it
12743   // an expression with viable lookup results, which should never
12744   // end up here.
12745   return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
12746                                MultiExprArg(Args.data(), Args.size()),
12747                                RParenLoc);
12748 }
12749 
12750 /// Constructs and populates an OverloadedCandidateSet from
12751 /// the given function.
12752 /// \returns true when an the ExprResult output parameter has been set.
12753 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
12754                                   UnresolvedLookupExpr *ULE,
12755                                   MultiExprArg Args,
12756                                   SourceLocation RParenLoc,
12757                                   OverloadCandidateSet *CandidateSet,
12758                                   ExprResult *Result) {
12759 #ifndef NDEBUG
12760   if (ULE->requiresADL()) {
12761     // To do ADL, we must have found an unqualified name.
12762     assert(!ULE->getQualifier() && "qualified name with ADL");
12763 
12764     // We don't perform ADL for implicit declarations of builtins.
12765     // Verify that this was correctly set up.
12766     FunctionDecl *F;
12767     if (ULE->decls_begin() != ULE->decls_end() &&
12768         ULE->decls_begin() + 1 == ULE->decls_end() &&
12769         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
12770         F->getBuiltinID() && F->isImplicit())
12771       llvm_unreachable("performing ADL for builtin");
12772 
12773     // We don't perform ADL in C.
12774     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
12775   }
12776 #endif
12777 
12778   UnbridgedCastsSet UnbridgedCasts;
12779   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
12780     *Result = ExprError();
12781     return true;
12782   }
12783 
12784   // Add the functions denoted by the callee to the set of candidate
12785   // functions, including those from argument-dependent lookup.
12786   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
12787 
12788   if (getLangOpts().MSVCCompat &&
12789       CurContext->isDependentContext() && !isSFINAEContext() &&
12790       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
12791 
12792     OverloadCandidateSet::iterator Best;
12793     if (CandidateSet->empty() ||
12794         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
12795             OR_No_Viable_Function) {
12796       // In Microsoft mode, if we are inside a template class member function
12797       // then create a type dependent CallExpr. The goal is to postpone name
12798       // lookup to instantiation time to be able to search into type dependent
12799       // base classes.
12800       CallExpr *CE =
12801           CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_RValue,
12802                            RParenLoc, CurFPFeatureOverrides());
12803       CE->markDependentForPostponedNameLookup();
12804       *Result = CE;
12805       return true;
12806     }
12807   }
12808 
12809   if (CandidateSet->empty())
12810     return false;
12811 
12812   UnbridgedCasts.restore();
12813   return false;
12814 }
12815 
12816 // Guess at what the return type for an unresolvable overload should be.
12817 static QualType chooseRecoveryType(OverloadCandidateSet &CS,
12818                                    OverloadCandidateSet::iterator *Best) {
12819   llvm::Optional<QualType> Result;
12820   // Adjust Type after seeing a candidate.
12821   auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
12822     if (!Candidate.Function)
12823       return;
12824     QualType T = Candidate.Function->getReturnType();
12825     if (T.isNull())
12826       return;
12827     if (!Result)
12828       Result = T;
12829     else if (Result != T)
12830       Result = QualType();
12831   };
12832 
12833   // Look for an unambiguous type from a progressively larger subset.
12834   // e.g. if types disagree, but all *viable* overloads return int, choose int.
12835   //
12836   // First, consider only the best candidate.
12837   if (Best && *Best != CS.end())
12838     ConsiderCandidate(**Best);
12839   // Next, consider only viable candidates.
12840   if (!Result)
12841     for (const auto &C : CS)
12842       if (C.Viable)
12843         ConsiderCandidate(C);
12844   // Finally, consider all candidates.
12845   if (!Result)
12846     for (const auto &C : CS)
12847       ConsiderCandidate(C);
12848 
12849   return Result.getValueOr(QualType());
12850 }
12851 
12852 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
12853 /// the completed call expression. If overload resolution fails, emits
12854 /// diagnostics and returns ExprError()
12855 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12856                                            UnresolvedLookupExpr *ULE,
12857                                            SourceLocation LParenLoc,
12858                                            MultiExprArg Args,
12859                                            SourceLocation RParenLoc,
12860                                            Expr *ExecConfig,
12861                                            OverloadCandidateSet *CandidateSet,
12862                                            OverloadCandidateSet::iterator *Best,
12863                                            OverloadingResult OverloadResult,
12864                                            bool AllowTypoCorrection) {
12865   if (CandidateSet->empty())
12866     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
12867                                  RParenLoc, /*EmptyLookup=*/true,
12868                                  AllowTypoCorrection);
12869 
12870   switch (OverloadResult) {
12871   case OR_Success: {
12872     FunctionDecl *FDecl = (*Best)->Function;
12873     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
12874     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
12875       return ExprError();
12876     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12877     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12878                                          ExecConfig, /*IsExecConfig=*/false,
12879                                          (*Best)->IsADLCandidate);
12880   }
12881 
12882   case OR_No_Viable_Function: {
12883     // Try to recover by looking for viable functions which the user might
12884     // have meant to call.
12885     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
12886                                                 Args, RParenLoc,
12887                                                 /*EmptyLookup=*/false,
12888                                                 AllowTypoCorrection);
12889     if (!Recovery.isInvalid())
12890       return Recovery;
12891 
12892     // If the user passes in a function that we can't take the address of, we
12893     // generally end up emitting really bad error messages. Here, we attempt to
12894     // emit better ones.
12895     for (const Expr *Arg : Args) {
12896       if (!Arg->getType()->isFunctionType())
12897         continue;
12898       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12899         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12900         if (FD &&
12901             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12902                                                        Arg->getExprLoc()))
12903           return ExprError();
12904       }
12905     }
12906 
12907     CandidateSet->NoteCandidates(
12908         PartialDiagnosticAt(
12909             Fn->getBeginLoc(),
12910             SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
12911                 << ULE->getName() << Fn->getSourceRange()),
12912         SemaRef, OCD_AllCandidates, Args);
12913     break;
12914   }
12915 
12916   case OR_Ambiguous:
12917     CandidateSet->NoteCandidates(
12918         PartialDiagnosticAt(Fn->getBeginLoc(),
12919                             SemaRef.PDiag(diag::err_ovl_ambiguous_call)
12920                                 << ULE->getName() << Fn->getSourceRange()),
12921         SemaRef, OCD_AmbiguousCandidates, Args);
12922     break;
12923 
12924   case OR_Deleted: {
12925     CandidateSet->NoteCandidates(
12926         PartialDiagnosticAt(Fn->getBeginLoc(),
12927                             SemaRef.PDiag(diag::err_ovl_deleted_call)
12928                                 << ULE->getName() << Fn->getSourceRange()),
12929         SemaRef, OCD_AllCandidates, Args);
12930 
12931     // We emitted an error for the unavailable/deleted function call but keep
12932     // the call in the AST.
12933     FunctionDecl *FDecl = (*Best)->Function;
12934     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12935     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12936                                          ExecConfig, /*IsExecConfig=*/false,
12937                                          (*Best)->IsADLCandidate);
12938   }
12939   }
12940 
12941   // Overload resolution failed, try to recover.
12942   SmallVector<Expr *, 8> SubExprs = {Fn};
12943   SubExprs.append(Args.begin(), Args.end());
12944   return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
12945                                     chooseRecoveryType(*CandidateSet, Best));
12946 }
12947 
12948 static void markUnaddressableCandidatesUnviable(Sema &S,
12949                                                 OverloadCandidateSet &CS) {
12950   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12951     if (I->Viable &&
12952         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12953       I->Viable = false;
12954       I->FailureKind = ovl_fail_addr_not_available;
12955     }
12956   }
12957 }
12958 
12959 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
12960 /// (which eventually refers to the declaration Func) and the call
12961 /// arguments Args/NumArgs, attempt to resolve the function call down
12962 /// to a specific function. If overload resolution succeeds, returns
12963 /// the call expression produced by overload resolution.
12964 /// Otherwise, emits diagnostics and returns ExprError.
12965 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12966                                          UnresolvedLookupExpr *ULE,
12967                                          SourceLocation LParenLoc,
12968                                          MultiExprArg Args,
12969                                          SourceLocation RParenLoc,
12970                                          Expr *ExecConfig,
12971                                          bool AllowTypoCorrection,
12972                                          bool CalleesAddressIsTaken) {
12973   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12974                                     OverloadCandidateSet::CSK_Normal);
12975   ExprResult result;
12976 
12977   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12978                              &result))
12979     return result;
12980 
12981   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12982   // functions that aren't addressible are considered unviable.
12983   if (CalleesAddressIsTaken)
12984     markUnaddressableCandidatesUnviable(*this, CandidateSet);
12985 
12986   OverloadCandidateSet::iterator Best;
12987   OverloadingResult OverloadResult =
12988       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
12989 
12990   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
12991                                   ExecConfig, &CandidateSet, &Best,
12992                                   OverloadResult, AllowTypoCorrection);
12993 }
12994 
12995 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
12996   return Functions.size() > 1 ||
12997          (Functions.size() == 1 &&
12998           isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl()));
12999 }
13000 
13001 ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
13002                                             NestedNameSpecifierLoc NNSLoc,
13003                                             DeclarationNameInfo DNI,
13004                                             const UnresolvedSetImpl &Fns,
13005                                             bool PerformADL) {
13006   return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI,
13007                                       PerformADL, IsOverloaded(Fns),
13008                                       Fns.begin(), Fns.end());
13009 }
13010 
13011 /// Create a unary operation that may resolve to an overloaded
13012 /// operator.
13013 ///
13014 /// \param OpLoc The location of the operator itself (e.g., '*').
13015 ///
13016 /// \param Opc The UnaryOperatorKind that describes this operator.
13017 ///
13018 /// \param Fns The set of non-member functions that will be
13019 /// considered by overload resolution. The caller needs to build this
13020 /// set based on the context using, e.g.,
13021 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13022 /// set should not contain any member functions; those will be added
13023 /// by CreateOverloadedUnaryOp().
13024 ///
13025 /// \param Input The input argument.
13026 ExprResult
13027 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
13028                               const UnresolvedSetImpl &Fns,
13029                               Expr *Input, bool PerformADL) {
13030   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
13031   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
13032   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13033   // TODO: provide better source location info.
13034   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13035 
13036   if (checkPlaceholderForOverload(*this, Input))
13037     return ExprError();
13038 
13039   Expr *Args[2] = { Input, nullptr };
13040   unsigned NumArgs = 1;
13041 
13042   // For post-increment and post-decrement, add the implicit '0' as
13043   // the second argument, so that we know this is a post-increment or
13044   // post-decrement.
13045   if (Opc == UO_PostInc || Opc == UO_PostDec) {
13046     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13047     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
13048                                      SourceLocation());
13049     NumArgs = 2;
13050   }
13051 
13052   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
13053 
13054   if (Input->isTypeDependent()) {
13055     if (Fns.empty())
13056       return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy,
13057                                    VK_RValue, OK_Ordinary, OpLoc, false,
13058                                    CurFPFeatureOverrides());
13059 
13060     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13061     ExprResult Fn = CreateUnresolvedLookupExpr(
13062         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
13063     if (Fn.isInvalid())
13064       return ExprError();
13065     return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
13066                                        Context.DependentTy, VK_RValue, OpLoc,
13067                                        CurFPFeatureOverrides());
13068   }
13069 
13070   // Build an empty overload set.
13071   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
13072 
13073   // Add the candidates from the given function set.
13074   AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
13075 
13076   // Add operator candidates that are member functions.
13077   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13078 
13079   // Add candidates from ADL.
13080   if (PerformADL) {
13081     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
13082                                          /*ExplicitTemplateArgs*/nullptr,
13083                                          CandidateSet);
13084   }
13085 
13086   // Add builtin operator candidates.
13087   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13088 
13089   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13090 
13091   // Perform overload resolution.
13092   OverloadCandidateSet::iterator Best;
13093   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13094   case OR_Success: {
13095     // We found a built-in operator or an overloaded operator.
13096     FunctionDecl *FnDecl = Best->Function;
13097 
13098     if (FnDecl) {
13099       Expr *Base = nullptr;
13100       // We matched an overloaded operator. Build a call to that
13101       // operator.
13102 
13103       // Convert the arguments.
13104       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13105         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
13106 
13107         ExprResult InputRes =
13108           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
13109                                               Best->FoundDecl, Method);
13110         if (InputRes.isInvalid())
13111           return ExprError();
13112         Base = Input = InputRes.get();
13113       } else {
13114         // Convert the arguments.
13115         ExprResult InputInit
13116           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13117                                                       Context,
13118                                                       FnDecl->getParamDecl(0)),
13119                                       SourceLocation(),
13120                                       Input);
13121         if (InputInit.isInvalid())
13122           return ExprError();
13123         Input = InputInit.get();
13124       }
13125 
13126       // Build the actual expression node.
13127       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
13128                                                 Base, HadMultipleCandidates,
13129                                                 OpLoc);
13130       if (FnExpr.isInvalid())
13131         return ExprError();
13132 
13133       // Determine the result type.
13134       QualType ResultTy = FnDecl->getReturnType();
13135       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13136       ResultTy = ResultTy.getNonLValueExprType(Context);
13137 
13138       Args[0] = Input;
13139       CallExpr *TheCall = CXXOperatorCallExpr::Create(
13140           Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
13141           CurFPFeatureOverrides(), Best->IsADLCandidate);
13142 
13143       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
13144         return ExprError();
13145 
13146       if (CheckFunctionCall(FnDecl, TheCall,
13147                             FnDecl->getType()->castAs<FunctionProtoType>()))
13148         return ExprError();
13149       return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
13150     } else {
13151       // We matched a built-in operator. Convert the arguments, then
13152       // break out so that we will build the appropriate built-in
13153       // operator node.
13154       ExprResult InputRes = PerformImplicitConversion(
13155           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
13156           CCK_ForBuiltinOverloadedOp);
13157       if (InputRes.isInvalid())
13158         return ExprError();
13159       Input = InputRes.get();
13160       break;
13161     }
13162   }
13163 
13164   case OR_No_Viable_Function:
13165     // This is an erroneous use of an operator which can be overloaded by
13166     // a non-member function. Check for non-member operators which were
13167     // defined too late to be candidates.
13168     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
13169       // FIXME: Recover by calling the found function.
13170       return ExprError();
13171 
13172     // No viable function; fall through to handling this as a
13173     // built-in operator, which will produce an error message for us.
13174     break;
13175 
13176   case OR_Ambiguous:
13177     CandidateSet.NoteCandidates(
13178         PartialDiagnosticAt(OpLoc,
13179                             PDiag(diag::err_ovl_ambiguous_oper_unary)
13180                                 << UnaryOperator::getOpcodeStr(Opc)
13181                                 << Input->getType() << Input->getSourceRange()),
13182         *this, OCD_AmbiguousCandidates, ArgsArray,
13183         UnaryOperator::getOpcodeStr(Opc), OpLoc);
13184     return ExprError();
13185 
13186   case OR_Deleted:
13187     CandidateSet.NoteCandidates(
13188         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
13189                                        << UnaryOperator::getOpcodeStr(Opc)
13190                                        << Input->getSourceRange()),
13191         *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
13192         OpLoc);
13193     return ExprError();
13194   }
13195 
13196   // Either we found no viable overloaded operator or we matched a
13197   // built-in operator. In either case, fall through to trying to
13198   // build a built-in operation.
13199   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13200 }
13201 
13202 /// Perform lookup for an overloaded binary operator.
13203 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
13204                                  OverloadedOperatorKind Op,
13205                                  const UnresolvedSetImpl &Fns,
13206                                  ArrayRef<Expr *> Args, bool PerformADL) {
13207   SourceLocation OpLoc = CandidateSet.getLocation();
13208 
13209   OverloadedOperatorKind ExtraOp =
13210       CandidateSet.getRewriteInfo().AllowRewrittenCandidates
13211           ? getRewrittenOverloadedOperator(Op)
13212           : OO_None;
13213 
13214   // Add the candidates from the given function set. This also adds the
13215   // rewritten candidates using these functions if necessary.
13216   AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
13217 
13218   // Add operator candidates that are member functions.
13219   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13220   if (CandidateSet.getRewriteInfo().shouldAddReversed(Op))
13221     AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
13222                                 OverloadCandidateParamOrder::Reversed);
13223 
13224   // In C++20, also add any rewritten member candidates.
13225   if (ExtraOp) {
13226     AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
13227     if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp))
13228       AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
13229                                   CandidateSet,
13230                                   OverloadCandidateParamOrder::Reversed);
13231   }
13232 
13233   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
13234   // performed for an assignment operator (nor for operator[] nor operator->,
13235   // which don't get here).
13236   if (Op != OO_Equal && PerformADL) {
13237     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13238     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
13239                                          /*ExplicitTemplateArgs*/ nullptr,
13240                                          CandidateSet);
13241     if (ExtraOp) {
13242       DeclarationName ExtraOpName =
13243           Context.DeclarationNames.getCXXOperatorName(ExtraOp);
13244       AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
13245                                            /*ExplicitTemplateArgs*/ nullptr,
13246                                            CandidateSet);
13247     }
13248   }
13249 
13250   // Add builtin operator candidates.
13251   //
13252   // FIXME: We don't add any rewritten candidates here. This is strictly
13253   // incorrect; a builtin candidate could be hidden by a non-viable candidate,
13254   // resulting in our selecting a rewritten builtin candidate. For example:
13255   //
13256   //   enum class E { e };
13257   //   bool operator!=(E, E) requires false;
13258   //   bool k = E::e != E::e;
13259   //
13260   // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
13261   // it seems unreasonable to consider rewritten builtin candidates. A core
13262   // issue has been filed proposing to removed this requirement.
13263   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13264 }
13265 
13266 /// Create a binary operation that may resolve to an overloaded
13267 /// operator.
13268 ///
13269 /// \param OpLoc The location of the operator itself (e.g., '+').
13270 ///
13271 /// \param Opc The BinaryOperatorKind that describes this operator.
13272 ///
13273 /// \param Fns The set of non-member functions that will be
13274 /// considered by overload resolution. The caller needs to build this
13275 /// set based on the context using, e.g.,
13276 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13277 /// set should not contain any member functions; those will be added
13278 /// by CreateOverloadedBinOp().
13279 ///
13280 /// \param LHS Left-hand argument.
13281 /// \param RHS Right-hand argument.
13282 /// \param PerformADL Whether to consider operator candidates found by ADL.
13283 /// \param AllowRewrittenCandidates Whether to consider candidates found by
13284 ///        C++20 operator rewrites.
13285 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
13286 ///        the function in question. Such a function is never a candidate in
13287 ///        our overload resolution. This also enables synthesizing a three-way
13288 ///        comparison from < and == as described in C++20 [class.spaceship]p1.
13289 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
13290                                        BinaryOperatorKind Opc,
13291                                        const UnresolvedSetImpl &Fns, Expr *LHS,
13292                                        Expr *RHS, bool PerformADL,
13293                                        bool AllowRewrittenCandidates,
13294                                        FunctionDecl *DefaultedFn) {
13295   Expr *Args[2] = { LHS, RHS };
13296   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
13297 
13298   if (!getLangOpts().CPlusPlus20)
13299     AllowRewrittenCandidates = false;
13300 
13301   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
13302 
13303   // If either side is type-dependent, create an appropriate dependent
13304   // expression.
13305   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13306     if (Fns.empty()) {
13307       // If there are no functions to store, just build a dependent
13308       // BinaryOperator or CompoundAssignment.
13309       if (Opc <= BO_Assign || Opc > BO_OrAssign)
13310         return BinaryOperator::Create(
13311             Context, Args[0], Args[1], Opc, Context.DependentTy, VK_RValue,
13312             OK_Ordinary, OpLoc, CurFPFeatureOverrides());
13313       return CompoundAssignOperator::Create(
13314           Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
13315           OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
13316           Context.DependentTy);
13317     }
13318 
13319     // FIXME: save results of ADL from here?
13320     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13321     // TODO: provide better source location info in DNLoc component.
13322     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13323     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13324     ExprResult Fn = CreateUnresolvedLookupExpr(
13325         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
13326     if (Fn.isInvalid())
13327       return ExprError();
13328     return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
13329                                        Context.DependentTy, VK_RValue, OpLoc,
13330                                        CurFPFeatureOverrides());
13331   }
13332 
13333   // Always do placeholder-like conversions on the RHS.
13334   if (checkPlaceholderForOverload(*this, Args[1]))
13335     return ExprError();
13336 
13337   // Do placeholder-like conversion on the LHS; note that we should
13338   // not get here with a PseudoObject LHS.
13339   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
13340   if (checkPlaceholderForOverload(*this, Args[0]))
13341     return ExprError();
13342 
13343   // If this is the assignment operator, we only perform overload resolution
13344   // if the left-hand side is a class or enumeration type. This is actually
13345   // a hack. The standard requires that we do overload resolution between the
13346   // various built-in candidates, but as DR507 points out, this can lead to
13347   // problems. So we do it this way, which pretty much follows what GCC does.
13348   // Note that we go the traditional code path for compound assignment forms.
13349   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
13350     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13351 
13352   // If this is the .* operator, which is not overloadable, just
13353   // create a built-in binary operator.
13354   if (Opc == BO_PtrMemD)
13355     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13356 
13357   // Build the overload set.
13358   OverloadCandidateSet CandidateSet(
13359       OpLoc, OverloadCandidateSet::CSK_Operator,
13360       OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates));
13361   if (DefaultedFn)
13362     CandidateSet.exclude(DefaultedFn);
13363   LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
13364 
13365   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13366 
13367   // Perform overload resolution.
13368   OverloadCandidateSet::iterator Best;
13369   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13370     case OR_Success: {
13371       // We found a built-in operator or an overloaded operator.
13372       FunctionDecl *FnDecl = Best->Function;
13373 
13374       bool IsReversed = Best->isReversed();
13375       if (IsReversed)
13376         std::swap(Args[0], Args[1]);
13377 
13378       if (FnDecl) {
13379         Expr *Base = nullptr;
13380         // We matched an overloaded operator. Build a call to that
13381         // operator.
13382 
13383         OverloadedOperatorKind ChosenOp =
13384             FnDecl->getDeclName().getCXXOverloadedOperator();
13385 
13386         // C++2a [over.match.oper]p9:
13387         //   If a rewritten operator== candidate is selected by overload
13388         //   resolution for an operator@, its return type shall be cv bool
13389         if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
13390             !FnDecl->getReturnType()->isBooleanType()) {
13391           bool IsExtension =
13392               FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
13393           Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
13394                                   : diag::err_ovl_rewrite_equalequal_not_bool)
13395               << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
13396               << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13397           Diag(FnDecl->getLocation(), diag::note_declared_at);
13398           if (!IsExtension)
13399             return ExprError();
13400         }
13401 
13402         if (AllowRewrittenCandidates && !IsReversed &&
13403             CandidateSet.getRewriteInfo().isReversible()) {
13404           // We could have reversed this operator, but didn't. Check if some
13405           // reversed form was a viable candidate, and if so, if it had a
13406           // better conversion for either parameter. If so, this call is
13407           // formally ambiguous, and allowing it is an extension.
13408           llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
13409           for (OverloadCandidate &Cand : CandidateSet) {
13410             if (Cand.Viable && Cand.Function && Cand.isReversed() &&
13411                 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) {
13412               for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
13413                 if (CompareImplicitConversionSequences(
13414                         *this, OpLoc, Cand.Conversions[ArgIdx],
13415                         Best->Conversions[ArgIdx]) ==
13416                     ImplicitConversionSequence::Better) {
13417                   AmbiguousWith.push_back(Cand.Function);
13418                   break;
13419                 }
13420               }
13421             }
13422           }
13423 
13424           if (!AmbiguousWith.empty()) {
13425             bool AmbiguousWithSelf =
13426                 AmbiguousWith.size() == 1 &&
13427                 declaresSameEntity(AmbiguousWith.front(), FnDecl);
13428             Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
13429                 << BinaryOperator::getOpcodeStr(Opc)
13430                 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
13431                 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13432             if (AmbiguousWithSelf) {
13433               Diag(FnDecl->getLocation(),
13434                    diag::note_ovl_ambiguous_oper_binary_reversed_self);
13435             } else {
13436               Diag(FnDecl->getLocation(),
13437                    diag::note_ovl_ambiguous_oper_binary_selected_candidate);
13438               for (auto *F : AmbiguousWith)
13439                 Diag(F->getLocation(),
13440                      diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
13441             }
13442           }
13443         }
13444 
13445         // Convert the arguments.
13446         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13447           // Best->Access is only meaningful for class members.
13448           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
13449 
13450           ExprResult Arg1 =
13451             PerformCopyInitialization(
13452               InitializedEntity::InitializeParameter(Context,
13453                                                      FnDecl->getParamDecl(0)),
13454               SourceLocation(), Args[1]);
13455           if (Arg1.isInvalid())
13456             return ExprError();
13457 
13458           ExprResult Arg0 =
13459             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13460                                                 Best->FoundDecl, Method);
13461           if (Arg0.isInvalid())
13462             return ExprError();
13463           Base = Args[0] = Arg0.getAs<Expr>();
13464           Args[1] = RHS = Arg1.getAs<Expr>();
13465         } else {
13466           // Convert the arguments.
13467           ExprResult Arg0 = PerformCopyInitialization(
13468             InitializedEntity::InitializeParameter(Context,
13469                                                    FnDecl->getParamDecl(0)),
13470             SourceLocation(), Args[0]);
13471           if (Arg0.isInvalid())
13472             return ExprError();
13473 
13474           ExprResult Arg1 =
13475             PerformCopyInitialization(
13476               InitializedEntity::InitializeParameter(Context,
13477                                                      FnDecl->getParamDecl(1)),
13478               SourceLocation(), Args[1]);
13479           if (Arg1.isInvalid())
13480             return ExprError();
13481           Args[0] = LHS = Arg0.getAs<Expr>();
13482           Args[1] = RHS = Arg1.getAs<Expr>();
13483         }
13484 
13485         // Build the actual expression node.
13486         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13487                                                   Best->FoundDecl, Base,
13488                                                   HadMultipleCandidates, OpLoc);
13489         if (FnExpr.isInvalid())
13490           return ExprError();
13491 
13492         // Determine the result type.
13493         QualType ResultTy = FnDecl->getReturnType();
13494         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13495         ResultTy = ResultTy.getNonLValueExprType(Context);
13496 
13497         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13498             Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
13499             CurFPFeatureOverrides(), Best->IsADLCandidate);
13500 
13501         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
13502                                 FnDecl))
13503           return ExprError();
13504 
13505         ArrayRef<const Expr *> ArgsArray(Args, 2);
13506         const Expr *ImplicitThis = nullptr;
13507         // Cut off the implicit 'this'.
13508         if (isa<CXXMethodDecl>(FnDecl)) {
13509           ImplicitThis = ArgsArray[0];
13510           ArgsArray = ArgsArray.slice(1);
13511         }
13512 
13513         // Check for a self move.
13514         if (Op == OO_Equal)
13515           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
13516 
13517         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
13518                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
13519                   VariadicDoesNotApply);
13520 
13521         ExprResult R = MaybeBindToTemporary(TheCall);
13522         if (R.isInvalid())
13523           return ExprError();
13524 
13525         R = CheckForImmediateInvocation(R, FnDecl);
13526         if (R.isInvalid())
13527           return ExprError();
13528 
13529         // For a rewritten candidate, we've already reversed the arguments
13530         // if needed. Perform the rest of the rewrite now.
13531         if ((Best->RewriteKind & CRK_DifferentOperator) ||
13532             (Op == OO_Spaceship && IsReversed)) {
13533           if (Op == OO_ExclaimEqual) {
13534             assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
13535             R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
13536           } else {
13537             assert(ChosenOp == OO_Spaceship && "unexpected operator name");
13538             llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13539             Expr *ZeroLiteral =
13540                 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
13541 
13542             Sema::CodeSynthesisContext Ctx;
13543             Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
13544             Ctx.Entity = FnDecl;
13545             pushCodeSynthesisContext(Ctx);
13546 
13547             R = CreateOverloadedBinOp(
13548                 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
13549                 IsReversed ? R.get() : ZeroLiteral, PerformADL,
13550                 /*AllowRewrittenCandidates=*/false);
13551 
13552             popCodeSynthesisContext();
13553           }
13554           if (R.isInvalid())
13555             return ExprError();
13556         } else {
13557           assert(ChosenOp == Op && "unexpected operator name");
13558         }
13559 
13560         // Make a note in the AST if we did any rewriting.
13561         if (Best->RewriteKind != CRK_None)
13562           R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
13563 
13564         return R;
13565       } else {
13566         // We matched a built-in operator. Convert the arguments, then
13567         // break out so that we will build the appropriate built-in
13568         // operator node.
13569         ExprResult ArgsRes0 = PerformImplicitConversion(
13570             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13571             AA_Passing, CCK_ForBuiltinOverloadedOp);
13572         if (ArgsRes0.isInvalid())
13573           return ExprError();
13574         Args[0] = ArgsRes0.get();
13575 
13576         ExprResult ArgsRes1 = PerformImplicitConversion(
13577             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13578             AA_Passing, CCK_ForBuiltinOverloadedOp);
13579         if (ArgsRes1.isInvalid())
13580           return ExprError();
13581         Args[1] = ArgsRes1.get();
13582         break;
13583       }
13584     }
13585 
13586     case OR_No_Viable_Function: {
13587       // C++ [over.match.oper]p9:
13588       //   If the operator is the operator , [...] and there are no
13589       //   viable functions, then the operator is assumed to be the
13590       //   built-in operator and interpreted according to clause 5.
13591       if (Opc == BO_Comma)
13592         break;
13593 
13594       // When defaulting an 'operator<=>', we can try to synthesize a three-way
13595       // compare result using '==' and '<'.
13596       if (DefaultedFn && Opc == BO_Cmp) {
13597         ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
13598                                                           Args[1], DefaultedFn);
13599         if (E.isInvalid() || E.isUsable())
13600           return E;
13601       }
13602 
13603       // For class as left operand for assignment or compound assignment
13604       // operator do not fall through to handling in built-in, but report that
13605       // no overloaded assignment operator found
13606       ExprResult Result = ExprError();
13607       StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
13608       auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
13609                                                    Args, OpLoc);
13610       if (Args[0]->getType()->isRecordType() &&
13611           Opc >= BO_Assign && Opc <= BO_OrAssign) {
13612         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
13613              << BinaryOperator::getOpcodeStr(Opc)
13614              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13615         if (Args[0]->getType()->isIncompleteType()) {
13616           Diag(OpLoc, diag::note_assign_lhs_incomplete)
13617             << Args[0]->getType()
13618             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13619         }
13620       } else {
13621         // This is an erroneous use of an operator which can be overloaded by
13622         // a non-member function. Check for non-member operators which were
13623         // defined too late to be candidates.
13624         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
13625           // FIXME: Recover by calling the found function.
13626           return ExprError();
13627 
13628         // No viable function; try to create a built-in operation, which will
13629         // produce an error. Then, show the non-viable candidates.
13630         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13631       }
13632       assert(Result.isInvalid() &&
13633              "C++ binary operator overloading is missing candidates!");
13634       CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
13635       return Result;
13636     }
13637 
13638     case OR_Ambiguous:
13639       CandidateSet.NoteCandidates(
13640           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13641                                          << BinaryOperator::getOpcodeStr(Opc)
13642                                          << Args[0]->getType()
13643                                          << Args[1]->getType()
13644                                          << Args[0]->getSourceRange()
13645                                          << Args[1]->getSourceRange()),
13646           *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13647           OpLoc);
13648       return ExprError();
13649 
13650     case OR_Deleted:
13651       if (isImplicitlyDeleted(Best->Function)) {
13652         FunctionDecl *DeletedFD = Best->Function;
13653         DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
13654         if (DFK.isSpecialMember()) {
13655           Diag(OpLoc, diag::err_ovl_deleted_special_oper)
13656             << Args[0]->getType() << DFK.asSpecialMember();
13657         } else {
13658           assert(DFK.isComparison());
13659           Diag(OpLoc, diag::err_ovl_deleted_comparison)
13660             << Args[0]->getType() << DeletedFD;
13661         }
13662 
13663         // The user probably meant to call this special member. Just
13664         // explain why it's deleted.
13665         NoteDeletedFunction(DeletedFD);
13666         return ExprError();
13667       }
13668       CandidateSet.NoteCandidates(
13669           PartialDiagnosticAt(
13670               OpLoc, PDiag(diag::err_ovl_deleted_oper)
13671                          << getOperatorSpelling(Best->Function->getDeclName()
13672                                                     .getCXXOverloadedOperator())
13673                          << Args[0]->getSourceRange()
13674                          << Args[1]->getSourceRange()),
13675           *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13676           OpLoc);
13677       return ExprError();
13678   }
13679 
13680   // We matched a built-in operator; build it.
13681   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13682 }
13683 
13684 ExprResult Sema::BuildSynthesizedThreeWayComparison(
13685     SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
13686     FunctionDecl *DefaultedFn) {
13687   const ComparisonCategoryInfo *Info =
13688       Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
13689   // If we're not producing a known comparison category type, we can't
13690   // synthesize a three-way comparison. Let the caller diagnose this.
13691   if (!Info)
13692     return ExprResult((Expr*)nullptr);
13693 
13694   // If we ever want to perform this synthesis more generally, we will need to
13695   // apply the temporary materialization conversion to the operands.
13696   assert(LHS->isGLValue() && RHS->isGLValue() &&
13697          "cannot use prvalue expressions more than once");
13698   Expr *OrigLHS = LHS;
13699   Expr *OrigRHS = RHS;
13700 
13701   // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
13702   // each of them multiple times below.
13703   LHS = new (Context)
13704       OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
13705                       LHS->getObjectKind(), LHS);
13706   RHS = new (Context)
13707       OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
13708                       RHS->getObjectKind(), RHS);
13709 
13710   ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
13711                                         DefaultedFn);
13712   if (Eq.isInvalid())
13713     return ExprError();
13714 
13715   ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
13716                                           true, DefaultedFn);
13717   if (Less.isInvalid())
13718     return ExprError();
13719 
13720   ExprResult Greater;
13721   if (Info->isPartial()) {
13722     Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
13723                                     DefaultedFn);
13724     if (Greater.isInvalid())
13725       return ExprError();
13726   }
13727 
13728   // Form the list of comparisons we're going to perform.
13729   struct Comparison {
13730     ExprResult Cmp;
13731     ComparisonCategoryResult Result;
13732   } Comparisons[4] =
13733   { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
13734                           : ComparisonCategoryResult::Equivalent},
13735     {Less, ComparisonCategoryResult::Less},
13736     {Greater, ComparisonCategoryResult::Greater},
13737     {ExprResult(), ComparisonCategoryResult::Unordered},
13738   };
13739 
13740   int I = Info->isPartial() ? 3 : 2;
13741 
13742   // Combine the comparisons with suitable conditional expressions.
13743   ExprResult Result;
13744   for (; I >= 0; --I) {
13745     // Build a reference to the comparison category constant.
13746     auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
13747     // FIXME: Missing a constant for a comparison category. Diagnose this?
13748     if (!VI)
13749       return ExprResult((Expr*)nullptr);
13750     ExprResult ThisResult =
13751         BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
13752     if (ThisResult.isInvalid())
13753       return ExprError();
13754 
13755     // Build a conditional unless this is the final case.
13756     if (Result.get()) {
13757       Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
13758                                   ThisResult.get(), Result.get());
13759       if (Result.isInvalid())
13760         return ExprError();
13761     } else {
13762       Result = ThisResult;
13763     }
13764   }
13765 
13766   // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
13767   // bind the OpaqueValueExprs before they're (repeatedly) used.
13768   Expr *SyntacticForm = BinaryOperator::Create(
13769       Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
13770       Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
13771       CurFPFeatureOverrides());
13772   Expr *SemanticForm[] = {LHS, RHS, Result.get()};
13773   return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
13774 }
13775 
13776 ExprResult
13777 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
13778                                          SourceLocation RLoc,
13779                                          Expr *Base, Expr *Idx) {
13780   Expr *Args[2] = { Base, Idx };
13781   DeclarationName OpName =
13782       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
13783 
13784   // If either side is type-dependent, create an appropriate dependent
13785   // expression.
13786   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13787 
13788     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13789     // CHECKME: no 'operator' keyword?
13790     DeclarationNameInfo OpNameInfo(OpName, LLoc);
13791     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13792     ExprResult Fn = CreateUnresolvedLookupExpr(
13793         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
13794     if (Fn.isInvalid())
13795       return ExprError();
13796     // Can't add any actual overloads yet
13797 
13798     return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
13799                                        Context.DependentTy, VK_RValue, RLoc,
13800                                        CurFPFeatureOverrides());
13801   }
13802 
13803   // Handle placeholders on both operands.
13804   if (checkPlaceholderForOverload(*this, Args[0]))
13805     return ExprError();
13806   if (checkPlaceholderForOverload(*this, Args[1]))
13807     return ExprError();
13808 
13809   // Build an empty overload set.
13810   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
13811 
13812   // Subscript can only be overloaded as a member function.
13813 
13814   // Add operator candidates that are member functions.
13815   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13816 
13817   // Add builtin operator candidates.
13818   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13819 
13820   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13821 
13822   // Perform overload resolution.
13823   OverloadCandidateSet::iterator Best;
13824   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
13825     case OR_Success: {
13826       // We found a built-in operator or an overloaded operator.
13827       FunctionDecl *FnDecl = Best->Function;
13828 
13829       if (FnDecl) {
13830         // We matched an overloaded operator. Build a call to that
13831         // operator.
13832 
13833         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
13834 
13835         // Convert the arguments.
13836         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
13837         ExprResult Arg0 =
13838           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13839                                               Best->FoundDecl, Method);
13840         if (Arg0.isInvalid())
13841           return ExprError();
13842         Args[0] = Arg0.get();
13843 
13844         // Convert the arguments.
13845         ExprResult InputInit
13846           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13847                                                       Context,
13848                                                       FnDecl->getParamDecl(0)),
13849                                       SourceLocation(),
13850                                       Args[1]);
13851         if (InputInit.isInvalid())
13852           return ExprError();
13853 
13854         Args[1] = InputInit.getAs<Expr>();
13855 
13856         // Build the actual expression node.
13857         DeclarationNameInfo OpLocInfo(OpName, LLoc);
13858         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13859         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13860                                                   Best->FoundDecl,
13861                                                   Base,
13862                                                   HadMultipleCandidates,
13863                                                   OpLocInfo.getLoc(),
13864                                                   OpLocInfo.getInfo());
13865         if (FnExpr.isInvalid())
13866           return ExprError();
13867 
13868         // Determine the result type
13869         QualType ResultTy = FnDecl->getReturnType();
13870         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13871         ResultTy = ResultTy.getNonLValueExprType(Context);
13872 
13873         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13874             Context, OO_Subscript, FnExpr.get(), Args, ResultTy, VK, RLoc,
13875             CurFPFeatureOverrides());
13876         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
13877           return ExprError();
13878 
13879         if (CheckFunctionCall(Method, TheCall,
13880                               Method->getType()->castAs<FunctionProtoType>()))
13881           return ExprError();
13882 
13883         return MaybeBindToTemporary(TheCall);
13884       } else {
13885         // We matched a built-in operator. Convert the arguments, then
13886         // break out so that we will build the appropriate built-in
13887         // operator node.
13888         ExprResult ArgsRes0 = PerformImplicitConversion(
13889             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13890             AA_Passing, CCK_ForBuiltinOverloadedOp);
13891         if (ArgsRes0.isInvalid())
13892           return ExprError();
13893         Args[0] = ArgsRes0.get();
13894 
13895         ExprResult ArgsRes1 = PerformImplicitConversion(
13896             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13897             AA_Passing, CCK_ForBuiltinOverloadedOp);
13898         if (ArgsRes1.isInvalid())
13899           return ExprError();
13900         Args[1] = ArgsRes1.get();
13901 
13902         break;
13903       }
13904     }
13905 
13906     case OR_No_Viable_Function: {
13907       PartialDiagnostic PD = CandidateSet.empty()
13908           ? (PDiag(diag::err_ovl_no_oper)
13909              << Args[0]->getType() << /*subscript*/ 0
13910              << Args[0]->getSourceRange() << Args[1]->getSourceRange())
13911           : (PDiag(diag::err_ovl_no_viable_subscript)
13912              << Args[0]->getType() << Args[0]->getSourceRange()
13913              << Args[1]->getSourceRange());
13914       CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
13915                                   OCD_AllCandidates, Args, "[]", LLoc);
13916       return ExprError();
13917     }
13918 
13919     case OR_Ambiguous:
13920       CandidateSet.NoteCandidates(
13921           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13922                                         << "[]" << Args[0]->getType()
13923                                         << Args[1]->getType()
13924                                         << Args[0]->getSourceRange()
13925                                         << Args[1]->getSourceRange()),
13926           *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
13927       return ExprError();
13928 
13929     case OR_Deleted:
13930       CandidateSet.NoteCandidates(
13931           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
13932                                         << "[]" << Args[0]->getSourceRange()
13933                                         << Args[1]->getSourceRange()),
13934           *this, OCD_AllCandidates, Args, "[]", LLoc);
13935       return ExprError();
13936     }
13937 
13938   // We matched a built-in operator; build it.
13939   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
13940 }
13941 
13942 /// BuildCallToMemberFunction - Build a call to a member
13943 /// function. MemExpr is the expression that refers to the member
13944 /// function (and includes the object parameter), Args/NumArgs are the
13945 /// arguments to the function call (not including the object
13946 /// parameter). The caller needs to validate that the member
13947 /// expression refers to a non-static member function or an overloaded
13948 /// member function.
13949 ExprResult
13950 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
13951                                 SourceLocation LParenLoc,
13952                                 MultiExprArg Args,
13953                                 SourceLocation RParenLoc) {
13954   assert(MemExprE->getType() == Context.BoundMemberTy ||
13955          MemExprE->getType() == Context.OverloadTy);
13956 
13957   // Dig out the member expression. This holds both the object
13958   // argument and the member function we're referring to.
13959   Expr *NakedMemExpr = MemExprE->IgnoreParens();
13960 
13961   // Determine whether this is a call to a pointer-to-member function.
13962   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
13963     assert(op->getType() == Context.BoundMemberTy);
13964     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
13965 
13966     QualType fnType =
13967       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
13968 
13969     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
13970     QualType resultType = proto->getCallResultType(Context);
13971     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
13972 
13973     // Check that the object type isn't more qualified than the
13974     // member function we're calling.
13975     Qualifiers funcQuals = proto->getMethodQuals();
13976 
13977     QualType objectType = op->getLHS()->getType();
13978     if (op->getOpcode() == BO_PtrMemI)
13979       objectType = objectType->castAs<PointerType>()->getPointeeType();
13980     Qualifiers objectQuals = objectType.getQualifiers();
13981 
13982     Qualifiers difference = objectQuals - funcQuals;
13983     difference.removeObjCGCAttr();
13984     difference.removeAddressSpace();
13985     if (difference) {
13986       std::string qualsString = difference.getAsString();
13987       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
13988         << fnType.getUnqualifiedType()
13989         << qualsString
13990         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
13991     }
13992 
13993     CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
13994         Context, MemExprE, Args, resultType, valueKind, RParenLoc,
13995         CurFPFeatureOverrides(), proto->getNumParams());
13996 
13997     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
13998                             call, nullptr))
13999       return ExprError();
14000 
14001     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
14002       return ExprError();
14003 
14004     if (CheckOtherCall(call, proto))
14005       return ExprError();
14006 
14007     return MaybeBindToTemporary(call);
14008   }
14009 
14010   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
14011     return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue,
14012                             RParenLoc, CurFPFeatureOverrides());
14013 
14014   UnbridgedCastsSet UnbridgedCasts;
14015   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14016     return ExprError();
14017 
14018   MemberExpr *MemExpr;
14019   CXXMethodDecl *Method = nullptr;
14020   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
14021   NestedNameSpecifier *Qualifier = nullptr;
14022   if (isa<MemberExpr>(NakedMemExpr)) {
14023     MemExpr = cast<MemberExpr>(NakedMemExpr);
14024     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
14025     FoundDecl = MemExpr->getFoundDecl();
14026     Qualifier = MemExpr->getQualifier();
14027     UnbridgedCasts.restore();
14028   } else {
14029     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
14030     Qualifier = UnresExpr->getQualifier();
14031 
14032     QualType ObjectType = UnresExpr->getBaseType();
14033     Expr::Classification ObjectClassification
14034       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
14035                             : UnresExpr->getBase()->Classify(Context);
14036 
14037     // Add overload candidates
14038     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
14039                                       OverloadCandidateSet::CSK_Normal);
14040 
14041     // FIXME: avoid copy.
14042     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14043     if (UnresExpr->hasExplicitTemplateArgs()) {
14044       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14045       TemplateArgs = &TemplateArgsBuffer;
14046     }
14047 
14048     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
14049            E = UnresExpr->decls_end(); I != E; ++I) {
14050 
14051       NamedDecl *Func = *I;
14052       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
14053       if (isa<UsingShadowDecl>(Func))
14054         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
14055 
14056 
14057       // Microsoft supports direct constructor calls.
14058       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
14059         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
14060                              CandidateSet,
14061                              /*SuppressUserConversions*/ false);
14062       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
14063         // If explicit template arguments were provided, we can't call a
14064         // non-template member function.
14065         if (TemplateArgs)
14066           continue;
14067 
14068         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
14069                            ObjectClassification, Args, CandidateSet,
14070                            /*SuppressUserConversions=*/false);
14071       } else {
14072         AddMethodTemplateCandidate(
14073             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
14074             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
14075             /*SuppressUserConversions=*/false);
14076       }
14077     }
14078 
14079     DeclarationName DeclName = UnresExpr->getMemberName();
14080 
14081     UnbridgedCasts.restore();
14082 
14083     OverloadCandidateSet::iterator Best;
14084     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
14085                                             Best)) {
14086     case OR_Success:
14087       Method = cast<CXXMethodDecl>(Best->Function);
14088       FoundDecl = Best->FoundDecl;
14089       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
14090       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
14091         return ExprError();
14092       // If FoundDecl is different from Method (such as if one is a template
14093       // and the other a specialization), make sure DiagnoseUseOfDecl is
14094       // called on both.
14095       // FIXME: This would be more comprehensively addressed by modifying
14096       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
14097       // being used.
14098       if (Method != FoundDecl.getDecl() &&
14099                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
14100         return ExprError();
14101       break;
14102 
14103     case OR_No_Viable_Function:
14104       CandidateSet.NoteCandidates(
14105           PartialDiagnosticAt(
14106               UnresExpr->getMemberLoc(),
14107               PDiag(diag::err_ovl_no_viable_member_function_in_call)
14108                   << DeclName << MemExprE->getSourceRange()),
14109           *this, OCD_AllCandidates, Args);
14110       // FIXME: Leaking incoming expressions!
14111       return ExprError();
14112 
14113     case OR_Ambiguous:
14114       CandidateSet.NoteCandidates(
14115           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14116                               PDiag(diag::err_ovl_ambiguous_member_call)
14117                                   << DeclName << MemExprE->getSourceRange()),
14118           *this, OCD_AmbiguousCandidates, Args);
14119       // FIXME: Leaking incoming expressions!
14120       return ExprError();
14121 
14122     case OR_Deleted:
14123       CandidateSet.NoteCandidates(
14124           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14125                               PDiag(diag::err_ovl_deleted_member_call)
14126                                   << DeclName << MemExprE->getSourceRange()),
14127           *this, OCD_AllCandidates, Args);
14128       // FIXME: Leaking incoming expressions!
14129       return ExprError();
14130     }
14131 
14132     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
14133 
14134     // If overload resolution picked a static member, build a
14135     // non-member call based on that function.
14136     if (Method->isStatic()) {
14137       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
14138                                    RParenLoc);
14139     }
14140 
14141     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
14142   }
14143 
14144   QualType ResultType = Method->getReturnType();
14145   ExprValueKind VK = Expr::getValueKindForType(ResultType);
14146   ResultType = ResultType.getNonLValueExprType(Context);
14147 
14148   assert(Method && "Member call to something that isn't a method?");
14149   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14150   CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create(
14151       Context, MemExprE, Args, ResultType, VK, RParenLoc,
14152       CurFPFeatureOverrides(), Proto->getNumParams());
14153 
14154   // Check for a valid return type.
14155   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
14156                           TheCall, Method))
14157     return ExprError();
14158 
14159   // Convert the object argument (for a non-static member function call).
14160   // We only need to do this if there was actually an overload; otherwise
14161   // it was done at lookup.
14162   if (!Method->isStatic()) {
14163     ExprResult ObjectArg =
14164       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
14165                                           FoundDecl, Method);
14166     if (ObjectArg.isInvalid())
14167       return ExprError();
14168     MemExpr->setBase(ObjectArg.get());
14169   }
14170 
14171   // Convert the rest of the arguments
14172   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
14173                               RParenLoc))
14174     return ExprError();
14175 
14176   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14177 
14178   if (CheckFunctionCall(Method, TheCall, Proto))
14179     return ExprError();
14180 
14181   // In the case the method to call was not selected by the overloading
14182   // resolution process, we still need to handle the enable_if attribute. Do
14183   // that here, so it will not hide previous -- and more relevant -- errors.
14184   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
14185     if (const EnableIfAttr *Attr =
14186             CheckEnableIf(Method, LParenLoc, Args, true)) {
14187       Diag(MemE->getMemberLoc(),
14188            diag::err_ovl_no_viable_member_function_in_call)
14189           << Method << Method->getSourceRange();
14190       Diag(Method->getLocation(),
14191            diag::note_ovl_candidate_disabled_by_function_cond_attr)
14192           << Attr->getCond()->getSourceRange() << Attr->getMessage();
14193       return ExprError();
14194     }
14195   }
14196 
14197   if ((isa<CXXConstructorDecl>(CurContext) ||
14198        isa<CXXDestructorDecl>(CurContext)) &&
14199       TheCall->getMethodDecl()->isPure()) {
14200     const CXXMethodDecl *MD = TheCall->getMethodDecl();
14201 
14202     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
14203         MemExpr->performsVirtualDispatch(getLangOpts())) {
14204       Diag(MemExpr->getBeginLoc(),
14205            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
14206           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
14207           << MD->getParent();
14208 
14209       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
14210       if (getLangOpts().AppleKext)
14211         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
14212             << MD->getParent() << MD->getDeclName();
14213     }
14214   }
14215 
14216   if (CXXDestructorDecl *DD =
14217           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
14218     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
14219     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
14220     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
14221                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
14222                          MemExpr->getMemberLoc());
14223   }
14224 
14225   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14226                                      TheCall->getMethodDecl());
14227 }
14228 
14229 /// BuildCallToObjectOfClassType - Build a call to an object of class
14230 /// type (C++ [over.call.object]), which can end up invoking an
14231 /// overloaded function call operator (@c operator()) or performing a
14232 /// user-defined conversion on the object argument.
14233 ExprResult
14234 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
14235                                    SourceLocation LParenLoc,
14236                                    MultiExprArg Args,
14237                                    SourceLocation RParenLoc) {
14238   if (checkPlaceholderForOverload(*this, Obj))
14239     return ExprError();
14240   ExprResult Object = Obj;
14241 
14242   UnbridgedCastsSet UnbridgedCasts;
14243   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14244     return ExprError();
14245 
14246   assert(Object.get()->getType()->isRecordType() &&
14247          "Requires object type argument");
14248 
14249   // C++ [over.call.object]p1:
14250   //  If the primary-expression E in the function call syntax
14251   //  evaluates to a class object of type "cv T", then the set of
14252   //  candidate functions includes at least the function call
14253   //  operators of T. The function call operators of T are obtained by
14254   //  ordinary lookup of the name operator() in the context of
14255   //  (E).operator().
14256   OverloadCandidateSet CandidateSet(LParenLoc,
14257                                     OverloadCandidateSet::CSK_Operator);
14258   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
14259 
14260   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
14261                           diag::err_incomplete_object_call, Object.get()))
14262     return true;
14263 
14264   const auto *Record = Object.get()->getType()->castAs<RecordType>();
14265   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
14266   LookupQualifiedName(R, Record->getDecl());
14267   R.suppressDiagnostics();
14268 
14269   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14270        Oper != OperEnd; ++Oper) {
14271     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
14272                        Object.get()->Classify(Context), Args, CandidateSet,
14273                        /*SuppressUserConversion=*/false);
14274   }
14275 
14276   // C++ [over.call.object]p2:
14277   //   In addition, for each (non-explicit in C++0x) conversion function
14278   //   declared in T of the form
14279   //
14280   //        operator conversion-type-id () cv-qualifier;
14281   //
14282   //   where cv-qualifier is the same cv-qualification as, or a
14283   //   greater cv-qualification than, cv, and where conversion-type-id
14284   //   denotes the type "pointer to function of (P1,...,Pn) returning
14285   //   R", or the type "reference to pointer to function of
14286   //   (P1,...,Pn) returning R", or the type "reference to function
14287   //   of (P1,...,Pn) returning R", a surrogate call function [...]
14288   //   is also considered as a candidate function. Similarly,
14289   //   surrogate call functions are added to the set of candidate
14290   //   functions for each conversion function declared in an
14291   //   accessible base class provided the function is not hidden
14292   //   within T by another intervening declaration.
14293   const auto &Conversions =
14294       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
14295   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
14296     NamedDecl *D = *I;
14297     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
14298     if (isa<UsingShadowDecl>(D))
14299       D = cast<UsingShadowDecl>(D)->getTargetDecl();
14300 
14301     // Skip over templated conversion functions; they aren't
14302     // surrogates.
14303     if (isa<FunctionTemplateDecl>(D))
14304       continue;
14305 
14306     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
14307     if (!Conv->isExplicit()) {
14308       // Strip the reference type (if any) and then the pointer type (if
14309       // any) to get down to what might be a function type.
14310       QualType ConvType = Conv->getConversionType().getNonReferenceType();
14311       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
14312         ConvType = ConvPtrType->getPointeeType();
14313 
14314       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
14315       {
14316         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
14317                               Object.get(), Args, CandidateSet);
14318       }
14319     }
14320   }
14321 
14322   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14323 
14324   // Perform overload resolution.
14325   OverloadCandidateSet::iterator Best;
14326   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
14327                                           Best)) {
14328   case OR_Success:
14329     // Overload resolution succeeded; we'll build the appropriate call
14330     // below.
14331     break;
14332 
14333   case OR_No_Viable_Function: {
14334     PartialDiagnostic PD =
14335         CandidateSet.empty()
14336             ? (PDiag(diag::err_ovl_no_oper)
14337                << Object.get()->getType() << /*call*/ 1
14338                << Object.get()->getSourceRange())
14339             : (PDiag(diag::err_ovl_no_viable_object_call)
14340                << Object.get()->getType() << Object.get()->getSourceRange());
14341     CandidateSet.NoteCandidates(
14342         PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
14343         OCD_AllCandidates, Args);
14344     break;
14345   }
14346   case OR_Ambiguous:
14347     CandidateSet.NoteCandidates(
14348         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14349                             PDiag(diag::err_ovl_ambiguous_object_call)
14350                                 << Object.get()->getType()
14351                                 << Object.get()->getSourceRange()),
14352         *this, OCD_AmbiguousCandidates, Args);
14353     break;
14354 
14355   case OR_Deleted:
14356     CandidateSet.NoteCandidates(
14357         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14358                             PDiag(diag::err_ovl_deleted_object_call)
14359                                 << Object.get()->getType()
14360                                 << Object.get()->getSourceRange()),
14361         *this, OCD_AllCandidates, Args);
14362     break;
14363   }
14364 
14365   if (Best == CandidateSet.end())
14366     return true;
14367 
14368   UnbridgedCasts.restore();
14369 
14370   if (Best->Function == nullptr) {
14371     // Since there is no function declaration, this is one of the
14372     // surrogate candidates. Dig out the conversion function.
14373     CXXConversionDecl *Conv
14374       = cast<CXXConversionDecl>(
14375                          Best->Conversions[0].UserDefined.ConversionFunction);
14376 
14377     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
14378                               Best->FoundDecl);
14379     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
14380       return ExprError();
14381     assert(Conv == Best->FoundDecl.getDecl() &&
14382              "Found Decl & conversion-to-functionptr should be same, right?!");
14383     // We selected one of the surrogate functions that converts the
14384     // object parameter to a function pointer. Perform the conversion
14385     // on the object argument, then let BuildCallExpr finish the job.
14386 
14387     // Create an implicit member expr to refer to the conversion operator.
14388     // and then call it.
14389     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
14390                                              Conv, HadMultipleCandidates);
14391     if (Call.isInvalid())
14392       return ExprError();
14393     // Record usage of conversion in an implicit cast.
14394     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
14395                                     CK_UserDefinedConversion, Call.get(),
14396                                     nullptr, VK_RValue);
14397 
14398     return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
14399   }
14400 
14401   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
14402 
14403   // We found an overloaded operator(). Build a CXXOperatorCallExpr
14404   // that calls this method, using Object for the implicit object
14405   // parameter and passing along the remaining arguments.
14406   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14407 
14408   // An error diagnostic has already been printed when parsing the declaration.
14409   if (Method->isInvalidDecl())
14410     return ExprError();
14411 
14412   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14413   unsigned NumParams = Proto->getNumParams();
14414 
14415   DeclarationNameInfo OpLocInfo(
14416                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
14417   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
14418   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14419                                            Obj, HadMultipleCandidates,
14420                                            OpLocInfo.getLoc(),
14421                                            OpLocInfo.getInfo());
14422   if (NewFn.isInvalid())
14423     return true;
14424 
14425   // The number of argument slots to allocate in the call. If we have default
14426   // arguments we need to allocate space for them as well. We additionally
14427   // need one more slot for the object parameter.
14428   unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
14429 
14430   // Build the full argument list for the method call (the implicit object
14431   // parameter is placed at the beginning of the list).
14432   SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
14433 
14434   bool IsError = false;
14435 
14436   // Initialize the implicit object parameter.
14437   ExprResult ObjRes =
14438     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
14439                                         Best->FoundDecl, Method);
14440   if (ObjRes.isInvalid())
14441     IsError = true;
14442   else
14443     Object = ObjRes;
14444   MethodArgs[0] = Object.get();
14445 
14446   // Check the argument types.
14447   for (unsigned i = 0; i != NumParams; i++) {
14448     Expr *Arg;
14449     if (i < Args.size()) {
14450       Arg = Args[i];
14451 
14452       // Pass the argument.
14453 
14454       ExprResult InputInit
14455         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14456                                                     Context,
14457                                                     Method->getParamDecl(i)),
14458                                     SourceLocation(), Arg);
14459 
14460       IsError |= InputInit.isInvalid();
14461       Arg = InputInit.getAs<Expr>();
14462     } else {
14463       ExprResult DefArg
14464         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14465       if (DefArg.isInvalid()) {
14466         IsError = true;
14467         break;
14468       }
14469 
14470       Arg = DefArg.getAs<Expr>();
14471     }
14472 
14473     MethodArgs[i + 1] = Arg;
14474   }
14475 
14476   // If this is a variadic call, handle args passed through "...".
14477   if (Proto->isVariadic()) {
14478     // Promote the arguments (C99 6.5.2.2p7).
14479     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
14480       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
14481                                                         nullptr);
14482       IsError |= Arg.isInvalid();
14483       MethodArgs[i + 1] = Arg.get();
14484     }
14485   }
14486 
14487   if (IsError)
14488     return true;
14489 
14490   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14491 
14492   // Once we've built TheCall, all of the expressions are properly owned.
14493   QualType ResultTy = Method->getReturnType();
14494   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14495   ResultTy = ResultTy.getNonLValueExprType(Context);
14496 
14497   CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14498       Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
14499       CurFPFeatureOverrides());
14500 
14501   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
14502     return true;
14503 
14504   if (CheckFunctionCall(Method, TheCall, Proto))
14505     return true;
14506 
14507   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
14508 }
14509 
14510 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
14511 ///  (if one exists), where @c Base is an expression of class type and
14512 /// @c Member is the name of the member we're trying to find.
14513 ExprResult
14514 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
14515                                bool *NoArrowOperatorFound) {
14516   assert(Base->getType()->isRecordType() &&
14517          "left-hand side must have class type");
14518 
14519   if (checkPlaceholderForOverload(*this, Base))
14520     return ExprError();
14521 
14522   SourceLocation Loc = Base->getExprLoc();
14523 
14524   // C++ [over.ref]p1:
14525   //
14526   //   [...] An expression x->m is interpreted as (x.operator->())->m
14527   //   for a class object x of type T if T::operator->() exists and if
14528   //   the operator is selected as the best match function by the
14529   //   overload resolution mechanism (13.3).
14530   DeclarationName OpName =
14531     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
14532   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
14533 
14534   if (RequireCompleteType(Loc, Base->getType(),
14535                           diag::err_typecheck_incomplete_tag, Base))
14536     return ExprError();
14537 
14538   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
14539   LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
14540   R.suppressDiagnostics();
14541 
14542   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14543        Oper != OperEnd; ++Oper) {
14544     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
14545                        None, CandidateSet, /*SuppressUserConversion=*/false);
14546   }
14547 
14548   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14549 
14550   // Perform overload resolution.
14551   OverloadCandidateSet::iterator Best;
14552   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14553   case OR_Success:
14554     // Overload resolution succeeded; we'll build the call below.
14555     break;
14556 
14557   case OR_No_Viable_Function: {
14558     auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
14559     if (CandidateSet.empty()) {
14560       QualType BaseType = Base->getType();
14561       if (NoArrowOperatorFound) {
14562         // Report this specific error to the caller instead of emitting a
14563         // diagnostic, as requested.
14564         *NoArrowOperatorFound = true;
14565         return ExprError();
14566       }
14567       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
14568         << BaseType << Base->getSourceRange();
14569       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
14570         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
14571           << FixItHint::CreateReplacement(OpLoc, ".");
14572       }
14573     } else
14574       Diag(OpLoc, diag::err_ovl_no_viable_oper)
14575         << "operator->" << Base->getSourceRange();
14576     CandidateSet.NoteCandidates(*this, Base, Cands);
14577     return ExprError();
14578   }
14579   case OR_Ambiguous:
14580     CandidateSet.NoteCandidates(
14581         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
14582                                        << "->" << Base->getType()
14583                                        << Base->getSourceRange()),
14584         *this, OCD_AmbiguousCandidates, Base);
14585     return ExprError();
14586 
14587   case OR_Deleted:
14588     CandidateSet.NoteCandidates(
14589         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14590                                        << "->" << Base->getSourceRange()),
14591         *this, OCD_AllCandidates, Base);
14592     return ExprError();
14593   }
14594 
14595   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
14596 
14597   // Convert the object parameter.
14598   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14599   ExprResult BaseResult =
14600     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
14601                                         Best->FoundDecl, Method);
14602   if (BaseResult.isInvalid())
14603     return ExprError();
14604   Base = BaseResult.get();
14605 
14606   // Build the operator call.
14607   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14608                                             Base, HadMultipleCandidates, OpLoc);
14609   if (FnExpr.isInvalid())
14610     return ExprError();
14611 
14612   QualType ResultTy = Method->getReturnType();
14613   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14614   ResultTy = ResultTy.getNonLValueExprType(Context);
14615   CXXOperatorCallExpr *TheCall =
14616       CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
14617                                   ResultTy, VK, OpLoc, CurFPFeatureOverrides());
14618 
14619   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
14620     return ExprError();
14621 
14622   if (CheckFunctionCall(Method, TheCall,
14623                         Method->getType()->castAs<FunctionProtoType>()))
14624     return ExprError();
14625 
14626   return MaybeBindToTemporary(TheCall);
14627 }
14628 
14629 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
14630 /// a literal operator described by the provided lookup results.
14631 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
14632                                           DeclarationNameInfo &SuffixInfo,
14633                                           ArrayRef<Expr*> Args,
14634                                           SourceLocation LitEndLoc,
14635                                        TemplateArgumentListInfo *TemplateArgs) {
14636   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
14637 
14638   OverloadCandidateSet CandidateSet(UDSuffixLoc,
14639                                     OverloadCandidateSet::CSK_Normal);
14640   AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
14641                                  TemplateArgs);
14642 
14643   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14644 
14645   // Perform overload resolution. This will usually be trivial, but might need
14646   // to perform substitutions for a literal operator template.
14647   OverloadCandidateSet::iterator Best;
14648   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
14649   case OR_Success:
14650   case OR_Deleted:
14651     break;
14652 
14653   case OR_No_Viable_Function:
14654     CandidateSet.NoteCandidates(
14655         PartialDiagnosticAt(UDSuffixLoc,
14656                             PDiag(diag::err_ovl_no_viable_function_in_call)
14657                                 << R.getLookupName()),
14658         *this, OCD_AllCandidates, Args);
14659     return ExprError();
14660 
14661   case OR_Ambiguous:
14662     CandidateSet.NoteCandidates(
14663         PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
14664                                                 << R.getLookupName()),
14665         *this, OCD_AmbiguousCandidates, Args);
14666     return ExprError();
14667   }
14668 
14669   FunctionDecl *FD = Best->Function;
14670   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
14671                                         nullptr, HadMultipleCandidates,
14672                                         SuffixInfo.getLoc(),
14673                                         SuffixInfo.getInfo());
14674   if (Fn.isInvalid())
14675     return true;
14676 
14677   // Check the argument types. This should almost always be a no-op, except
14678   // that array-to-pointer decay is applied to string literals.
14679   Expr *ConvArgs[2];
14680   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
14681     ExprResult InputInit = PerformCopyInitialization(
14682       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
14683       SourceLocation(), Args[ArgIdx]);
14684     if (InputInit.isInvalid())
14685       return true;
14686     ConvArgs[ArgIdx] = InputInit.get();
14687   }
14688 
14689   QualType ResultTy = FD->getReturnType();
14690   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14691   ResultTy = ResultTy.getNonLValueExprType(Context);
14692 
14693   UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
14694       Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
14695       VK, LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
14696 
14697   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
14698     return ExprError();
14699 
14700   if (CheckFunctionCall(FD, UDL, nullptr))
14701     return ExprError();
14702 
14703   return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
14704 }
14705 
14706 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
14707 /// given LookupResult is non-empty, it is assumed to describe a member which
14708 /// will be invoked. Otherwise, the function will be found via argument
14709 /// dependent lookup.
14710 /// CallExpr is set to a valid expression and FRS_Success returned on success,
14711 /// otherwise CallExpr is set to ExprError() and some non-success value
14712 /// is returned.
14713 Sema::ForRangeStatus
14714 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
14715                                 SourceLocation RangeLoc,
14716                                 const DeclarationNameInfo &NameInfo,
14717                                 LookupResult &MemberLookup,
14718                                 OverloadCandidateSet *CandidateSet,
14719                                 Expr *Range, ExprResult *CallExpr) {
14720   Scope *S = nullptr;
14721 
14722   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
14723   if (!MemberLookup.empty()) {
14724     ExprResult MemberRef =
14725         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
14726                                  /*IsPtr=*/false, CXXScopeSpec(),
14727                                  /*TemplateKWLoc=*/SourceLocation(),
14728                                  /*FirstQualifierInScope=*/nullptr,
14729                                  MemberLookup,
14730                                  /*TemplateArgs=*/nullptr, S);
14731     if (MemberRef.isInvalid()) {
14732       *CallExpr = ExprError();
14733       return FRS_DiagnosticIssued;
14734     }
14735     *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
14736     if (CallExpr->isInvalid()) {
14737       *CallExpr = ExprError();
14738       return FRS_DiagnosticIssued;
14739     }
14740   } else {
14741     ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
14742                                                 NestedNameSpecifierLoc(),
14743                                                 NameInfo, UnresolvedSet<0>());
14744     if (FnR.isInvalid())
14745       return FRS_DiagnosticIssued;
14746     UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
14747 
14748     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
14749                                                     CandidateSet, CallExpr);
14750     if (CandidateSet->empty() || CandidateSetError) {
14751       *CallExpr = ExprError();
14752       return FRS_NoViableFunction;
14753     }
14754     OverloadCandidateSet::iterator Best;
14755     OverloadingResult OverloadResult =
14756         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
14757 
14758     if (OverloadResult == OR_No_Viable_Function) {
14759       *CallExpr = ExprError();
14760       return FRS_NoViableFunction;
14761     }
14762     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
14763                                          Loc, nullptr, CandidateSet, &Best,
14764                                          OverloadResult,
14765                                          /*AllowTypoCorrection=*/false);
14766     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
14767       *CallExpr = ExprError();
14768       return FRS_DiagnosticIssued;
14769     }
14770   }
14771   return FRS_Success;
14772 }
14773 
14774 
14775 /// FixOverloadedFunctionReference - E is an expression that refers to
14776 /// a C++ overloaded function (possibly with some parentheses and
14777 /// perhaps a '&' around it). We have resolved the overloaded function
14778 /// to the function declaration Fn, so patch up the expression E to
14779 /// refer (possibly indirectly) to Fn. Returns the new expr.
14780 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
14781                                            FunctionDecl *Fn) {
14782   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
14783     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
14784                                                    Found, Fn);
14785     if (SubExpr == PE->getSubExpr())
14786       return PE;
14787 
14788     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
14789   }
14790 
14791   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
14792     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
14793                                                    Found, Fn);
14794     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
14795                                SubExpr->getType()) &&
14796            "Implicit cast type cannot be determined from overload");
14797     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
14798     if (SubExpr == ICE->getSubExpr())
14799       return ICE;
14800 
14801     return ImplicitCastExpr::Create(Context, ICE->getType(),
14802                                     ICE->getCastKind(),
14803                                     SubExpr, nullptr,
14804                                     ICE->getValueKind());
14805   }
14806 
14807   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
14808     if (!GSE->isResultDependent()) {
14809       Expr *SubExpr =
14810           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
14811       if (SubExpr == GSE->getResultExpr())
14812         return GSE;
14813 
14814       // Replace the resulting type information before rebuilding the generic
14815       // selection expression.
14816       ArrayRef<Expr *> A = GSE->getAssocExprs();
14817       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
14818       unsigned ResultIdx = GSE->getResultIndex();
14819       AssocExprs[ResultIdx] = SubExpr;
14820 
14821       return GenericSelectionExpr::Create(
14822           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
14823           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
14824           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
14825           ResultIdx);
14826     }
14827     // Rather than fall through to the unreachable, return the original generic
14828     // selection expression.
14829     return GSE;
14830   }
14831 
14832   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
14833     assert(UnOp->getOpcode() == UO_AddrOf &&
14834            "Can only take the address of an overloaded function");
14835     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
14836       if (Method->isStatic()) {
14837         // Do nothing: static member functions aren't any different
14838         // from non-member functions.
14839       } else {
14840         // Fix the subexpression, which really has to be an
14841         // UnresolvedLookupExpr holding an overloaded member function
14842         // or template.
14843         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14844                                                        Found, Fn);
14845         if (SubExpr == UnOp->getSubExpr())
14846           return UnOp;
14847 
14848         assert(isa<DeclRefExpr>(SubExpr)
14849                && "fixed to something other than a decl ref");
14850         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
14851                && "fixed to a member ref with no nested name qualifier");
14852 
14853         // We have taken the address of a pointer to member
14854         // function. Perform the computation here so that we get the
14855         // appropriate pointer to member type.
14856         QualType ClassType
14857           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
14858         QualType MemPtrType
14859           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
14860         // Under the MS ABI, lock down the inheritance model now.
14861         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14862           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
14863 
14864         return UnaryOperator::Create(
14865             Context, SubExpr, UO_AddrOf, MemPtrType, VK_RValue, OK_Ordinary,
14866             UnOp->getOperatorLoc(), false, CurFPFeatureOverrides());
14867       }
14868     }
14869     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14870                                                    Found, Fn);
14871     if (SubExpr == UnOp->getSubExpr())
14872       return UnOp;
14873 
14874     return UnaryOperator::Create(Context, SubExpr, UO_AddrOf,
14875                                  Context.getPointerType(SubExpr->getType()),
14876                                  VK_RValue, OK_Ordinary, UnOp->getOperatorLoc(),
14877                                  false, CurFPFeatureOverrides());
14878   }
14879 
14880   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14881     // FIXME: avoid copy.
14882     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14883     if (ULE->hasExplicitTemplateArgs()) {
14884       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
14885       TemplateArgs = &TemplateArgsBuffer;
14886     }
14887 
14888     DeclRefExpr *DRE =
14889         BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(),
14890                          ULE->getQualifierLoc(), Found.getDecl(),
14891                          ULE->getTemplateKeywordLoc(), TemplateArgs);
14892     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
14893     return DRE;
14894   }
14895 
14896   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
14897     // FIXME: avoid copy.
14898     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14899     if (MemExpr->hasExplicitTemplateArgs()) {
14900       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14901       TemplateArgs = &TemplateArgsBuffer;
14902     }
14903 
14904     Expr *Base;
14905 
14906     // If we're filling in a static method where we used to have an
14907     // implicit member access, rewrite to a simple decl ref.
14908     if (MemExpr->isImplicitAccess()) {
14909       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14910         DeclRefExpr *DRE = BuildDeclRefExpr(
14911             Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
14912             MemExpr->getQualifierLoc(), Found.getDecl(),
14913             MemExpr->getTemplateKeywordLoc(), TemplateArgs);
14914         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
14915         return DRE;
14916       } else {
14917         SourceLocation Loc = MemExpr->getMemberLoc();
14918         if (MemExpr->getQualifier())
14919           Loc = MemExpr->getQualifierLoc().getBeginLoc();
14920         Base =
14921             BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
14922       }
14923     } else
14924       Base = MemExpr->getBase();
14925 
14926     ExprValueKind valueKind;
14927     QualType type;
14928     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14929       valueKind = VK_LValue;
14930       type = Fn->getType();
14931     } else {
14932       valueKind = VK_RValue;
14933       type = Context.BoundMemberTy;
14934     }
14935 
14936     return BuildMemberExpr(
14937         Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
14938         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
14939         /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
14940         type, valueKind, OK_Ordinary, TemplateArgs);
14941   }
14942 
14943   llvm_unreachable("Invalid reference to overloaded function");
14944 }
14945 
14946 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
14947                                                 DeclAccessPair Found,
14948                                                 FunctionDecl *Fn) {
14949   return FixOverloadedFunctionReference(E.get(), Found, Fn);
14950 }
14951