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/Sema/Overload.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/CXXInheritance.h"
16 #include "clang/AST/DeclObjC.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/TargetInfo.h"
25 #include "clang/Sema/Initialization.h"
26 #include "clang/Sema/Lookup.h"
27 #include "clang/Sema/SemaInternal.h"
28 #include "clang/Sema/Template.h"
29 #include "clang/Sema/TemplateDeduction.h"
30 #include "llvm/ADT/DenseSet.h"
31 #include "llvm/ADT/Optional.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallString.h"
35 #include <algorithm>
36 #include <cstdlib>
37 
38 using namespace clang;
39 using namespace sema;
40 
41 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
42   return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
43     return P->hasAttr<PassObjectSizeAttr>();
44   });
45 }
46 
47 /// A convenience routine for creating a decayed reference to a function.
48 static ExprResult
49 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
50                       const Expr *Base, bool HadMultipleCandidates,
51                       SourceLocation Loc = SourceLocation(),
52                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
53   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
54     return ExprError();
55   // If FoundDecl is different from Fn (such as if one is a template
56   // and the other a specialization), make sure DiagnoseUseOfDecl is
57   // called on both.
58   // FIXME: This would be more comprehensively addressed by modifying
59   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
60   // being used.
61   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
62     return ExprError();
63   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
64     S.ResolveExceptionSpec(Loc, FPT);
65   DeclRefExpr *DRE = new (S.Context)
66       DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
67   if (HadMultipleCandidates)
68     DRE->setHadMultipleCandidates(true);
69 
70   S.MarkDeclRefReferenced(DRE, Base);
71   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
72                              CK_FunctionToPointerDecay);
73 }
74 
75 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
76                                  bool InOverloadResolution,
77                                  StandardConversionSequence &SCS,
78                                  bool CStyle,
79                                  bool AllowObjCWritebackConversion);
80 
81 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
82                                                  QualType &ToType,
83                                                  bool InOverloadResolution,
84                                                  StandardConversionSequence &SCS,
85                                                  bool CStyle);
86 static OverloadingResult
87 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
88                         UserDefinedConversionSequence& User,
89                         OverloadCandidateSet& Conversions,
90                         bool AllowExplicit,
91                         bool AllowObjCConversionOnExplicit);
92 
93 
94 static ImplicitConversionSequence::CompareKind
95 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
96                                    const StandardConversionSequence& SCS1,
97                                    const StandardConversionSequence& SCS2);
98 
99 static ImplicitConversionSequence::CompareKind
100 CompareQualificationConversions(Sema &S,
101                                 const StandardConversionSequence& SCS1,
102                                 const StandardConversionSequence& SCS2);
103 
104 static ImplicitConversionSequence::CompareKind
105 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
106                                 const StandardConversionSequence& SCS1,
107                                 const StandardConversionSequence& SCS2);
108 
109 /// GetConversionRank - Retrieve the implicit conversion rank
110 /// corresponding to the given implicit conversion kind.
111 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
112   static const ImplicitConversionRank
113     Rank[(int)ICK_Num_Conversion_Kinds] = {
114     ICR_Exact_Match,
115     ICR_Exact_Match,
116     ICR_Exact_Match,
117     ICR_Exact_Match,
118     ICR_Exact_Match,
119     ICR_Exact_Match,
120     ICR_Promotion,
121     ICR_Promotion,
122     ICR_Promotion,
123     ICR_Conversion,
124     ICR_Conversion,
125     ICR_Conversion,
126     ICR_Conversion,
127     ICR_Conversion,
128     ICR_Conversion,
129     ICR_Conversion,
130     ICR_Conversion,
131     ICR_Conversion,
132     ICR_Conversion,
133     ICR_OCL_Scalar_Widening,
134     ICR_Complex_Real_Conversion,
135     ICR_Conversion,
136     ICR_Conversion,
137     ICR_Writeback_Conversion,
138     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
139                      // it was omitted by the patch that added
140                      // ICK_Zero_Event_Conversion
141     ICR_C_Conversion,
142     ICR_C_Conversion_Extension
143   };
144   return Rank[(int)Kind];
145 }
146 
147 /// GetImplicitConversionName - Return the name of this kind of
148 /// implicit conversion.
149 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
150   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
151     "No conversion",
152     "Lvalue-to-rvalue",
153     "Array-to-pointer",
154     "Function-to-pointer",
155     "Function pointer conversion",
156     "Qualification",
157     "Integral promotion",
158     "Floating point promotion",
159     "Complex promotion",
160     "Integral conversion",
161     "Floating conversion",
162     "Complex conversion",
163     "Floating-integral conversion",
164     "Pointer conversion",
165     "Pointer-to-member conversion",
166     "Boolean conversion",
167     "Compatible-types conversion",
168     "Derived-to-base conversion",
169     "Vector conversion",
170     "Vector splat",
171     "Complex-real conversion",
172     "Block Pointer conversion",
173     "Transparent Union Conversion",
174     "Writeback conversion",
175     "OpenCL Zero Event Conversion",
176     "C specific type conversion",
177     "Incompatible pointer conversion"
178   };
179   return Name[Kind];
180 }
181 
182 /// StandardConversionSequence - Set the standard conversion
183 /// sequence to the identity conversion.
184 void StandardConversionSequence::setAsIdentityConversion() {
185   First = ICK_Identity;
186   Second = ICK_Identity;
187   Third = ICK_Identity;
188   DeprecatedStringLiteralToCharPtr = false;
189   QualificationIncludesObjCLifetime = false;
190   ReferenceBinding = false;
191   DirectBinding = false;
192   IsLvalueReference = true;
193   BindsToFunctionLvalue = false;
194   BindsToRvalue = false;
195   BindsImplicitObjectArgumentWithoutRefQualifier = false;
196   ObjCLifetimeConversionBinding = false;
197   CopyConstructor = nullptr;
198 }
199 
200 /// getRank - Retrieve the rank of this standard conversion sequence
201 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
202 /// implicit conversions.
203 ImplicitConversionRank StandardConversionSequence::getRank() const {
204   ImplicitConversionRank Rank = ICR_Exact_Match;
205   if  (GetConversionRank(First) > Rank)
206     Rank = GetConversionRank(First);
207   if  (GetConversionRank(Second) > Rank)
208     Rank = GetConversionRank(Second);
209   if  (GetConversionRank(Third) > Rank)
210     Rank = GetConversionRank(Third);
211   return Rank;
212 }
213 
214 /// isPointerConversionToBool - Determines whether this conversion is
215 /// a conversion of a pointer or pointer-to-member to bool. This is
216 /// used as part of the ranking of standard conversion sequences
217 /// (C++ 13.3.3.2p4).
218 bool StandardConversionSequence::isPointerConversionToBool() const {
219   // Note that FromType has not necessarily been transformed by the
220   // array-to-pointer or function-to-pointer implicit conversions, so
221   // check for their presence as well as checking whether FromType is
222   // a pointer.
223   if (getToType(1)->isBooleanType() &&
224       (getFromType()->isPointerType() ||
225        getFromType()->isMemberPointerType() ||
226        getFromType()->isObjCObjectPointerType() ||
227        getFromType()->isBlockPointerType() ||
228        getFromType()->isNullPtrType() ||
229        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
230     return true;
231 
232   return false;
233 }
234 
235 /// isPointerConversionToVoidPointer - Determines whether this
236 /// conversion is a conversion of a pointer to a void pointer. This is
237 /// used as part of the ranking of standard conversion sequences (C++
238 /// 13.3.3.2p4).
239 bool
240 StandardConversionSequence::
241 isPointerConversionToVoidPointer(ASTContext& Context) const {
242   QualType FromType = getFromType();
243   QualType ToType = getToType(1);
244 
245   // Note that FromType has not necessarily been transformed by the
246   // array-to-pointer implicit conversion, so check for its presence
247   // and redo the conversion to get a pointer.
248   if (First == ICK_Array_To_Pointer)
249     FromType = Context.getArrayDecayedType(FromType);
250 
251   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
252     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
253       return ToPtrType->getPointeeType()->isVoidType();
254 
255   return false;
256 }
257 
258 /// Skip any implicit casts which could be either part of a narrowing conversion
259 /// or after one in an implicit conversion.
260 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
261                                              const Expr *Converted) {
262   // We can have cleanups wrapping the converted expression; these need to be
263   // preserved so that destructors run if necessary.
264   if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
265     Expr *Inner =
266         const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
267     return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
268                                     EWC->getObjects());
269   }
270 
271   while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
272     switch (ICE->getCastKind()) {
273     case CK_NoOp:
274     case CK_IntegralCast:
275     case CK_IntegralToBoolean:
276     case CK_IntegralToFloating:
277     case CK_BooleanToSignedIntegral:
278     case CK_FloatingToIntegral:
279     case CK_FloatingToBoolean:
280     case CK_FloatingCast:
281       Converted = ICE->getSubExpr();
282       continue;
283 
284     default:
285       return Converted;
286     }
287   }
288 
289   return Converted;
290 }
291 
292 /// Check if this standard conversion sequence represents a narrowing
293 /// conversion, according to C++11 [dcl.init.list]p7.
294 ///
295 /// \param Ctx  The AST context.
296 /// \param Converted  The result of applying this standard conversion sequence.
297 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
298 ///        value of the expression prior to the narrowing conversion.
299 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
300 ///        type of the expression prior to the narrowing conversion.
301 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
302 ///        from floating point types to integral types should be ignored.
303 NarrowingKind StandardConversionSequence::getNarrowingKind(
304     ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
305     QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
306   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
307 
308   // C++11 [dcl.init.list]p7:
309   //   A narrowing conversion is an implicit conversion ...
310   QualType FromType = getToType(0);
311   QualType ToType = getToType(1);
312 
313   // A conversion to an enumeration type is narrowing if the conversion to
314   // the underlying type is narrowing. This only arises for expressions of
315   // the form 'Enum{init}'.
316   if (auto *ET = ToType->getAs<EnumType>())
317     ToType = ET->getDecl()->getIntegerType();
318 
319   switch (Second) {
320   // 'bool' is an integral type; dispatch to the right place to handle it.
321   case ICK_Boolean_Conversion:
322     if (FromType->isRealFloatingType())
323       goto FloatingIntegralConversion;
324     if (FromType->isIntegralOrUnscopedEnumerationType())
325       goto IntegralConversion;
326     // Boolean conversions can be from pointers and pointers to members
327     // [conv.bool], and those aren't considered narrowing conversions.
328     return NK_Not_Narrowing;
329 
330   // -- from a floating-point type to an integer type, or
331   //
332   // -- from an integer type or unscoped enumeration type to a floating-point
333   //    type, except where the source is a constant expression and the actual
334   //    value after conversion will fit into the target type and will produce
335   //    the original value when converted back to the original type, or
336   case ICK_Floating_Integral:
337   FloatingIntegralConversion:
338     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
339       return NK_Type_Narrowing;
340     } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
341                ToType->isRealFloatingType()) {
342       if (IgnoreFloatToIntegralConversion)
343         return NK_Not_Narrowing;
344       llvm::APSInt IntConstantValue;
345       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
346       assert(Initializer && "Unknown conversion expression");
347 
348       // If it's value-dependent, we can't tell whether it's narrowing.
349       if (Initializer->isValueDependent())
350         return NK_Dependent_Narrowing;
351 
352       if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
353         // Convert the integer to the floating type.
354         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
355         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
356                                 llvm::APFloat::rmNearestTiesToEven);
357         // And back.
358         llvm::APSInt ConvertedValue = IntConstantValue;
359         bool ignored;
360         Result.convertToInteger(ConvertedValue,
361                                 llvm::APFloat::rmTowardZero, &ignored);
362         // If the resulting value is different, this was a narrowing conversion.
363         if (IntConstantValue != ConvertedValue) {
364           ConstantValue = APValue(IntConstantValue);
365           ConstantType = Initializer->getType();
366           return NK_Constant_Narrowing;
367         }
368       } else {
369         // Variables are always narrowings.
370         return NK_Variable_Narrowing;
371       }
372     }
373     return NK_Not_Narrowing;
374 
375   // -- from long double to double or float, or from double to float, except
376   //    where the source is a constant expression and the actual value after
377   //    conversion is within the range of values that can be represented (even
378   //    if it cannot be represented exactly), or
379   case ICK_Floating_Conversion:
380     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
381         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
382       // FromType is larger than ToType.
383       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
384 
385       // If it's value-dependent, we can't tell whether it's narrowing.
386       if (Initializer->isValueDependent())
387         return NK_Dependent_Narrowing;
388 
389       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
390         // Constant!
391         assert(ConstantValue.isFloat());
392         llvm::APFloat FloatVal = ConstantValue.getFloat();
393         // Convert the source value into the target type.
394         bool ignored;
395         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
396           Ctx.getFloatTypeSemantics(ToType),
397           llvm::APFloat::rmNearestTiesToEven, &ignored);
398         // If there was no overflow, the source value is within the range of
399         // values that can be represented.
400         if (ConvertStatus & llvm::APFloat::opOverflow) {
401           ConstantType = Initializer->getType();
402           return NK_Constant_Narrowing;
403         }
404       } else {
405         return NK_Variable_Narrowing;
406       }
407     }
408     return NK_Not_Narrowing;
409 
410   // -- from an integer type or unscoped enumeration type to an integer type
411   //    that cannot represent all the values of the original type, except where
412   //    the source is a constant expression and the actual value after
413   //    conversion will fit into the target type and will produce the original
414   //    value when converted back to the original type.
415   case ICK_Integral_Conversion:
416   IntegralConversion: {
417     assert(FromType->isIntegralOrUnscopedEnumerationType());
418     assert(ToType->isIntegralOrUnscopedEnumerationType());
419     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
420     const unsigned FromWidth = Ctx.getIntWidth(FromType);
421     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
422     const unsigned ToWidth = Ctx.getIntWidth(ToType);
423 
424     if (FromWidth > ToWidth ||
425         (FromWidth == ToWidth && FromSigned != ToSigned) ||
426         (FromSigned && !ToSigned)) {
427       // Not all values of FromType can be represented in ToType.
428       llvm::APSInt InitializerValue;
429       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
430 
431       // If it's value-dependent, we can't tell whether it's narrowing.
432       if (Initializer->isValueDependent())
433         return NK_Dependent_Narrowing;
434 
435       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
436         // Such conversions on variables are always narrowing.
437         return NK_Variable_Narrowing;
438       }
439       bool Narrowing = false;
440       if (FromWidth < ToWidth) {
441         // Negative -> unsigned is narrowing. Otherwise, more bits is never
442         // narrowing.
443         if (InitializerValue.isSigned() && InitializerValue.isNegative())
444           Narrowing = true;
445       } else {
446         // Add a bit to the InitializerValue so we don't have to worry about
447         // signed vs. unsigned comparisons.
448         InitializerValue = InitializerValue.extend(
449           InitializerValue.getBitWidth() + 1);
450         // Convert the initializer to and from the target width and signed-ness.
451         llvm::APSInt ConvertedValue = InitializerValue;
452         ConvertedValue = ConvertedValue.trunc(ToWidth);
453         ConvertedValue.setIsSigned(ToSigned);
454         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
455         ConvertedValue.setIsSigned(InitializerValue.isSigned());
456         // If the result is different, this was a narrowing conversion.
457         if (ConvertedValue != InitializerValue)
458           Narrowing = true;
459       }
460       if (Narrowing) {
461         ConstantType = Initializer->getType();
462         ConstantValue = APValue(InitializerValue);
463         return NK_Constant_Narrowing;
464       }
465     }
466     return NK_Not_Narrowing;
467   }
468 
469   default:
470     // Other kinds of conversions are not narrowings.
471     return NK_Not_Narrowing;
472   }
473 }
474 
475 /// dump - Print this standard conversion sequence to standard
476 /// error. Useful for debugging overloading issues.
477 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
478   raw_ostream &OS = llvm::errs();
479   bool PrintedSomething = false;
480   if (First != ICK_Identity) {
481     OS << GetImplicitConversionName(First);
482     PrintedSomething = true;
483   }
484 
485   if (Second != ICK_Identity) {
486     if (PrintedSomething) {
487       OS << " -> ";
488     }
489     OS << GetImplicitConversionName(Second);
490 
491     if (CopyConstructor) {
492       OS << " (by copy constructor)";
493     } else if (DirectBinding) {
494       OS << " (direct reference binding)";
495     } else if (ReferenceBinding) {
496       OS << " (reference binding)";
497     }
498     PrintedSomething = true;
499   }
500 
501   if (Third != ICK_Identity) {
502     if (PrintedSomething) {
503       OS << " -> ";
504     }
505     OS << GetImplicitConversionName(Third);
506     PrintedSomething = true;
507   }
508 
509   if (!PrintedSomething) {
510     OS << "No conversions required";
511   }
512 }
513 
514 /// dump - Print this user-defined conversion sequence to standard
515 /// error. Useful for debugging overloading issues.
516 void UserDefinedConversionSequence::dump() const {
517   raw_ostream &OS = llvm::errs();
518   if (Before.First || Before.Second || Before.Third) {
519     Before.dump();
520     OS << " -> ";
521   }
522   if (ConversionFunction)
523     OS << '\'' << *ConversionFunction << '\'';
524   else
525     OS << "aggregate initialization";
526   if (After.First || After.Second || After.Third) {
527     OS << " -> ";
528     After.dump();
529   }
530 }
531 
532 /// dump - Print this implicit conversion sequence to standard
533 /// error. Useful for debugging overloading issues.
534 void ImplicitConversionSequence::dump() const {
535   raw_ostream &OS = llvm::errs();
536   if (isStdInitializerListElement())
537     OS << "Worst std::initializer_list element conversion: ";
538   switch (ConversionKind) {
539   case StandardConversion:
540     OS << "Standard conversion: ";
541     Standard.dump();
542     break;
543   case UserDefinedConversion:
544     OS << "User-defined conversion: ";
545     UserDefined.dump();
546     break;
547   case EllipsisConversion:
548     OS << "Ellipsis conversion";
549     break;
550   case AmbiguousConversion:
551     OS << "Ambiguous conversion";
552     break;
553   case BadConversion:
554     OS << "Bad conversion";
555     break;
556   }
557 
558   OS << "\n";
559 }
560 
561 void AmbiguousConversionSequence::construct() {
562   new (&conversions()) ConversionSet();
563 }
564 
565 void AmbiguousConversionSequence::destruct() {
566   conversions().~ConversionSet();
567 }
568 
569 void
570 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
571   FromTypePtr = O.FromTypePtr;
572   ToTypePtr = O.ToTypePtr;
573   new (&conversions()) ConversionSet(O.conversions());
574 }
575 
576 namespace {
577   // Structure used by DeductionFailureInfo to store
578   // template argument information.
579   struct DFIArguments {
580     TemplateArgument FirstArg;
581     TemplateArgument SecondArg;
582   };
583   // Structure used by DeductionFailureInfo to store
584   // template parameter and template argument information.
585   struct DFIParamWithArguments : DFIArguments {
586     TemplateParameter Param;
587   };
588   // Structure used by DeductionFailureInfo to store template argument
589   // information and the index of the problematic call argument.
590   struct DFIDeducedMismatchArgs : DFIArguments {
591     TemplateArgumentList *TemplateArgs;
592     unsigned CallArgIndex;
593   };
594   // Structure used by DeductionFailureInfo to store information about
595   // unsatisfied constraints.
596   struct CNSInfo {
597     TemplateArgumentList *TemplateArgs;
598     ConstraintSatisfaction Satisfaction;
599   };
600 }
601 
602 /// Convert from Sema's representation of template deduction information
603 /// to the form used in overload-candidate information.
604 DeductionFailureInfo
605 clang::MakeDeductionFailureInfo(ASTContext &Context,
606                                 Sema::TemplateDeductionResult TDK,
607                                 TemplateDeductionInfo &Info) {
608   DeductionFailureInfo Result;
609   Result.Result = static_cast<unsigned>(TDK);
610   Result.HasDiagnostic = false;
611   switch (TDK) {
612   case Sema::TDK_Invalid:
613   case Sema::TDK_InstantiationDepth:
614   case Sema::TDK_TooManyArguments:
615   case Sema::TDK_TooFewArguments:
616   case Sema::TDK_MiscellaneousDeductionFailure:
617   case Sema::TDK_CUDATargetMismatch:
618     Result.Data = nullptr;
619     break;
620 
621   case Sema::TDK_Incomplete:
622   case Sema::TDK_InvalidExplicitArguments:
623     Result.Data = Info.Param.getOpaqueValue();
624     break;
625 
626   case Sema::TDK_DeducedMismatch:
627   case Sema::TDK_DeducedMismatchNested: {
628     // FIXME: Should allocate from normal heap so that we can free this later.
629     auto *Saved = new (Context) DFIDeducedMismatchArgs;
630     Saved->FirstArg = Info.FirstArg;
631     Saved->SecondArg = Info.SecondArg;
632     Saved->TemplateArgs = Info.take();
633     Saved->CallArgIndex = Info.CallArgIndex;
634     Result.Data = Saved;
635     break;
636   }
637 
638   case Sema::TDK_NonDeducedMismatch: {
639     // FIXME: Should allocate from normal heap so that we can free this later.
640     DFIArguments *Saved = new (Context) DFIArguments;
641     Saved->FirstArg = Info.FirstArg;
642     Saved->SecondArg = Info.SecondArg;
643     Result.Data = Saved;
644     break;
645   }
646 
647   case Sema::TDK_IncompletePack:
648     // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
649   case Sema::TDK_Inconsistent:
650   case Sema::TDK_Underqualified: {
651     // FIXME: Should allocate from normal heap so that we can free this later.
652     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
653     Saved->Param = Info.Param;
654     Saved->FirstArg = Info.FirstArg;
655     Saved->SecondArg = Info.SecondArg;
656     Result.Data = Saved;
657     break;
658   }
659 
660   case Sema::TDK_SubstitutionFailure:
661     Result.Data = Info.take();
662     if (Info.hasSFINAEDiagnostic()) {
663       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
664           SourceLocation(), PartialDiagnostic::NullDiagnostic());
665       Info.takeSFINAEDiagnostic(*Diag);
666       Result.HasDiagnostic = true;
667     }
668     break;
669 
670   case Sema::TDK_ConstraintsNotSatisfied: {
671     CNSInfo *Saved = new (Context) CNSInfo;
672     Saved->TemplateArgs = Info.take();
673     Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
674     Result.Data = Saved;
675     break;
676   }
677 
678   case Sema::TDK_Success:
679   case Sema::TDK_NonDependentConversionFailure:
680     llvm_unreachable("not a deduction failure");
681   }
682 
683   return Result;
684 }
685 
686 void DeductionFailureInfo::Destroy() {
687   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
688   case Sema::TDK_Success:
689   case Sema::TDK_Invalid:
690   case Sema::TDK_InstantiationDepth:
691   case Sema::TDK_Incomplete:
692   case Sema::TDK_TooManyArguments:
693   case Sema::TDK_TooFewArguments:
694   case Sema::TDK_InvalidExplicitArguments:
695   case Sema::TDK_CUDATargetMismatch:
696   case Sema::TDK_NonDependentConversionFailure:
697     break;
698 
699   case Sema::TDK_IncompletePack:
700   case Sema::TDK_Inconsistent:
701   case Sema::TDK_Underqualified:
702   case Sema::TDK_DeducedMismatch:
703   case Sema::TDK_DeducedMismatchNested:
704   case Sema::TDK_NonDeducedMismatch:
705     // FIXME: Destroy the data?
706     Data = nullptr;
707     break;
708 
709   case Sema::TDK_SubstitutionFailure:
710     // FIXME: Destroy the template argument list?
711     Data = nullptr;
712     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
713       Diag->~PartialDiagnosticAt();
714       HasDiagnostic = false;
715     }
716     break;
717 
718   case Sema::TDK_ConstraintsNotSatisfied:
719     // FIXME: Destroy the template argument list?
720     Data = nullptr;
721     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
722       Diag->~PartialDiagnosticAt();
723       HasDiagnostic = false;
724     }
725     break;
726 
727   // Unhandled
728   case Sema::TDK_MiscellaneousDeductionFailure:
729     break;
730   }
731 }
732 
733 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
734   if (HasDiagnostic)
735     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
736   return nullptr;
737 }
738 
739 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
740   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
741   case Sema::TDK_Success:
742   case Sema::TDK_Invalid:
743   case Sema::TDK_InstantiationDepth:
744   case Sema::TDK_TooManyArguments:
745   case Sema::TDK_TooFewArguments:
746   case Sema::TDK_SubstitutionFailure:
747   case Sema::TDK_DeducedMismatch:
748   case Sema::TDK_DeducedMismatchNested:
749   case Sema::TDK_NonDeducedMismatch:
750   case Sema::TDK_CUDATargetMismatch:
751   case Sema::TDK_NonDependentConversionFailure:
752   case Sema::TDK_ConstraintsNotSatisfied:
753     return TemplateParameter();
754 
755   case Sema::TDK_Incomplete:
756   case Sema::TDK_InvalidExplicitArguments:
757     return TemplateParameter::getFromOpaqueValue(Data);
758 
759   case Sema::TDK_IncompletePack:
760   case Sema::TDK_Inconsistent:
761   case Sema::TDK_Underqualified:
762     return static_cast<DFIParamWithArguments*>(Data)->Param;
763 
764   // Unhandled
765   case Sema::TDK_MiscellaneousDeductionFailure:
766     break;
767   }
768 
769   return TemplateParameter();
770 }
771 
772 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
773   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
774   case Sema::TDK_Success:
775   case Sema::TDK_Invalid:
776   case Sema::TDK_InstantiationDepth:
777   case Sema::TDK_TooManyArguments:
778   case Sema::TDK_TooFewArguments:
779   case Sema::TDK_Incomplete:
780   case Sema::TDK_IncompletePack:
781   case Sema::TDK_InvalidExplicitArguments:
782   case Sema::TDK_Inconsistent:
783   case Sema::TDK_Underqualified:
784   case Sema::TDK_NonDeducedMismatch:
785   case Sema::TDK_CUDATargetMismatch:
786   case Sema::TDK_NonDependentConversionFailure:
787     return nullptr;
788 
789   case Sema::TDK_DeducedMismatch:
790   case Sema::TDK_DeducedMismatchNested:
791     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
792 
793   case Sema::TDK_SubstitutionFailure:
794     return static_cast<TemplateArgumentList*>(Data);
795 
796   case Sema::TDK_ConstraintsNotSatisfied:
797     return static_cast<CNSInfo*>(Data)->TemplateArgs;
798 
799   // Unhandled
800   case Sema::TDK_MiscellaneousDeductionFailure:
801     break;
802   }
803 
804   return nullptr;
805 }
806 
807 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
808   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
809   case Sema::TDK_Success:
810   case Sema::TDK_Invalid:
811   case Sema::TDK_InstantiationDepth:
812   case Sema::TDK_Incomplete:
813   case Sema::TDK_TooManyArguments:
814   case Sema::TDK_TooFewArguments:
815   case Sema::TDK_InvalidExplicitArguments:
816   case Sema::TDK_SubstitutionFailure:
817   case Sema::TDK_CUDATargetMismatch:
818   case Sema::TDK_NonDependentConversionFailure:
819   case Sema::TDK_ConstraintsNotSatisfied:
820     return nullptr;
821 
822   case Sema::TDK_IncompletePack:
823   case Sema::TDK_Inconsistent:
824   case Sema::TDK_Underqualified:
825   case Sema::TDK_DeducedMismatch:
826   case Sema::TDK_DeducedMismatchNested:
827   case Sema::TDK_NonDeducedMismatch:
828     return &static_cast<DFIArguments*>(Data)->FirstArg;
829 
830   // Unhandled
831   case Sema::TDK_MiscellaneousDeductionFailure:
832     break;
833   }
834 
835   return nullptr;
836 }
837 
838 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
839   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
840   case Sema::TDK_Success:
841   case Sema::TDK_Invalid:
842   case Sema::TDK_InstantiationDepth:
843   case Sema::TDK_Incomplete:
844   case Sema::TDK_IncompletePack:
845   case Sema::TDK_TooManyArguments:
846   case Sema::TDK_TooFewArguments:
847   case Sema::TDK_InvalidExplicitArguments:
848   case Sema::TDK_SubstitutionFailure:
849   case Sema::TDK_CUDATargetMismatch:
850   case Sema::TDK_NonDependentConversionFailure:
851   case Sema::TDK_ConstraintsNotSatisfied:
852     return nullptr;
853 
854   case Sema::TDK_Inconsistent:
855   case Sema::TDK_Underqualified:
856   case Sema::TDK_DeducedMismatch:
857   case Sema::TDK_DeducedMismatchNested:
858   case Sema::TDK_NonDeducedMismatch:
859     return &static_cast<DFIArguments*>(Data)->SecondArg;
860 
861   // Unhandled
862   case Sema::TDK_MiscellaneousDeductionFailure:
863     break;
864   }
865 
866   return nullptr;
867 }
868 
869 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
870   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
871   case Sema::TDK_DeducedMismatch:
872   case Sema::TDK_DeducedMismatchNested:
873     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
874 
875   default:
876     return llvm::None;
877   }
878 }
879 
880 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
881     OverloadedOperatorKind Op) {
882   if (!AllowRewrittenCandidates)
883     return false;
884   return Op == OO_EqualEqual || Op == OO_Spaceship;
885 }
886 
887 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
888     ASTContext &Ctx, const FunctionDecl *FD) {
889   if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator()))
890     return false;
891   // Don't bother adding a reversed candidate that can never be a better
892   // match than the non-reversed version.
893   return FD->getNumParams() != 2 ||
894          !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
895                                      FD->getParamDecl(1)->getType()) ||
896          FD->hasAttr<EnableIfAttr>();
897 }
898 
899 void OverloadCandidateSet::destroyCandidates() {
900   for (iterator i = begin(), e = end(); i != e; ++i) {
901     for (auto &C : i->Conversions)
902       C.~ImplicitConversionSequence();
903     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
904       i->DeductionFailure.Destroy();
905   }
906 }
907 
908 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
909   destroyCandidates();
910   SlabAllocator.Reset();
911   NumInlineBytesUsed = 0;
912   Candidates.clear();
913   Functions.clear();
914   Kind = CSK;
915 }
916 
917 namespace {
918   class UnbridgedCastsSet {
919     struct Entry {
920       Expr **Addr;
921       Expr *Saved;
922     };
923     SmallVector<Entry, 2> Entries;
924 
925   public:
926     void save(Sema &S, Expr *&E) {
927       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
928       Entry entry = { &E, E };
929       Entries.push_back(entry);
930       E = S.stripARCUnbridgedCast(E);
931     }
932 
933     void restore() {
934       for (SmallVectorImpl<Entry>::iterator
935              i = Entries.begin(), e = Entries.end(); i != e; ++i)
936         *i->Addr = i->Saved;
937     }
938   };
939 }
940 
941 /// checkPlaceholderForOverload - Do any interesting placeholder-like
942 /// preprocessing on the given expression.
943 ///
944 /// \param unbridgedCasts a collection to which to add unbridged casts;
945 ///   without this, they will be immediately diagnosed as errors
946 ///
947 /// Return true on unrecoverable error.
948 static bool
949 checkPlaceholderForOverload(Sema &S, Expr *&E,
950                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
951   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
952     // We can't handle overloaded expressions here because overload
953     // resolution might reasonably tweak them.
954     if (placeholder->getKind() == BuiltinType::Overload) return false;
955 
956     // If the context potentially accepts unbridged ARC casts, strip
957     // the unbridged cast and add it to the collection for later restoration.
958     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
959         unbridgedCasts) {
960       unbridgedCasts->save(S, E);
961       return false;
962     }
963 
964     // Go ahead and check everything else.
965     ExprResult result = S.CheckPlaceholderExpr(E);
966     if (result.isInvalid())
967       return true;
968 
969     E = result.get();
970     return false;
971   }
972 
973   // Nothing to do.
974   return false;
975 }
976 
977 /// checkArgPlaceholdersForOverload - Check a set of call operands for
978 /// placeholders.
979 static bool checkArgPlaceholdersForOverload(Sema &S,
980                                             MultiExprArg Args,
981                                             UnbridgedCastsSet &unbridged) {
982   for (unsigned i = 0, e = Args.size(); i != e; ++i)
983     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
984       return true;
985 
986   return false;
987 }
988 
989 /// Determine whether the given New declaration is an overload of the
990 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
991 /// New and Old cannot be overloaded, e.g., if New has the same signature as
992 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
993 /// functions (or function templates) at all. When it does return Ovl_Match or
994 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
995 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
996 /// declaration.
997 ///
998 /// Example: Given the following input:
999 ///
1000 ///   void f(int, float); // #1
1001 ///   void f(int, int); // #2
1002 ///   int f(int, int); // #3
1003 ///
1004 /// When we process #1, there is no previous declaration of "f", so IsOverload
1005 /// will not be used.
1006 ///
1007 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1008 /// the parameter types, we see that #1 and #2 are overloaded (since they have
1009 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1010 /// unchanged.
1011 ///
1012 /// When we process #3, Old is an overload set containing #1 and #2. We compare
1013 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1014 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1015 /// functions are not part of the signature), IsOverload returns Ovl_Match and
1016 /// MatchedDecl will be set to point to the FunctionDecl for #2.
1017 ///
1018 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1019 /// by a using declaration. The rules for whether to hide shadow declarations
1020 /// ignore some properties which otherwise figure into a function template's
1021 /// signature.
1022 Sema::OverloadKind
1023 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1024                     NamedDecl *&Match, bool NewIsUsingDecl) {
1025   for (LookupResult::iterator I = Old.begin(), E = Old.end();
1026          I != E; ++I) {
1027     NamedDecl *OldD = *I;
1028 
1029     bool OldIsUsingDecl = false;
1030     if (isa<UsingShadowDecl>(OldD)) {
1031       OldIsUsingDecl = true;
1032 
1033       // We can always introduce two using declarations into the same
1034       // context, even if they have identical signatures.
1035       if (NewIsUsingDecl) continue;
1036 
1037       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1038     }
1039 
1040     // A using-declaration does not conflict with another declaration
1041     // if one of them is hidden.
1042     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1043       continue;
1044 
1045     // If either declaration was introduced by a using declaration,
1046     // we'll need to use slightly different rules for matching.
1047     // Essentially, these rules are the normal rules, except that
1048     // function templates hide function templates with different
1049     // return types or template parameter lists.
1050     bool UseMemberUsingDeclRules =
1051       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1052       !New->getFriendObjectKind();
1053 
1054     if (FunctionDecl *OldF = OldD->getAsFunction()) {
1055       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1056         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1057           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1058           continue;
1059         }
1060 
1061         if (!isa<FunctionTemplateDecl>(OldD) &&
1062             !shouldLinkPossiblyHiddenDecl(*I, New))
1063           continue;
1064 
1065         Match = *I;
1066         return Ovl_Match;
1067       }
1068 
1069       // Builtins that have custom typechecking or have a reference should
1070       // not be overloadable or redeclarable.
1071       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1072         Match = *I;
1073         return Ovl_NonFunction;
1074       }
1075     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1076       // We can overload with these, which can show up when doing
1077       // redeclaration checks for UsingDecls.
1078       assert(Old.getLookupKind() == LookupUsingDeclName);
1079     } else if (isa<TagDecl>(OldD)) {
1080       // We can always overload with tags by hiding them.
1081     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1082       // Optimistically assume that an unresolved using decl will
1083       // overload; if it doesn't, we'll have to diagnose during
1084       // template instantiation.
1085       //
1086       // Exception: if the scope is dependent and this is not a class
1087       // member, the using declaration can only introduce an enumerator.
1088       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1089         Match = *I;
1090         return Ovl_NonFunction;
1091       }
1092     } else {
1093       // (C++ 13p1):
1094       //   Only function declarations can be overloaded; object and type
1095       //   declarations cannot be overloaded.
1096       Match = *I;
1097       return Ovl_NonFunction;
1098     }
1099   }
1100 
1101   // C++ [temp.friend]p1:
1102   //   For a friend function declaration that is not a template declaration:
1103   //    -- if the name of the friend is a qualified or unqualified template-id,
1104   //       [...], otherwise
1105   //    -- if the name of the friend is a qualified-id and a matching
1106   //       non-template function is found in the specified class or namespace,
1107   //       the friend declaration refers to that function, otherwise,
1108   //    -- if the name of the friend is a qualified-id and a matching function
1109   //       template is found in the specified class or namespace, the friend
1110   //       declaration refers to the deduced specialization of that function
1111   //       template, otherwise
1112   //    -- the name shall be an unqualified-id [...]
1113   // If we get here for a qualified friend declaration, we've just reached the
1114   // third bullet. If the type of the friend is dependent, skip this lookup
1115   // until instantiation.
1116   if (New->getFriendObjectKind() && New->getQualifier() &&
1117       !New->getDescribedFunctionTemplate() &&
1118       !New->getDependentSpecializationInfo() &&
1119       !New->getType()->isDependentType()) {
1120     LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1121     TemplateSpecResult.addAllDecls(Old);
1122     if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1123                                             /*QualifiedFriend*/true)) {
1124       New->setInvalidDecl();
1125       return Ovl_Overload;
1126     }
1127 
1128     Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1129     return Ovl_Match;
1130   }
1131 
1132   return Ovl_Overload;
1133 }
1134 
1135 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1136                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1137   // C++ [basic.start.main]p2: This function shall not be overloaded.
1138   if (New->isMain())
1139     return false;
1140 
1141   // MSVCRT user defined entry points cannot be overloaded.
1142   if (New->isMSVCRTEntryPoint())
1143     return false;
1144 
1145   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1146   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1147 
1148   // C++ [temp.fct]p2:
1149   //   A function template can be overloaded with other function templates
1150   //   and with normal (non-template) functions.
1151   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1152     return true;
1153 
1154   // Is the function New an overload of the function Old?
1155   QualType OldQType = Context.getCanonicalType(Old->getType());
1156   QualType NewQType = Context.getCanonicalType(New->getType());
1157 
1158   // Compare the signatures (C++ 1.3.10) of the two functions to
1159   // determine whether they are overloads. If we find any mismatch
1160   // in the signature, they are overloads.
1161 
1162   // If either of these functions is a K&R-style function (no
1163   // prototype), then we consider them to have matching signatures.
1164   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1165       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1166     return false;
1167 
1168   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1169   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1170 
1171   // The signature of a function includes the types of its
1172   // parameters (C++ 1.3.10), which includes the presence or absence
1173   // of the ellipsis; see C++ DR 357).
1174   if (OldQType != NewQType &&
1175       (OldType->getNumParams() != NewType->getNumParams() ||
1176        OldType->isVariadic() != NewType->isVariadic() ||
1177        !FunctionParamTypesAreEqual(OldType, NewType)))
1178     return true;
1179 
1180   // C++ [temp.over.link]p4:
1181   //   The signature of a function template consists of its function
1182   //   signature, its return type and its template parameter list. The names
1183   //   of the template parameters are significant only for establishing the
1184   //   relationship between the template parameters and the rest of the
1185   //   signature.
1186   //
1187   // We check the return type and template parameter lists for function
1188   // templates first; the remaining checks follow.
1189   //
1190   // However, we don't consider either of these when deciding whether
1191   // a member introduced by a shadow declaration is hidden.
1192   if (!UseMemberUsingDeclRules && NewTemplate &&
1193       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1194                                        OldTemplate->getTemplateParameters(),
1195                                        false, TPL_TemplateMatch) ||
1196        !Context.hasSameType(Old->getDeclaredReturnType(),
1197                             New->getDeclaredReturnType())))
1198     return true;
1199 
1200   // If the function is a class member, its signature includes the
1201   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1202   //
1203   // As part of this, also check whether one of the member functions
1204   // is static, in which case they are not overloads (C++
1205   // 13.1p2). While not part of the definition of the signature,
1206   // this check is important to determine whether these functions
1207   // can be overloaded.
1208   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1209   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1210   if (OldMethod && NewMethod &&
1211       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1212     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1213       if (!UseMemberUsingDeclRules &&
1214           (OldMethod->getRefQualifier() == RQ_None ||
1215            NewMethod->getRefQualifier() == RQ_None)) {
1216         // C++0x [over.load]p2:
1217         //   - Member function declarations with the same name and the same
1218         //     parameter-type-list as well as member function template
1219         //     declarations with the same name, the same parameter-type-list, and
1220         //     the same template parameter lists cannot be overloaded if any of
1221         //     them, but not all, have a ref-qualifier (8.3.5).
1222         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1223           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1224         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1225       }
1226       return true;
1227     }
1228 
1229     // We may not have applied the implicit const for a constexpr member
1230     // function yet (because we haven't yet resolved whether this is a static
1231     // or non-static member function). Add it now, on the assumption that this
1232     // is a redeclaration of OldMethod.
1233     auto OldQuals = OldMethod->getMethodQualifiers();
1234     auto NewQuals = NewMethod->getMethodQualifiers();
1235     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1236         !isa<CXXConstructorDecl>(NewMethod))
1237       NewQuals.addConst();
1238     // We do not allow overloading based off of '__restrict'.
1239     OldQuals.removeRestrict();
1240     NewQuals.removeRestrict();
1241     if (OldQuals != NewQuals)
1242       return true;
1243   }
1244 
1245   // Though pass_object_size is placed on parameters and takes an argument, we
1246   // consider it to be a function-level modifier for the sake of function
1247   // identity. Either the function has one or more parameters with
1248   // pass_object_size or it doesn't.
1249   if (functionHasPassObjectSizeParams(New) !=
1250       functionHasPassObjectSizeParams(Old))
1251     return true;
1252 
1253   // enable_if attributes are an order-sensitive part of the signature.
1254   for (specific_attr_iterator<EnableIfAttr>
1255          NewI = New->specific_attr_begin<EnableIfAttr>(),
1256          NewE = New->specific_attr_end<EnableIfAttr>(),
1257          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1258          OldE = Old->specific_attr_end<EnableIfAttr>();
1259        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1260     if (NewI == NewE || OldI == OldE)
1261       return true;
1262     llvm::FoldingSetNodeID NewID, OldID;
1263     NewI->getCond()->Profile(NewID, Context, true);
1264     OldI->getCond()->Profile(OldID, Context, true);
1265     if (NewID != OldID)
1266       return true;
1267   }
1268 
1269   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1270     // Don't allow overloading of destructors.  (In theory we could, but it
1271     // would be a giant change to clang.)
1272     if (isa<CXXDestructorDecl>(New))
1273       return false;
1274 
1275     CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1276                        OldTarget = IdentifyCUDATarget(Old);
1277     if (NewTarget == CFT_InvalidTarget)
1278       return false;
1279 
1280     assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1281 
1282     // Allow overloading of functions with same signature and different CUDA
1283     // target attributes.
1284     return NewTarget != OldTarget;
1285   }
1286 
1287   // TODO: Concepts: Check function trailing requires clauses here.
1288 
1289   // The signatures match; this is not an overload.
1290   return false;
1291 }
1292 
1293 /// Tries a user-defined conversion from From to ToType.
1294 ///
1295 /// Produces an implicit conversion sequence for when a standard conversion
1296 /// is not an option. See TryImplicitConversion for more information.
1297 static ImplicitConversionSequence
1298 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1299                          bool SuppressUserConversions,
1300                          bool AllowExplicit,
1301                          bool InOverloadResolution,
1302                          bool CStyle,
1303                          bool AllowObjCWritebackConversion,
1304                          bool AllowObjCConversionOnExplicit) {
1305   ImplicitConversionSequence ICS;
1306 
1307   if (SuppressUserConversions) {
1308     // We're not in the case above, so there is no conversion that
1309     // we can perform.
1310     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1311     return ICS;
1312   }
1313 
1314   // Attempt user-defined conversion.
1315   OverloadCandidateSet Conversions(From->getExprLoc(),
1316                                    OverloadCandidateSet::CSK_Normal);
1317   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1318                                   Conversions, AllowExplicit,
1319                                   AllowObjCConversionOnExplicit)) {
1320   case OR_Success:
1321   case OR_Deleted:
1322     ICS.setUserDefined();
1323     // C++ [over.ics.user]p4:
1324     //   A conversion of an expression of class type to the same class
1325     //   type is given Exact Match rank, and a conversion of an
1326     //   expression of class type to a base class of that type is
1327     //   given Conversion rank, in spite of the fact that a copy
1328     //   constructor (i.e., a user-defined conversion function) is
1329     //   called for those cases.
1330     if (CXXConstructorDecl *Constructor
1331           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1332       QualType FromCanon
1333         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1334       QualType ToCanon
1335         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1336       if (Constructor->isCopyConstructor() &&
1337           (FromCanon == ToCanon ||
1338            S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1339         // Turn this into a "standard" conversion sequence, so that it
1340         // gets ranked with standard conversion sequences.
1341         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1342         ICS.setStandard();
1343         ICS.Standard.setAsIdentityConversion();
1344         ICS.Standard.setFromType(From->getType());
1345         ICS.Standard.setAllToTypes(ToType);
1346         ICS.Standard.CopyConstructor = Constructor;
1347         ICS.Standard.FoundCopyConstructor = Found;
1348         if (ToCanon != FromCanon)
1349           ICS.Standard.Second = ICK_Derived_To_Base;
1350       }
1351     }
1352     break;
1353 
1354   case OR_Ambiguous:
1355     ICS.setAmbiguous();
1356     ICS.Ambiguous.setFromType(From->getType());
1357     ICS.Ambiguous.setToType(ToType);
1358     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1359          Cand != Conversions.end(); ++Cand)
1360       if (Cand->Best)
1361         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1362     break;
1363 
1364     // Fall through.
1365   case OR_No_Viable_Function:
1366     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1367     break;
1368   }
1369 
1370   return ICS;
1371 }
1372 
1373 /// TryImplicitConversion - Attempt to perform an implicit conversion
1374 /// from the given expression (Expr) to the given type (ToType). This
1375 /// function returns an implicit conversion sequence that can be used
1376 /// to perform the initialization. Given
1377 ///
1378 ///   void f(float f);
1379 ///   void g(int i) { f(i); }
1380 ///
1381 /// this routine would produce an implicit conversion sequence to
1382 /// describe the initialization of f from i, which will be a standard
1383 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1384 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1385 //
1386 /// Note that this routine only determines how the conversion can be
1387 /// performed; it does not actually perform the conversion. As such,
1388 /// it will not produce any diagnostics if no conversion is available,
1389 /// but will instead return an implicit conversion sequence of kind
1390 /// "BadConversion".
1391 ///
1392 /// If @p SuppressUserConversions, then user-defined conversions are
1393 /// not permitted.
1394 /// If @p AllowExplicit, then explicit user-defined conversions are
1395 /// permitted.
1396 ///
1397 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1398 /// writeback conversion, which allows __autoreleasing id* parameters to
1399 /// be initialized with __strong id* or __weak id* arguments.
1400 static ImplicitConversionSequence
1401 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1402                       bool SuppressUserConversions,
1403                       bool AllowExplicit,
1404                       bool InOverloadResolution,
1405                       bool CStyle,
1406                       bool AllowObjCWritebackConversion,
1407                       bool AllowObjCConversionOnExplicit) {
1408   ImplicitConversionSequence ICS;
1409   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1410                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1411     ICS.setStandard();
1412     return ICS;
1413   }
1414 
1415   if (!S.getLangOpts().CPlusPlus) {
1416     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1417     return ICS;
1418   }
1419 
1420   // C++ [over.ics.user]p4:
1421   //   A conversion of an expression of class type to the same class
1422   //   type is given Exact Match rank, and a conversion of an
1423   //   expression of class type to a base class of that type is
1424   //   given Conversion rank, in spite of the fact that a copy/move
1425   //   constructor (i.e., a user-defined conversion function) is
1426   //   called for those cases.
1427   QualType FromType = From->getType();
1428   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1429       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1430        S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1431     ICS.setStandard();
1432     ICS.Standard.setAsIdentityConversion();
1433     ICS.Standard.setFromType(FromType);
1434     ICS.Standard.setAllToTypes(ToType);
1435 
1436     // We don't actually check at this point whether there is a valid
1437     // copy/move constructor, since overloading just assumes that it
1438     // exists. When we actually perform initialization, we'll find the
1439     // appropriate constructor to copy the returned object, if needed.
1440     ICS.Standard.CopyConstructor = nullptr;
1441 
1442     // Determine whether this is considered a derived-to-base conversion.
1443     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1444       ICS.Standard.Second = ICK_Derived_To_Base;
1445 
1446     return ICS;
1447   }
1448 
1449   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1450                                   AllowExplicit, InOverloadResolution, CStyle,
1451                                   AllowObjCWritebackConversion,
1452                                   AllowObjCConversionOnExplicit);
1453 }
1454 
1455 ImplicitConversionSequence
1456 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1457                             bool SuppressUserConversions,
1458                             bool AllowExplicit,
1459                             bool InOverloadResolution,
1460                             bool CStyle,
1461                             bool AllowObjCWritebackConversion) {
1462   return ::TryImplicitConversion(*this, From, ToType,
1463                                  SuppressUserConversions, AllowExplicit,
1464                                  InOverloadResolution, CStyle,
1465                                  AllowObjCWritebackConversion,
1466                                  /*AllowObjCConversionOnExplicit=*/false);
1467 }
1468 
1469 /// PerformImplicitConversion - Perform an implicit conversion of the
1470 /// expression From to the type ToType. Returns the
1471 /// converted expression. Flavor is the kind of conversion we're
1472 /// performing, used in the error message. If @p AllowExplicit,
1473 /// explicit user-defined conversions are permitted.
1474 ExprResult
1475 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1476                                 AssignmentAction Action, bool AllowExplicit) {
1477   ImplicitConversionSequence ICS;
1478   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1479 }
1480 
1481 ExprResult
1482 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1483                                 AssignmentAction Action, bool AllowExplicit,
1484                                 ImplicitConversionSequence& ICS) {
1485   if (checkPlaceholderForOverload(*this, From))
1486     return ExprError();
1487 
1488   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1489   bool AllowObjCWritebackConversion
1490     = getLangOpts().ObjCAutoRefCount &&
1491       (Action == AA_Passing || Action == AA_Sending);
1492   if (getLangOpts().ObjC)
1493     CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1494                                       From->getType(), From);
1495   ICS = ::TryImplicitConversion(*this, From, ToType,
1496                                 /*SuppressUserConversions=*/false,
1497                                 AllowExplicit,
1498                                 /*InOverloadResolution=*/false,
1499                                 /*CStyle=*/false,
1500                                 AllowObjCWritebackConversion,
1501                                 /*AllowObjCConversionOnExplicit=*/false);
1502   return PerformImplicitConversion(From, ToType, ICS, Action);
1503 }
1504 
1505 /// Determine whether the conversion from FromType to ToType is a valid
1506 /// conversion that strips "noexcept" or "noreturn" off the nested function
1507 /// type.
1508 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1509                                 QualType &ResultTy) {
1510   if (Context.hasSameUnqualifiedType(FromType, ToType))
1511     return false;
1512 
1513   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1514   //                    or F(t noexcept) -> F(t)
1515   // where F adds one of the following at most once:
1516   //   - a pointer
1517   //   - a member pointer
1518   //   - a block pointer
1519   // Changes here need matching changes in FindCompositePointerType.
1520   CanQualType CanTo = Context.getCanonicalType(ToType);
1521   CanQualType CanFrom = Context.getCanonicalType(FromType);
1522   Type::TypeClass TyClass = CanTo->getTypeClass();
1523   if (TyClass != CanFrom->getTypeClass()) return false;
1524   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1525     if (TyClass == Type::Pointer) {
1526       CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1527       CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1528     } else if (TyClass == Type::BlockPointer) {
1529       CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1530       CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1531     } else if (TyClass == Type::MemberPointer) {
1532       auto ToMPT = CanTo.castAs<MemberPointerType>();
1533       auto FromMPT = CanFrom.castAs<MemberPointerType>();
1534       // A function pointer conversion cannot change the class of the function.
1535       if (ToMPT->getClass() != FromMPT->getClass())
1536         return false;
1537       CanTo = ToMPT->getPointeeType();
1538       CanFrom = FromMPT->getPointeeType();
1539     } else {
1540       return false;
1541     }
1542 
1543     TyClass = CanTo->getTypeClass();
1544     if (TyClass != CanFrom->getTypeClass()) return false;
1545     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1546       return false;
1547   }
1548 
1549   const auto *FromFn = cast<FunctionType>(CanFrom);
1550   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1551 
1552   const auto *ToFn = cast<FunctionType>(CanTo);
1553   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1554 
1555   bool Changed = false;
1556 
1557   // Drop 'noreturn' if not present in target type.
1558   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1559     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1560     Changed = true;
1561   }
1562 
1563   // Drop 'noexcept' if not present in target type.
1564   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1565     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1566     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1567       FromFn = cast<FunctionType>(
1568           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1569                                                    EST_None)
1570                  .getTypePtr());
1571       Changed = true;
1572     }
1573 
1574     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1575     // only if the ExtParameterInfo lists of the two function prototypes can be
1576     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1577     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1578     bool CanUseToFPT, CanUseFromFPT;
1579     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1580                                       CanUseFromFPT, NewParamInfos) &&
1581         CanUseToFPT && !CanUseFromFPT) {
1582       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1583       ExtInfo.ExtParameterInfos =
1584           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1585       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1586                                             FromFPT->getParamTypes(), ExtInfo);
1587       FromFn = QT->getAs<FunctionType>();
1588       Changed = true;
1589     }
1590   }
1591 
1592   if (!Changed)
1593     return false;
1594 
1595   assert(QualType(FromFn, 0).isCanonical());
1596   if (QualType(FromFn, 0) != CanTo) return false;
1597 
1598   ResultTy = ToType;
1599   return true;
1600 }
1601 
1602 /// Determine whether the conversion from FromType to ToType is a valid
1603 /// vector conversion.
1604 ///
1605 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1606 /// conversion.
1607 static bool IsVectorConversion(Sema &S, QualType FromType,
1608                                QualType ToType, ImplicitConversionKind &ICK) {
1609   // We need at least one of these types to be a vector type to have a vector
1610   // conversion.
1611   if (!ToType->isVectorType() && !FromType->isVectorType())
1612     return false;
1613 
1614   // Identical types require no conversions.
1615   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1616     return false;
1617 
1618   // There are no conversions between extended vector types, only identity.
1619   if (ToType->isExtVectorType()) {
1620     // There are no conversions between extended vector types other than the
1621     // identity conversion.
1622     if (FromType->isExtVectorType())
1623       return false;
1624 
1625     // Vector splat from any arithmetic type to a vector.
1626     if (FromType->isArithmeticType()) {
1627       ICK = ICK_Vector_Splat;
1628       return true;
1629     }
1630   }
1631 
1632   // We can perform the conversion between vector types in the following cases:
1633   // 1)vector types are equivalent AltiVec and GCC vector types
1634   // 2)lax vector conversions are permitted and the vector types are of the
1635   //   same size
1636   if (ToType->isVectorType() && FromType->isVectorType()) {
1637     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1638         S.isLaxVectorConversion(FromType, ToType)) {
1639       ICK = ICK_Vector_Conversion;
1640       return true;
1641     }
1642   }
1643 
1644   return false;
1645 }
1646 
1647 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1648                                 bool InOverloadResolution,
1649                                 StandardConversionSequence &SCS,
1650                                 bool CStyle);
1651 
1652 /// IsStandardConversion - Determines whether there is a standard
1653 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1654 /// expression From to the type ToType. Standard conversion sequences
1655 /// only consider non-class types; for conversions that involve class
1656 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1657 /// contain the standard conversion sequence required to perform this
1658 /// conversion and this routine will return true. Otherwise, this
1659 /// routine will return false and the value of SCS is unspecified.
1660 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1661                                  bool InOverloadResolution,
1662                                  StandardConversionSequence &SCS,
1663                                  bool CStyle,
1664                                  bool AllowObjCWritebackConversion) {
1665   QualType FromType = From->getType();
1666 
1667   // Standard conversions (C++ [conv])
1668   SCS.setAsIdentityConversion();
1669   SCS.IncompatibleObjC = false;
1670   SCS.setFromType(FromType);
1671   SCS.CopyConstructor = nullptr;
1672 
1673   // There are no standard conversions for class types in C++, so
1674   // abort early. When overloading in C, however, we do permit them.
1675   if (S.getLangOpts().CPlusPlus &&
1676       (FromType->isRecordType() || ToType->isRecordType()))
1677     return false;
1678 
1679   // The first conversion can be an lvalue-to-rvalue conversion,
1680   // array-to-pointer conversion, or function-to-pointer conversion
1681   // (C++ 4p1).
1682 
1683   if (FromType == S.Context.OverloadTy) {
1684     DeclAccessPair AccessPair;
1685     if (FunctionDecl *Fn
1686           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1687                                                  AccessPair)) {
1688       // We were able to resolve the address of the overloaded function,
1689       // so we can convert to the type of that function.
1690       FromType = Fn->getType();
1691       SCS.setFromType(FromType);
1692 
1693       // we can sometimes resolve &foo<int> regardless of ToType, so check
1694       // if the type matches (identity) or we are converting to bool
1695       if (!S.Context.hasSameUnqualifiedType(
1696                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1697         QualType resultTy;
1698         // if the function type matches except for [[noreturn]], it's ok
1699         if (!S.IsFunctionConversion(FromType,
1700               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1701           // otherwise, only a boolean conversion is standard
1702           if (!ToType->isBooleanType())
1703             return false;
1704       }
1705 
1706       // Check if the "from" expression is taking the address of an overloaded
1707       // function and recompute the FromType accordingly. Take advantage of the
1708       // fact that non-static member functions *must* have such an address-of
1709       // expression.
1710       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1711       if (Method && !Method->isStatic()) {
1712         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1713                "Non-unary operator on non-static member address");
1714         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1715                == UO_AddrOf &&
1716                "Non-address-of operator on non-static member address");
1717         const Type *ClassType
1718           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1719         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1720       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1721         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1722                UO_AddrOf &&
1723                "Non-address-of operator for overloaded function expression");
1724         FromType = S.Context.getPointerType(FromType);
1725       }
1726 
1727       // Check that we've computed the proper type after overload resolution.
1728       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1729       // be calling it from within an NDEBUG block.
1730       assert(S.Context.hasSameType(
1731         FromType,
1732         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1733     } else {
1734       return false;
1735     }
1736   }
1737   // Lvalue-to-rvalue conversion (C++11 4.1):
1738   //   A glvalue (3.10) of a non-function, non-array type T can
1739   //   be converted to a prvalue.
1740   bool argIsLValue = From->isGLValue();
1741   if (argIsLValue &&
1742       !FromType->isFunctionType() && !FromType->isArrayType() &&
1743       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1744     SCS.First = ICK_Lvalue_To_Rvalue;
1745 
1746     // C11 6.3.2.1p2:
1747     //   ... if the lvalue has atomic type, the value has the non-atomic version
1748     //   of the type of the lvalue ...
1749     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1750       FromType = Atomic->getValueType();
1751 
1752     // If T is a non-class type, the type of the rvalue is the
1753     // cv-unqualified version of T. Otherwise, the type of the rvalue
1754     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1755     // just strip the qualifiers because they don't matter.
1756     FromType = FromType.getUnqualifiedType();
1757   } else if (FromType->isArrayType()) {
1758     // Array-to-pointer conversion (C++ 4.2)
1759     SCS.First = ICK_Array_To_Pointer;
1760 
1761     // An lvalue or rvalue of type "array of N T" or "array of unknown
1762     // bound of T" can be converted to an rvalue of type "pointer to
1763     // T" (C++ 4.2p1).
1764     FromType = S.Context.getArrayDecayedType(FromType);
1765 
1766     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1767       // This conversion is deprecated in C++03 (D.4)
1768       SCS.DeprecatedStringLiteralToCharPtr = true;
1769 
1770       // For the purpose of ranking in overload resolution
1771       // (13.3.3.1.1), this conversion is considered an
1772       // array-to-pointer conversion followed by a qualification
1773       // conversion (4.4). (C++ 4.2p2)
1774       SCS.Second = ICK_Identity;
1775       SCS.Third = ICK_Qualification;
1776       SCS.QualificationIncludesObjCLifetime = false;
1777       SCS.setAllToTypes(FromType);
1778       return true;
1779     }
1780   } else if (FromType->isFunctionType() && argIsLValue) {
1781     // Function-to-pointer conversion (C++ 4.3).
1782     SCS.First = ICK_Function_To_Pointer;
1783 
1784     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1785       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1786         if (!S.checkAddressOfFunctionIsAvailable(FD))
1787           return false;
1788 
1789     // An lvalue of function type T can be converted to an rvalue of
1790     // type "pointer to T." The result is a pointer to the
1791     // function. (C++ 4.3p1).
1792     FromType = S.Context.getPointerType(FromType);
1793   } else {
1794     // We don't require any conversions for the first step.
1795     SCS.First = ICK_Identity;
1796   }
1797   SCS.setToType(0, FromType);
1798 
1799   // The second conversion can be an integral promotion, floating
1800   // point promotion, integral conversion, floating point conversion,
1801   // floating-integral conversion, pointer conversion,
1802   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1803   // For overloading in C, this can also be a "compatible-type"
1804   // conversion.
1805   bool IncompatibleObjC = false;
1806   ImplicitConversionKind SecondICK = ICK_Identity;
1807   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1808     // The unqualified versions of the types are the same: there's no
1809     // conversion to do.
1810     SCS.Second = ICK_Identity;
1811   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1812     // Integral promotion (C++ 4.5).
1813     SCS.Second = ICK_Integral_Promotion;
1814     FromType = ToType.getUnqualifiedType();
1815   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1816     // Floating point promotion (C++ 4.6).
1817     SCS.Second = ICK_Floating_Promotion;
1818     FromType = ToType.getUnqualifiedType();
1819   } else if (S.IsComplexPromotion(FromType, ToType)) {
1820     // Complex promotion (Clang extension)
1821     SCS.Second = ICK_Complex_Promotion;
1822     FromType = ToType.getUnqualifiedType();
1823   } else if (ToType->isBooleanType() &&
1824              (FromType->isArithmeticType() ||
1825               FromType->isAnyPointerType() ||
1826               FromType->isBlockPointerType() ||
1827               FromType->isMemberPointerType() ||
1828               FromType->isNullPtrType())) {
1829     // Boolean conversions (C++ 4.12).
1830     SCS.Second = ICK_Boolean_Conversion;
1831     FromType = S.Context.BoolTy;
1832   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1833              ToType->isIntegralType(S.Context)) {
1834     // Integral conversions (C++ 4.7).
1835     SCS.Second = ICK_Integral_Conversion;
1836     FromType = ToType.getUnqualifiedType();
1837   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1838     // Complex conversions (C99 6.3.1.6)
1839     SCS.Second = ICK_Complex_Conversion;
1840     FromType = ToType.getUnqualifiedType();
1841   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1842              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1843     // Complex-real conversions (C99 6.3.1.7)
1844     SCS.Second = ICK_Complex_Real;
1845     FromType = ToType.getUnqualifiedType();
1846   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1847     // FIXME: disable conversions between long double and __float128 if
1848     // their representation is different until there is back end support
1849     // We of course allow this conversion if long double is really double.
1850     if (&S.Context.getFloatTypeSemantics(FromType) !=
1851         &S.Context.getFloatTypeSemantics(ToType)) {
1852       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1853                                     ToType == S.Context.LongDoubleTy) ||
1854                                    (FromType == S.Context.LongDoubleTy &&
1855                                     ToType == S.Context.Float128Ty));
1856       if (Float128AndLongDouble &&
1857           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1858            &llvm::APFloat::PPCDoubleDouble()))
1859         return false;
1860     }
1861     // Floating point conversions (C++ 4.8).
1862     SCS.Second = ICK_Floating_Conversion;
1863     FromType = ToType.getUnqualifiedType();
1864   } else if ((FromType->isRealFloatingType() &&
1865               ToType->isIntegralType(S.Context)) ||
1866              (FromType->isIntegralOrUnscopedEnumerationType() &&
1867               ToType->isRealFloatingType())) {
1868     // Floating-integral conversions (C++ 4.9).
1869     SCS.Second = ICK_Floating_Integral;
1870     FromType = ToType.getUnqualifiedType();
1871   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1872     SCS.Second = ICK_Block_Pointer_Conversion;
1873   } else if (AllowObjCWritebackConversion &&
1874              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1875     SCS.Second = ICK_Writeback_Conversion;
1876   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1877                                    FromType, IncompatibleObjC)) {
1878     // Pointer conversions (C++ 4.10).
1879     SCS.Second = ICK_Pointer_Conversion;
1880     SCS.IncompatibleObjC = IncompatibleObjC;
1881     FromType = FromType.getUnqualifiedType();
1882   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1883                                          InOverloadResolution, FromType)) {
1884     // Pointer to member conversions (4.11).
1885     SCS.Second = ICK_Pointer_Member;
1886   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1887     SCS.Second = SecondICK;
1888     FromType = ToType.getUnqualifiedType();
1889   } else if (!S.getLangOpts().CPlusPlus &&
1890              S.Context.typesAreCompatible(ToType, FromType)) {
1891     // Compatible conversions (Clang extension for C function overloading)
1892     SCS.Second = ICK_Compatible_Conversion;
1893     FromType = ToType.getUnqualifiedType();
1894   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1895                                              InOverloadResolution,
1896                                              SCS, CStyle)) {
1897     SCS.Second = ICK_TransparentUnionConversion;
1898     FromType = ToType;
1899   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1900                                  CStyle)) {
1901     // tryAtomicConversion has updated the standard conversion sequence
1902     // appropriately.
1903     return true;
1904   } else if (ToType->isEventT() &&
1905              From->isIntegerConstantExpr(S.getASTContext()) &&
1906              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1907     SCS.Second = ICK_Zero_Event_Conversion;
1908     FromType = ToType;
1909   } else if (ToType->isQueueT() &&
1910              From->isIntegerConstantExpr(S.getASTContext()) &&
1911              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1912     SCS.Second = ICK_Zero_Queue_Conversion;
1913     FromType = ToType;
1914   } else if (ToType->isSamplerT() &&
1915              From->isIntegerConstantExpr(S.getASTContext())) {
1916     SCS.Second = ICK_Compatible_Conversion;
1917     FromType = ToType;
1918   } else {
1919     // No second conversion required.
1920     SCS.Second = ICK_Identity;
1921   }
1922   SCS.setToType(1, FromType);
1923 
1924   // The third conversion can be a function pointer conversion or a
1925   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1926   bool ObjCLifetimeConversion;
1927   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1928     // Function pointer conversions (removing 'noexcept') including removal of
1929     // 'noreturn' (Clang extension).
1930     SCS.Third = ICK_Function_Conversion;
1931   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1932                                          ObjCLifetimeConversion)) {
1933     SCS.Third = ICK_Qualification;
1934     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1935     FromType = ToType;
1936   } else {
1937     // No conversion required
1938     SCS.Third = ICK_Identity;
1939   }
1940 
1941   // C++ [over.best.ics]p6:
1942   //   [...] Any difference in top-level cv-qualification is
1943   //   subsumed by the initialization itself and does not constitute
1944   //   a conversion. [...]
1945   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1946   QualType CanonTo = S.Context.getCanonicalType(ToType);
1947   if (CanonFrom.getLocalUnqualifiedType()
1948                                      == CanonTo.getLocalUnqualifiedType() &&
1949       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1950     FromType = ToType;
1951     CanonFrom = CanonTo;
1952   }
1953 
1954   SCS.setToType(2, FromType);
1955 
1956   if (CanonFrom == CanonTo)
1957     return true;
1958 
1959   // If we have not converted the argument type to the parameter type,
1960   // this is a bad conversion sequence, unless we're resolving an overload in C.
1961   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1962     return false;
1963 
1964   ExprResult ER = ExprResult{From};
1965   Sema::AssignConvertType Conv =
1966       S.CheckSingleAssignmentConstraints(ToType, ER,
1967                                          /*Diagnose=*/false,
1968                                          /*DiagnoseCFAudited=*/false,
1969                                          /*ConvertRHS=*/false);
1970   ImplicitConversionKind SecondConv;
1971   switch (Conv) {
1972   case Sema::Compatible:
1973     SecondConv = ICK_C_Only_Conversion;
1974     break;
1975   // For our purposes, discarding qualifiers is just as bad as using an
1976   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1977   // qualifiers, as well.
1978   case Sema::CompatiblePointerDiscardsQualifiers:
1979   case Sema::IncompatiblePointer:
1980   case Sema::IncompatiblePointerSign:
1981     SecondConv = ICK_Incompatible_Pointer_Conversion;
1982     break;
1983   default:
1984     return false;
1985   }
1986 
1987   // First can only be an lvalue conversion, so we pretend that this was the
1988   // second conversion. First should already be valid from earlier in the
1989   // function.
1990   SCS.Second = SecondConv;
1991   SCS.setToType(1, ToType);
1992 
1993   // Third is Identity, because Second should rank us worse than any other
1994   // conversion. This could also be ICK_Qualification, but it's simpler to just
1995   // lump everything in with the second conversion, and we don't gain anything
1996   // from making this ICK_Qualification.
1997   SCS.Third = ICK_Identity;
1998   SCS.setToType(2, ToType);
1999   return true;
2000 }
2001 
2002 static bool
2003 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2004                                      QualType &ToType,
2005                                      bool InOverloadResolution,
2006                                      StandardConversionSequence &SCS,
2007                                      bool CStyle) {
2008 
2009   const RecordType *UT = ToType->getAsUnionType();
2010   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2011     return false;
2012   // The field to initialize within the transparent union.
2013   RecordDecl *UD = UT->getDecl();
2014   // It's compatible if the expression matches any of the fields.
2015   for (const auto *it : UD->fields()) {
2016     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2017                              CStyle, /*AllowObjCWritebackConversion=*/false)) {
2018       ToType = it->getType();
2019       return true;
2020     }
2021   }
2022   return false;
2023 }
2024 
2025 /// IsIntegralPromotion - Determines whether the conversion from the
2026 /// expression From (whose potentially-adjusted type is FromType) to
2027 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
2028 /// sets PromotedType to the promoted type.
2029 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2030   const BuiltinType *To = ToType->getAs<BuiltinType>();
2031   // All integers are built-in.
2032   if (!To) {
2033     return false;
2034   }
2035 
2036   // An rvalue of type char, signed char, unsigned char, short int, or
2037   // unsigned short int can be converted to an rvalue of type int if
2038   // int can represent all the values of the source type; otherwise,
2039   // the source rvalue can be converted to an rvalue of type unsigned
2040   // int (C++ 4.5p1).
2041   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
2042       !FromType->isEnumeralType()) {
2043     if (// We can promote any signed, promotable integer type to an int
2044         (FromType->isSignedIntegerType() ||
2045          // We can promote any unsigned integer type whose size is
2046          // less than int to an int.
2047          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2048       return To->getKind() == BuiltinType::Int;
2049     }
2050 
2051     return To->getKind() == BuiltinType::UInt;
2052   }
2053 
2054   // C++11 [conv.prom]p3:
2055   //   A prvalue of an unscoped enumeration type whose underlying type is not
2056   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2057   //   following types that can represent all the values of the enumeration
2058   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
2059   //   unsigned int, long int, unsigned long int, long long int, or unsigned
2060   //   long long int. If none of the types in that list can represent all the
2061   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2062   //   type can be converted to an rvalue a prvalue of the extended integer type
2063   //   with lowest integer conversion rank (4.13) greater than the rank of long
2064   //   long in which all the values of the enumeration can be represented. If
2065   //   there are two such extended types, the signed one is chosen.
2066   // C++11 [conv.prom]p4:
2067   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
2068   //   can be converted to a prvalue of its underlying type. Moreover, if
2069   //   integral promotion can be applied to its underlying type, a prvalue of an
2070   //   unscoped enumeration type whose underlying type is fixed can also be
2071   //   converted to a prvalue of the promoted underlying type.
2072   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2073     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2074     // provided for a scoped enumeration.
2075     if (FromEnumType->getDecl()->isScoped())
2076       return false;
2077 
2078     // We can perform an integral promotion to the underlying type of the enum,
2079     // even if that's not the promoted type. Note that the check for promoting
2080     // the underlying type is based on the type alone, and does not consider
2081     // the bitfield-ness of the actual source expression.
2082     if (FromEnumType->getDecl()->isFixed()) {
2083       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2084       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2085              IsIntegralPromotion(nullptr, Underlying, ToType);
2086     }
2087 
2088     // We have already pre-calculated the promotion type, so this is trivial.
2089     if (ToType->isIntegerType() &&
2090         isCompleteType(From->getBeginLoc(), FromType))
2091       return Context.hasSameUnqualifiedType(
2092           ToType, FromEnumType->getDecl()->getPromotionType());
2093 
2094     // C++ [conv.prom]p5:
2095     //   If the bit-field has an enumerated type, it is treated as any other
2096     //   value of that type for promotion purposes.
2097     //
2098     // ... so do not fall through into the bit-field checks below in C++.
2099     if (getLangOpts().CPlusPlus)
2100       return false;
2101   }
2102 
2103   // C++0x [conv.prom]p2:
2104   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2105   //   to an rvalue a prvalue of the first of the following types that can
2106   //   represent all the values of its underlying type: int, unsigned int,
2107   //   long int, unsigned long int, long long int, or unsigned long long int.
2108   //   If none of the types in that list can represent all the values of its
2109   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2110   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2111   //   type.
2112   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2113       ToType->isIntegerType()) {
2114     // Determine whether the type we're converting from is signed or
2115     // unsigned.
2116     bool FromIsSigned = FromType->isSignedIntegerType();
2117     uint64_t FromSize = Context.getTypeSize(FromType);
2118 
2119     // The types we'll try to promote to, in the appropriate
2120     // order. Try each of these types.
2121     QualType PromoteTypes[6] = {
2122       Context.IntTy, Context.UnsignedIntTy,
2123       Context.LongTy, Context.UnsignedLongTy ,
2124       Context.LongLongTy, Context.UnsignedLongLongTy
2125     };
2126     for (int Idx = 0; Idx < 6; ++Idx) {
2127       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2128       if (FromSize < ToSize ||
2129           (FromSize == ToSize &&
2130            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2131         // We found the type that we can promote to. If this is the
2132         // type we wanted, we have a promotion. Otherwise, no
2133         // promotion.
2134         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2135       }
2136     }
2137   }
2138 
2139   // An rvalue for an integral bit-field (9.6) can be converted to an
2140   // rvalue of type int if int can represent all the values of the
2141   // bit-field; otherwise, it can be converted to unsigned int if
2142   // unsigned int can represent all the values of the bit-field. If
2143   // the bit-field is larger yet, no integral promotion applies to
2144   // it. If the bit-field has an enumerated type, it is treated as any
2145   // other value of that type for promotion purposes (C++ 4.5p3).
2146   // FIXME: We should delay checking of bit-fields until we actually perform the
2147   // conversion.
2148   //
2149   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2150   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2151   // bit-fields and those whose underlying type is larger than int) for GCC
2152   // compatibility.
2153   if (From) {
2154     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2155       llvm::APSInt BitWidth;
2156       if (FromType->isIntegralType(Context) &&
2157           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2158         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2159         ToSize = Context.getTypeSize(ToType);
2160 
2161         // Are we promoting to an int from a bitfield that fits in an int?
2162         if (BitWidth < ToSize ||
2163             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2164           return To->getKind() == BuiltinType::Int;
2165         }
2166 
2167         // Are we promoting to an unsigned int from an unsigned bitfield
2168         // that fits into an unsigned int?
2169         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2170           return To->getKind() == BuiltinType::UInt;
2171         }
2172 
2173         return false;
2174       }
2175     }
2176   }
2177 
2178   // An rvalue of type bool can be converted to an rvalue of type int,
2179   // with false becoming zero and true becoming one (C++ 4.5p4).
2180   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2181     return true;
2182   }
2183 
2184   return false;
2185 }
2186 
2187 /// IsFloatingPointPromotion - Determines whether the conversion from
2188 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2189 /// returns true and sets PromotedType to the promoted type.
2190 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2191   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2192     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2193       /// An rvalue of type float can be converted to an rvalue of type
2194       /// double. (C++ 4.6p1).
2195       if (FromBuiltin->getKind() == BuiltinType::Float &&
2196           ToBuiltin->getKind() == BuiltinType::Double)
2197         return true;
2198 
2199       // C99 6.3.1.5p1:
2200       //   When a float is promoted to double or long double, or a
2201       //   double is promoted to long double [...].
2202       if (!getLangOpts().CPlusPlus &&
2203           (FromBuiltin->getKind() == BuiltinType::Float ||
2204            FromBuiltin->getKind() == BuiltinType::Double) &&
2205           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2206            ToBuiltin->getKind() == BuiltinType::Float128))
2207         return true;
2208 
2209       // Half can be promoted to float.
2210       if (!getLangOpts().NativeHalfType &&
2211            FromBuiltin->getKind() == BuiltinType::Half &&
2212           ToBuiltin->getKind() == BuiltinType::Float)
2213         return true;
2214     }
2215 
2216   return false;
2217 }
2218 
2219 /// Determine if a conversion is a complex promotion.
2220 ///
2221 /// A complex promotion is defined as a complex -> complex conversion
2222 /// where the conversion between the underlying real types is a
2223 /// floating-point or integral promotion.
2224 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2225   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2226   if (!FromComplex)
2227     return false;
2228 
2229   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2230   if (!ToComplex)
2231     return false;
2232 
2233   return IsFloatingPointPromotion(FromComplex->getElementType(),
2234                                   ToComplex->getElementType()) ||
2235     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2236                         ToComplex->getElementType());
2237 }
2238 
2239 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2240 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2241 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2242 /// if non-empty, will be a pointer to ToType that may or may not have
2243 /// the right set of qualifiers on its pointee.
2244 ///
2245 static QualType
2246 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2247                                    QualType ToPointee, QualType ToType,
2248                                    ASTContext &Context,
2249                                    bool StripObjCLifetime = false) {
2250   assert((FromPtr->getTypeClass() == Type::Pointer ||
2251           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2252          "Invalid similarly-qualified pointer type");
2253 
2254   /// Conversions to 'id' subsume cv-qualifier conversions.
2255   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2256     return ToType.getUnqualifiedType();
2257 
2258   QualType CanonFromPointee
2259     = Context.getCanonicalType(FromPtr->getPointeeType());
2260   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2261   Qualifiers Quals = CanonFromPointee.getQualifiers();
2262 
2263   if (StripObjCLifetime)
2264     Quals.removeObjCLifetime();
2265 
2266   // Exact qualifier match -> return the pointer type we're converting to.
2267   if (CanonToPointee.getLocalQualifiers() == Quals) {
2268     // ToType is exactly what we need. Return it.
2269     if (!ToType.isNull())
2270       return ToType.getUnqualifiedType();
2271 
2272     // Build a pointer to ToPointee. It has the right qualifiers
2273     // already.
2274     if (isa<ObjCObjectPointerType>(ToType))
2275       return Context.getObjCObjectPointerType(ToPointee);
2276     return Context.getPointerType(ToPointee);
2277   }
2278 
2279   // Just build a canonical type that has the right qualifiers.
2280   QualType QualifiedCanonToPointee
2281     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2282 
2283   if (isa<ObjCObjectPointerType>(ToType))
2284     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2285   return Context.getPointerType(QualifiedCanonToPointee);
2286 }
2287 
2288 static bool isNullPointerConstantForConversion(Expr *Expr,
2289                                                bool InOverloadResolution,
2290                                                ASTContext &Context) {
2291   // Handle value-dependent integral null pointer constants correctly.
2292   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2293   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2294       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2295     return !InOverloadResolution;
2296 
2297   return Expr->isNullPointerConstant(Context,
2298                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2299                                         : Expr::NPC_ValueDependentIsNull);
2300 }
2301 
2302 /// IsPointerConversion - Determines whether the conversion of the
2303 /// expression From, which has the (possibly adjusted) type FromType,
2304 /// can be converted to the type ToType via a pointer conversion (C++
2305 /// 4.10). If so, returns true and places the converted type (that
2306 /// might differ from ToType in its cv-qualifiers at some level) into
2307 /// ConvertedType.
2308 ///
2309 /// This routine also supports conversions to and from block pointers
2310 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2311 /// pointers to interfaces. FIXME: Once we've determined the
2312 /// appropriate overloading rules for Objective-C, we may want to
2313 /// split the Objective-C checks into a different routine; however,
2314 /// GCC seems to consider all of these conversions to be pointer
2315 /// conversions, so for now they live here. IncompatibleObjC will be
2316 /// set if the conversion is an allowed Objective-C conversion that
2317 /// should result in a warning.
2318 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2319                                bool InOverloadResolution,
2320                                QualType& ConvertedType,
2321                                bool &IncompatibleObjC) {
2322   IncompatibleObjC = false;
2323   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2324                               IncompatibleObjC))
2325     return true;
2326 
2327   // Conversion from a null pointer constant to any Objective-C pointer type.
2328   if (ToType->isObjCObjectPointerType() &&
2329       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2330     ConvertedType = ToType;
2331     return true;
2332   }
2333 
2334   // Blocks: Block pointers can be converted to void*.
2335   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2336       ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2337     ConvertedType = ToType;
2338     return true;
2339   }
2340   // Blocks: A null pointer constant can be converted to a block
2341   // pointer type.
2342   if (ToType->isBlockPointerType() &&
2343       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2344     ConvertedType = ToType;
2345     return true;
2346   }
2347 
2348   // If the left-hand-side is nullptr_t, the right side can be a null
2349   // pointer constant.
2350   if (ToType->isNullPtrType() &&
2351       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2352     ConvertedType = ToType;
2353     return true;
2354   }
2355 
2356   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2357   if (!ToTypePtr)
2358     return false;
2359 
2360   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2361   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2362     ConvertedType = ToType;
2363     return true;
2364   }
2365 
2366   // Beyond this point, both types need to be pointers
2367   // , including objective-c pointers.
2368   QualType ToPointeeType = ToTypePtr->getPointeeType();
2369   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2370       !getLangOpts().ObjCAutoRefCount) {
2371     ConvertedType = BuildSimilarlyQualifiedPointerType(
2372                                       FromType->getAs<ObjCObjectPointerType>(),
2373                                                        ToPointeeType,
2374                                                        ToType, Context);
2375     return true;
2376   }
2377   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2378   if (!FromTypePtr)
2379     return false;
2380 
2381   QualType FromPointeeType = FromTypePtr->getPointeeType();
2382 
2383   // If the unqualified pointee types are the same, this can't be a
2384   // pointer conversion, so don't do all of the work below.
2385   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2386     return false;
2387 
2388   // An rvalue of type "pointer to cv T," where T is an object type,
2389   // can be converted to an rvalue of type "pointer to cv void" (C++
2390   // 4.10p2).
2391   if (FromPointeeType->isIncompleteOrObjectType() &&
2392       ToPointeeType->isVoidType()) {
2393     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2394                                                        ToPointeeType,
2395                                                        ToType, Context,
2396                                                    /*StripObjCLifetime=*/true);
2397     return true;
2398   }
2399 
2400   // MSVC allows implicit function to void* type conversion.
2401   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2402       ToPointeeType->isVoidType()) {
2403     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2404                                                        ToPointeeType,
2405                                                        ToType, Context);
2406     return true;
2407   }
2408 
2409   // When we're overloading in C, we allow a special kind of pointer
2410   // conversion for compatible-but-not-identical pointee types.
2411   if (!getLangOpts().CPlusPlus &&
2412       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2413     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2414                                                        ToPointeeType,
2415                                                        ToType, Context);
2416     return true;
2417   }
2418 
2419   // C++ [conv.ptr]p3:
2420   //
2421   //   An rvalue of type "pointer to cv D," where D is a class type,
2422   //   can be converted to an rvalue of type "pointer to cv B," where
2423   //   B is a base class (clause 10) of D. If B is an inaccessible
2424   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2425   //   necessitates this conversion is ill-formed. The result of the
2426   //   conversion is a pointer to the base class sub-object of the
2427   //   derived class object. The null pointer value is converted to
2428   //   the null pointer value of the destination type.
2429   //
2430   // Note that we do not check for ambiguity or inaccessibility
2431   // here. That is handled by CheckPointerConversion.
2432   if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2433       ToPointeeType->isRecordType() &&
2434       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2435       IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2436     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2437                                                        ToPointeeType,
2438                                                        ToType, Context);
2439     return true;
2440   }
2441 
2442   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2443       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2444     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2445                                                        ToPointeeType,
2446                                                        ToType, Context);
2447     return true;
2448   }
2449 
2450   return false;
2451 }
2452 
2453 /// Adopt the given qualifiers for the given type.
2454 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2455   Qualifiers TQs = T.getQualifiers();
2456 
2457   // Check whether qualifiers already match.
2458   if (TQs == Qs)
2459     return T;
2460 
2461   if (Qs.compatiblyIncludes(TQs))
2462     return Context.getQualifiedType(T, Qs);
2463 
2464   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2465 }
2466 
2467 /// isObjCPointerConversion - Determines whether this is an
2468 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2469 /// with the same arguments and return values.
2470 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2471                                    QualType& ConvertedType,
2472                                    bool &IncompatibleObjC) {
2473   if (!getLangOpts().ObjC)
2474     return false;
2475 
2476   // The set of qualifiers on the type we're converting from.
2477   Qualifiers FromQualifiers = FromType.getQualifiers();
2478 
2479   // First, we handle all conversions on ObjC object pointer types.
2480   const ObjCObjectPointerType* ToObjCPtr =
2481     ToType->getAs<ObjCObjectPointerType>();
2482   const ObjCObjectPointerType *FromObjCPtr =
2483     FromType->getAs<ObjCObjectPointerType>();
2484 
2485   if (ToObjCPtr && FromObjCPtr) {
2486     // If the pointee types are the same (ignoring qualifications),
2487     // then this is not a pointer conversion.
2488     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2489                                        FromObjCPtr->getPointeeType()))
2490       return false;
2491 
2492     // Conversion between Objective-C pointers.
2493     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2494       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2495       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2496       if (getLangOpts().CPlusPlus && LHS && RHS &&
2497           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2498                                                 FromObjCPtr->getPointeeType()))
2499         return false;
2500       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2501                                                    ToObjCPtr->getPointeeType(),
2502                                                          ToType, Context);
2503       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2504       return true;
2505     }
2506 
2507     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2508       // Okay: this is some kind of implicit downcast of Objective-C
2509       // interfaces, which is permitted. However, we're going to
2510       // complain about it.
2511       IncompatibleObjC = true;
2512       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2513                                                    ToObjCPtr->getPointeeType(),
2514                                                          ToType, Context);
2515       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2516       return true;
2517     }
2518   }
2519   // Beyond this point, both types need to be C pointers or block pointers.
2520   QualType ToPointeeType;
2521   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2522     ToPointeeType = ToCPtr->getPointeeType();
2523   else if (const BlockPointerType *ToBlockPtr =
2524             ToType->getAs<BlockPointerType>()) {
2525     // Objective C++: We're able to convert from a pointer to any object
2526     // to a block pointer type.
2527     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2528       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2529       return true;
2530     }
2531     ToPointeeType = ToBlockPtr->getPointeeType();
2532   }
2533   else if (FromType->getAs<BlockPointerType>() &&
2534            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2535     // Objective C++: We're able to convert from a block pointer type to a
2536     // pointer to any object.
2537     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2538     return true;
2539   }
2540   else
2541     return false;
2542 
2543   QualType FromPointeeType;
2544   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2545     FromPointeeType = FromCPtr->getPointeeType();
2546   else if (const BlockPointerType *FromBlockPtr =
2547            FromType->getAs<BlockPointerType>())
2548     FromPointeeType = FromBlockPtr->getPointeeType();
2549   else
2550     return false;
2551 
2552   // If we have pointers to pointers, recursively check whether this
2553   // is an Objective-C conversion.
2554   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2555       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2556                               IncompatibleObjC)) {
2557     // We always complain about this conversion.
2558     IncompatibleObjC = true;
2559     ConvertedType = Context.getPointerType(ConvertedType);
2560     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2561     return true;
2562   }
2563   // Allow conversion of pointee being objective-c pointer to another one;
2564   // as in I* to id.
2565   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2566       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2567       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2568                               IncompatibleObjC)) {
2569 
2570     ConvertedType = Context.getPointerType(ConvertedType);
2571     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2572     return true;
2573   }
2574 
2575   // If we have pointers to functions or blocks, check whether the only
2576   // differences in the argument and result types are in Objective-C
2577   // pointer conversions. If so, we permit the conversion (but
2578   // complain about it).
2579   const FunctionProtoType *FromFunctionType
2580     = FromPointeeType->getAs<FunctionProtoType>();
2581   const FunctionProtoType *ToFunctionType
2582     = ToPointeeType->getAs<FunctionProtoType>();
2583   if (FromFunctionType && ToFunctionType) {
2584     // If the function types are exactly the same, this isn't an
2585     // Objective-C pointer conversion.
2586     if (Context.getCanonicalType(FromPointeeType)
2587           == Context.getCanonicalType(ToPointeeType))
2588       return false;
2589 
2590     // Perform the quick checks that will tell us whether these
2591     // function types are obviously different.
2592     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2593         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2594         FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2595       return false;
2596 
2597     bool HasObjCConversion = false;
2598     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2599         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2600       // Okay, the types match exactly. Nothing to do.
2601     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2602                                        ToFunctionType->getReturnType(),
2603                                        ConvertedType, IncompatibleObjC)) {
2604       // Okay, we have an Objective-C pointer conversion.
2605       HasObjCConversion = true;
2606     } else {
2607       // Function types are too different. Abort.
2608       return false;
2609     }
2610 
2611     // Check argument types.
2612     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2613          ArgIdx != NumArgs; ++ArgIdx) {
2614       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2615       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2616       if (Context.getCanonicalType(FromArgType)
2617             == Context.getCanonicalType(ToArgType)) {
2618         // Okay, the types match exactly. Nothing to do.
2619       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2620                                          ConvertedType, IncompatibleObjC)) {
2621         // Okay, we have an Objective-C pointer conversion.
2622         HasObjCConversion = true;
2623       } else {
2624         // Argument types are too different. Abort.
2625         return false;
2626       }
2627     }
2628 
2629     if (HasObjCConversion) {
2630       // We had an Objective-C conversion. Allow this pointer
2631       // conversion, but complain about it.
2632       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2633       IncompatibleObjC = true;
2634       return true;
2635     }
2636   }
2637 
2638   return false;
2639 }
2640 
2641 /// Determine whether this is an Objective-C writeback conversion,
2642 /// used for parameter passing when performing automatic reference counting.
2643 ///
2644 /// \param FromType The type we're converting form.
2645 ///
2646 /// \param ToType The type we're converting to.
2647 ///
2648 /// \param ConvertedType The type that will be produced after applying
2649 /// this conversion.
2650 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2651                                      QualType &ConvertedType) {
2652   if (!getLangOpts().ObjCAutoRefCount ||
2653       Context.hasSameUnqualifiedType(FromType, ToType))
2654     return false;
2655 
2656   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2657   QualType ToPointee;
2658   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2659     ToPointee = ToPointer->getPointeeType();
2660   else
2661     return false;
2662 
2663   Qualifiers ToQuals = ToPointee.getQualifiers();
2664   if (!ToPointee->isObjCLifetimeType() ||
2665       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2666       !ToQuals.withoutObjCLifetime().empty())
2667     return false;
2668 
2669   // Argument must be a pointer to __strong to __weak.
2670   QualType FromPointee;
2671   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2672     FromPointee = FromPointer->getPointeeType();
2673   else
2674     return false;
2675 
2676   Qualifiers FromQuals = FromPointee.getQualifiers();
2677   if (!FromPointee->isObjCLifetimeType() ||
2678       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2679        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2680     return false;
2681 
2682   // Make sure that we have compatible qualifiers.
2683   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2684   if (!ToQuals.compatiblyIncludes(FromQuals))
2685     return false;
2686 
2687   // Remove qualifiers from the pointee type we're converting from; they
2688   // aren't used in the compatibility check belong, and we'll be adding back
2689   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2690   FromPointee = FromPointee.getUnqualifiedType();
2691 
2692   // The unqualified form of the pointee types must be compatible.
2693   ToPointee = ToPointee.getUnqualifiedType();
2694   bool IncompatibleObjC;
2695   if (Context.typesAreCompatible(FromPointee, ToPointee))
2696     FromPointee = ToPointee;
2697   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2698                                     IncompatibleObjC))
2699     return false;
2700 
2701   /// Construct the type we're converting to, which is a pointer to
2702   /// __autoreleasing pointee.
2703   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2704   ConvertedType = Context.getPointerType(FromPointee);
2705   return true;
2706 }
2707 
2708 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2709                                     QualType& ConvertedType) {
2710   QualType ToPointeeType;
2711   if (const BlockPointerType *ToBlockPtr =
2712         ToType->getAs<BlockPointerType>())
2713     ToPointeeType = ToBlockPtr->getPointeeType();
2714   else
2715     return false;
2716 
2717   QualType FromPointeeType;
2718   if (const BlockPointerType *FromBlockPtr =
2719       FromType->getAs<BlockPointerType>())
2720     FromPointeeType = FromBlockPtr->getPointeeType();
2721   else
2722     return false;
2723   // We have pointer to blocks, check whether the only
2724   // differences in the argument and result types are in Objective-C
2725   // pointer conversions. If so, we permit the conversion.
2726 
2727   const FunctionProtoType *FromFunctionType
2728     = FromPointeeType->getAs<FunctionProtoType>();
2729   const FunctionProtoType *ToFunctionType
2730     = ToPointeeType->getAs<FunctionProtoType>();
2731 
2732   if (!FromFunctionType || !ToFunctionType)
2733     return false;
2734 
2735   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2736     return true;
2737 
2738   // Perform the quick checks that will tell us whether these
2739   // function types are obviously different.
2740   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2741       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2742     return false;
2743 
2744   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2745   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2746   if (FromEInfo != ToEInfo)
2747     return false;
2748 
2749   bool IncompatibleObjC = false;
2750   if (Context.hasSameType(FromFunctionType->getReturnType(),
2751                           ToFunctionType->getReturnType())) {
2752     // Okay, the types match exactly. Nothing to do.
2753   } else {
2754     QualType RHS = FromFunctionType->getReturnType();
2755     QualType LHS = ToFunctionType->getReturnType();
2756     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2757         !RHS.hasQualifiers() && LHS.hasQualifiers())
2758        LHS = LHS.getUnqualifiedType();
2759 
2760      if (Context.hasSameType(RHS,LHS)) {
2761        // OK exact match.
2762      } else if (isObjCPointerConversion(RHS, LHS,
2763                                         ConvertedType, IncompatibleObjC)) {
2764      if (IncompatibleObjC)
2765        return false;
2766      // Okay, we have an Objective-C pointer conversion.
2767      }
2768      else
2769        return false;
2770    }
2771 
2772    // Check argument types.
2773    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2774         ArgIdx != NumArgs; ++ArgIdx) {
2775      IncompatibleObjC = false;
2776      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2777      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2778      if (Context.hasSameType(FromArgType, ToArgType)) {
2779        // Okay, the types match exactly. Nothing to do.
2780      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2781                                         ConvertedType, IncompatibleObjC)) {
2782        if (IncompatibleObjC)
2783          return false;
2784        // Okay, we have an Objective-C pointer conversion.
2785      } else
2786        // Argument types are too different. Abort.
2787        return false;
2788    }
2789 
2790    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2791    bool CanUseToFPT, CanUseFromFPT;
2792    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2793                                       CanUseToFPT, CanUseFromFPT,
2794                                       NewParamInfos))
2795      return false;
2796 
2797    ConvertedType = ToType;
2798    return true;
2799 }
2800 
2801 enum {
2802   ft_default,
2803   ft_different_class,
2804   ft_parameter_arity,
2805   ft_parameter_mismatch,
2806   ft_return_type,
2807   ft_qualifer_mismatch,
2808   ft_noexcept
2809 };
2810 
2811 /// Attempts to get the FunctionProtoType from a Type. Handles
2812 /// MemberFunctionPointers properly.
2813 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2814   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2815     return FPT;
2816 
2817   if (auto *MPT = FromType->getAs<MemberPointerType>())
2818     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2819 
2820   return nullptr;
2821 }
2822 
2823 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2824 /// function types.  Catches different number of parameter, mismatch in
2825 /// parameter types, and different return types.
2826 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2827                                       QualType FromType, QualType ToType) {
2828   // If either type is not valid, include no extra info.
2829   if (FromType.isNull() || ToType.isNull()) {
2830     PDiag << ft_default;
2831     return;
2832   }
2833 
2834   // Get the function type from the pointers.
2835   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2836     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2837                             *ToMember = ToType->getAs<MemberPointerType>();
2838     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2839       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2840             << QualType(FromMember->getClass(), 0);
2841       return;
2842     }
2843     FromType = FromMember->getPointeeType();
2844     ToType = ToMember->getPointeeType();
2845   }
2846 
2847   if (FromType->isPointerType())
2848     FromType = FromType->getPointeeType();
2849   if (ToType->isPointerType())
2850     ToType = ToType->getPointeeType();
2851 
2852   // Remove references.
2853   FromType = FromType.getNonReferenceType();
2854   ToType = ToType.getNonReferenceType();
2855 
2856   // Don't print extra info for non-specialized template functions.
2857   if (FromType->isInstantiationDependentType() &&
2858       !FromType->getAs<TemplateSpecializationType>()) {
2859     PDiag << ft_default;
2860     return;
2861   }
2862 
2863   // No extra info for same types.
2864   if (Context.hasSameType(FromType, ToType)) {
2865     PDiag << ft_default;
2866     return;
2867   }
2868 
2869   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2870                           *ToFunction = tryGetFunctionProtoType(ToType);
2871 
2872   // Both types need to be function types.
2873   if (!FromFunction || !ToFunction) {
2874     PDiag << ft_default;
2875     return;
2876   }
2877 
2878   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2879     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2880           << FromFunction->getNumParams();
2881     return;
2882   }
2883 
2884   // Handle different parameter types.
2885   unsigned ArgPos;
2886   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2887     PDiag << ft_parameter_mismatch << ArgPos + 1
2888           << ToFunction->getParamType(ArgPos)
2889           << FromFunction->getParamType(ArgPos);
2890     return;
2891   }
2892 
2893   // Handle different return type.
2894   if (!Context.hasSameType(FromFunction->getReturnType(),
2895                            ToFunction->getReturnType())) {
2896     PDiag << ft_return_type << ToFunction->getReturnType()
2897           << FromFunction->getReturnType();
2898     return;
2899   }
2900 
2901   if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2902     PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2903           << FromFunction->getMethodQuals();
2904     return;
2905   }
2906 
2907   // Handle exception specification differences on canonical type (in C++17
2908   // onwards).
2909   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2910           ->isNothrow() !=
2911       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2912           ->isNothrow()) {
2913     PDiag << ft_noexcept;
2914     return;
2915   }
2916 
2917   // Unable to find a difference, so add no extra info.
2918   PDiag << ft_default;
2919 }
2920 
2921 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2922 /// for equality of their argument types. Caller has already checked that
2923 /// they have same number of arguments.  If the parameters are different,
2924 /// ArgPos will have the parameter index of the first different parameter.
2925 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2926                                       const FunctionProtoType *NewType,
2927                                       unsigned *ArgPos) {
2928   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2929                                               N = NewType->param_type_begin(),
2930                                               E = OldType->param_type_end();
2931        O && (O != E); ++O, ++N) {
2932     if (!Context.hasSameType(O->getUnqualifiedType(),
2933                              N->getUnqualifiedType())) {
2934       if (ArgPos)
2935         *ArgPos = O - OldType->param_type_begin();
2936       return false;
2937     }
2938   }
2939   return true;
2940 }
2941 
2942 /// CheckPointerConversion - Check the pointer conversion from the
2943 /// expression From to the type ToType. This routine checks for
2944 /// ambiguous or inaccessible derived-to-base pointer
2945 /// conversions for which IsPointerConversion has already returned
2946 /// true. It returns true and produces a diagnostic if there was an
2947 /// error, or returns false otherwise.
2948 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2949                                   CastKind &Kind,
2950                                   CXXCastPath& BasePath,
2951                                   bool IgnoreBaseAccess,
2952                                   bool Diagnose) {
2953   QualType FromType = From->getType();
2954   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2955 
2956   Kind = CK_BitCast;
2957 
2958   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2959       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2960           Expr::NPCK_ZeroExpression) {
2961     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2962       DiagRuntimeBehavior(From->getExprLoc(), From,
2963                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2964                             << ToType << From->getSourceRange());
2965     else if (!isUnevaluatedContext())
2966       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2967         << ToType << From->getSourceRange();
2968   }
2969   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2970     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2971       QualType FromPointeeType = FromPtrType->getPointeeType(),
2972                ToPointeeType   = ToPtrType->getPointeeType();
2973 
2974       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2975           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2976         // We must have a derived-to-base conversion. Check an
2977         // ambiguous or inaccessible conversion.
2978         unsigned InaccessibleID = 0;
2979         unsigned AmbigiousID = 0;
2980         if (Diagnose) {
2981           InaccessibleID = diag::err_upcast_to_inaccessible_base;
2982           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2983         }
2984         if (CheckDerivedToBaseConversion(
2985                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2986                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2987                 &BasePath, IgnoreBaseAccess))
2988           return true;
2989 
2990         // The conversion was successful.
2991         Kind = CK_DerivedToBase;
2992       }
2993 
2994       if (Diagnose && !IsCStyleOrFunctionalCast &&
2995           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2996         assert(getLangOpts().MSVCCompat &&
2997                "this should only be possible with MSVCCompat!");
2998         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2999             << From->getSourceRange();
3000       }
3001     }
3002   } else if (const ObjCObjectPointerType *ToPtrType =
3003                ToType->getAs<ObjCObjectPointerType>()) {
3004     if (const ObjCObjectPointerType *FromPtrType =
3005           FromType->getAs<ObjCObjectPointerType>()) {
3006       // Objective-C++ conversions are always okay.
3007       // FIXME: We should have a different class of conversions for the
3008       // Objective-C++ implicit conversions.
3009       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3010         return false;
3011     } else if (FromType->isBlockPointerType()) {
3012       Kind = CK_BlockPointerToObjCPointerCast;
3013     } else {
3014       Kind = CK_CPointerToObjCPointerCast;
3015     }
3016   } else if (ToType->isBlockPointerType()) {
3017     if (!FromType->isBlockPointerType())
3018       Kind = CK_AnyPointerToBlockPointerCast;
3019   }
3020 
3021   // We shouldn't fall into this case unless it's valid for other
3022   // reasons.
3023   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3024     Kind = CK_NullToPointer;
3025 
3026   return false;
3027 }
3028 
3029 /// IsMemberPointerConversion - Determines whether the conversion of the
3030 /// expression From, which has the (possibly adjusted) type FromType, can be
3031 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
3032 /// If so, returns true and places the converted type (that might differ from
3033 /// ToType in its cv-qualifiers at some level) into ConvertedType.
3034 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3035                                      QualType ToType,
3036                                      bool InOverloadResolution,
3037                                      QualType &ConvertedType) {
3038   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3039   if (!ToTypePtr)
3040     return false;
3041 
3042   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3043   if (From->isNullPointerConstant(Context,
3044                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3045                                         : Expr::NPC_ValueDependentIsNull)) {
3046     ConvertedType = ToType;
3047     return true;
3048   }
3049 
3050   // Otherwise, both types have to be member pointers.
3051   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3052   if (!FromTypePtr)
3053     return false;
3054 
3055   // A pointer to member of B can be converted to a pointer to member of D,
3056   // where D is derived from B (C++ 4.11p2).
3057   QualType FromClass(FromTypePtr->getClass(), 0);
3058   QualType ToClass(ToTypePtr->getClass(), 0);
3059 
3060   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3061       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3062     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3063                                                  ToClass.getTypePtr());
3064     return true;
3065   }
3066 
3067   return false;
3068 }
3069 
3070 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3071 /// expression From to the type ToType. This routine checks for ambiguous or
3072 /// virtual or inaccessible base-to-derived member pointer conversions
3073 /// for which IsMemberPointerConversion has already returned true. It returns
3074 /// true and produces a diagnostic if there was an error, or returns false
3075 /// otherwise.
3076 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3077                                         CastKind &Kind,
3078                                         CXXCastPath &BasePath,
3079                                         bool IgnoreBaseAccess) {
3080   QualType FromType = From->getType();
3081   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3082   if (!FromPtrType) {
3083     // This must be a null pointer to member pointer conversion
3084     assert(From->isNullPointerConstant(Context,
3085                                        Expr::NPC_ValueDependentIsNull) &&
3086            "Expr must be null pointer constant!");
3087     Kind = CK_NullToMemberPointer;
3088     return false;
3089   }
3090 
3091   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3092   assert(ToPtrType && "No member pointer cast has a target type "
3093                       "that is not a member pointer.");
3094 
3095   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3096   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3097 
3098   // FIXME: What about dependent types?
3099   assert(FromClass->isRecordType() && "Pointer into non-class.");
3100   assert(ToClass->isRecordType() && "Pointer into non-class.");
3101 
3102   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3103                      /*DetectVirtual=*/true);
3104   bool DerivationOkay =
3105       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3106   assert(DerivationOkay &&
3107          "Should not have been called if derivation isn't OK.");
3108   (void)DerivationOkay;
3109 
3110   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3111                                   getUnqualifiedType())) {
3112     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3113     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3114       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3115     return true;
3116   }
3117 
3118   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3119     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3120       << FromClass << ToClass << QualType(VBase, 0)
3121       << From->getSourceRange();
3122     return true;
3123   }
3124 
3125   if (!IgnoreBaseAccess)
3126     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3127                          Paths.front(),
3128                          diag::err_downcast_from_inaccessible_base);
3129 
3130   // Must be a base to derived member conversion.
3131   BuildBasePathArray(Paths, BasePath);
3132   Kind = CK_BaseToDerivedMemberPointer;
3133   return false;
3134 }
3135 
3136 /// Determine whether the lifetime conversion between the two given
3137 /// qualifiers sets is nontrivial.
3138 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3139                                                Qualifiers ToQuals) {
3140   // Converting anything to const __unsafe_unretained is trivial.
3141   if (ToQuals.hasConst() &&
3142       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3143     return false;
3144 
3145   return true;
3146 }
3147 
3148 /// IsQualificationConversion - Determines whether the conversion from
3149 /// an rvalue of type FromType to ToType is a qualification conversion
3150 /// (C++ 4.4).
3151 ///
3152 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3153 /// when the qualification conversion involves a change in the Objective-C
3154 /// object lifetime.
3155 bool
3156 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3157                                 bool CStyle, bool &ObjCLifetimeConversion) {
3158   FromType = Context.getCanonicalType(FromType);
3159   ToType = Context.getCanonicalType(ToType);
3160   ObjCLifetimeConversion = false;
3161 
3162   // If FromType and ToType are the same type, this is not a
3163   // qualification conversion.
3164   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3165     return false;
3166 
3167   // (C++ 4.4p4):
3168   //   A conversion can add cv-qualifiers at levels other than the first
3169   //   in multi-level pointers, subject to the following rules: [...]
3170   bool PreviousToQualsIncludeConst = true;
3171   bool UnwrappedAnyPointer = false;
3172   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3173     // Within each iteration of the loop, we check the qualifiers to
3174     // determine if this still looks like a qualification
3175     // conversion. Then, if all is well, we unwrap one more level of
3176     // pointers or pointers-to-members and do it all again
3177     // until there are no more pointers or pointers-to-members left to
3178     // unwrap.
3179     UnwrappedAnyPointer = true;
3180 
3181     Qualifiers FromQuals = FromType.getQualifiers();
3182     Qualifiers ToQuals = ToType.getQualifiers();
3183 
3184     // Ignore __unaligned qualifier if this type is void.
3185     if (ToType.getUnqualifiedType()->isVoidType())
3186       FromQuals.removeUnaligned();
3187 
3188     // Objective-C ARC:
3189     //   Check Objective-C lifetime conversions.
3190     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3191         UnwrappedAnyPointer) {
3192       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3193         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3194           ObjCLifetimeConversion = true;
3195         FromQuals.removeObjCLifetime();
3196         ToQuals.removeObjCLifetime();
3197       } else {
3198         // Qualification conversions cannot cast between different
3199         // Objective-C lifetime qualifiers.
3200         return false;
3201       }
3202     }
3203 
3204     // Allow addition/removal of GC attributes but not changing GC attributes.
3205     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3206         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3207       FromQuals.removeObjCGCAttr();
3208       ToQuals.removeObjCGCAttr();
3209     }
3210 
3211     //   -- for every j > 0, if const is in cv 1,j then const is in cv
3212     //      2,j, and similarly for volatile.
3213     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3214       return false;
3215 
3216     //   -- if the cv 1,j and cv 2,j are different, then const is in
3217     //      every cv for 0 < k < j.
3218     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3219         && !PreviousToQualsIncludeConst)
3220       return false;
3221 
3222     // Keep track of whether all prior cv-qualifiers in the "to" type
3223     // include const.
3224     PreviousToQualsIncludeConst
3225       = PreviousToQualsIncludeConst && ToQuals.hasConst();
3226   }
3227 
3228   // Allows address space promotion by language rules implemented in
3229   // Type::Qualifiers::isAddressSpaceSupersetOf.
3230   Qualifiers FromQuals = FromType.getQualifiers();
3231   Qualifiers ToQuals = ToType.getQualifiers();
3232   if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) &&
3233       !FromQuals.isAddressSpaceSupersetOf(ToQuals)) {
3234     return false;
3235   }
3236 
3237   // We are left with FromType and ToType being the pointee types
3238   // after unwrapping the original FromType and ToType the same number
3239   // of types. If we unwrapped any pointers, and if FromType and
3240   // ToType have the same unqualified type (since we checked
3241   // qualifiers above), then this is a qualification conversion.
3242   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3243 }
3244 
3245 /// - Determine whether this is a conversion from a scalar type to an
3246 /// atomic type.
3247 ///
3248 /// If successful, updates \c SCS's second and third steps in the conversion
3249 /// sequence to finish the conversion.
3250 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3251                                 bool InOverloadResolution,
3252                                 StandardConversionSequence &SCS,
3253                                 bool CStyle) {
3254   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3255   if (!ToAtomic)
3256     return false;
3257 
3258   StandardConversionSequence InnerSCS;
3259   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3260                             InOverloadResolution, InnerSCS,
3261                             CStyle, /*AllowObjCWritebackConversion=*/false))
3262     return false;
3263 
3264   SCS.Second = InnerSCS.Second;
3265   SCS.setToType(1, InnerSCS.getToType(1));
3266   SCS.Third = InnerSCS.Third;
3267   SCS.QualificationIncludesObjCLifetime
3268     = InnerSCS.QualificationIncludesObjCLifetime;
3269   SCS.setToType(2, InnerSCS.getToType(2));
3270   return true;
3271 }
3272 
3273 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3274                                               CXXConstructorDecl *Constructor,
3275                                               QualType Type) {
3276   const FunctionProtoType *CtorType =
3277       Constructor->getType()->getAs<FunctionProtoType>();
3278   if (CtorType->getNumParams() > 0) {
3279     QualType FirstArg = CtorType->getParamType(0);
3280     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3281       return true;
3282   }
3283   return false;
3284 }
3285 
3286 static OverloadingResult
3287 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3288                                        CXXRecordDecl *To,
3289                                        UserDefinedConversionSequence &User,
3290                                        OverloadCandidateSet &CandidateSet,
3291                                        bool AllowExplicit) {
3292   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3293   for (auto *D : S.LookupConstructors(To)) {
3294     auto Info = getConstructorInfo(D);
3295     if (!Info)
3296       continue;
3297 
3298     bool Usable = !Info.Constructor->isInvalidDecl() &&
3299                   S.isInitListConstructor(Info.Constructor) &&
3300                   (AllowExplicit || !Info.Constructor->isExplicit());
3301     if (Usable) {
3302       // If the first argument is (a reference to) the target type,
3303       // suppress conversions.
3304       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3305           S.Context, Info.Constructor, ToType);
3306       if (Info.ConstructorTmpl)
3307         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3308                                        /*ExplicitArgs*/ nullptr, From,
3309                                        CandidateSet, SuppressUserConversions,
3310                                        /*PartialOverloading*/ false,
3311                                        AllowExplicit);
3312       else
3313         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3314                                CandidateSet, SuppressUserConversions,
3315                                /*PartialOverloading*/ false, AllowExplicit);
3316     }
3317   }
3318 
3319   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3320 
3321   OverloadCandidateSet::iterator Best;
3322   switch (auto Result =
3323               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3324   case OR_Deleted:
3325   case OR_Success: {
3326     // Record the standard conversion we used and the conversion function.
3327     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3328     QualType ThisType = Constructor->getThisType();
3329     // Initializer lists don't have conversions as such.
3330     User.Before.setAsIdentityConversion();
3331     User.HadMultipleCandidates = HadMultipleCandidates;
3332     User.ConversionFunction = Constructor;
3333     User.FoundConversionFunction = Best->FoundDecl;
3334     User.After.setAsIdentityConversion();
3335     User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3336     User.After.setAllToTypes(ToType);
3337     return Result;
3338   }
3339 
3340   case OR_No_Viable_Function:
3341     return OR_No_Viable_Function;
3342   case OR_Ambiguous:
3343     return OR_Ambiguous;
3344   }
3345 
3346   llvm_unreachable("Invalid OverloadResult!");
3347 }
3348 
3349 /// Determines whether there is a user-defined conversion sequence
3350 /// (C++ [over.ics.user]) that converts expression From to the type
3351 /// ToType. If such a conversion exists, User will contain the
3352 /// user-defined conversion sequence that performs such a conversion
3353 /// and this routine will return true. Otherwise, this routine returns
3354 /// false and User is unspecified.
3355 ///
3356 /// \param AllowExplicit  true if the conversion should consider C++0x
3357 /// "explicit" conversion functions as well as non-explicit conversion
3358 /// functions (C++0x [class.conv.fct]p2).
3359 ///
3360 /// \param AllowObjCConversionOnExplicit true if the conversion should
3361 /// allow an extra Objective-C pointer conversion on uses of explicit
3362 /// constructors. Requires \c AllowExplicit to also be set.
3363 static OverloadingResult
3364 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3365                         UserDefinedConversionSequence &User,
3366                         OverloadCandidateSet &CandidateSet,
3367                         bool AllowExplicit,
3368                         bool AllowObjCConversionOnExplicit) {
3369   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3370   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3371 
3372   // Whether we will only visit constructors.
3373   bool ConstructorsOnly = false;
3374 
3375   // If the type we are conversion to is a class type, enumerate its
3376   // constructors.
3377   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3378     // C++ [over.match.ctor]p1:
3379     //   When objects of class type are direct-initialized (8.5), or
3380     //   copy-initialized from an expression of the same or a
3381     //   derived class type (8.5), overload resolution selects the
3382     //   constructor. [...] For copy-initialization, the candidate
3383     //   functions are all the converting constructors (12.3.1) of
3384     //   that class. The argument list is the expression-list within
3385     //   the parentheses of the initializer.
3386     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3387         (From->getType()->getAs<RecordType>() &&
3388          S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3389       ConstructorsOnly = true;
3390 
3391     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3392       // We're not going to find any constructors.
3393     } else if (CXXRecordDecl *ToRecordDecl
3394                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3395 
3396       Expr **Args = &From;
3397       unsigned NumArgs = 1;
3398       bool ListInitializing = false;
3399       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3400         // But first, see if there is an init-list-constructor that will work.
3401         OverloadingResult Result = IsInitializerListConstructorConversion(
3402             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3403         if (Result != OR_No_Viable_Function)
3404           return Result;
3405         // Never mind.
3406         CandidateSet.clear(
3407             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3408 
3409         // If we're list-initializing, we pass the individual elements as
3410         // arguments, not the entire list.
3411         Args = InitList->getInits();
3412         NumArgs = InitList->getNumInits();
3413         ListInitializing = true;
3414       }
3415 
3416       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3417         auto Info = getConstructorInfo(D);
3418         if (!Info)
3419           continue;
3420 
3421         bool Usable = !Info.Constructor->isInvalidDecl();
3422         if (ListInitializing)
3423           Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3424         else
3425           Usable = Usable &&
3426                    Info.Constructor->isConvertingConstructor(AllowExplicit);
3427         if (Usable) {
3428           bool SuppressUserConversions = !ConstructorsOnly;
3429           if (SuppressUserConversions && ListInitializing) {
3430             SuppressUserConversions = false;
3431             if (NumArgs == 1) {
3432               // If the first argument is (a reference to) the target type,
3433               // suppress conversions.
3434               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3435                   S.Context, Info.Constructor, ToType);
3436             }
3437           }
3438           if (Info.ConstructorTmpl)
3439             S.AddTemplateOverloadCandidate(
3440                 Info.ConstructorTmpl, Info.FoundDecl,
3441                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3442                 CandidateSet, SuppressUserConversions,
3443                 /*PartialOverloading*/ false, AllowExplicit);
3444           else
3445             // Allow one user-defined conversion when user specifies a
3446             // From->ToType conversion via an static cast (c-style, etc).
3447             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3448                                    llvm::makeArrayRef(Args, NumArgs),
3449                                    CandidateSet, SuppressUserConversions,
3450                                    /*PartialOverloading*/ false, AllowExplicit);
3451         }
3452       }
3453     }
3454   }
3455 
3456   // Enumerate conversion functions, if we're allowed to.
3457   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3458   } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3459     // No conversion functions from incomplete types.
3460   } else if (const RecordType *FromRecordType =
3461                  From->getType()->getAs<RecordType>()) {
3462     if (CXXRecordDecl *FromRecordDecl
3463          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3464       // Add all of the conversion functions as candidates.
3465       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3466       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3467         DeclAccessPair FoundDecl = I.getPair();
3468         NamedDecl *D = FoundDecl.getDecl();
3469         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3470         if (isa<UsingShadowDecl>(D))
3471           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3472 
3473         CXXConversionDecl *Conv;
3474         FunctionTemplateDecl *ConvTemplate;
3475         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3476           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3477         else
3478           Conv = cast<CXXConversionDecl>(D);
3479 
3480         if (AllowExplicit || !Conv->isExplicit()) {
3481           if (ConvTemplate)
3482             S.AddTemplateConversionCandidate(
3483                 ConvTemplate, FoundDecl, ActingContext, From, ToType,
3484                 CandidateSet, AllowObjCConversionOnExplicit, AllowExplicit);
3485           else
3486             S.AddConversionCandidate(
3487                 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
3488                 AllowObjCConversionOnExplicit, AllowExplicit);
3489         }
3490       }
3491     }
3492   }
3493 
3494   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3495 
3496   OverloadCandidateSet::iterator Best;
3497   switch (auto Result =
3498               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3499   case OR_Success:
3500   case OR_Deleted:
3501     // Record the standard conversion we used and the conversion function.
3502     if (CXXConstructorDecl *Constructor
3503           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3504       // C++ [over.ics.user]p1:
3505       //   If the user-defined conversion is specified by a
3506       //   constructor (12.3.1), the initial standard conversion
3507       //   sequence converts the source type to the type required by
3508       //   the argument of the constructor.
3509       //
3510       QualType ThisType = Constructor->getThisType();
3511       if (isa<InitListExpr>(From)) {
3512         // Initializer lists don't have conversions as such.
3513         User.Before.setAsIdentityConversion();
3514       } else {
3515         if (Best->Conversions[0].isEllipsis())
3516           User.EllipsisConversion = true;
3517         else {
3518           User.Before = Best->Conversions[0].Standard;
3519           User.EllipsisConversion = false;
3520         }
3521       }
3522       User.HadMultipleCandidates = HadMultipleCandidates;
3523       User.ConversionFunction = Constructor;
3524       User.FoundConversionFunction = Best->FoundDecl;
3525       User.After.setAsIdentityConversion();
3526       User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3527       User.After.setAllToTypes(ToType);
3528       return Result;
3529     }
3530     if (CXXConversionDecl *Conversion
3531                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3532       // C++ [over.ics.user]p1:
3533       //
3534       //   [...] If the user-defined conversion is specified by a
3535       //   conversion function (12.3.2), the initial standard
3536       //   conversion sequence converts the source type to the
3537       //   implicit object parameter of the conversion function.
3538       User.Before = Best->Conversions[0].Standard;
3539       User.HadMultipleCandidates = HadMultipleCandidates;
3540       User.ConversionFunction = Conversion;
3541       User.FoundConversionFunction = Best->FoundDecl;
3542       User.EllipsisConversion = false;
3543 
3544       // C++ [over.ics.user]p2:
3545       //   The second standard conversion sequence converts the
3546       //   result of the user-defined conversion to the target type
3547       //   for the sequence. Since an implicit conversion sequence
3548       //   is an initialization, the special rules for
3549       //   initialization by user-defined conversion apply when
3550       //   selecting the best user-defined conversion for a
3551       //   user-defined conversion sequence (see 13.3.3 and
3552       //   13.3.3.1).
3553       User.After = Best->FinalConversion;
3554       return Result;
3555     }
3556     llvm_unreachable("Not a constructor or conversion function?");
3557 
3558   case OR_No_Viable_Function:
3559     return OR_No_Viable_Function;
3560 
3561   case OR_Ambiguous:
3562     return OR_Ambiguous;
3563   }
3564 
3565   llvm_unreachable("Invalid OverloadResult!");
3566 }
3567 
3568 bool
3569 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3570   ImplicitConversionSequence ICS;
3571   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3572                                     OverloadCandidateSet::CSK_Normal);
3573   OverloadingResult OvResult =
3574     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3575                             CandidateSet, false, false);
3576 
3577   if (!(OvResult == OR_Ambiguous ||
3578         (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3579     return false;
3580 
3581   auto Cands = CandidateSet.CompleteCandidates(
3582       *this,
3583       OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3584       From);
3585   if (OvResult == OR_Ambiguous)
3586     Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3587         << From->getType() << ToType << From->getSourceRange();
3588   else { // OR_No_Viable_Function && !CandidateSet.empty()
3589     if (!RequireCompleteType(From->getBeginLoc(), ToType,
3590                              diag::err_typecheck_nonviable_condition_incomplete,
3591                              From->getType(), From->getSourceRange()))
3592       Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3593           << false << From->getType() << From->getSourceRange() << ToType;
3594   }
3595 
3596   CandidateSet.NoteCandidates(
3597                               *this, From, Cands);
3598   return true;
3599 }
3600 
3601 /// Compare the user-defined conversion functions or constructors
3602 /// of two user-defined conversion sequences to determine whether any ordering
3603 /// is possible.
3604 static ImplicitConversionSequence::CompareKind
3605 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3606                            FunctionDecl *Function2) {
3607   if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11)
3608     return ImplicitConversionSequence::Indistinguishable;
3609 
3610   // Objective-C++:
3611   //   If both conversion functions are implicitly-declared conversions from
3612   //   a lambda closure type to a function pointer and a block pointer,
3613   //   respectively, always prefer the conversion to a function pointer,
3614   //   because the function pointer is more lightweight and is more likely
3615   //   to keep code working.
3616   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3617   if (!Conv1)
3618     return ImplicitConversionSequence::Indistinguishable;
3619 
3620   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3621   if (!Conv2)
3622     return ImplicitConversionSequence::Indistinguishable;
3623 
3624   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3625     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3626     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3627     if (Block1 != Block2)
3628       return Block1 ? ImplicitConversionSequence::Worse
3629                     : ImplicitConversionSequence::Better;
3630   }
3631 
3632   return ImplicitConversionSequence::Indistinguishable;
3633 }
3634 
3635 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3636     const ImplicitConversionSequence &ICS) {
3637   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3638          (ICS.isUserDefined() &&
3639           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3640 }
3641 
3642 /// CompareImplicitConversionSequences - Compare two implicit
3643 /// conversion sequences to determine whether one is better than the
3644 /// other or if they are indistinguishable (C++ 13.3.3.2).
3645 static ImplicitConversionSequence::CompareKind
3646 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3647                                    const ImplicitConversionSequence& ICS1,
3648                                    const ImplicitConversionSequence& ICS2)
3649 {
3650   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3651   // conversion sequences (as defined in 13.3.3.1)
3652   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3653   //      conversion sequence than a user-defined conversion sequence or
3654   //      an ellipsis conversion sequence, and
3655   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3656   //      conversion sequence than an ellipsis conversion sequence
3657   //      (13.3.3.1.3).
3658   //
3659   // C++0x [over.best.ics]p10:
3660   //   For the purpose of ranking implicit conversion sequences as
3661   //   described in 13.3.3.2, the ambiguous conversion sequence is
3662   //   treated as a user-defined sequence that is indistinguishable
3663   //   from any other user-defined conversion sequence.
3664 
3665   // String literal to 'char *' conversion has been deprecated in C++03. It has
3666   // been removed from C++11. We still accept this conversion, if it happens at
3667   // the best viable function. Otherwise, this conversion is considered worse
3668   // than ellipsis conversion. Consider this as an extension; this is not in the
3669   // standard. For example:
3670   //
3671   // int &f(...);    // #1
3672   // void f(char*);  // #2
3673   // void g() { int &r = f("foo"); }
3674   //
3675   // In C++03, we pick #2 as the best viable function.
3676   // In C++11, we pick #1 as the best viable function, because ellipsis
3677   // conversion is better than string-literal to char* conversion (since there
3678   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3679   // convert arguments, #2 would be the best viable function in C++11.
3680   // If the best viable function has this conversion, a warning will be issued
3681   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3682 
3683   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3684       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3685       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3686     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3687                ? ImplicitConversionSequence::Worse
3688                : ImplicitConversionSequence::Better;
3689 
3690   if (ICS1.getKindRank() < ICS2.getKindRank())
3691     return ImplicitConversionSequence::Better;
3692   if (ICS2.getKindRank() < ICS1.getKindRank())
3693     return ImplicitConversionSequence::Worse;
3694 
3695   // The following checks require both conversion sequences to be of
3696   // the same kind.
3697   if (ICS1.getKind() != ICS2.getKind())
3698     return ImplicitConversionSequence::Indistinguishable;
3699 
3700   ImplicitConversionSequence::CompareKind Result =
3701       ImplicitConversionSequence::Indistinguishable;
3702 
3703   // Two implicit conversion sequences of the same form are
3704   // indistinguishable conversion sequences unless one of the
3705   // following rules apply: (C++ 13.3.3.2p3):
3706 
3707   // List-initialization sequence L1 is a better conversion sequence than
3708   // list-initialization sequence L2 if:
3709   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3710   //   if not that,
3711   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3712   //   and N1 is smaller than N2.,
3713   // even if one of the other rules in this paragraph would otherwise apply.
3714   if (!ICS1.isBad()) {
3715     if (ICS1.isStdInitializerListElement() &&
3716         !ICS2.isStdInitializerListElement())
3717       return ImplicitConversionSequence::Better;
3718     if (!ICS1.isStdInitializerListElement() &&
3719         ICS2.isStdInitializerListElement())
3720       return ImplicitConversionSequence::Worse;
3721   }
3722 
3723   if (ICS1.isStandard())
3724     // Standard conversion sequence S1 is a better conversion sequence than
3725     // standard conversion sequence S2 if [...]
3726     Result = CompareStandardConversionSequences(S, Loc,
3727                                                 ICS1.Standard, ICS2.Standard);
3728   else if (ICS1.isUserDefined()) {
3729     // User-defined conversion sequence U1 is a better conversion
3730     // sequence than another user-defined conversion sequence U2 if
3731     // they contain the same user-defined conversion function or
3732     // constructor and if the second standard conversion sequence of
3733     // U1 is better than the second standard conversion sequence of
3734     // U2 (C++ 13.3.3.2p3).
3735     if (ICS1.UserDefined.ConversionFunction ==
3736           ICS2.UserDefined.ConversionFunction)
3737       Result = CompareStandardConversionSequences(S, Loc,
3738                                                   ICS1.UserDefined.After,
3739                                                   ICS2.UserDefined.After);
3740     else
3741       Result = compareConversionFunctions(S,
3742                                           ICS1.UserDefined.ConversionFunction,
3743                                           ICS2.UserDefined.ConversionFunction);
3744   }
3745 
3746   return Result;
3747 }
3748 
3749 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3750 // determine if one is a proper subset of the other.
3751 static ImplicitConversionSequence::CompareKind
3752 compareStandardConversionSubsets(ASTContext &Context,
3753                                  const StandardConversionSequence& SCS1,
3754                                  const StandardConversionSequence& SCS2) {
3755   ImplicitConversionSequence::CompareKind Result
3756     = ImplicitConversionSequence::Indistinguishable;
3757 
3758   // the identity conversion sequence is considered to be a subsequence of
3759   // any non-identity conversion sequence
3760   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3761     return ImplicitConversionSequence::Better;
3762   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3763     return ImplicitConversionSequence::Worse;
3764 
3765   if (SCS1.Second != SCS2.Second) {
3766     if (SCS1.Second == ICK_Identity)
3767       Result = ImplicitConversionSequence::Better;
3768     else if (SCS2.Second == ICK_Identity)
3769       Result = ImplicitConversionSequence::Worse;
3770     else
3771       return ImplicitConversionSequence::Indistinguishable;
3772   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3773     return ImplicitConversionSequence::Indistinguishable;
3774 
3775   if (SCS1.Third == SCS2.Third) {
3776     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3777                              : ImplicitConversionSequence::Indistinguishable;
3778   }
3779 
3780   if (SCS1.Third == ICK_Identity)
3781     return Result == ImplicitConversionSequence::Worse
3782              ? ImplicitConversionSequence::Indistinguishable
3783              : ImplicitConversionSequence::Better;
3784 
3785   if (SCS2.Third == ICK_Identity)
3786     return Result == ImplicitConversionSequence::Better
3787              ? ImplicitConversionSequence::Indistinguishable
3788              : ImplicitConversionSequence::Worse;
3789 
3790   return ImplicitConversionSequence::Indistinguishable;
3791 }
3792 
3793 /// Determine whether one of the given reference bindings is better
3794 /// than the other based on what kind of bindings they are.
3795 static bool
3796 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3797                              const StandardConversionSequence &SCS2) {
3798   // C++0x [over.ics.rank]p3b4:
3799   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3800   //      implicit object parameter of a non-static member function declared
3801   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3802   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3803   //      lvalue reference to a function lvalue and S2 binds an rvalue
3804   //      reference*.
3805   //
3806   // FIXME: Rvalue references. We're going rogue with the above edits,
3807   // because the semantics in the current C++0x working paper (N3225 at the
3808   // time of this writing) break the standard definition of std::forward
3809   // and std::reference_wrapper when dealing with references to functions.
3810   // Proposed wording changes submitted to CWG for consideration.
3811   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3812       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3813     return false;
3814 
3815   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3816           SCS2.IsLvalueReference) ||
3817          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3818           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3819 }
3820 
3821 enum class FixedEnumPromotion {
3822   None,
3823   ToUnderlyingType,
3824   ToPromotedUnderlyingType
3825 };
3826 
3827 /// Returns kind of fixed enum promotion the \a SCS uses.
3828 static FixedEnumPromotion
3829 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
3830 
3831   if (SCS.Second != ICK_Integral_Promotion)
3832     return FixedEnumPromotion::None;
3833 
3834   QualType FromType = SCS.getFromType();
3835   if (!FromType->isEnumeralType())
3836     return FixedEnumPromotion::None;
3837 
3838   EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl();
3839   if (!Enum->isFixed())
3840     return FixedEnumPromotion::None;
3841 
3842   QualType UnderlyingType = Enum->getIntegerType();
3843   if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
3844     return FixedEnumPromotion::ToUnderlyingType;
3845 
3846   return FixedEnumPromotion::ToPromotedUnderlyingType;
3847 }
3848 
3849 /// CompareStandardConversionSequences - Compare two standard
3850 /// conversion sequences to determine whether one is better than the
3851 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3852 static ImplicitConversionSequence::CompareKind
3853 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3854                                    const StandardConversionSequence& SCS1,
3855                                    const StandardConversionSequence& SCS2)
3856 {
3857   // Standard conversion sequence S1 is a better conversion sequence
3858   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3859 
3860   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3861   //     sequences in the canonical form defined by 13.3.3.1.1,
3862   //     excluding any Lvalue Transformation; the identity conversion
3863   //     sequence is considered to be a subsequence of any
3864   //     non-identity conversion sequence) or, if not that,
3865   if (ImplicitConversionSequence::CompareKind CK
3866         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3867     return CK;
3868 
3869   //  -- the rank of S1 is better than the rank of S2 (by the rules
3870   //     defined below), or, if not that,
3871   ImplicitConversionRank Rank1 = SCS1.getRank();
3872   ImplicitConversionRank Rank2 = SCS2.getRank();
3873   if (Rank1 < Rank2)
3874     return ImplicitConversionSequence::Better;
3875   else if (Rank2 < Rank1)
3876     return ImplicitConversionSequence::Worse;
3877 
3878   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3879   // are indistinguishable unless one of the following rules
3880   // applies:
3881 
3882   //   A conversion that is not a conversion of a pointer, or
3883   //   pointer to member, to bool is better than another conversion
3884   //   that is such a conversion.
3885   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3886     return SCS2.isPointerConversionToBool()
3887              ? ImplicitConversionSequence::Better
3888              : ImplicitConversionSequence::Worse;
3889 
3890   // C++14 [over.ics.rank]p4b2:
3891   // This is retroactively applied to C++11 by CWG 1601.
3892   //
3893   //   A conversion that promotes an enumeration whose underlying type is fixed
3894   //   to its underlying type is better than one that promotes to the promoted
3895   //   underlying type, if the two are different.
3896   FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
3897   FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
3898   if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
3899       FEP1 != FEP2)
3900     return FEP1 == FixedEnumPromotion::ToUnderlyingType
3901                ? ImplicitConversionSequence::Better
3902                : ImplicitConversionSequence::Worse;
3903 
3904   // C++ [over.ics.rank]p4b2:
3905   //
3906   //   If class B is derived directly or indirectly from class A,
3907   //   conversion of B* to A* is better than conversion of B* to
3908   //   void*, and conversion of A* to void* is better than conversion
3909   //   of B* to void*.
3910   bool SCS1ConvertsToVoid
3911     = SCS1.isPointerConversionToVoidPointer(S.Context);
3912   bool SCS2ConvertsToVoid
3913     = SCS2.isPointerConversionToVoidPointer(S.Context);
3914   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3915     // Exactly one of the conversion sequences is a conversion to
3916     // a void pointer; it's the worse conversion.
3917     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3918                               : ImplicitConversionSequence::Worse;
3919   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3920     // Neither conversion sequence converts to a void pointer; compare
3921     // their derived-to-base conversions.
3922     if (ImplicitConversionSequence::CompareKind DerivedCK
3923           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3924       return DerivedCK;
3925   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3926              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3927     // Both conversion sequences are conversions to void
3928     // pointers. Compare the source types to determine if there's an
3929     // inheritance relationship in their sources.
3930     QualType FromType1 = SCS1.getFromType();
3931     QualType FromType2 = SCS2.getFromType();
3932 
3933     // Adjust the types we're converting from via the array-to-pointer
3934     // conversion, if we need to.
3935     if (SCS1.First == ICK_Array_To_Pointer)
3936       FromType1 = S.Context.getArrayDecayedType(FromType1);
3937     if (SCS2.First == ICK_Array_To_Pointer)
3938       FromType2 = S.Context.getArrayDecayedType(FromType2);
3939 
3940     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3941     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3942 
3943     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3944       return ImplicitConversionSequence::Better;
3945     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3946       return ImplicitConversionSequence::Worse;
3947 
3948     // Objective-C++: If one interface is more specific than the
3949     // other, it is the better one.
3950     const ObjCObjectPointerType* FromObjCPtr1
3951       = FromType1->getAs<ObjCObjectPointerType>();
3952     const ObjCObjectPointerType* FromObjCPtr2
3953       = FromType2->getAs<ObjCObjectPointerType>();
3954     if (FromObjCPtr1 && FromObjCPtr2) {
3955       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3956                                                           FromObjCPtr2);
3957       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3958                                                            FromObjCPtr1);
3959       if (AssignLeft != AssignRight) {
3960         return AssignLeft? ImplicitConversionSequence::Better
3961                          : ImplicitConversionSequence::Worse;
3962       }
3963     }
3964   }
3965 
3966   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3967   // bullet 3).
3968   if (ImplicitConversionSequence::CompareKind QualCK
3969         = CompareQualificationConversions(S, SCS1, SCS2))
3970     return QualCK;
3971 
3972   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3973     // Check for a better reference binding based on the kind of bindings.
3974     if (isBetterReferenceBindingKind(SCS1, SCS2))
3975       return ImplicitConversionSequence::Better;
3976     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3977       return ImplicitConversionSequence::Worse;
3978 
3979     // C++ [over.ics.rank]p3b4:
3980     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3981     //      which the references refer are the same type except for
3982     //      top-level cv-qualifiers, and the type to which the reference
3983     //      initialized by S2 refers is more cv-qualified than the type
3984     //      to which the reference initialized by S1 refers.
3985     QualType T1 = SCS1.getToType(2);
3986     QualType T2 = SCS2.getToType(2);
3987     T1 = S.Context.getCanonicalType(T1);
3988     T2 = S.Context.getCanonicalType(T2);
3989     Qualifiers T1Quals, T2Quals;
3990     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3991     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3992     if (UnqualT1 == UnqualT2) {
3993       // Objective-C++ ARC: If the references refer to objects with different
3994       // lifetimes, prefer bindings that don't change lifetime.
3995       if (SCS1.ObjCLifetimeConversionBinding !=
3996                                           SCS2.ObjCLifetimeConversionBinding) {
3997         return SCS1.ObjCLifetimeConversionBinding
3998                                            ? ImplicitConversionSequence::Worse
3999                                            : ImplicitConversionSequence::Better;
4000       }
4001 
4002       // If the type is an array type, promote the element qualifiers to the
4003       // type for comparison.
4004       if (isa<ArrayType>(T1) && T1Quals)
4005         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4006       if (isa<ArrayType>(T2) && T2Quals)
4007         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4008       if (T2.isMoreQualifiedThan(T1))
4009         return ImplicitConversionSequence::Better;
4010       else if (T1.isMoreQualifiedThan(T2))
4011         return ImplicitConversionSequence::Worse;
4012     }
4013   }
4014 
4015   // In Microsoft mode, prefer an integral conversion to a
4016   // floating-to-integral conversion if the integral conversion
4017   // is between types of the same size.
4018   // For example:
4019   // void f(float);
4020   // void f(int);
4021   // int main {
4022   //    long a;
4023   //    f(a);
4024   // }
4025   // Here, MSVC will call f(int) instead of generating a compile error
4026   // as clang will do in standard mode.
4027   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
4028       SCS2.Second == ICK_Floating_Integral &&
4029       S.Context.getTypeSize(SCS1.getFromType()) ==
4030           S.Context.getTypeSize(SCS1.getToType(2)))
4031     return ImplicitConversionSequence::Better;
4032 
4033   // Prefer a compatible vector conversion over a lax vector conversion
4034   // For example:
4035   //
4036   // typedef float __v4sf __attribute__((__vector_size__(16)));
4037   // void f(vector float);
4038   // void f(vector signed int);
4039   // int main() {
4040   //   __v4sf a;
4041   //   f(a);
4042   // }
4043   // Here, we'd like to choose f(vector float) and not
4044   // report an ambiguous call error
4045   if (SCS1.Second == ICK_Vector_Conversion &&
4046       SCS2.Second == ICK_Vector_Conversion) {
4047     bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4048         SCS1.getFromType(), SCS1.getToType(2));
4049     bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4050         SCS2.getFromType(), SCS2.getToType(2));
4051 
4052     if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4053       return SCS1IsCompatibleVectorConversion
4054                  ? ImplicitConversionSequence::Better
4055                  : ImplicitConversionSequence::Worse;
4056   }
4057 
4058   return ImplicitConversionSequence::Indistinguishable;
4059 }
4060 
4061 /// CompareQualificationConversions - Compares two standard conversion
4062 /// sequences to determine whether they can be ranked based on their
4063 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4064 static ImplicitConversionSequence::CompareKind
4065 CompareQualificationConversions(Sema &S,
4066                                 const StandardConversionSequence& SCS1,
4067                                 const StandardConversionSequence& SCS2) {
4068   // C++ 13.3.3.2p3:
4069   //  -- S1 and S2 differ only in their qualification conversion and
4070   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
4071   //     cv-qualification signature of type T1 is a proper subset of
4072   //     the cv-qualification signature of type T2, and S1 is not the
4073   //     deprecated string literal array-to-pointer conversion (4.2).
4074   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4075       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4076     return ImplicitConversionSequence::Indistinguishable;
4077 
4078   // FIXME: the example in the standard doesn't use a qualification
4079   // conversion (!)
4080   QualType T1 = SCS1.getToType(2);
4081   QualType T2 = SCS2.getToType(2);
4082   T1 = S.Context.getCanonicalType(T1);
4083   T2 = S.Context.getCanonicalType(T2);
4084   Qualifiers T1Quals, T2Quals;
4085   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4086   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4087 
4088   // If the types are the same, we won't learn anything by unwrapped
4089   // them.
4090   if (UnqualT1 == UnqualT2)
4091     return ImplicitConversionSequence::Indistinguishable;
4092 
4093   // If the type is an array type, promote the element qualifiers to the type
4094   // for comparison.
4095   if (isa<ArrayType>(T1) && T1Quals)
4096     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4097   if (isa<ArrayType>(T2) && T2Quals)
4098     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4099 
4100   ImplicitConversionSequence::CompareKind Result
4101     = ImplicitConversionSequence::Indistinguishable;
4102 
4103   // Objective-C++ ARC:
4104   //   Prefer qualification conversions not involving a change in lifetime
4105   //   to qualification conversions that do not change lifetime.
4106   if (SCS1.QualificationIncludesObjCLifetime !=
4107                                       SCS2.QualificationIncludesObjCLifetime) {
4108     Result = SCS1.QualificationIncludesObjCLifetime
4109                ? ImplicitConversionSequence::Worse
4110                : ImplicitConversionSequence::Better;
4111   }
4112 
4113   while (S.Context.UnwrapSimilarTypes(T1, T2)) {
4114     // Within each iteration of the loop, we check the qualifiers to
4115     // determine if this still looks like a qualification
4116     // conversion. Then, if all is well, we unwrap one more level of
4117     // pointers or pointers-to-members and do it all again
4118     // until there are no more pointers or pointers-to-members left
4119     // to unwrap. This essentially mimics what
4120     // IsQualificationConversion does, but here we're checking for a
4121     // strict subset of qualifiers.
4122     if (T1.getQualifiers().withoutObjCLifetime() ==
4123         T2.getQualifiers().withoutObjCLifetime())
4124       // The qualifiers are the same, so this doesn't tell us anything
4125       // about how the sequences rank.
4126       // ObjC ownership quals are omitted above as they interfere with
4127       // the ARC overload rule.
4128       ;
4129     else if (T2.isMoreQualifiedThan(T1)) {
4130       // T1 has fewer qualifiers, so it could be the better sequence.
4131       if (Result == ImplicitConversionSequence::Worse)
4132         // Neither has qualifiers that are a subset of the other's
4133         // qualifiers.
4134         return ImplicitConversionSequence::Indistinguishable;
4135 
4136       Result = ImplicitConversionSequence::Better;
4137     } else if (T1.isMoreQualifiedThan(T2)) {
4138       // T2 has fewer qualifiers, so it could be the better sequence.
4139       if (Result == ImplicitConversionSequence::Better)
4140         // Neither has qualifiers that are a subset of the other's
4141         // qualifiers.
4142         return ImplicitConversionSequence::Indistinguishable;
4143 
4144       Result = ImplicitConversionSequence::Worse;
4145     } else {
4146       // Qualifiers are disjoint.
4147       return ImplicitConversionSequence::Indistinguishable;
4148     }
4149 
4150     // If the types after this point are equivalent, we're done.
4151     if (S.Context.hasSameUnqualifiedType(T1, T2))
4152       break;
4153   }
4154 
4155   // Check that the winning standard conversion sequence isn't using
4156   // the deprecated string literal array to pointer conversion.
4157   switch (Result) {
4158   case ImplicitConversionSequence::Better:
4159     if (SCS1.DeprecatedStringLiteralToCharPtr)
4160       Result = ImplicitConversionSequence::Indistinguishable;
4161     break;
4162 
4163   case ImplicitConversionSequence::Indistinguishable:
4164     break;
4165 
4166   case ImplicitConversionSequence::Worse:
4167     if (SCS2.DeprecatedStringLiteralToCharPtr)
4168       Result = ImplicitConversionSequence::Indistinguishable;
4169     break;
4170   }
4171 
4172   return Result;
4173 }
4174 
4175 /// CompareDerivedToBaseConversions - Compares two standard conversion
4176 /// sequences to determine whether they can be ranked based on their
4177 /// various kinds of derived-to-base conversions (C++
4178 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4179 /// conversions between Objective-C interface types.
4180 static ImplicitConversionSequence::CompareKind
4181 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4182                                 const StandardConversionSequence& SCS1,
4183                                 const StandardConversionSequence& SCS2) {
4184   QualType FromType1 = SCS1.getFromType();
4185   QualType ToType1 = SCS1.getToType(1);
4186   QualType FromType2 = SCS2.getFromType();
4187   QualType ToType2 = SCS2.getToType(1);
4188 
4189   // Adjust the types we're converting from via the array-to-pointer
4190   // conversion, if we need to.
4191   if (SCS1.First == ICK_Array_To_Pointer)
4192     FromType1 = S.Context.getArrayDecayedType(FromType1);
4193   if (SCS2.First == ICK_Array_To_Pointer)
4194     FromType2 = S.Context.getArrayDecayedType(FromType2);
4195 
4196   // Canonicalize all of the types.
4197   FromType1 = S.Context.getCanonicalType(FromType1);
4198   ToType1 = S.Context.getCanonicalType(ToType1);
4199   FromType2 = S.Context.getCanonicalType(FromType2);
4200   ToType2 = S.Context.getCanonicalType(ToType2);
4201 
4202   // C++ [over.ics.rank]p4b3:
4203   //
4204   //   If class B is derived directly or indirectly from class A and
4205   //   class C is derived directly or indirectly from B,
4206   //
4207   // Compare based on pointer conversions.
4208   if (SCS1.Second == ICK_Pointer_Conversion &&
4209       SCS2.Second == ICK_Pointer_Conversion &&
4210       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4211       FromType1->isPointerType() && FromType2->isPointerType() &&
4212       ToType1->isPointerType() && ToType2->isPointerType()) {
4213     QualType FromPointee1 =
4214         FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4215     QualType ToPointee1 =
4216         ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4217     QualType FromPointee2 =
4218         FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4219     QualType ToPointee2 =
4220         ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4221 
4222     //   -- conversion of C* to B* is better than conversion of C* to A*,
4223     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4224       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4225         return ImplicitConversionSequence::Better;
4226       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4227         return ImplicitConversionSequence::Worse;
4228     }
4229 
4230     //   -- conversion of B* to A* is better than conversion of C* to A*,
4231     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4232       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4233         return ImplicitConversionSequence::Better;
4234       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4235         return ImplicitConversionSequence::Worse;
4236     }
4237   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4238              SCS2.Second == ICK_Pointer_Conversion) {
4239     const ObjCObjectPointerType *FromPtr1
4240       = FromType1->getAs<ObjCObjectPointerType>();
4241     const ObjCObjectPointerType *FromPtr2
4242       = FromType2->getAs<ObjCObjectPointerType>();
4243     const ObjCObjectPointerType *ToPtr1
4244       = ToType1->getAs<ObjCObjectPointerType>();
4245     const ObjCObjectPointerType *ToPtr2
4246       = ToType2->getAs<ObjCObjectPointerType>();
4247 
4248     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4249       // Apply the same conversion ranking rules for Objective-C pointer types
4250       // that we do for C++ pointers to class types. However, we employ the
4251       // Objective-C pseudo-subtyping relationship used for assignment of
4252       // Objective-C pointer types.
4253       bool FromAssignLeft
4254         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4255       bool FromAssignRight
4256         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4257       bool ToAssignLeft
4258         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4259       bool ToAssignRight
4260         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4261 
4262       // A conversion to an a non-id object pointer type or qualified 'id'
4263       // type is better than a conversion to 'id'.
4264       if (ToPtr1->isObjCIdType() &&
4265           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4266         return ImplicitConversionSequence::Worse;
4267       if (ToPtr2->isObjCIdType() &&
4268           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4269         return ImplicitConversionSequence::Better;
4270 
4271       // A conversion to a non-id object pointer type is better than a
4272       // conversion to a qualified 'id' type
4273       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4274         return ImplicitConversionSequence::Worse;
4275       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4276         return ImplicitConversionSequence::Better;
4277 
4278       // A conversion to an a non-Class object pointer type or qualified 'Class'
4279       // type is better than a conversion to 'Class'.
4280       if (ToPtr1->isObjCClassType() &&
4281           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4282         return ImplicitConversionSequence::Worse;
4283       if (ToPtr2->isObjCClassType() &&
4284           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4285         return ImplicitConversionSequence::Better;
4286 
4287       // A conversion to a non-Class object pointer type is better than a
4288       // conversion to a qualified 'Class' type.
4289       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4290         return ImplicitConversionSequence::Worse;
4291       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4292         return ImplicitConversionSequence::Better;
4293 
4294       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4295       if (S.Context.hasSameType(FromType1, FromType2) &&
4296           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4297           (ToAssignLeft != ToAssignRight)) {
4298         if (FromPtr1->isSpecialized()) {
4299           // "conversion of B<A> * to B * is better than conversion of B * to
4300           // C *.
4301           bool IsFirstSame =
4302               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4303           bool IsSecondSame =
4304               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4305           if (IsFirstSame) {
4306             if (!IsSecondSame)
4307               return ImplicitConversionSequence::Better;
4308           } else if (IsSecondSame)
4309             return ImplicitConversionSequence::Worse;
4310         }
4311         return ToAssignLeft? ImplicitConversionSequence::Worse
4312                            : ImplicitConversionSequence::Better;
4313       }
4314 
4315       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4316       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4317           (FromAssignLeft != FromAssignRight))
4318         return FromAssignLeft? ImplicitConversionSequence::Better
4319         : ImplicitConversionSequence::Worse;
4320     }
4321   }
4322 
4323   // Ranking of member-pointer types.
4324   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4325       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4326       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4327     const MemberPointerType * FromMemPointer1 =
4328                                         FromType1->getAs<MemberPointerType>();
4329     const MemberPointerType * ToMemPointer1 =
4330                                           ToType1->getAs<MemberPointerType>();
4331     const MemberPointerType * FromMemPointer2 =
4332                                           FromType2->getAs<MemberPointerType>();
4333     const MemberPointerType * ToMemPointer2 =
4334                                           ToType2->getAs<MemberPointerType>();
4335     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4336     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4337     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4338     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4339     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4340     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4341     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4342     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4343     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4344     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4345       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4346         return ImplicitConversionSequence::Worse;
4347       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4348         return ImplicitConversionSequence::Better;
4349     }
4350     // conversion of B::* to C::* is better than conversion of A::* to C::*
4351     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4352       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4353         return ImplicitConversionSequence::Better;
4354       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4355         return ImplicitConversionSequence::Worse;
4356     }
4357   }
4358 
4359   if (SCS1.Second == ICK_Derived_To_Base) {
4360     //   -- conversion of C to B is better than conversion of C to A,
4361     //   -- binding of an expression of type C to a reference of type
4362     //      B& is better than binding an expression of type C to a
4363     //      reference of type A&,
4364     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4365         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4366       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4367         return ImplicitConversionSequence::Better;
4368       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4369         return ImplicitConversionSequence::Worse;
4370     }
4371 
4372     //   -- conversion of B to A is better than conversion of C to A.
4373     //   -- binding of an expression of type B to a reference of type
4374     //      A& is better than binding an expression of type C to a
4375     //      reference of type A&,
4376     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4377         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4378       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4379         return ImplicitConversionSequence::Better;
4380       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4381         return ImplicitConversionSequence::Worse;
4382     }
4383   }
4384 
4385   return ImplicitConversionSequence::Indistinguishable;
4386 }
4387 
4388 /// Determine whether the given type is valid, e.g., it is not an invalid
4389 /// C++ class.
4390 static bool isTypeValid(QualType T) {
4391   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4392     return !Record->isInvalidDecl();
4393 
4394   return true;
4395 }
4396 
4397 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4398 /// determine whether they are reference-related,
4399 /// reference-compatible, reference-compatible with added
4400 /// qualification, or incompatible, for use in C++ initialization by
4401 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4402 /// type, and the first type (T1) is the pointee type of the reference
4403 /// type being initialized.
4404 Sema::ReferenceCompareResult
4405 Sema::CompareReferenceRelationship(SourceLocation Loc,
4406                                    QualType OrigT1, QualType OrigT2,
4407                                    bool &DerivedToBase,
4408                                    bool &ObjCConversion,
4409                                    bool &ObjCLifetimeConversion,
4410                                    bool &FunctionConversion) {
4411   assert(!OrigT1->isReferenceType() &&
4412     "T1 must be the pointee type of the reference type");
4413   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4414 
4415   QualType T1 = Context.getCanonicalType(OrigT1);
4416   QualType T2 = Context.getCanonicalType(OrigT2);
4417   Qualifiers T1Quals, T2Quals;
4418   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4419   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4420 
4421   // C++ [dcl.init.ref]p4:
4422   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4423   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4424   //   T1 is a base class of T2.
4425   DerivedToBase = false;
4426   ObjCConversion = false;
4427   ObjCLifetimeConversion = false;
4428   QualType ConvertedT2;
4429   if (UnqualT1 == UnqualT2) {
4430     // Nothing to do.
4431   } else if (isCompleteType(Loc, OrigT2) &&
4432              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4433              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4434     DerivedToBase = true;
4435   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4436            UnqualT2->isObjCObjectOrInterfaceType() &&
4437            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4438     ObjCConversion = true;
4439   else if (UnqualT2->isFunctionType() &&
4440            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4441     // C++1z [dcl.init.ref]p4:
4442     //   cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4443     //   function" and T1 is "function"
4444     //
4445     // We extend this to also apply to 'noreturn', so allow any function
4446     // conversion between function types.
4447     FunctionConversion = true;
4448     return Ref_Compatible;
4449   } else
4450     return Ref_Incompatible;
4451 
4452   // At this point, we know that T1 and T2 are reference-related (at
4453   // least).
4454 
4455   // If the type is an array type, promote the element qualifiers to the type
4456   // for comparison.
4457   if (isa<ArrayType>(T1) && T1Quals)
4458     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4459   if (isa<ArrayType>(T2) && T2Quals)
4460     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4461 
4462   // C++ [dcl.init.ref]p4:
4463   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4464   //   reference-related to T2 and cv1 is the same cv-qualification
4465   //   as, or greater cv-qualification than, cv2. For purposes of
4466   //   overload resolution, cases for which cv1 is greater
4467   //   cv-qualification than cv2 are identified as
4468   //   reference-compatible with added qualification (see 13.3.3.2).
4469   //
4470   // Note that we also require equivalence of Objective-C GC and address-space
4471   // qualifiers when performing these computations, so that e.g., an int in
4472   // address space 1 is not reference-compatible with an int in address
4473   // space 2.
4474   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4475       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4476     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4477       ObjCLifetimeConversion = true;
4478 
4479     T1Quals.removeObjCLifetime();
4480     T2Quals.removeObjCLifetime();
4481   }
4482 
4483   // MS compiler ignores __unaligned qualifier for references; do the same.
4484   T1Quals.removeUnaligned();
4485   T2Quals.removeUnaligned();
4486 
4487   if (T1Quals.compatiblyIncludes(T2Quals))
4488     return Ref_Compatible;
4489   else
4490     return Ref_Related;
4491 }
4492 
4493 /// Look for a user-defined conversion to a value reference-compatible
4494 ///        with DeclType. Return true if something definite is found.
4495 static bool
4496 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4497                          QualType DeclType, SourceLocation DeclLoc,
4498                          Expr *Init, QualType T2, bool AllowRvalues,
4499                          bool AllowExplicit) {
4500   assert(T2->isRecordType() && "Can only find conversions of record types.");
4501   CXXRecordDecl *T2RecordDecl
4502     = dyn_cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4503 
4504   OverloadCandidateSet CandidateSet(
4505       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4506   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4507   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4508     NamedDecl *D = *I;
4509     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4510     if (isa<UsingShadowDecl>(D))
4511       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4512 
4513     FunctionTemplateDecl *ConvTemplate
4514       = dyn_cast<FunctionTemplateDecl>(D);
4515     CXXConversionDecl *Conv;
4516     if (ConvTemplate)
4517       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4518     else
4519       Conv = cast<CXXConversionDecl>(D);
4520 
4521     // If this is an explicit conversion, and we're not allowed to consider
4522     // explicit conversions, skip it.
4523     if (!AllowExplicit && Conv->isExplicit())
4524       continue;
4525 
4526     if (AllowRvalues) {
4527       bool DerivedToBase = false;
4528       bool ObjCConversion = false;
4529       bool ObjCLifetimeConversion = false;
4530       bool FunctionConversion = false;
4531 
4532       // If we are initializing an rvalue reference, don't permit conversion
4533       // functions that return lvalues.
4534       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4535         const ReferenceType *RefType
4536           = Conv->getConversionType()->getAs<LValueReferenceType>();
4537         if (RefType && !RefType->getPointeeType()->isFunctionType())
4538           continue;
4539       }
4540 
4541       if (!ConvTemplate &&
4542           S.CompareReferenceRelationship(
4543               DeclLoc,
4544               Conv->getConversionType()
4545                   .getNonReferenceType()
4546                   .getUnqualifiedType(),
4547               DeclType.getNonReferenceType().getUnqualifiedType(),
4548               DerivedToBase, ObjCConversion, ObjCLifetimeConversion,
4549               FunctionConversion) == Sema::Ref_Incompatible)
4550         continue;
4551     } else {
4552       // If the conversion function doesn't return a reference type,
4553       // it can't be considered for this conversion. An rvalue reference
4554       // is only acceptable if its referencee is a function type.
4555 
4556       const ReferenceType *RefType =
4557         Conv->getConversionType()->getAs<ReferenceType>();
4558       if (!RefType ||
4559           (!RefType->isLValueReferenceType() &&
4560            !RefType->getPointeeType()->isFunctionType()))
4561         continue;
4562     }
4563 
4564     if (ConvTemplate)
4565       S.AddTemplateConversionCandidate(
4566           ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4567           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4568     else
4569       S.AddConversionCandidate(
4570           Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4571           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4572   }
4573 
4574   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4575 
4576   OverloadCandidateSet::iterator Best;
4577   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4578   case OR_Success:
4579     // C++ [over.ics.ref]p1:
4580     //
4581     //   [...] If the parameter binds directly to the result of
4582     //   applying a conversion function to the argument
4583     //   expression, the implicit conversion sequence is a
4584     //   user-defined conversion sequence (13.3.3.1.2), with the
4585     //   second standard conversion sequence either an identity
4586     //   conversion or, if the conversion function returns an
4587     //   entity of a type that is a derived class of the parameter
4588     //   type, a derived-to-base Conversion.
4589     if (!Best->FinalConversion.DirectBinding)
4590       return false;
4591 
4592     ICS.setUserDefined();
4593     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4594     ICS.UserDefined.After = Best->FinalConversion;
4595     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4596     ICS.UserDefined.ConversionFunction = Best->Function;
4597     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4598     ICS.UserDefined.EllipsisConversion = false;
4599     assert(ICS.UserDefined.After.ReferenceBinding &&
4600            ICS.UserDefined.After.DirectBinding &&
4601            "Expected a direct reference binding!");
4602     return true;
4603 
4604   case OR_Ambiguous:
4605     ICS.setAmbiguous();
4606     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4607          Cand != CandidateSet.end(); ++Cand)
4608       if (Cand->Best)
4609         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4610     return true;
4611 
4612   case OR_No_Viable_Function:
4613   case OR_Deleted:
4614     // There was no suitable conversion, or we found a deleted
4615     // conversion; continue with other checks.
4616     return false;
4617   }
4618 
4619   llvm_unreachable("Invalid OverloadResult!");
4620 }
4621 
4622 /// Compute an implicit conversion sequence for reference
4623 /// initialization.
4624 static ImplicitConversionSequence
4625 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4626                  SourceLocation DeclLoc,
4627                  bool SuppressUserConversions,
4628                  bool AllowExplicit) {
4629   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4630 
4631   // Most paths end in a failed conversion.
4632   ImplicitConversionSequence ICS;
4633   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4634 
4635   QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4636   QualType T2 = Init->getType();
4637 
4638   // If the initializer is the address of an overloaded function, try
4639   // to resolve the overloaded function. If all goes well, T2 is the
4640   // type of the resulting function.
4641   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4642     DeclAccessPair Found;
4643     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4644                                                                 false, Found))
4645       T2 = Fn->getType();
4646   }
4647 
4648   // Compute some basic properties of the types and the initializer.
4649   bool isRValRef = DeclType->isRValueReferenceType();
4650   bool DerivedToBase = false;
4651   bool ObjCConversion = false;
4652   bool ObjCLifetimeConversion = false;
4653   bool FunctionConversion = false;
4654   Expr::Classification InitCategory = Init->Classify(S.Context);
4655   Sema::ReferenceCompareResult RefRelationship = S.CompareReferenceRelationship(
4656       DeclLoc, T1, T2, DerivedToBase, ObjCConversion, ObjCLifetimeConversion,
4657       FunctionConversion);
4658 
4659   // C++0x [dcl.init.ref]p5:
4660   //   A reference to type "cv1 T1" is initialized by an expression
4661   //   of type "cv2 T2" as follows:
4662 
4663   //     -- If reference is an lvalue reference and the initializer expression
4664   if (!isRValRef) {
4665     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4666     //        reference-compatible with "cv2 T2," or
4667     //
4668     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4669     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4670       // C++ [over.ics.ref]p1:
4671       //   When a parameter of reference type binds directly (8.5.3)
4672       //   to an argument expression, the implicit conversion sequence
4673       //   is the identity conversion, unless the argument expression
4674       //   has a type that is a derived class of the parameter type,
4675       //   in which case the implicit conversion sequence is a
4676       //   derived-to-base Conversion (13.3.3.1).
4677       ICS.setStandard();
4678       ICS.Standard.First = ICK_Identity;
4679       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4680                          : ObjCConversion? ICK_Compatible_Conversion
4681                          : ICK_Identity;
4682       ICS.Standard.Third = ICK_Identity;
4683       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4684       ICS.Standard.setToType(0, T2);
4685       ICS.Standard.setToType(1, T1);
4686       ICS.Standard.setToType(2, T1);
4687       ICS.Standard.ReferenceBinding = true;
4688       ICS.Standard.DirectBinding = true;
4689       ICS.Standard.IsLvalueReference = !isRValRef;
4690       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4691       ICS.Standard.BindsToRvalue = false;
4692       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4693       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4694       ICS.Standard.CopyConstructor = nullptr;
4695       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4696 
4697       // Nothing more to do: the inaccessibility/ambiguity check for
4698       // derived-to-base conversions is suppressed when we're
4699       // computing the implicit conversion sequence (C++
4700       // [over.best.ics]p2).
4701       return ICS;
4702     }
4703 
4704     //       -- has a class type (i.e., T2 is a class type), where T1 is
4705     //          not reference-related to T2, and can be implicitly
4706     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4707     //          is reference-compatible with "cv3 T3" 92) (this
4708     //          conversion is selected by enumerating the applicable
4709     //          conversion functions (13.3.1.6) and choosing the best
4710     //          one through overload resolution (13.3)),
4711     if (!SuppressUserConversions && T2->isRecordType() &&
4712         S.isCompleteType(DeclLoc, T2) &&
4713         RefRelationship == Sema::Ref_Incompatible) {
4714       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4715                                    Init, T2, /*AllowRvalues=*/false,
4716                                    AllowExplicit))
4717         return ICS;
4718     }
4719   }
4720 
4721   //     -- Otherwise, the reference shall be an lvalue reference to a
4722   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4723   //        shall be an rvalue reference.
4724   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4725     return ICS;
4726 
4727   //       -- If the initializer expression
4728   //
4729   //            -- is an xvalue, class prvalue, array prvalue or function
4730   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4731   if (RefRelationship == Sema::Ref_Compatible &&
4732       (InitCategory.isXValue() ||
4733        (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4734        (InitCategory.isLValue() && T2->isFunctionType()))) {
4735     ICS.setStandard();
4736     ICS.Standard.First = ICK_Identity;
4737     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4738                       : ObjCConversion? ICK_Compatible_Conversion
4739                       : ICK_Identity;
4740     ICS.Standard.Third = ICK_Identity;
4741     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4742     ICS.Standard.setToType(0, T2);
4743     ICS.Standard.setToType(1, T1);
4744     ICS.Standard.setToType(2, T1);
4745     ICS.Standard.ReferenceBinding = true;
4746     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4747     // binding unless we're binding to a class prvalue.
4748     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4749     // allow the use of rvalue references in C++98/03 for the benefit of
4750     // standard library implementors; therefore, we need the xvalue check here.
4751     ICS.Standard.DirectBinding =
4752       S.getLangOpts().CPlusPlus11 ||
4753       !(InitCategory.isPRValue() || T2->isRecordType());
4754     ICS.Standard.IsLvalueReference = !isRValRef;
4755     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4756     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4757     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4758     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4759     ICS.Standard.CopyConstructor = nullptr;
4760     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4761     return ICS;
4762   }
4763 
4764   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4765   //               reference-related to T2, and can be implicitly converted to
4766   //               an xvalue, class prvalue, or function lvalue of type
4767   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4768   //               "cv3 T3",
4769   //
4770   //          then the reference is bound to the value of the initializer
4771   //          expression in the first case and to the result of the conversion
4772   //          in the second case (or, in either case, to an appropriate base
4773   //          class subobject).
4774   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4775       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4776       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4777                                Init, T2, /*AllowRvalues=*/true,
4778                                AllowExplicit)) {
4779     // In the second case, if the reference is an rvalue reference
4780     // and the second standard conversion sequence of the
4781     // user-defined conversion sequence includes an lvalue-to-rvalue
4782     // conversion, the program is ill-formed.
4783     if (ICS.isUserDefined() && isRValRef &&
4784         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4785       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4786 
4787     return ICS;
4788   }
4789 
4790   // A temporary of function type cannot be created; don't even try.
4791   if (T1->isFunctionType())
4792     return ICS;
4793 
4794   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4795   //          initialized from the initializer expression using the
4796   //          rules for a non-reference copy initialization (8.5). The
4797   //          reference is then bound to the temporary. If T1 is
4798   //          reference-related to T2, cv1 must be the same
4799   //          cv-qualification as, or greater cv-qualification than,
4800   //          cv2; otherwise, the program is ill-formed.
4801   if (RefRelationship == Sema::Ref_Related) {
4802     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4803     // we would be reference-compatible or reference-compatible with
4804     // added qualification. But that wasn't the case, so the reference
4805     // initialization fails.
4806     //
4807     // Note that we only want to check address spaces and cvr-qualifiers here.
4808     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4809     Qualifiers T1Quals = T1.getQualifiers();
4810     Qualifiers T2Quals = T2.getQualifiers();
4811     T1Quals.removeObjCGCAttr();
4812     T1Quals.removeObjCLifetime();
4813     T2Quals.removeObjCGCAttr();
4814     T2Quals.removeObjCLifetime();
4815     // MS compiler ignores __unaligned qualifier for references; do the same.
4816     T1Quals.removeUnaligned();
4817     T2Quals.removeUnaligned();
4818     if (!T1Quals.compatiblyIncludes(T2Quals))
4819       return ICS;
4820   }
4821 
4822   // If at least one of the types is a class type, the types are not
4823   // related, and we aren't allowed any user conversions, the
4824   // reference binding fails. This case is important for breaking
4825   // recursion, since TryImplicitConversion below will attempt to
4826   // create a temporary through the use of a copy constructor.
4827   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4828       (T1->isRecordType() || T2->isRecordType()))
4829     return ICS;
4830 
4831   // If T1 is reference-related to T2 and the reference is an rvalue
4832   // reference, the initializer expression shall not be an lvalue.
4833   if (RefRelationship >= Sema::Ref_Related &&
4834       isRValRef && Init->Classify(S.Context).isLValue())
4835     return ICS;
4836 
4837   // C++ [over.ics.ref]p2:
4838   //   When a parameter of reference type is not bound directly to
4839   //   an argument expression, the conversion sequence is the one
4840   //   required to convert the argument expression to the
4841   //   underlying type of the reference according to
4842   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4843   //   to copy-initializing a temporary of the underlying type with
4844   //   the argument expression. Any difference in top-level
4845   //   cv-qualification is subsumed by the initialization itself
4846   //   and does not constitute a conversion.
4847   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4848                               /*AllowExplicit=*/false,
4849                               /*InOverloadResolution=*/false,
4850                               /*CStyle=*/false,
4851                               /*AllowObjCWritebackConversion=*/false,
4852                               /*AllowObjCConversionOnExplicit=*/false);
4853 
4854   // Of course, that's still a reference binding.
4855   if (ICS.isStandard()) {
4856     ICS.Standard.ReferenceBinding = true;
4857     ICS.Standard.IsLvalueReference = !isRValRef;
4858     ICS.Standard.BindsToFunctionLvalue = false;
4859     ICS.Standard.BindsToRvalue = true;
4860     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4861     ICS.Standard.ObjCLifetimeConversionBinding = false;
4862   } else if (ICS.isUserDefined()) {
4863     const ReferenceType *LValRefType =
4864         ICS.UserDefined.ConversionFunction->getReturnType()
4865             ->getAs<LValueReferenceType>();
4866 
4867     // C++ [over.ics.ref]p3:
4868     //   Except for an implicit object parameter, for which see 13.3.1, a
4869     //   standard conversion sequence cannot be formed if it requires [...]
4870     //   binding an rvalue reference to an lvalue other than a function
4871     //   lvalue.
4872     // Note that the function case is not possible here.
4873     if (DeclType->isRValueReferenceType() && LValRefType) {
4874       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4875       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4876       // reference to an rvalue!
4877       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4878       return ICS;
4879     }
4880 
4881     ICS.UserDefined.After.ReferenceBinding = true;
4882     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4883     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4884     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4885     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4886     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4887   }
4888 
4889   return ICS;
4890 }
4891 
4892 static ImplicitConversionSequence
4893 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4894                       bool SuppressUserConversions,
4895                       bool InOverloadResolution,
4896                       bool AllowObjCWritebackConversion,
4897                       bool AllowExplicit = false);
4898 
4899 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4900 /// initializer list From.
4901 static ImplicitConversionSequence
4902 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4903                   bool SuppressUserConversions,
4904                   bool InOverloadResolution,
4905                   bool AllowObjCWritebackConversion) {
4906   // C++11 [over.ics.list]p1:
4907   //   When an argument is an initializer list, it is not an expression and
4908   //   special rules apply for converting it to a parameter type.
4909 
4910   ImplicitConversionSequence Result;
4911   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4912 
4913   // We need a complete type for what follows. Incomplete types can never be
4914   // initialized from init lists.
4915   if (!S.isCompleteType(From->getBeginLoc(), ToType))
4916     return Result;
4917 
4918   // Per DR1467:
4919   //   If the parameter type is a class X and the initializer list has a single
4920   //   element of type cv U, where U is X or a class derived from X, the
4921   //   implicit conversion sequence is the one required to convert the element
4922   //   to the parameter type.
4923   //
4924   //   Otherwise, if the parameter type is a character array [... ]
4925   //   and the initializer list has a single element that is an
4926   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4927   //   implicit conversion sequence is the identity conversion.
4928   if (From->getNumInits() == 1) {
4929     if (ToType->isRecordType()) {
4930       QualType InitType = From->getInit(0)->getType();
4931       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4932           S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
4933         return TryCopyInitialization(S, From->getInit(0), ToType,
4934                                      SuppressUserConversions,
4935                                      InOverloadResolution,
4936                                      AllowObjCWritebackConversion);
4937     }
4938     // FIXME: Check the other conditions here: array of character type,
4939     // initializer is a string literal.
4940     if (ToType->isArrayType()) {
4941       InitializedEntity Entity =
4942         InitializedEntity::InitializeParameter(S.Context, ToType,
4943                                                /*Consumed=*/false);
4944       if (S.CanPerformCopyInitialization(Entity, From)) {
4945         Result.setStandard();
4946         Result.Standard.setAsIdentityConversion();
4947         Result.Standard.setFromType(ToType);
4948         Result.Standard.setAllToTypes(ToType);
4949         return Result;
4950       }
4951     }
4952   }
4953 
4954   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4955   // C++11 [over.ics.list]p2:
4956   //   If the parameter type is std::initializer_list<X> or "array of X" and
4957   //   all the elements can be implicitly converted to X, the implicit
4958   //   conversion sequence is the worst conversion necessary to convert an
4959   //   element of the list to X.
4960   //
4961   // C++14 [over.ics.list]p3:
4962   //   Otherwise, if the parameter type is "array of N X", if the initializer
4963   //   list has exactly N elements or if it has fewer than N elements and X is
4964   //   default-constructible, and if all the elements of the initializer list
4965   //   can be implicitly converted to X, the implicit conversion sequence is
4966   //   the worst conversion necessary to convert an element of the list to X.
4967   //
4968   // FIXME: We're missing a lot of these checks.
4969   bool toStdInitializerList = false;
4970   QualType X;
4971   if (ToType->isArrayType())
4972     X = S.Context.getAsArrayType(ToType)->getElementType();
4973   else
4974     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4975   if (!X.isNull()) {
4976     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4977       Expr *Init = From->getInit(i);
4978       ImplicitConversionSequence ICS =
4979           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4980                                 InOverloadResolution,
4981                                 AllowObjCWritebackConversion);
4982       // If a single element isn't convertible, fail.
4983       if (ICS.isBad()) {
4984         Result = ICS;
4985         break;
4986       }
4987       // Otherwise, look for the worst conversion.
4988       if (Result.isBad() || CompareImplicitConversionSequences(
4989                                 S, From->getBeginLoc(), ICS, Result) ==
4990                                 ImplicitConversionSequence::Worse)
4991         Result = ICS;
4992     }
4993 
4994     // For an empty list, we won't have computed any conversion sequence.
4995     // Introduce the identity conversion sequence.
4996     if (From->getNumInits() == 0) {
4997       Result.setStandard();
4998       Result.Standard.setAsIdentityConversion();
4999       Result.Standard.setFromType(ToType);
5000       Result.Standard.setAllToTypes(ToType);
5001     }
5002 
5003     Result.setStdInitializerListElement(toStdInitializerList);
5004     return Result;
5005   }
5006 
5007   // C++14 [over.ics.list]p4:
5008   // C++11 [over.ics.list]p3:
5009   //   Otherwise, if the parameter is a non-aggregate class X and overload
5010   //   resolution chooses a single best constructor [...] the implicit
5011   //   conversion sequence is a user-defined conversion sequence. If multiple
5012   //   constructors are viable but none is better than the others, the
5013   //   implicit conversion sequence is a user-defined conversion sequence.
5014   if (ToType->isRecordType() && !ToType->isAggregateType()) {
5015     // This function can deal with initializer lists.
5016     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5017                                     /*AllowExplicit=*/false,
5018                                     InOverloadResolution, /*CStyle=*/false,
5019                                     AllowObjCWritebackConversion,
5020                                     /*AllowObjCConversionOnExplicit=*/false);
5021   }
5022 
5023   // C++14 [over.ics.list]p5:
5024   // C++11 [over.ics.list]p4:
5025   //   Otherwise, if the parameter has an aggregate type which can be
5026   //   initialized from the initializer list [...] the implicit conversion
5027   //   sequence is a user-defined conversion sequence.
5028   if (ToType->isAggregateType()) {
5029     // Type is an aggregate, argument is an init list. At this point it comes
5030     // down to checking whether the initialization works.
5031     // FIXME: Find out whether this parameter is consumed or not.
5032     InitializedEntity Entity =
5033         InitializedEntity::InitializeParameter(S.Context, ToType,
5034                                                /*Consumed=*/false);
5035     if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5036                                                                  From)) {
5037       Result.setUserDefined();
5038       Result.UserDefined.Before.setAsIdentityConversion();
5039       // Initializer lists don't have a type.
5040       Result.UserDefined.Before.setFromType(QualType());
5041       Result.UserDefined.Before.setAllToTypes(QualType());
5042 
5043       Result.UserDefined.After.setAsIdentityConversion();
5044       Result.UserDefined.After.setFromType(ToType);
5045       Result.UserDefined.After.setAllToTypes(ToType);
5046       Result.UserDefined.ConversionFunction = nullptr;
5047     }
5048     return Result;
5049   }
5050 
5051   // C++14 [over.ics.list]p6:
5052   // C++11 [over.ics.list]p5:
5053   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5054   if (ToType->isReferenceType()) {
5055     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5056     // mention initializer lists in any way. So we go by what list-
5057     // initialization would do and try to extrapolate from that.
5058 
5059     QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5060 
5061     // If the initializer list has a single element that is reference-related
5062     // to the parameter type, we initialize the reference from that.
5063     if (From->getNumInits() == 1) {
5064       Expr *Init = From->getInit(0);
5065 
5066       QualType T2 = Init->getType();
5067 
5068       // If the initializer is the address of an overloaded function, try
5069       // to resolve the overloaded function. If all goes well, T2 is the
5070       // type of the resulting function.
5071       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5072         DeclAccessPair Found;
5073         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5074                                    Init, ToType, false, Found))
5075           T2 = Fn->getType();
5076       }
5077 
5078       // Compute some basic properties of the types and the initializer.
5079       bool dummy1 = false;
5080       bool dummy2 = false;
5081       bool dummy3 = false;
5082       bool dummy4 = false;
5083       Sema::ReferenceCompareResult RefRelationship =
5084           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2, dummy1,
5085                                          dummy2, dummy3, dummy4);
5086 
5087       if (RefRelationship >= Sema::Ref_Related) {
5088         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5089                                 SuppressUserConversions,
5090                                 /*AllowExplicit=*/false);
5091       }
5092     }
5093 
5094     // Otherwise, we bind the reference to a temporary created from the
5095     // initializer list.
5096     Result = TryListConversion(S, From, T1, SuppressUserConversions,
5097                                InOverloadResolution,
5098                                AllowObjCWritebackConversion);
5099     if (Result.isFailure())
5100       return Result;
5101     assert(!Result.isEllipsis() &&
5102            "Sub-initialization cannot result in ellipsis conversion.");
5103 
5104     // Can we even bind to a temporary?
5105     if (ToType->isRValueReferenceType() ||
5106         (T1.isConstQualified() && !T1.isVolatileQualified())) {
5107       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5108                                             Result.UserDefined.After;
5109       SCS.ReferenceBinding = true;
5110       SCS.IsLvalueReference = ToType->isLValueReferenceType();
5111       SCS.BindsToRvalue = true;
5112       SCS.BindsToFunctionLvalue = false;
5113       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5114       SCS.ObjCLifetimeConversionBinding = false;
5115     } else
5116       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5117                     From, ToType);
5118     return Result;
5119   }
5120 
5121   // C++14 [over.ics.list]p7:
5122   // C++11 [over.ics.list]p6:
5123   //   Otherwise, if the parameter type is not a class:
5124   if (!ToType->isRecordType()) {
5125     //    - if the initializer list has one element that is not itself an
5126     //      initializer list, the implicit conversion sequence is the one
5127     //      required to convert the element to the parameter type.
5128     unsigned NumInits = From->getNumInits();
5129     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5130       Result = TryCopyInitialization(S, From->getInit(0), ToType,
5131                                      SuppressUserConversions,
5132                                      InOverloadResolution,
5133                                      AllowObjCWritebackConversion);
5134     //    - if the initializer list has no elements, the implicit conversion
5135     //      sequence is the identity conversion.
5136     else if (NumInits == 0) {
5137       Result.setStandard();
5138       Result.Standard.setAsIdentityConversion();
5139       Result.Standard.setFromType(ToType);
5140       Result.Standard.setAllToTypes(ToType);
5141     }
5142     return Result;
5143   }
5144 
5145   // C++14 [over.ics.list]p8:
5146   // C++11 [over.ics.list]p7:
5147   //   In all cases other than those enumerated above, no conversion is possible
5148   return Result;
5149 }
5150 
5151 /// TryCopyInitialization - Try to copy-initialize a value of type
5152 /// ToType from the expression From. Return the implicit conversion
5153 /// sequence required to pass this argument, which may be a bad
5154 /// conversion sequence (meaning that the argument cannot be passed to
5155 /// a parameter of this type). If @p SuppressUserConversions, then we
5156 /// do not permit any user-defined conversion sequences.
5157 static ImplicitConversionSequence
5158 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5159                       bool SuppressUserConversions,
5160                       bool InOverloadResolution,
5161                       bool AllowObjCWritebackConversion,
5162                       bool AllowExplicit) {
5163   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5164     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5165                              InOverloadResolution,AllowObjCWritebackConversion);
5166 
5167   if (ToType->isReferenceType())
5168     return TryReferenceInit(S, From, ToType,
5169                             /*FIXME:*/ From->getBeginLoc(),
5170                             SuppressUserConversions, AllowExplicit);
5171 
5172   return TryImplicitConversion(S, From, ToType,
5173                                SuppressUserConversions,
5174                                /*AllowExplicit=*/false,
5175                                InOverloadResolution,
5176                                /*CStyle=*/false,
5177                                AllowObjCWritebackConversion,
5178                                /*AllowObjCConversionOnExplicit=*/false);
5179 }
5180 
5181 static bool TryCopyInitialization(const CanQualType FromQTy,
5182                                   const CanQualType ToQTy,
5183                                   Sema &S,
5184                                   SourceLocation Loc,
5185                                   ExprValueKind FromVK) {
5186   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5187   ImplicitConversionSequence ICS =
5188     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5189 
5190   return !ICS.isBad();
5191 }
5192 
5193 /// TryObjectArgumentInitialization - Try to initialize the object
5194 /// parameter of the given member function (@c Method) from the
5195 /// expression @p From.
5196 static ImplicitConversionSequence
5197 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5198                                 Expr::Classification FromClassification,
5199                                 CXXMethodDecl *Method,
5200                                 CXXRecordDecl *ActingContext) {
5201   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5202   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5203   //                 const volatile object.
5204   Qualifiers Quals = Method->getMethodQualifiers();
5205   if (isa<CXXDestructorDecl>(Method)) {
5206     Quals.addConst();
5207     Quals.addVolatile();
5208   }
5209 
5210   QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5211 
5212   // Set up the conversion sequence as a "bad" conversion, to allow us
5213   // to exit early.
5214   ImplicitConversionSequence ICS;
5215 
5216   // We need to have an object of class type.
5217   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5218     FromType = PT->getPointeeType();
5219 
5220     // When we had a pointer, it's implicitly dereferenced, so we
5221     // better have an lvalue.
5222     assert(FromClassification.isLValue());
5223   }
5224 
5225   assert(FromType->isRecordType());
5226 
5227   // C++0x [over.match.funcs]p4:
5228   //   For non-static member functions, the type of the implicit object
5229   //   parameter is
5230   //
5231   //     - "lvalue reference to cv X" for functions declared without a
5232   //        ref-qualifier or with the & ref-qualifier
5233   //     - "rvalue reference to cv X" for functions declared with the &&
5234   //        ref-qualifier
5235   //
5236   // where X is the class of which the function is a member and cv is the
5237   // cv-qualification on the member function declaration.
5238   //
5239   // However, when finding an implicit conversion sequence for the argument, we
5240   // are not allowed to perform user-defined conversions
5241   // (C++ [over.match.funcs]p5). We perform a simplified version of
5242   // reference binding here, that allows class rvalues to bind to
5243   // non-constant references.
5244 
5245   // First check the qualifiers.
5246   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5247   if (ImplicitParamType.getCVRQualifiers()
5248                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5249       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5250     ICS.setBad(BadConversionSequence::bad_qualifiers,
5251                FromType, ImplicitParamType);
5252     return ICS;
5253   }
5254 
5255   if (FromTypeCanon.hasAddressSpace()) {
5256     Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5257     Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5258     if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5259       ICS.setBad(BadConversionSequence::bad_qualifiers,
5260                  FromType, ImplicitParamType);
5261       return ICS;
5262     }
5263   }
5264 
5265   // Check that we have either the same type or a derived type. It
5266   // affects the conversion rank.
5267   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5268   ImplicitConversionKind SecondKind;
5269   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5270     SecondKind = ICK_Identity;
5271   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5272     SecondKind = ICK_Derived_To_Base;
5273   else {
5274     ICS.setBad(BadConversionSequence::unrelated_class,
5275                FromType, ImplicitParamType);
5276     return ICS;
5277   }
5278 
5279   // Check the ref-qualifier.
5280   switch (Method->getRefQualifier()) {
5281   case RQ_None:
5282     // Do nothing; we don't care about lvalueness or rvalueness.
5283     break;
5284 
5285   case RQ_LValue:
5286     if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5287       // non-const lvalue reference cannot bind to an rvalue
5288       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5289                  ImplicitParamType);
5290       return ICS;
5291     }
5292     break;
5293 
5294   case RQ_RValue:
5295     if (!FromClassification.isRValue()) {
5296       // rvalue reference cannot bind to an lvalue
5297       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5298                  ImplicitParamType);
5299       return ICS;
5300     }
5301     break;
5302   }
5303 
5304   // Success. Mark this as a reference binding.
5305   ICS.setStandard();
5306   ICS.Standard.setAsIdentityConversion();
5307   ICS.Standard.Second = SecondKind;
5308   ICS.Standard.setFromType(FromType);
5309   ICS.Standard.setAllToTypes(ImplicitParamType);
5310   ICS.Standard.ReferenceBinding = true;
5311   ICS.Standard.DirectBinding = true;
5312   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5313   ICS.Standard.BindsToFunctionLvalue = false;
5314   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5315   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5316     = (Method->getRefQualifier() == RQ_None);
5317   return ICS;
5318 }
5319 
5320 /// PerformObjectArgumentInitialization - Perform initialization of
5321 /// the implicit object parameter for the given Method with the given
5322 /// expression.
5323 ExprResult
5324 Sema::PerformObjectArgumentInitialization(Expr *From,
5325                                           NestedNameSpecifier *Qualifier,
5326                                           NamedDecl *FoundDecl,
5327                                           CXXMethodDecl *Method) {
5328   QualType FromRecordType, DestType;
5329   QualType ImplicitParamRecordType  =
5330     Method->getThisType()->castAs<PointerType>()->getPointeeType();
5331 
5332   Expr::Classification FromClassification;
5333   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5334     FromRecordType = PT->getPointeeType();
5335     DestType = Method->getThisType();
5336     FromClassification = Expr::Classification::makeSimpleLValue();
5337   } else {
5338     FromRecordType = From->getType();
5339     DestType = ImplicitParamRecordType;
5340     FromClassification = From->Classify(Context);
5341 
5342     // When performing member access on an rvalue, materialize a temporary.
5343     if (From->isRValue()) {
5344       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5345                                             Method->getRefQualifier() !=
5346                                                 RefQualifierKind::RQ_RValue);
5347     }
5348   }
5349 
5350   // Note that we always use the true parent context when performing
5351   // the actual argument initialization.
5352   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5353       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5354       Method->getParent());
5355   if (ICS.isBad()) {
5356     switch (ICS.Bad.Kind) {
5357     case BadConversionSequence::bad_qualifiers: {
5358       Qualifiers FromQs = FromRecordType.getQualifiers();
5359       Qualifiers ToQs = DestType.getQualifiers();
5360       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5361       if (CVR) {
5362         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5363             << Method->getDeclName() << FromRecordType << (CVR - 1)
5364             << From->getSourceRange();
5365         Diag(Method->getLocation(), diag::note_previous_decl)
5366           << Method->getDeclName();
5367         return ExprError();
5368       }
5369       break;
5370     }
5371 
5372     case BadConversionSequence::lvalue_ref_to_rvalue:
5373     case BadConversionSequence::rvalue_ref_to_lvalue: {
5374       bool IsRValueQualified =
5375         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5376       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5377           << Method->getDeclName() << FromClassification.isRValue()
5378           << IsRValueQualified;
5379       Diag(Method->getLocation(), diag::note_previous_decl)
5380         << Method->getDeclName();
5381       return ExprError();
5382     }
5383 
5384     case BadConversionSequence::no_conversion:
5385     case BadConversionSequence::unrelated_class:
5386       break;
5387     }
5388 
5389     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5390            << ImplicitParamRecordType << FromRecordType
5391            << From->getSourceRange();
5392   }
5393 
5394   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5395     ExprResult FromRes =
5396       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5397     if (FromRes.isInvalid())
5398       return ExprError();
5399     From = FromRes.get();
5400   }
5401 
5402   if (!Context.hasSameType(From->getType(), DestType)) {
5403     CastKind CK;
5404     QualType PteeTy = DestType->getPointeeType();
5405     LangAS DestAS =
5406         PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5407     if (FromRecordType.getAddressSpace() != DestAS)
5408       CK = CK_AddressSpaceConversion;
5409     else
5410       CK = CK_NoOp;
5411     From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5412   }
5413   return From;
5414 }
5415 
5416 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5417 /// expression From to bool (C++0x [conv]p3).
5418 static ImplicitConversionSequence
5419 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5420   return TryImplicitConversion(S, From, S.Context.BoolTy,
5421                                /*SuppressUserConversions=*/false,
5422                                /*AllowExplicit=*/true,
5423                                /*InOverloadResolution=*/false,
5424                                /*CStyle=*/false,
5425                                /*AllowObjCWritebackConversion=*/false,
5426                                /*AllowObjCConversionOnExplicit=*/false);
5427 }
5428 
5429 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5430 /// of the expression From to bool (C++0x [conv]p3).
5431 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5432   if (checkPlaceholderForOverload(*this, From))
5433     return ExprError();
5434 
5435   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5436   if (!ICS.isBad())
5437     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5438 
5439   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5440     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5441            << From->getType() << From->getSourceRange();
5442   return ExprError();
5443 }
5444 
5445 /// Check that the specified conversion is permitted in a converted constant
5446 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5447 /// is acceptable.
5448 static bool CheckConvertedConstantConversions(Sema &S,
5449                                               StandardConversionSequence &SCS) {
5450   // Since we know that the target type is an integral or unscoped enumeration
5451   // type, most conversion kinds are impossible. All possible First and Third
5452   // conversions are fine.
5453   switch (SCS.Second) {
5454   case ICK_Identity:
5455   case ICK_Function_Conversion:
5456   case ICK_Integral_Promotion:
5457   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5458   case ICK_Zero_Queue_Conversion:
5459     return true;
5460 
5461   case ICK_Boolean_Conversion:
5462     // Conversion from an integral or unscoped enumeration type to bool is
5463     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5464     // conversion, so we allow it in a converted constant expression.
5465     //
5466     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5467     // a lot of popular code. We should at least add a warning for this
5468     // (non-conforming) extension.
5469     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5470            SCS.getToType(2)->isBooleanType();
5471 
5472   case ICK_Pointer_Conversion:
5473   case ICK_Pointer_Member:
5474     // C++1z: null pointer conversions and null member pointer conversions are
5475     // only permitted if the source type is std::nullptr_t.
5476     return SCS.getFromType()->isNullPtrType();
5477 
5478   case ICK_Floating_Promotion:
5479   case ICK_Complex_Promotion:
5480   case ICK_Floating_Conversion:
5481   case ICK_Complex_Conversion:
5482   case ICK_Floating_Integral:
5483   case ICK_Compatible_Conversion:
5484   case ICK_Derived_To_Base:
5485   case ICK_Vector_Conversion:
5486   case ICK_Vector_Splat:
5487   case ICK_Complex_Real:
5488   case ICK_Block_Pointer_Conversion:
5489   case ICK_TransparentUnionConversion:
5490   case ICK_Writeback_Conversion:
5491   case ICK_Zero_Event_Conversion:
5492   case ICK_C_Only_Conversion:
5493   case ICK_Incompatible_Pointer_Conversion:
5494     return false;
5495 
5496   case ICK_Lvalue_To_Rvalue:
5497   case ICK_Array_To_Pointer:
5498   case ICK_Function_To_Pointer:
5499     llvm_unreachable("found a first conversion kind in Second");
5500 
5501   case ICK_Qualification:
5502     llvm_unreachable("found a third conversion kind in Second");
5503 
5504   case ICK_Num_Conversion_Kinds:
5505     break;
5506   }
5507 
5508   llvm_unreachable("unknown conversion kind");
5509 }
5510 
5511 /// CheckConvertedConstantExpression - Check that the expression From is a
5512 /// converted constant expression of type T, perform the conversion and produce
5513 /// the converted expression, per C++11 [expr.const]p3.
5514 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5515                                                    QualType T, APValue &Value,
5516                                                    Sema::CCEKind CCE,
5517                                                    bool RequireInt) {
5518   assert(S.getLangOpts().CPlusPlus11 &&
5519          "converted constant expression outside C++11");
5520 
5521   if (checkPlaceholderForOverload(S, From))
5522     return ExprError();
5523 
5524   // C++1z [expr.const]p3:
5525   //  A converted constant expression of type T is an expression,
5526   //  implicitly converted to type T, where the converted
5527   //  expression is a constant expression and the implicit conversion
5528   //  sequence contains only [... list of conversions ...].
5529   // C++1z [stmt.if]p2:
5530   //  If the if statement is of the form if constexpr, the value of the
5531   //  condition shall be a contextually converted constant expression of type
5532   //  bool.
5533   ImplicitConversionSequence ICS =
5534       CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool
5535           ? TryContextuallyConvertToBool(S, From)
5536           : TryCopyInitialization(S, From, T,
5537                                   /*SuppressUserConversions=*/false,
5538                                   /*InOverloadResolution=*/false,
5539                                   /*AllowObjCWritebackConversion=*/false,
5540                                   /*AllowExplicit=*/false);
5541   StandardConversionSequence *SCS = nullptr;
5542   switch (ICS.getKind()) {
5543   case ImplicitConversionSequence::StandardConversion:
5544     SCS = &ICS.Standard;
5545     break;
5546   case ImplicitConversionSequence::UserDefinedConversion:
5547     // We are converting to a non-class type, so the Before sequence
5548     // must be trivial.
5549     SCS = &ICS.UserDefined.After;
5550     break;
5551   case ImplicitConversionSequence::AmbiguousConversion:
5552   case ImplicitConversionSequence::BadConversion:
5553     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5554       return S.Diag(From->getBeginLoc(),
5555                     diag::err_typecheck_converted_constant_expression)
5556              << From->getType() << From->getSourceRange() << T;
5557     return ExprError();
5558 
5559   case ImplicitConversionSequence::EllipsisConversion:
5560     llvm_unreachable("ellipsis conversion in converted constant expression");
5561   }
5562 
5563   // Check that we would only use permitted conversions.
5564   if (!CheckConvertedConstantConversions(S, *SCS)) {
5565     return S.Diag(From->getBeginLoc(),
5566                   diag::err_typecheck_converted_constant_expression_disallowed)
5567            << From->getType() << From->getSourceRange() << T;
5568   }
5569   // [...] and where the reference binding (if any) binds directly.
5570   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5571     return S.Diag(From->getBeginLoc(),
5572                   diag::err_typecheck_converted_constant_expression_indirect)
5573            << From->getType() << From->getSourceRange() << T;
5574   }
5575 
5576   ExprResult Result =
5577       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5578   if (Result.isInvalid())
5579     return Result;
5580 
5581   // C++2a [intro.execution]p5:
5582   //   A full-expression is [...] a constant-expression [...]
5583   Result =
5584       S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5585                             /*DiscardedValue=*/false, /*IsConstexpr=*/true);
5586   if (Result.isInvalid())
5587     return Result;
5588 
5589   // Check for a narrowing implicit conversion.
5590   APValue PreNarrowingValue;
5591   QualType PreNarrowingType;
5592   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5593                                 PreNarrowingType)) {
5594   case NK_Dependent_Narrowing:
5595     // Implicit conversion to a narrower type, but the expression is
5596     // value-dependent so we can't tell whether it's actually narrowing.
5597   case NK_Variable_Narrowing:
5598     // Implicit conversion to a narrower type, and the value is not a constant
5599     // expression. We'll diagnose this in a moment.
5600   case NK_Not_Narrowing:
5601     break;
5602 
5603   case NK_Constant_Narrowing:
5604     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5605         << CCE << /*Constant*/ 1
5606         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5607     break;
5608 
5609   case NK_Type_Narrowing:
5610     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5611         << CCE << /*Constant*/ 0 << From->getType() << T;
5612     break;
5613   }
5614 
5615   if (Result.get()->isValueDependent()) {
5616     Value = APValue();
5617     return Result;
5618   }
5619 
5620   // Check the expression is a constant expression.
5621   SmallVector<PartialDiagnosticAt, 8> Notes;
5622   Expr::EvalResult Eval;
5623   Eval.Diag = &Notes;
5624   Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5625                                    ? Expr::EvaluateForMangling
5626                                    : Expr::EvaluateForCodeGen;
5627 
5628   if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5629       (RequireInt && !Eval.Val.isInt())) {
5630     // The expression can't be folded, so we can't keep it at this position in
5631     // the AST.
5632     Result = ExprError();
5633   } else {
5634     Value = Eval.Val;
5635 
5636     if (Notes.empty()) {
5637       // It's a constant expression.
5638       return ConstantExpr::Create(S.Context, Result.get(), Value);
5639     }
5640   }
5641 
5642   // It's not a constant expression. Produce an appropriate diagnostic.
5643   if (Notes.size() == 1 &&
5644       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5645     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5646   else {
5647     S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5648         << CCE << From->getSourceRange();
5649     for (unsigned I = 0; I < Notes.size(); ++I)
5650       S.Diag(Notes[I].first, Notes[I].second);
5651   }
5652   return ExprError();
5653 }
5654 
5655 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5656                                                   APValue &Value, CCEKind CCE) {
5657   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5658 }
5659 
5660 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5661                                                   llvm::APSInt &Value,
5662                                                   CCEKind CCE) {
5663   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5664 
5665   APValue V;
5666   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5667   if (!R.isInvalid() && !R.get()->isValueDependent())
5668     Value = V.getInt();
5669   return R;
5670 }
5671 
5672 
5673 /// dropPointerConversions - If the given standard conversion sequence
5674 /// involves any pointer conversions, remove them.  This may change
5675 /// the result type of the conversion sequence.
5676 static void dropPointerConversion(StandardConversionSequence &SCS) {
5677   if (SCS.Second == ICK_Pointer_Conversion) {
5678     SCS.Second = ICK_Identity;
5679     SCS.Third = ICK_Identity;
5680     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5681   }
5682 }
5683 
5684 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5685 /// convert the expression From to an Objective-C pointer type.
5686 static ImplicitConversionSequence
5687 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5688   // Do an implicit conversion to 'id'.
5689   QualType Ty = S.Context.getObjCIdType();
5690   ImplicitConversionSequence ICS
5691     = TryImplicitConversion(S, From, Ty,
5692                             // FIXME: Are these flags correct?
5693                             /*SuppressUserConversions=*/false,
5694                             /*AllowExplicit=*/true,
5695                             /*InOverloadResolution=*/false,
5696                             /*CStyle=*/false,
5697                             /*AllowObjCWritebackConversion=*/false,
5698                             /*AllowObjCConversionOnExplicit=*/true);
5699 
5700   // Strip off any final conversions to 'id'.
5701   switch (ICS.getKind()) {
5702   case ImplicitConversionSequence::BadConversion:
5703   case ImplicitConversionSequence::AmbiguousConversion:
5704   case ImplicitConversionSequence::EllipsisConversion:
5705     break;
5706 
5707   case ImplicitConversionSequence::UserDefinedConversion:
5708     dropPointerConversion(ICS.UserDefined.After);
5709     break;
5710 
5711   case ImplicitConversionSequence::StandardConversion:
5712     dropPointerConversion(ICS.Standard);
5713     break;
5714   }
5715 
5716   return ICS;
5717 }
5718 
5719 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5720 /// conversion of the expression From to an Objective-C pointer type.
5721 /// Returns a valid but null ExprResult if no conversion sequence exists.
5722 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5723   if (checkPlaceholderForOverload(*this, From))
5724     return ExprError();
5725 
5726   QualType Ty = Context.getObjCIdType();
5727   ImplicitConversionSequence ICS =
5728     TryContextuallyConvertToObjCPointer(*this, From);
5729   if (!ICS.isBad())
5730     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5731   return ExprResult();
5732 }
5733 
5734 /// Determine whether the provided type is an integral type, or an enumeration
5735 /// type of a permitted flavor.
5736 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5737   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5738                                  : T->isIntegralOrUnscopedEnumerationType();
5739 }
5740 
5741 static ExprResult
5742 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5743                             Sema::ContextualImplicitConverter &Converter,
5744                             QualType T, UnresolvedSetImpl &ViableConversions) {
5745 
5746   if (Converter.Suppress)
5747     return ExprError();
5748 
5749   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5750   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5751     CXXConversionDecl *Conv =
5752         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5753     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5754     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5755   }
5756   return From;
5757 }
5758 
5759 static bool
5760 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5761                            Sema::ContextualImplicitConverter &Converter,
5762                            QualType T, bool HadMultipleCandidates,
5763                            UnresolvedSetImpl &ExplicitConversions) {
5764   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5765     DeclAccessPair Found = ExplicitConversions[0];
5766     CXXConversionDecl *Conversion =
5767         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5768 
5769     // The user probably meant to invoke the given explicit
5770     // conversion; use it.
5771     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5772     std::string TypeStr;
5773     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5774 
5775     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5776         << FixItHint::CreateInsertion(From->getBeginLoc(),
5777                                       "static_cast<" + TypeStr + ">(")
5778         << FixItHint::CreateInsertion(
5779                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5780     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5781 
5782     // If we aren't in a SFINAE context, build a call to the
5783     // explicit conversion function.
5784     if (SemaRef.isSFINAEContext())
5785       return true;
5786 
5787     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5788     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5789                                                        HadMultipleCandidates);
5790     if (Result.isInvalid())
5791       return true;
5792     // Record usage of conversion in an implicit cast.
5793     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5794                                     CK_UserDefinedConversion, Result.get(),
5795                                     nullptr, Result.get()->getValueKind());
5796   }
5797   return false;
5798 }
5799 
5800 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5801                              Sema::ContextualImplicitConverter &Converter,
5802                              QualType T, bool HadMultipleCandidates,
5803                              DeclAccessPair &Found) {
5804   CXXConversionDecl *Conversion =
5805       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5806   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5807 
5808   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5809   if (!Converter.SuppressConversion) {
5810     if (SemaRef.isSFINAEContext())
5811       return true;
5812 
5813     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5814         << From->getSourceRange();
5815   }
5816 
5817   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5818                                                      HadMultipleCandidates);
5819   if (Result.isInvalid())
5820     return true;
5821   // Record usage of conversion in an implicit cast.
5822   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5823                                   CK_UserDefinedConversion, Result.get(),
5824                                   nullptr, Result.get()->getValueKind());
5825   return false;
5826 }
5827 
5828 static ExprResult finishContextualImplicitConversion(
5829     Sema &SemaRef, SourceLocation Loc, Expr *From,
5830     Sema::ContextualImplicitConverter &Converter) {
5831   if (!Converter.match(From->getType()) && !Converter.Suppress)
5832     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5833         << From->getSourceRange();
5834 
5835   return SemaRef.DefaultLvalueConversion(From);
5836 }
5837 
5838 static void
5839 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5840                                   UnresolvedSetImpl &ViableConversions,
5841                                   OverloadCandidateSet &CandidateSet) {
5842   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5843     DeclAccessPair FoundDecl = ViableConversions[I];
5844     NamedDecl *D = FoundDecl.getDecl();
5845     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5846     if (isa<UsingShadowDecl>(D))
5847       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5848 
5849     CXXConversionDecl *Conv;
5850     FunctionTemplateDecl *ConvTemplate;
5851     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5852       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5853     else
5854       Conv = cast<CXXConversionDecl>(D);
5855 
5856     if (ConvTemplate)
5857       SemaRef.AddTemplateConversionCandidate(
5858           ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5859           /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
5860     else
5861       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5862                                      ToType, CandidateSet,
5863                                      /*AllowObjCConversionOnExplicit=*/false,
5864                                      /*AllowExplicit*/ true);
5865   }
5866 }
5867 
5868 /// Attempt to convert the given expression to a type which is accepted
5869 /// by the given converter.
5870 ///
5871 /// This routine will attempt to convert an expression of class type to a
5872 /// type accepted by the specified converter. In C++11 and before, the class
5873 /// must have a single non-explicit conversion function converting to a matching
5874 /// type. In C++1y, there can be multiple such conversion functions, but only
5875 /// one target type.
5876 ///
5877 /// \param Loc The source location of the construct that requires the
5878 /// conversion.
5879 ///
5880 /// \param From The expression we're converting from.
5881 ///
5882 /// \param Converter Used to control and diagnose the conversion process.
5883 ///
5884 /// \returns The expression, converted to an integral or enumeration type if
5885 /// successful.
5886 ExprResult Sema::PerformContextualImplicitConversion(
5887     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5888   // We can't perform any more checking for type-dependent expressions.
5889   if (From->isTypeDependent())
5890     return From;
5891 
5892   // Process placeholders immediately.
5893   if (From->hasPlaceholderType()) {
5894     ExprResult result = CheckPlaceholderExpr(From);
5895     if (result.isInvalid())
5896       return result;
5897     From = result.get();
5898   }
5899 
5900   // If the expression already has a matching type, we're golden.
5901   QualType T = From->getType();
5902   if (Converter.match(T))
5903     return DefaultLvalueConversion(From);
5904 
5905   // FIXME: Check for missing '()' if T is a function type?
5906 
5907   // We can only perform contextual implicit conversions on objects of class
5908   // type.
5909   const RecordType *RecordTy = T->getAs<RecordType>();
5910   if (!RecordTy || !getLangOpts().CPlusPlus) {
5911     if (!Converter.Suppress)
5912       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5913     return From;
5914   }
5915 
5916   // We must have a complete class type.
5917   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5918     ContextualImplicitConverter &Converter;
5919     Expr *From;
5920 
5921     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5922         : Converter(Converter), From(From) {}
5923 
5924     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5925       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5926     }
5927   } IncompleteDiagnoser(Converter, From);
5928 
5929   if (Converter.Suppress ? !isCompleteType(Loc, T)
5930                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5931     return From;
5932 
5933   // Look for a conversion to an integral or enumeration type.
5934   UnresolvedSet<4>
5935       ViableConversions; // These are *potentially* viable in C++1y.
5936   UnresolvedSet<4> ExplicitConversions;
5937   const auto &Conversions =
5938       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5939 
5940   bool HadMultipleCandidates =
5941       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5942 
5943   // To check that there is only one target type, in C++1y:
5944   QualType ToType;
5945   bool HasUniqueTargetType = true;
5946 
5947   // Collect explicit or viable (potentially in C++1y) conversions.
5948   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5949     NamedDecl *D = (*I)->getUnderlyingDecl();
5950     CXXConversionDecl *Conversion;
5951     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5952     if (ConvTemplate) {
5953       if (getLangOpts().CPlusPlus14)
5954         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5955       else
5956         continue; // C++11 does not consider conversion operator templates(?).
5957     } else
5958       Conversion = cast<CXXConversionDecl>(D);
5959 
5960     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5961            "Conversion operator templates are considered potentially "
5962            "viable in C++1y");
5963 
5964     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5965     if (Converter.match(CurToType) || ConvTemplate) {
5966 
5967       if (Conversion->isExplicit()) {
5968         // FIXME: For C++1y, do we need this restriction?
5969         // cf. diagnoseNoViableConversion()
5970         if (!ConvTemplate)
5971           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5972       } else {
5973         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5974           if (ToType.isNull())
5975             ToType = CurToType.getUnqualifiedType();
5976           else if (HasUniqueTargetType &&
5977                    (CurToType.getUnqualifiedType() != ToType))
5978             HasUniqueTargetType = false;
5979         }
5980         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5981       }
5982     }
5983   }
5984 
5985   if (getLangOpts().CPlusPlus14) {
5986     // C++1y [conv]p6:
5987     // ... An expression e of class type E appearing in such a context
5988     // is said to be contextually implicitly converted to a specified
5989     // type T and is well-formed if and only if e can be implicitly
5990     // converted to a type T that is determined as follows: E is searched
5991     // for conversion functions whose return type is cv T or reference to
5992     // cv T such that T is allowed by the context. There shall be
5993     // exactly one such T.
5994 
5995     // If no unique T is found:
5996     if (ToType.isNull()) {
5997       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5998                                      HadMultipleCandidates,
5999                                      ExplicitConversions))
6000         return ExprError();
6001       return finishContextualImplicitConversion(*this, Loc, From, Converter);
6002     }
6003 
6004     // If more than one unique Ts are found:
6005     if (!HasUniqueTargetType)
6006       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6007                                          ViableConversions);
6008 
6009     // If one unique T is found:
6010     // First, build a candidate set from the previously recorded
6011     // potentially viable conversions.
6012     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6013     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6014                                       CandidateSet);
6015 
6016     // Then, perform overload resolution over the candidate set.
6017     OverloadCandidateSet::iterator Best;
6018     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6019     case OR_Success: {
6020       // Apply this conversion.
6021       DeclAccessPair Found =
6022           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6023       if (recordConversion(*this, Loc, From, Converter, T,
6024                            HadMultipleCandidates, Found))
6025         return ExprError();
6026       break;
6027     }
6028     case OR_Ambiguous:
6029       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6030                                          ViableConversions);
6031     case OR_No_Viable_Function:
6032       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6033                                      HadMultipleCandidates,
6034                                      ExplicitConversions))
6035         return ExprError();
6036       LLVM_FALLTHROUGH;
6037     case OR_Deleted:
6038       // We'll complain below about a non-integral condition type.
6039       break;
6040     }
6041   } else {
6042     switch (ViableConversions.size()) {
6043     case 0: {
6044       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6045                                      HadMultipleCandidates,
6046                                      ExplicitConversions))
6047         return ExprError();
6048 
6049       // We'll complain below about a non-integral condition type.
6050       break;
6051     }
6052     case 1: {
6053       // Apply this conversion.
6054       DeclAccessPair Found = ViableConversions[0];
6055       if (recordConversion(*this, Loc, From, Converter, T,
6056                            HadMultipleCandidates, Found))
6057         return ExprError();
6058       break;
6059     }
6060     default:
6061       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6062                                          ViableConversions);
6063     }
6064   }
6065 
6066   return finishContextualImplicitConversion(*this, Loc, From, Converter);
6067 }
6068 
6069 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6070 /// an acceptable non-member overloaded operator for a call whose
6071 /// arguments have types T1 (and, if non-empty, T2). This routine
6072 /// implements the check in C++ [over.match.oper]p3b2 concerning
6073 /// enumeration types.
6074 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6075                                                    FunctionDecl *Fn,
6076                                                    ArrayRef<Expr *> Args) {
6077   QualType T1 = Args[0]->getType();
6078   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6079 
6080   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6081     return true;
6082 
6083   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6084     return true;
6085 
6086   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
6087   if (Proto->getNumParams() < 1)
6088     return false;
6089 
6090   if (T1->isEnumeralType()) {
6091     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6092     if (Context.hasSameUnqualifiedType(T1, ArgType))
6093       return true;
6094   }
6095 
6096   if (Proto->getNumParams() < 2)
6097     return false;
6098 
6099   if (!T2.isNull() && T2->isEnumeralType()) {
6100     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6101     if (Context.hasSameUnqualifiedType(T2, ArgType))
6102       return true;
6103   }
6104 
6105   return false;
6106 }
6107 
6108 /// AddOverloadCandidate - Adds the given function to the set of
6109 /// candidate functions, using the given function call arguments.  If
6110 /// @p SuppressUserConversions, then don't allow user-defined
6111 /// conversions via constructors or conversion operators.
6112 ///
6113 /// \param PartialOverloading true if we are performing "partial" overloading
6114 /// based on an incomplete set of function arguments. This feature is used by
6115 /// code completion.
6116 void Sema::AddOverloadCandidate(
6117     FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6118     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6119     bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6120     ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6121     OverloadCandidateParamOrder PO) {
6122   const FunctionProtoType *Proto
6123     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6124   assert(Proto && "Functions without a prototype cannot be overloaded");
6125   assert(!Function->getDescribedFunctionTemplate() &&
6126          "Use AddTemplateOverloadCandidate for function templates");
6127 
6128   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6129     if (!isa<CXXConstructorDecl>(Method)) {
6130       // If we get here, it's because we're calling a member function
6131       // that is named without a member access expression (e.g.,
6132       // "this->f") that was either written explicitly or created
6133       // implicitly. This can happen with a qualified call to a member
6134       // function, e.g., X::f(). We use an empty type for the implied
6135       // object argument (C++ [over.call.func]p3), and the acting context
6136       // is irrelevant.
6137       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6138                          Expr::Classification::makeSimpleLValue(), Args,
6139                          CandidateSet, SuppressUserConversions,
6140                          PartialOverloading, EarlyConversions, PO);
6141       return;
6142     }
6143     // We treat a constructor like a non-member function, since its object
6144     // argument doesn't participate in overload resolution.
6145   }
6146 
6147   if (!CandidateSet.isNewCandidate(Function, PO))
6148     return;
6149 
6150   // C++11 [class.copy]p11: [DR1402]
6151   //   A defaulted move constructor that is defined as deleted is ignored by
6152   //   overload resolution.
6153   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6154   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6155       Constructor->isMoveConstructor())
6156     return;
6157 
6158   // Overload resolution is always an unevaluated context.
6159   EnterExpressionEvaluationContext Unevaluated(
6160       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6161 
6162   // C++ [over.match.oper]p3:
6163   //   if no operand has a class type, only those non-member functions in the
6164   //   lookup set that have a first parameter of type T1 or "reference to
6165   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6166   //   is a right operand) a second parameter of type T2 or "reference to
6167   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
6168   //   candidate functions.
6169   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6170       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6171     return;
6172 
6173   // Add this candidate
6174   OverloadCandidate &Candidate =
6175       CandidateSet.addCandidate(Args.size(), EarlyConversions);
6176   Candidate.FoundDecl = FoundDecl;
6177   Candidate.Function = Function;
6178   Candidate.Viable = true;
6179   Candidate.RewriteKind =
6180       CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6181   Candidate.IsSurrogate = false;
6182   Candidate.IsADLCandidate = IsADLCandidate;
6183   Candidate.IgnoreObjectArgument = false;
6184   Candidate.ExplicitCallArguments = Args.size();
6185 
6186   if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6187       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6188     Candidate.Viable = false;
6189     Candidate.FailureKind = ovl_non_default_multiversion_function;
6190     return;
6191   }
6192 
6193   if (Constructor) {
6194     // C++ [class.copy]p3:
6195     //   A member function template is never instantiated to perform the copy
6196     //   of a class object to an object of its class type.
6197     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6198     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6199         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6200          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6201                        ClassType))) {
6202       Candidate.Viable = false;
6203       Candidate.FailureKind = ovl_fail_illegal_constructor;
6204       return;
6205     }
6206 
6207     // C++ [over.match.funcs]p8: (proposed DR resolution)
6208     //   A constructor inherited from class type C that has a first parameter
6209     //   of type "reference to P" (including such a constructor instantiated
6210     //   from a template) is excluded from the set of candidate functions when
6211     //   constructing an object of type cv D if the argument list has exactly
6212     //   one argument and D is reference-related to P and P is reference-related
6213     //   to C.
6214     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6215     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6216         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6217       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6218       QualType C = Context.getRecordType(Constructor->getParent());
6219       QualType D = Context.getRecordType(Shadow->getParent());
6220       SourceLocation Loc = Args.front()->getExprLoc();
6221       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6222           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6223         Candidate.Viable = false;
6224         Candidate.FailureKind = ovl_fail_inhctor_slice;
6225         return;
6226       }
6227     }
6228 
6229     // Check that the constructor is capable of constructing an object in the
6230     // destination address space.
6231     if (!Qualifiers::isAddressSpaceSupersetOf(
6232             Constructor->getMethodQualifiers().getAddressSpace(),
6233             CandidateSet.getDestAS())) {
6234       Candidate.Viable = false;
6235       Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6236     }
6237   }
6238 
6239   unsigned NumParams = Proto->getNumParams();
6240 
6241   // (C++ 13.3.2p2): A candidate function having fewer than m
6242   // parameters is viable only if it has an ellipsis in its parameter
6243   // list (8.3.5).
6244   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6245       !Proto->isVariadic()) {
6246     Candidate.Viable = false;
6247     Candidate.FailureKind = ovl_fail_too_many_arguments;
6248     return;
6249   }
6250 
6251   // (C++ 13.3.2p2): A candidate function having more than m parameters
6252   // is viable only if the (m+1)st parameter has a default argument
6253   // (8.3.6). For the purposes of overload resolution, the
6254   // parameter list is truncated on the right, so that there are
6255   // exactly m parameters.
6256   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6257   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6258     // Not enough arguments.
6259     Candidate.Viable = false;
6260     Candidate.FailureKind = ovl_fail_too_few_arguments;
6261     return;
6262   }
6263 
6264   // (CUDA B.1): Check for invalid calls between targets.
6265   if (getLangOpts().CUDA)
6266     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6267       // Skip the check for callers that are implicit members, because in this
6268       // case we may not yet know what the member's target is; the target is
6269       // inferred for the member automatically, based on the bases and fields of
6270       // the class.
6271       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6272         Candidate.Viable = false;
6273         Candidate.FailureKind = ovl_fail_bad_target;
6274         return;
6275       }
6276 
6277   // Determine the implicit conversion sequences for each of the
6278   // arguments.
6279   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6280     unsigned ConvIdx =
6281         PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6282     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6283       // We already formed a conversion sequence for this parameter during
6284       // template argument deduction.
6285     } else if (ArgIdx < NumParams) {
6286       // (C++ 13.3.2p3): for F to be a viable function, there shall
6287       // exist for each argument an implicit conversion sequence
6288       // (13.3.3.1) that converts that argument to the corresponding
6289       // parameter of F.
6290       QualType ParamType = Proto->getParamType(ArgIdx);
6291       Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6292           *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6293           /*InOverloadResolution=*/true,
6294           /*AllowObjCWritebackConversion=*/
6295           getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6296       if (Candidate.Conversions[ConvIdx].isBad()) {
6297         Candidate.Viable = false;
6298         Candidate.FailureKind = ovl_fail_bad_conversion;
6299         return;
6300       }
6301     } else {
6302       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6303       // argument for which there is no corresponding parameter is
6304       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6305       Candidate.Conversions[ConvIdx].setEllipsis();
6306     }
6307   }
6308 
6309   if (!AllowExplicit) {
6310     ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function);
6311     if (ES.getKind() != ExplicitSpecKind::ResolvedFalse) {
6312       Candidate.Viable = false;
6313       Candidate.FailureKind = ovl_fail_explicit_resolved;
6314       return;
6315     }
6316   }
6317 
6318   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6319     Candidate.Viable = false;
6320     Candidate.FailureKind = ovl_fail_enable_if;
6321     Candidate.DeductionFailure.Data = FailedAttr;
6322     return;
6323   }
6324 
6325   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6326     Candidate.Viable = false;
6327     Candidate.FailureKind = ovl_fail_ext_disabled;
6328     return;
6329   }
6330 }
6331 
6332 ObjCMethodDecl *
6333 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6334                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6335   if (Methods.size() <= 1)
6336     return nullptr;
6337 
6338   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6339     bool Match = true;
6340     ObjCMethodDecl *Method = Methods[b];
6341     unsigned NumNamedArgs = Sel.getNumArgs();
6342     // Method might have more arguments than selector indicates. This is due
6343     // to addition of c-style arguments in method.
6344     if (Method->param_size() > NumNamedArgs)
6345       NumNamedArgs = Method->param_size();
6346     if (Args.size() < NumNamedArgs)
6347       continue;
6348 
6349     for (unsigned i = 0; i < NumNamedArgs; i++) {
6350       // We can't do any type-checking on a type-dependent argument.
6351       if (Args[i]->isTypeDependent()) {
6352         Match = false;
6353         break;
6354       }
6355 
6356       ParmVarDecl *param = Method->parameters()[i];
6357       Expr *argExpr = Args[i];
6358       assert(argExpr && "SelectBestMethod(): missing expression");
6359 
6360       // Strip the unbridged-cast placeholder expression off unless it's
6361       // a consumed argument.
6362       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6363           !param->hasAttr<CFConsumedAttr>())
6364         argExpr = stripARCUnbridgedCast(argExpr);
6365 
6366       // If the parameter is __unknown_anytype, move on to the next method.
6367       if (param->getType() == Context.UnknownAnyTy) {
6368         Match = false;
6369         break;
6370       }
6371 
6372       ImplicitConversionSequence ConversionState
6373         = TryCopyInitialization(*this, argExpr, param->getType(),
6374                                 /*SuppressUserConversions*/false,
6375                                 /*InOverloadResolution=*/true,
6376                                 /*AllowObjCWritebackConversion=*/
6377                                 getLangOpts().ObjCAutoRefCount,
6378                                 /*AllowExplicit*/false);
6379       // This function looks for a reasonably-exact match, so we consider
6380       // incompatible pointer conversions to be a failure here.
6381       if (ConversionState.isBad() ||
6382           (ConversionState.isStandard() &&
6383            ConversionState.Standard.Second ==
6384                ICK_Incompatible_Pointer_Conversion)) {
6385         Match = false;
6386         break;
6387       }
6388     }
6389     // Promote additional arguments to variadic methods.
6390     if (Match && Method->isVariadic()) {
6391       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6392         if (Args[i]->isTypeDependent()) {
6393           Match = false;
6394           break;
6395         }
6396         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6397                                                           nullptr);
6398         if (Arg.isInvalid()) {
6399           Match = false;
6400           break;
6401         }
6402       }
6403     } else {
6404       // Check for extra arguments to non-variadic methods.
6405       if (Args.size() != NumNamedArgs)
6406         Match = false;
6407       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6408         // Special case when selectors have no argument. In this case, select
6409         // one with the most general result type of 'id'.
6410         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6411           QualType ReturnT = Methods[b]->getReturnType();
6412           if (ReturnT->isObjCIdType())
6413             return Methods[b];
6414         }
6415       }
6416     }
6417 
6418     if (Match)
6419       return Method;
6420   }
6421   return nullptr;
6422 }
6423 
6424 static bool
6425 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6426                                  ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6427                                  bool MissingImplicitThis, Expr *&ConvertedThis,
6428                                  SmallVectorImpl<Expr *> &ConvertedArgs) {
6429   if (ThisArg) {
6430     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6431     assert(!isa<CXXConstructorDecl>(Method) &&
6432            "Shouldn't have `this` for ctors!");
6433     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6434     ExprResult R = S.PerformObjectArgumentInitialization(
6435         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6436     if (R.isInvalid())
6437       return false;
6438     ConvertedThis = R.get();
6439   } else {
6440     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6441       (void)MD;
6442       assert((MissingImplicitThis || MD->isStatic() ||
6443               isa<CXXConstructorDecl>(MD)) &&
6444              "Expected `this` for non-ctor instance methods");
6445     }
6446     ConvertedThis = nullptr;
6447   }
6448 
6449   // Ignore any variadic arguments. Converting them is pointless, since the
6450   // user can't refer to them in the function condition.
6451   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6452 
6453   // Convert the arguments.
6454   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6455     ExprResult R;
6456     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6457                                         S.Context, Function->getParamDecl(I)),
6458                                     SourceLocation(), Args[I]);
6459 
6460     if (R.isInvalid())
6461       return false;
6462 
6463     ConvertedArgs.push_back(R.get());
6464   }
6465 
6466   if (Trap.hasErrorOccurred())
6467     return false;
6468 
6469   // Push default arguments if needed.
6470   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6471     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6472       ParmVarDecl *P = Function->getParamDecl(i);
6473       Expr *DefArg = P->hasUninstantiatedDefaultArg()
6474                          ? P->getUninstantiatedDefaultArg()
6475                          : P->getDefaultArg();
6476       // This can only happen in code completion, i.e. when PartialOverloading
6477       // is true.
6478       if (!DefArg)
6479         return false;
6480       ExprResult R =
6481           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6482                                           S.Context, Function->getParamDecl(i)),
6483                                       SourceLocation(), DefArg);
6484       if (R.isInvalid())
6485         return false;
6486       ConvertedArgs.push_back(R.get());
6487     }
6488 
6489     if (Trap.hasErrorOccurred())
6490       return false;
6491   }
6492   return true;
6493 }
6494 
6495 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6496                                   bool MissingImplicitThis) {
6497   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6498   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6499     return nullptr;
6500 
6501   SFINAETrap Trap(*this);
6502   SmallVector<Expr *, 16> ConvertedArgs;
6503   // FIXME: We should look into making enable_if late-parsed.
6504   Expr *DiscardedThis;
6505   if (!convertArgsForAvailabilityChecks(
6506           *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6507           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6508     return *EnableIfAttrs.begin();
6509 
6510   for (auto *EIA : EnableIfAttrs) {
6511     APValue Result;
6512     // FIXME: This doesn't consider value-dependent cases, because doing so is
6513     // very difficult. Ideally, we should handle them more gracefully.
6514     if (EIA->getCond()->isValueDependent() ||
6515         !EIA->getCond()->EvaluateWithSubstitution(
6516             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6517       return EIA;
6518 
6519     if (!Result.isInt() || !Result.getInt().getBoolValue())
6520       return EIA;
6521   }
6522   return nullptr;
6523 }
6524 
6525 template <typename CheckFn>
6526 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6527                                         bool ArgDependent, SourceLocation Loc,
6528                                         CheckFn &&IsSuccessful) {
6529   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6530   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6531     if (ArgDependent == DIA->getArgDependent())
6532       Attrs.push_back(DIA);
6533   }
6534 
6535   // Common case: No diagnose_if attributes, so we can quit early.
6536   if (Attrs.empty())
6537     return false;
6538 
6539   auto WarningBegin = std::stable_partition(
6540       Attrs.begin(), Attrs.end(),
6541       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6542 
6543   // Note that diagnose_if attributes are late-parsed, so they appear in the
6544   // correct order (unlike enable_if attributes).
6545   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6546                                IsSuccessful);
6547   if (ErrAttr != WarningBegin) {
6548     const DiagnoseIfAttr *DIA = *ErrAttr;
6549     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6550     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6551         << DIA->getParent() << DIA->getCond()->getSourceRange();
6552     return true;
6553   }
6554 
6555   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6556     if (IsSuccessful(DIA)) {
6557       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6558       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6559           << DIA->getParent() << DIA->getCond()->getSourceRange();
6560     }
6561 
6562   return false;
6563 }
6564 
6565 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6566                                                const Expr *ThisArg,
6567                                                ArrayRef<const Expr *> Args,
6568                                                SourceLocation Loc) {
6569   return diagnoseDiagnoseIfAttrsWith(
6570       *this, Function, /*ArgDependent=*/true, Loc,
6571       [&](const DiagnoseIfAttr *DIA) {
6572         APValue Result;
6573         // It's sane to use the same Args for any redecl of this function, since
6574         // EvaluateWithSubstitution only cares about the position of each
6575         // argument in the arg list, not the ParmVarDecl* it maps to.
6576         if (!DIA->getCond()->EvaluateWithSubstitution(
6577                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6578           return false;
6579         return Result.isInt() && Result.getInt().getBoolValue();
6580       });
6581 }
6582 
6583 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6584                                                  SourceLocation Loc) {
6585   return diagnoseDiagnoseIfAttrsWith(
6586       *this, ND, /*ArgDependent=*/false, Loc,
6587       [&](const DiagnoseIfAttr *DIA) {
6588         bool Result;
6589         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6590                Result;
6591       });
6592 }
6593 
6594 /// Add all of the function declarations in the given function set to
6595 /// the overload candidate set.
6596 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6597                                  ArrayRef<Expr *> Args,
6598                                  OverloadCandidateSet &CandidateSet,
6599                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6600                                  bool SuppressUserConversions,
6601                                  bool PartialOverloading,
6602                                  bool FirstArgumentIsBase) {
6603   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6604     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6605     ArrayRef<Expr *> FunctionArgs = Args;
6606 
6607     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6608     FunctionDecl *FD =
6609         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6610 
6611     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6612       QualType ObjectType;
6613       Expr::Classification ObjectClassification;
6614       if (Args.size() > 0) {
6615         if (Expr *E = Args[0]) {
6616           // Use the explicit base to restrict the lookup:
6617           ObjectType = E->getType();
6618           // Pointers in the object arguments are implicitly dereferenced, so we
6619           // always classify them as l-values.
6620           if (!ObjectType.isNull() && ObjectType->isPointerType())
6621             ObjectClassification = Expr::Classification::makeSimpleLValue();
6622           else
6623             ObjectClassification = E->Classify(Context);
6624         } // .. else there is an implicit base.
6625         FunctionArgs = Args.slice(1);
6626       }
6627       if (FunTmpl) {
6628         AddMethodTemplateCandidate(
6629             FunTmpl, F.getPair(),
6630             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6631             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6632             FunctionArgs, CandidateSet, SuppressUserConversions,
6633             PartialOverloading);
6634       } else {
6635         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6636                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6637                            ObjectClassification, FunctionArgs, CandidateSet,
6638                            SuppressUserConversions, PartialOverloading);
6639       }
6640     } else {
6641       // This branch handles both standalone functions and static methods.
6642 
6643       // Slice the first argument (which is the base) when we access
6644       // static method as non-static.
6645       if (Args.size() > 0 &&
6646           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6647                         !isa<CXXConstructorDecl>(FD)))) {
6648         assert(cast<CXXMethodDecl>(FD)->isStatic());
6649         FunctionArgs = Args.slice(1);
6650       }
6651       if (FunTmpl) {
6652         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6653                                      ExplicitTemplateArgs, FunctionArgs,
6654                                      CandidateSet, SuppressUserConversions,
6655                                      PartialOverloading);
6656       } else {
6657         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6658                              SuppressUserConversions, PartialOverloading);
6659       }
6660     }
6661   }
6662 }
6663 
6664 /// AddMethodCandidate - Adds a named decl (which is some kind of
6665 /// method) as a method candidate to the given overload set.
6666 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
6667                               Expr::Classification ObjectClassification,
6668                               ArrayRef<Expr *> Args,
6669                               OverloadCandidateSet &CandidateSet,
6670                               bool SuppressUserConversions,
6671                               OverloadCandidateParamOrder PO) {
6672   NamedDecl *Decl = FoundDecl.getDecl();
6673   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6674 
6675   if (isa<UsingShadowDecl>(Decl))
6676     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6677 
6678   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6679     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6680            "Expected a member function template");
6681     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6682                                /*ExplicitArgs*/ nullptr, ObjectType,
6683                                ObjectClassification, Args, CandidateSet,
6684                                SuppressUserConversions, false, PO);
6685   } else {
6686     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6687                        ObjectType, ObjectClassification, Args, CandidateSet,
6688                        SuppressUserConversions, false, None, PO);
6689   }
6690 }
6691 
6692 /// AddMethodCandidate - Adds the given C++ member function to the set
6693 /// of candidate functions, using the given function call arguments
6694 /// and the object argument (@c Object). For example, in a call
6695 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6696 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6697 /// allow user-defined conversions via constructors or conversion
6698 /// operators.
6699 void
6700 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6701                          CXXRecordDecl *ActingContext, QualType ObjectType,
6702                          Expr::Classification ObjectClassification,
6703                          ArrayRef<Expr *> Args,
6704                          OverloadCandidateSet &CandidateSet,
6705                          bool SuppressUserConversions,
6706                          bool PartialOverloading,
6707                          ConversionSequenceList EarlyConversions,
6708                          OverloadCandidateParamOrder PO) {
6709   const FunctionProtoType *Proto
6710     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6711   assert(Proto && "Methods without a prototype cannot be overloaded");
6712   assert(!isa<CXXConstructorDecl>(Method) &&
6713          "Use AddOverloadCandidate for constructors");
6714 
6715   if (!CandidateSet.isNewCandidate(Method, PO))
6716     return;
6717 
6718   // C++11 [class.copy]p23: [DR1402]
6719   //   A defaulted move assignment operator that is defined as deleted is
6720   //   ignored by overload resolution.
6721   if (Method->isDefaulted() && Method->isDeleted() &&
6722       Method->isMoveAssignmentOperator())
6723     return;
6724 
6725   // Overload resolution is always an unevaluated context.
6726   EnterExpressionEvaluationContext Unevaluated(
6727       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6728 
6729   // Add this candidate
6730   OverloadCandidate &Candidate =
6731       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6732   Candidate.FoundDecl = FoundDecl;
6733   Candidate.Function = Method;
6734   Candidate.RewriteKind =
6735       CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
6736   Candidate.IsSurrogate = false;
6737   Candidate.IgnoreObjectArgument = false;
6738   Candidate.ExplicitCallArguments = Args.size();
6739 
6740   unsigned NumParams = Proto->getNumParams();
6741 
6742   // (C++ 13.3.2p2): A candidate function having fewer than m
6743   // parameters is viable only if it has an ellipsis in its parameter
6744   // list (8.3.5).
6745   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6746       !Proto->isVariadic()) {
6747     Candidate.Viable = false;
6748     Candidate.FailureKind = ovl_fail_too_many_arguments;
6749     return;
6750   }
6751 
6752   // (C++ 13.3.2p2): A candidate function having more than m parameters
6753   // is viable only if the (m+1)st parameter has a default argument
6754   // (8.3.6). For the purposes of overload resolution, the
6755   // parameter list is truncated on the right, so that there are
6756   // exactly m parameters.
6757   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6758   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6759     // Not enough arguments.
6760     Candidate.Viable = false;
6761     Candidate.FailureKind = ovl_fail_too_few_arguments;
6762     return;
6763   }
6764 
6765   Candidate.Viable = true;
6766 
6767   if (Method->isStatic() || ObjectType.isNull())
6768     // The implicit object argument is ignored.
6769     Candidate.IgnoreObjectArgument = true;
6770   else {
6771     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
6772     // Determine the implicit conversion sequence for the object
6773     // parameter.
6774     Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization(
6775         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6776         Method, ActingContext);
6777     if (Candidate.Conversions[ConvIdx].isBad()) {
6778       Candidate.Viable = false;
6779       Candidate.FailureKind = ovl_fail_bad_conversion;
6780       return;
6781     }
6782   }
6783 
6784   // (CUDA B.1): Check for invalid calls between targets.
6785   if (getLangOpts().CUDA)
6786     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6787       if (!IsAllowedCUDACall(Caller, Method)) {
6788         Candidate.Viable = false;
6789         Candidate.FailureKind = ovl_fail_bad_target;
6790         return;
6791       }
6792 
6793   // Determine the implicit conversion sequences for each of the
6794   // arguments.
6795   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6796     unsigned ConvIdx =
6797         PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
6798     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6799       // We already formed a conversion sequence for this parameter during
6800       // template argument deduction.
6801     } else if (ArgIdx < NumParams) {
6802       // (C++ 13.3.2p3): for F to be a viable function, there shall
6803       // exist for each argument an implicit conversion sequence
6804       // (13.3.3.1) that converts that argument to the corresponding
6805       // parameter of F.
6806       QualType ParamType = Proto->getParamType(ArgIdx);
6807       Candidate.Conversions[ConvIdx]
6808         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6809                                 SuppressUserConversions,
6810                                 /*InOverloadResolution=*/true,
6811                                 /*AllowObjCWritebackConversion=*/
6812                                   getLangOpts().ObjCAutoRefCount);
6813       if (Candidate.Conversions[ConvIdx].isBad()) {
6814         Candidate.Viable = false;
6815         Candidate.FailureKind = ovl_fail_bad_conversion;
6816         return;
6817       }
6818     } else {
6819       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6820       // argument for which there is no corresponding parameter is
6821       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6822       Candidate.Conversions[ConvIdx].setEllipsis();
6823     }
6824   }
6825 
6826   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6827     Candidate.Viable = false;
6828     Candidate.FailureKind = ovl_fail_enable_if;
6829     Candidate.DeductionFailure.Data = FailedAttr;
6830     return;
6831   }
6832 
6833   if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6834       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6835     Candidate.Viable = false;
6836     Candidate.FailureKind = ovl_non_default_multiversion_function;
6837   }
6838 }
6839 
6840 /// Add a C++ member function template as a candidate to the candidate
6841 /// set, using template argument deduction to produce an appropriate member
6842 /// function template specialization.
6843 void Sema::AddMethodTemplateCandidate(
6844     FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
6845     CXXRecordDecl *ActingContext,
6846     TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
6847     Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
6848     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6849     bool PartialOverloading, OverloadCandidateParamOrder PO) {
6850   if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
6851     return;
6852 
6853   // C++ [over.match.funcs]p7:
6854   //   In each case where a candidate is a function template, candidate
6855   //   function template specializations are generated using template argument
6856   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6857   //   candidate functions in the usual way.113) A given name can refer to one
6858   //   or more function templates and also to a set of overloaded non-template
6859   //   functions. In such a case, the candidate functions generated from each
6860   //   function template are combined with the set of non-template candidate
6861   //   functions.
6862   TemplateDeductionInfo Info(CandidateSet.getLocation());
6863   FunctionDecl *Specialization = nullptr;
6864   ConversionSequenceList Conversions;
6865   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6866           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6867           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6868             return CheckNonDependentConversions(
6869                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6870                 SuppressUserConversions, ActingContext, ObjectType,
6871                 ObjectClassification, PO);
6872           })) {
6873     OverloadCandidate &Candidate =
6874         CandidateSet.addCandidate(Conversions.size(), Conversions);
6875     Candidate.FoundDecl = FoundDecl;
6876     Candidate.Function = MethodTmpl->getTemplatedDecl();
6877     Candidate.Viable = false;
6878     Candidate.RewriteKind =
6879       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
6880     Candidate.IsSurrogate = false;
6881     Candidate.IgnoreObjectArgument =
6882         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6883         ObjectType.isNull();
6884     Candidate.ExplicitCallArguments = Args.size();
6885     if (Result == TDK_NonDependentConversionFailure)
6886       Candidate.FailureKind = ovl_fail_bad_conversion;
6887     else {
6888       Candidate.FailureKind = ovl_fail_bad_deduction;
6889       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6890                                                             Info);
6891     }
6892     return;
6893   }
6894 
6895   // Add the function template specialization produced by template argument
6896   // deduction as a candidate.
6897   assert(Specialization && "Missing member function template specialization?");
6898   assert(isa<CXXMethodDecl>(Specialization) &&
6899          "Specialization is not a member function?");
6900   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6901                      ActingContext, ObjectType, ObjectClassification, Args,
6902                      CandidateSet, SuppressUserConversions, PartialOverloading,
6903                      Conversions, PO);
6904 }
6905 
6906 /// Add a C++ function template specialization as a candidate
6907 /// in the candidate set, using template argument deduction to produce
6908 /// an appropriate function template specialization.
6909 void Sema::AddTemplateOverloadCandidate(
6910     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
6911     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6912     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6913     bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
6914     OverloadCandidateParamOrder PO) {
6915   if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
6916     return;
6917 
6918   // C++ [over.match.funcs]p7:
6919   //   In each case where a candidate is a function template, candidate
6920   //   function template specializations are generated using template argument
6921   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6922   //   candidate functions in the usual way.113) A given name can refer to one
6923   //   or more function templates and also to a set of overloaded non-template
6924   //   functions. In such a case, the candidate functions generated from each
6925   //   function template are combined with the set of non-template candidate
6926   //   functions.
6927   TemplateDeductionInfo Info(CandidateSet.getLocation());
6928   FunctionDecl *Specialization = nullptr;
6929   ConversionSequenceList Conversions;
6930   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6931           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6932           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6933             return CheckNonDependentConversions(
6934                 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
6935                 SuppressUserConversions, nullptr, QualType(), {}, PO);
6936           })) {
6937     OverloadCandidate &Candidate =
6938         CandidateSet.addCandidate(Conversions.size(), Conversions);
6939     Candidate.FoundDecl = FoundDecl;
6940     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6941     Candidate.Viable = false;
6942     Candidate.RewriteKind =
6943       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
6944     Candidate.IsSurrogate = false;
6945     Candidate.IsADLCandidate = IsADLCandidate;
6946     // Ignore the object argument if there is one, since we don't have an object
6947     // type.
6948     Candidate.IgnoreObjectArgument =
6949         isa<CXXMethodDecl>(Candidate.Function) &&
6950         !isa<CXXConstructorDecl>(Candidate.Function);
6951     Candidate.ExplicitCallArguments = Args.size();
6952     if (Result == TDK_NonDependentConversionFailure)
6953       Candidate.FailureKind = ovl_fail_bad_conversion;
6954     else {
6955       Candidate.FailureKind = ovl_fail_bad_deduction;
6956       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6957                                                             Info);
6958     }
6959     return;
6960   }
6961 
6962   // Add the function template specialization produced by template argument
6963   // deduction as a candidate.
6964   assert(Specialization && "Missing function template specialization?");
6965   AddOverloadCandidate(
6966       Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
6967       PartialOverloading, AllowExplicit,
6968       /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO);
6969 }
6970 
6971 /// Check that implicit conversion sequences can be formed for each argument
6972 /// whose corresponding parameter has a non-dependent type, per DR1391's
6973 /// [temp.deduct.call]p10.
6974 bool Sema::CheckNonDependentConversions(
6975     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6976     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6977     ConversionSequenceList &Conversions, bool SuppressUserConversions,
6978     CXXRecordDecl *ActingContext, QualType ObjectType,
6979     Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
6980   // FIXME: The cases in which we allow explicit conversions for constructor
6981   // arguments never consider calling a constructor template. It's not clear
6982   // that is correct.
6983   const bool AllowExplicit = false;
6984 
6985   auto *FD = FunctionTemplate->getTemplatedDecl();
6986   auto *Method = dyn_cast<CXXMethodDecl>(FD);
6987   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6988   unsigned ThisConversions = HasThisConversion ? 1 : 0;
6989 
6990   Conversions =
6991       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6992 
6993   // Overload resolution is always an unevaluated context.
6994   EnterExpressionEvaluationContext Unevaluated(
6995       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6996 
6997   // For a method call, check the 'this' conversion here too. DR1391 doesn't
6998   // require that, but this check should never result in a hard error, and
6999   // overload resolution is permitted to sidestep instantiations.
7000   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7001       !ObjectType.isNull()) {
7002     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7003     Conversions[ConvIdx] = TryObjectArgumentInitialization(
7004         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7005         Method, ActingContext);
7006     if (Conversions[ConvIdx].isBad())
7007       return true;
7008   }
7009 
7010   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
7011        ++I) {
7012     QualType ParamType = ParamTypes[I];
7013     if (!ParamType->isDependentType()) {
7014       unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
7015                              ? 0
7016                              : (ThisConversions + I);
7017       Conversions[ConvIdx]
7018         = TryCopyInitialization(*this, Args[I], ParamType,
7019                                 SuppressUserConversions,
7020                                 /*InOverloadResolution=*/true,
7021                                 /*AllowObjCWritebackConversion=*/
7022                                   getLangOpts().ObjCAutoRefCount,
7023                                 AllowExplicit);
7024       if (Conversions[ConvIdx].isBad())
7025         return true;
7026     }
7027   }
7028 
7029   return false;
7030 }
7031 
7032 /// Determine whether this is an allowable conversion from the result
7033 /// of an explicit conversion operator to the expected type, per C++
7034 /// [over.match.conv]p1 and [over.match.ref]p1.
7035 ///
7036 /// \param ConvType The return type of the conversion function.
7037 ///
7038 /// \param ToType The type we are converting to.
7039 ///
7040 /// \param AllowObjCPointerConversion Allow a conversion from one
7041 /// Objective-C pointer to another.
7042 ///
7043 /// \returns true if the conversion is allowable, false otherwise.
7044 static bool isAllowableExplicitConversion(Sema &S,
7045                                           QualType ConvType, QualType ToType,
7046                                           bool AllowObjCPointerConversion) {
7047   QualType ToNonRefType = ToType.getNonReferenceType();
7048 
7049   // Easy case: the types are the same.
7050   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7051     return true;
7052 
7053   // Allow qualification conversions.
7054   bool ObjCLifetimeConversion;
7055   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7056                                   ObjCLifetimeConversion))
7057     return true;
7058 
7059   // If we're not allowed to consider Objective-C pointer conversions,
7060   // we're done.
7061   if (!AllowObjCPointerConversion)
7062     return false;
7063 
7064   // Is this an Objective-C pointer conversion?
7065   bool IncompatibleObjC = false;
7066   QualType ConvertedType;
7067   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7068                                    IncompatibleObjC);
7069 }
7070 
7071 /// AddConversionCandidate - Add a C++ conversion function as a
7072 /// candidate in the candidate set (C++ [over.match.conv],
7073 /// C++ [over.match.copy]). From is the expression we're converting from,
7074 /// and ToType is the type that we're eventually trying to convert to
7075 /// (which may or may not be the same type as the type that the
7076 /// conversion function produces).
7077 void Sema::AddConversionCandidate(
7078     CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7079     CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7080     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7081     bool AllowExplicit, bool AllowResultConversion) {
7082   assert(!Conversion->getDescribedFunctionTemplate() &&
7083          "Conversion function templates use AddTemplateConversionCandidate");
7084   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7085   if (!CandidateSet.isNewCandidate(Conversion))
7086     return;
7087 
7088   // If the conversion function has an undeduced return type, trigger its
7089   // deduction now.
7090   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7091     if (DeduceReturnType(Conversion, From->getExprLoc()))
7092       return;
7093     ConvType = Conversion->getConversionType().getNonReferenceType();
7094   }
7095 
7096   // If we don't allow any conversion of the result type, ignore conversion
7097   // functions that don't convert to exactly (possibly cv-qualified) T.
7098   if (!AllowResultConversion &&
7099       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7100     return;
7101 
7102   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7103   // operator is only a candidate if its return type is the target type or
7104   // can be converted to the target type with a qualification conversion.
7105   if (Conversion->isExplicit() &&
7106       !isAllowableExplicitConversion(*this, ConvType, ToType,
7107                                      AllowObjCConversionOnExplicit))
7108     return;
7109 
7110   // Overload resolution is always an unevaluated context.
7111   EnterExpressionEvaluationContext Unevaluated(
7112       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7113 
7114   // Add this candidate
7115   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7116   Candidate.FoundDecl = FoundDecl;
7117   Candidate.Function = Conversion;
7118   Candidate.IsSurrogate = false;
7119   Candidate.IgnoreObjectArgument = false;
7120   Candidate.FinalConversion.setAsIdentityConversion();
7121   Candidate.FinalConversion.setFromType(ConvType);
7122   Candidate.FinalConversion.setAllToTypes(ToType);
7123   Candidate.Viable = true;
7124   Candidate.ExplicitCallArguments = 1;
7125 
7126   // C++ [over.match.funcs]p4:
7127   //   For conversion functions, the function is considered to be a member of
7128   //   the class of the implicit implied object argument for the purpose of
7129   //   defining the type of the implicit object parameter.
7130   //
7131   // Determine the implicit conversion sequence for the implicit
7132   // object parameter.
7133   QualType ImplicitParamType = From->getType();
7134   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7135     ImplicitParamType = FromPtrType->getPointeeType();
7136   CXXRecordDecl *ConversionContext
7137     = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
7138 
7139   Candidate.Conversions[0] = TryObjectArgumentInitialization(
7140       *this, CandidateSet.getLocation(), From->getType(),
7141       From->Classify(Context), Conversion, ConversionContext);
7142 
7143   if (Candidate.Conversions[0].isBad()) {
7144     Candidate.Viable = false;
7145     Candidate.FailureKind = ovl_fail_bad_conversion;
7146     return;
7147   }
7148 
7149   // We won't go through a user-defined type conversion function to convert a
7150   // derived to base as such conversions are given Conversion Rank. They only
7151   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7152   QualType FromCanon
7153     = Context.getCanonicalType(From->getType().getUnqualifiedType());
7154   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7155   if (FromCanon == ToCanon ||
7156       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7157     Candidate.Viable = false;
7158     Candidate.FailureKind = ovl_fail_trivial_conversion;
7159     return;
7160   }
7161 
7162   // To determine what the conversion from the result of calling the
7163   // conversion function to the type we're eventually trying to
7164   // convert to (ToType), we need to synthesize a call to the
7165   // conversion function and attempt copy initialization from it. This
7166   // makes sure that we get the right semantics with respect to
7167   // lvalues/rvalues and the type. Fortunately, we can allocate this
7168   // call on the stack and we don't need its arguments to be
7169   // well-formed.
7170   DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7171                             VK_LValue, From->getBeginLoc());
7172   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7173                                 Context.getPointerType(Conversion->getType()),
7174                                 CK_FunctionToPointerDecay,
7175                                 &ConversionRef, VK_RValue);
7176 
7177   QualType ConversionType = Conversion->getConversionType();
7178   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7179     Candidate.Viable = false;
7180     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7181     return;
7182   }
7183 
7184   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7185 
7186   // Note that it is safe to allocate CallExpr on the stack here because
7187   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7188   // allocator).
7189   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7190 
7191   alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7192   CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7193       Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7194 
7195   ImplicitConversionSequence ICS =
7196       TryCopyInitialization(*this, TheTemporaryCall, ToType,
7197                             /*SuppressUserConversions=*/true,
7198                             /*InOverloadResolution=*/false,
7199                             /*AllowObjCWritebackConversion=*/false);
7200 
7201   switch (ICS.getKind()) {
7202   case ImplicitConversionSequence::StandardConversion:
7203     Candidate.FinalConversion = ICS.Standard;
7204 
7205     // C++ [over.ics.user]p3:
7206     //   If the user-defined conversion is specified by a specialization of a
7207     //   conversion function template, the second standard conversion sequence
7208     //   shall have exact match rank.
7209     if (Conversion->getPrimaryTemplate() &&
7210         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7211       Candidate.Viable = false;
7212       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7213       return;
7214     }
7215 
7216     // C++0x [dcl.init.ref]p5:
7217     //    In the second case, if the reference is an rvalue reference and
7218     //    the second standard conversion sequence of the user-defined
7219     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7220     //    program is ill-formed.
7221     if (ToType->isRValueReferenceType() &&
7222         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7223       Candidate.Viable = false;
7224       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7225       return;
7226     }
7227     break;
7228 
7229   case ImplicitConversionSequence::BadConversion:
7230     Candidate.Viable = false;
7231     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7232     return;
7233 
7234   default:
7235     llvm_unreachable(
7236            "Can only end up with a standard conversion sequence or failure");
7237   }
7238 
7239   if (!AllowExplicit && Conversion->getExplicitSpecifier().getKind() !=
7240                             ExplicitSpecKind::ResolvedFalse) {
7241     Candidate.Viable = false;
7242     Candidate.FailureKind = ovl_fail_explicit_resolved;
7243     return;
7244   }
7245 
7246   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7247     Candidate.Viable = false;
7248     Candidate.FailureKind = ovl_fail_enable_if;
7249     Candidate.DeductionFailure.Data = FailedAttr;
7250     return;
7251   }
7252 
7253   if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7254       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7255     Candidate.Viable = false;
7256     Candidate.FailureKind = ovl_non_default_multiversion_function;
7257   }
7258 }
7259 
7260 /// Adds a conversion function template specialization
7261 /// candidate to the overload set, using template argument deduction
7262 /// to deduce the template arguments of the conversion function
7263 /// template from the type that we are converting to (C++
7264 /// [temp.deduct.conv]).
7265 void Sema::AddTemplateConversionCandidate(
7266     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7267     CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7268     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7269     bool AllowExplicit, bool AllowResultConversion) {
7270   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7271          "Only conversion function templates permitted here");
7272 
7273   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7274     return;
7275 
7276   TemplateDeductionInfo Info(CandidateSet.getLocation());
7277   CXXConversionDecl *Specialization = nullptr;
7278   if (TemplateDeductionResult Result
7279         = DeduceTemplateArguments(FunctionTemplate, ToType,
7280                                   Specialization, Info)) {
7281     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7282     Candidate.FoundDecl = FoundDecl;
7283     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7284     Candidate.Viable = false;
7285     Candidate.FailureKind = ovl_fail_bad_deduction;
7286     Candidate.IsSurrogate = false;
7287     Candidate.IgnoreObjectArgument = false;
7288     Candidate.ExplicitCallArguments = 1;
7289     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7290                                                           Info);
7291     return;
7292   }
7293 
7294   // Add the conversion function template specialization produced by
7295   // template argument deduction as a candidate.
7296   assert(Specialization && "Missing function template specialization?");
7297   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7298                          CandidateSet, AllowObjCConversionOnExplicit,
7299                          AllowExplicit, AllowResultConversion);
7300 }
7301 
7302 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7303 /// converts the given @c Object to a function pointer via the
7304 /// conversion function @c Conversion, and then attempts to call it
7305 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7306 /// the type of function that we'll eventually be calling.
7307 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7308                                  DeclAccessPair FoundDecl,
7309                                  CXXRecordDecl *ActingContext,
7310                                  const FunctionProtoType *Proto,
7311                                  Expr *Object,
7312                                  ArrayRef<Expr *> Args,
7313                                  OverloadCandidateSet& CandidateSet) {
7314   if (!CandidateSet.isNewCandidate(Conversion))
7315     return;
7316 
7317   // Overload resolution is always an unevaluated context.
7318   EnterExpressionEvaluationContext Unevaluated(
7319       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7320 
7321   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7322   Candidate.FoundDecl = FoundDecl;
7323   Candidate.Function = nullptr;
7324   Candidate.Surrogate = Conversion;
7325   Candidate.Viable = true;
7326   Candidate.IsSurrogate = true;
7327   Candidate.IgnoreObjectArgument = false;
7328   Candidate.ExplicitCallArguments = Args.size();
7329 
7330   // Determine the implicit conversion sequence for the implicit
7331   // object parameter.
7332   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7333       *this, CandidateSet.getLocation(), Object->getType(),
7334       Object->Classify(Context), Conversion, ActingContext);
7335   if (ObjectInit.isBad()) {
7336     Candidate.Viable = false;
7337     Candidate.FailureKind = ovl_fail_bad_conversion;
7338     Candidate.Conversions[0] = ObjectInit;
7339     return;
7340   }
7341 
7342   // The first conversion is actually a user-defined conversion whose
7343   // first conversion is ObjectInit's standard conversion (which is
7344   // effectively a reference binding). Record it as such.
7345   Candidate.Conversions[0].setUserDefined();
7346   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7347   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7348   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7349   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7350   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7351   Candidate.Conversions[0].UserDefined.After
7352     = Candidate.Conversions[0].UserDefined.Before;
7353   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7354 
7355   // Find the
7356   unsigned NumParams = Proto->getNumParams();
7357 
7358   // (C++ 13.3.2p2): A candidate function having fewer than m
7359   // parameters is viable only if it has an ellipsis in its parameter
7360   // list (8.3.5).
7361   if (Args.size() > NumParams && !Proto->isVariadic()) {
7362     Candidate.Viable = false;
7363     Candidate.FailureKind = ovl_fail_too_many_arguments;
7364     return;
7365   }
7366 
7367   // Function types don't have any default arguments, so just check if
7368   // we have enough arguments.
7369   if (Args.size() < NumParams) {
7370     // Not enough arguments.
7371     Candidate.Viable = false;
7372     Candidate.FailureKind = ovl_fail_too_few_arguments;
7373     return;
7374   }
7375 
7376   // Determine the implicit conversion sequences for each of the
7377   // arguments.
7378   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7379     if (ArgIdx < NumParams) {
7380       // (C++ 13.3.2p3): for F to be a viable function, there shall
7381       // exist for each argument an implicit conversion sequence
7382       // (13.3.3.1) that converts that argument to the corresponding
7383       // parameter of F.
7384       QualType ParamType = Proto->getParamType(ArgIdx);
7385       Candidate.Conversions[ArgIdx + 1]
7386         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7387                                 /*SuppressUserConversions=*/false,
7388                                 /*InOverloadResolution=*/false,
7389                                 /*AllowObjCWritebackConversion=*/
7390                                   getLangOpts().ObjCAutoRefCount);
7391       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7392         Candidate.Viable = false;
7393         Candidate.FailureKind = ovl_fail_bad_conversion;
7394         return;
7395       }
7396     } else {
7397       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7398       // argument for which there is no corresponding parameter is
7399       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7400       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7401     }
7402   }
7403 
7404   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7405     Candidate.Viable = false;
7406     Candidate.FailureKind = ovl_fail_enable_if;
7407     Candidate.DeductionFailure.Data = FailedAttr;
7408     return;
7409   }
7410 }
7411 
7412 /// Add all of the non-member operator function declarations in the given
7413 /// function set to the overload candidate set.
7414 void Sema::AddNonMemberOperatorCandidates(
7415     const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
7416     OverloadCandidateSet &CandidateSet,
7417     TemplateArgumentListInfo *ExplicitTemplateArgs) {
7418   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7419     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7420     ArrayRef<Expr *> FunctionArgs = Args;
7421 
7422     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7423     FunctionDecl *FD =
7424         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7425 
7426     // Don't consider rewritten functions if we're not rewriting.
7427     if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
7428       continue;
7429 
7430     assert(!isa<CXXMethodDecl>(FD) &&
7431            "unqualified operator lookup found a member function");
7432 
7433     if (FunTmpl) {
7434       AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
7435                                    FunctionArgs, CandidateSet);
7436       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7437         AddTemplateOverloadCandidate(
7438             FunTmpl, F.getPair(), ExplicitTemplateArgs,
7439             {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
7440             true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
7441     } else {
7442       if (ExplicitTemplateArgs)
7443         continue;
7444       AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
7445       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7446         AddOverloadCandidate(FD, F.getPair(),
7447                              {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
7448                              false, false, true, false, ADLCallKind::NotADL,
7449                              None, OverloadCandidateParamOrder::Reversed);
7450     }
7451   }
7452 }
7453 
7454 /// Add overload candidates for overloaded operators that are
7455 /// member functions.
7456 ///
7457 /// Add the overloaded operator candidates that are member functions
7458 /// for the operator Op that was used in an operator expression such
7459 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7460 /// CandidateSet will store the added overload candidates. (C++
7461 /// [over.match.oper]).
7462 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7463                                        SourceLocation OpLoc,
7464                                        ArrayRef<Expr *> Args,
7465                                        OverloadCandidateSet &CandidateSet,
7466                                        OverloadCandidateParamOrder PO) {
7467   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7468 
7469   // C++ [over.match.oper]p3:
7470   //   For a unary operator @ with an operand of a type whose
7471   //   cv-unqualified version is T1, and for a binary operator @ with
7472   //   a left operand of a type whose cv-unqualified version is T1 and
7473   //   a right operand of a type whose cv-unqualified version is T2,
7474   //   three sets of candidate functions, designated member
7475   //   candidates, non-member candidates and built-in candidates, are
7476   //   constructed as follows:
7477   QualType T1 = Args[0]->getType();
7478 
7479   //     -- If T1 is a complete class type or a class currently being
7480   //        defined, the set of member candidates is the result of the
7481   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7482   //        the set of member candidates is empty.
7483   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7484     // Complete the type if it can be completed.
7485     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7486       return;
7487     // If the type is neither complete nor being defined, bail out now.
7488     if (!T1Rec->getDecl()->getDefinition())
7489       return;
7490 
7491     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7492     LookupQualifiedName(Operators, T1Rec->getDecl());
7493     Operators.suppressDiagnostics();
7494 
7495     for (LookupResult::iterator Oper = Operators.begin(),
7496                              OperEnd = Operators.end();
7497          Oper != OperEnd;
7498          ++Oper)
7499       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7500                          Args[0]->Classify(Context), Args.slice(1),
7501                          CandidateSet, /*SuppressUserConversion=*/false, PO);
7502   }
7503 }
7504 
7505 /// AddBuiltinCandidate - Add a candidate for a built-in
7506 /// operator. ResultTy and ParamTys are the result and parameter types
7507 /// of the built-in candidate, respectively. Args and NumArgs are the
7508 /// arguments being passed to the candidate. IsAssignmentOperator
7509 /// should be true when this built-in candidate is an assignment
7510 /// operator. NumContextualBoolArguments is the number of arguments
7511 /// (at the beginning of the argument list) that will be contextually
7512 /// converted to bool.
7513 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7514                                OverloadCandidateSet& CandidateSet,
7515                                bool IsAssignmentOperator,
7516                                unsigned NumContextualBoolArguments) {
7517   // Overload resolution is always an unevaluated context.
7518   EnterExpressionEvaluationContext Unevaluated(
7519       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7520 
7521   // Add this candidate
7522   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7523   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7524   Candidate.Function = nullptr;
7525   Candidate.IsSurrogate = false;
7526   Candidate.IgnoreObjectArgument = false;
7527   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7528 
7529   // Determine the implicit conversion sequences for each of the
7530   // arguments.
7531   Candidate.Viable = true;
7532   Candidate.ExplicitCallArguments = Args.size();
7533   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7534     // C++ [over.match.oper]p4:
7535     //   For the built-in assignment operators, conversions of the
7536     //   left operand are restricted as follows:
7537     //     -- no temporaries are introduced to hold the left operand, and
7538     //     -- no user-defined conversions are applied to the left
7539     //        operand to achieve a type match with the left-most
7540     //        parameter of a built-in candidate.
7541     //
7542     // We block these conversions by turning off user-defined
7543     // conversions, since that is the only way that initialization of
7544     // a reference to a non-class type can occur from something that
7545     // is not of the same type.
7546     if (ArgIdx < NumContextualBoolArguments) {
7547       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7548              "Contextual conversion to bool requires bool type");
7549       Candidate.Conversions[ArgIdx]
7550         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7551     } else {
7552       Candidate.Conversions[ArgIdx]
7553         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7554                                 ArgIdx == 0 && IsAssignmentOperator,
7555                                 /*InOverloadResolution=*/false,
7556                                 /*AllowObjCWritebackConversion=*/
7557                                   getLangOpts().ObjCAutoRefCount);
7558     }
7559     if (Candidate.Conversions[ArgIdx].isBad()) {
7560       Candidate.Viable = false;
7561       Candidate.FailureKind = ovl_fail_bad_conversion;
7562       break;
7563     }
7564   }
7565 }
7566 
7567 namespace {
7568 
7569 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7570 /// candidate operator functions for built-in operators (C++
7571 /// [over.built]). The types are separated into pointer types and
7572 /// enumeration types.
7573 class BuiltinCandidateTypeSet  {
7574   /// TypeSet - A set of types.
7575   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7576                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7577 
7578   /// PointerTypes - The set of pointer types that will be used in the
7579   /// built-in candidates.
7580   TypeSet PointerTypes;
7581 
7582   /// MemberPointerTypes - The set of member pointer types that will be
7583   /// used in the built-in candidates.
7584   TypeSet MemberPointerTypes;
7585 
7586   /// EnumerationTypes - The set of enumeration types that will be
7587   /// used in the built-in candidates.
7588   TypeSet EnumerationTypes;
7589 
7590   /// The set of vector types that will be used in the built-in
7591   /// candidates.
7592   TypeSet VectorTypes;
7593 
7594   /// A flag indicating non-record types are viable candidates
7595   bool HasNonRecordTypes;
7596 
7597   /// A flag indicating whether either arithmetic or enumeration types
7598   /// were present in the candidate set.
7599   bool HasArithmeticOrEnumeralTypes;
7600 
7601   /// A flag indicating whether the nullptr type was present in the
7602   /// candidate set.
7603   bool HasNullPtrType;
7604 
7605   /// Sema - The semantic analysis instance where we are building the
7606   /// candidate type set.
7607   Sema &SemaRef;
7608 
7609   /// Context - The AST context in which we will build the type sets.
7610   ASTContext &Context;
7611 
7612   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7613                                                const Qualifiers &VisibleQuals);
7614   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7615 
7616 public:
7617   /// iterator - Iterates through the types that are part of the set.
7618   typedef TypeSet::iterator iterator;
7619 
7620   BuiltinCandidateTypeSet(Sema &SemaRef)
7621     : HasNonRecordTypes(false),
7622       HasArithmeticOrEnumeralTypes(false),
7623       HasNullPtrType(false),
7624       SemaRef(SemaRef),
7625       Context(SemaRef.Context) { }
7626 
7627   void AddTypesConvertedFrom(QualType Ty,
7628                              SourceLocation Loc,
7629                              bool AllowUserConversions,
7630                              bool AllowExplicitConversions,
7631                              const Qualifiers &VisibleTypeConversionsQuals);
7632 
7633   /// pointer_begin - First pointer type found;
7634   iterator pointer_begin() { return PointerTypes.begin(); }
7635 
7636   /// pointer_end - Past the last pointer type found;
7637   iterator pointer_end() { return PointerTypes.end(); }
7638 
7639   /// member_pointer_begin - First member pointer type found;
7640   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7641 
7642   /// member_pointer_end - Past the last member pointer type found;
7643   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7644 
7645   /// enumeration_begin - First enumeration type found;
7646   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7647 
7648   /// enumeration_end - Past the last enumeration type found;
7649   iterator enumeration_end() { return EnumerationTypes.end(); }
7650 
7651   iterator vector_begin() { return VectorTypes.begin(); }
7652   iterator vector_end() { return VectorTypes.end(); }
7653 
7654   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7655   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7656   bool hasNullPtrType() const { return HasNullPtrType; }
7657 };
7658 
7659 } // end anonymous namespace
7660 
7661 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7662 /// the set of pointer types along with any more-qualified variants of
7663 /// that type. For example, if @p Ty is "int const *", this routine
7664 /// will add "int const *", "int const volatile *", "int const
7665 /// restrict *", and "int const volatile restrict *" to the set of
7666 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7667 /// false otherwise.
7668 ///
7669 /// FIXME: what to do about extended qualifiers?
7670 bool
7671 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7672                                              const Qualifiers &VisibleQuals) {
7673 
7674   // Insert this type.
7675   if (!PointerTypes.insert(Ty))
7676     return false;
7677 
7678   QualType PointeeTy;
7679   const PointerType *PointerTy = Ty->getAs<PointerType>();
7680   bool buildObjCPtr = false;
7681   if (!PointerTy) {
7682     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7683     PointeeTy = PTy->getPointeeType();
7684     buildObjCPtr = true;
7685   } else {
7686     PointeeTy = PointerTy->getPointeeType();
7687   }
7688 
7689   // Don't add qualified variants of arrays. For one, they're not allowed
7690   // (the qualifier would sink to the element type), and for another, the
7691   // only overload situation where it matters is subscript or pointer +- int,
7692   // and those shouldn't have qualifier variants anyway.
7693   if (PointeeTy->isArrayType())
7694     return true;
7695 
7696   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7697   bool hasVolatile = VisibleQuals.hasVolatile();
7698   bool hasRestrict = VisibleQuals.hasRestrict();
7699 
7700   // Iterate through all strict supersets of BaseCVR.
7701   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7702     if ((CVR | BaseCVR) != CVR) continue;
7703     // Skip over volatile if no volatile found anywhere in the types.
7704     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7705 
7706     // Skip over restrict if no restrict found anywhere in the types, or if
7707     // the type cannot be restrict-qualified.
7708     if ((CVR & Qualifiers::Restrict) &&
7709         (!hasRestrict ||
7710          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7711       continue;
7712 
7713     // Build qualified pointee type.
7714     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7715 
7716     // Build qualified pointer type.
7717     QualType QPointerTy;
7718     if (!buildObjCPtr)
7719       QPointerTy = Context.getPointerType(QPointeeTy);
7720     else
7721       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7722 
7723     // Insert qualified pointer type.
7724     PointerTypes.insert(QPointerTy);
7725   }
7726 
7727   return true;
7728 }
7729 
7730 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7731 /// to the set of pointer types along with any more-qualified variants of
7732 /// that type. For example, if @p Ty is "int const *", this routine
7733 /// will add "int const *", "int const volatile *", "int const
7734 /// restrict *", and "int const volatile restrict *" to the set of
7735 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7736 /// false otherwise.
7737 ///
7738 /// FIXME: what to do about extended qualifiers?
7739 bool
7740 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7741     QualType Ty) {
7742   // Insert this type.
7743   if (!MemberPointerTypes.insert(Ty))
7744     return false;
7745 
7746   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7747   assert(PointerTy && "type was not a member pointer type!");
7748 
7749   QualType PointeeTy = PointerTy->getPointeeType();
7750   // Don't add qualified variants of arrays. For one, they're not allowed
7751   // (the qualifier would sink to the element type), and for another, the
7752   // only overload situation where it matters is subscript or pointer +- int,
7753   // and those shouldn't have qualifier variants anyway.
7754   if (PointeeTy->isArrayType())
7755     return true;
7756   const Type *ClassTy = PointerTy->getClass();
7757 
7758   // Iterate through all strict supersets of the pointee type's CVR
7759   // qualifiers.
7760   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7761   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7762     if ((CVR | BaseCVR) != CVR) continue;
7763 
7764     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7765     MemberPointerTypes.insert(
7766       Context.getMemberPointerType(QPointeeTy, ClassTy));
7767   }
7768 
7769   return true;
7770 }
7771 
7772 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7773 /// Ty can be implicit converted to the given set of @p Types. We're
7774 /// primarily interested in pointer types and enumeration types. We also
7775 /// take member pointer types, for the conditional operator.
7776 /// AllowUserConversions is true if we should look at the conversion
7777 /// functions of a class type, and AllowExplicitConversions if we
7778 /// should also include the explicit conversion functions of a class
7779 /// type.
7780 void
7781 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7782                                                SourceLocation Loc,
7783                                                bool AllowUserConversions,
7784                                                bool AllowExplicitConversions,
7785                                                const Qualifiers &VisibleQuals) {
7786   // Only deal with canonical types.
7787   Ty = Context.getCanonicalType(Ty);
7788 
7789   // Look through reference types; they aren't part of the type of an
7790   // expression for the purposes of conversions.
7791   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7792     Ty = RefTy->getPointeeType();
7793 
7794   // If we're dealing with an array type, decay to the pointer.
7795   if (Ty->isArrayType())
7796     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7797 
7798   // Otherwise, we don't care about qualifiers on the type.
7799   Ty = Ty.getLocalUnqualifiedType();
7800 
7801   // Flag if we ever add a non-record type.
7802   const RecordType *TyRec = Ty->getAs<RecordType>();
7803   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7804 
7805   // Flag if we encounter an arithmetic type.
7806   HasArithmeticOrEnumeralTypes =
7807     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7808 
7809   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7810     PointerTypes.insert(Ty);
7811   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7812     // Insert our type, and its more-qualified variants, into the set
7813     // of types.
7814     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7815       return;
7816   } else if (Ty->isMemberPointerType()) {
7817     // Member pointers are far easier, since the pointee can't be converted.
7818     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7819       return;
7820   } else if (Ty->isEnumeralType()) {
7821     HasArithmeticOrEnumeralTypes = true;
7822     EnumerationTypes.insert(Ty);
7823   } else if (Ty->isVectorType()) {
7824     // We treat vector types as arithmetic types in many contexts as an
7825     // extension.
7826     HasArithmeticOrEnumeralTypes = true;
7827     VectorTypes.insert(Ty);
7828   } else if (Ty->isNullPtrType()) {
7829     HasNullPtrType = true;
7830   } else if (AllowUserConversions && TyRec) {
7831     // No conversion functions in incomplete types.
7832     if (!SemaRef.isCompleteType(Loc, Ty))
7833       return;
7834 
7835     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7836     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7837       if (isa<UsingShadowDecl>(D))
7838         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7839 
7840       // Skip conversion function templates; they don't tell us anything
7841       // about which builtin types we can convert to.
7842       if (isa<FunctionTemplateDecl>(D))
7843         continue;
7844 
7845       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7846       if (AllowExplicitConversions || !Conv->isExplicit()) {
7847         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7848                               VisibleQuals);
7849       }
7850     }
7851   }
7852 }
7853 /// Helper function for adjusting address spaces for the pointer or reference
7854 /// operands of builtin operators depending on the argument.
7855 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
7856                                                         Expr *Arg) {
7857   return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
7858 }
7859 
7860 /// Helper function for AddBuiltinOperatorCandidates() that adds
7861 /// the volatile- and non-volatile-qualified assignment operators for the
7862 /// given type to the candidate set.
7863 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7864                                                    QualType T,
7865                                                    ArrayRef<Expr *> Args,
7866                                     OverloadCandidateSet &CandidateSet) {
7867   QualType ParamTypes[2];
7868 
7869   // T& operator=(T&, T)
7870   ParamTypes[0] = S.Context.getLValueReferenceType(
7871       AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
7872   ParamTypes[1] = T;
7873   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7874                         /*IsAssignmentOperator=*/true);
7875 
7876   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7877     // volatile T& operator=(volatile T&, T)
7878     ParamTypes[0] = S.Context.getLValueReferenceType(
7879         AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
7880                                                 Args[0]));
7881     ParamTypes[1] = T;
7882     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7883                           /*IsAssignmentOperator=*/true);
7884   }
7885 }
7886 
7887 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7888 /// if any, found in visible type conversion functions found in ArgExpr's type.
7889 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7890     Qualifiers VRQuals;
7891     const RecordType *TyRec;
7892     if (const MemberPointerType *RHSMPType =
7893         ArgExpr->getType()->getAs<MemberPointerType>())
7894       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7895     else
7896       TyRec = ArgExpr->getType()->getAs<RecordType>();
7897     if (!TyRec) {
7898       // Just to be safe, assume the worst case.
7899       VRQuals.addVolatile();
7900       VRQuals.addRestrict();
7901       return VRQuals;
7902     }
7903 
7904     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7905     if (!ClassDecl->hasDefinition())
7906       return VRQuals;
7907 
7908     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7909       if (isa<UsingShadowDecl>(D))
7910         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7911       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7912         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7913         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7914           CanTy = ResTypeRef->getPointeeType();
7915         // Need to go down the pointer/mempointer chain and add qualifiers
7916         // as see them.
7917         bool done = false;
7918         while (!done) {
7919           if (CanTy.isRestrictQualified())
7920             VRQuals.addRestrict();
7921           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7922             CanTy = ResTypePtr->getPointeeType();
7923           else if (const MemberPointerType *ResTypeMPtr =
7924                 CanTy->getAs<MemberPointerType>())
7925             CanTy = ResTypeMPtr->getPointeeType();
7926           else
7927             done = true;
7928           if (CanTy.isVolatileQualified())
7929             VRQuals.addVolatile();
7930           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7931             return VRQuals;
7932         }
7933       }
7934     }
7935     return VRQuals;
7936 }
7937 
7938 namespace {
7939 
7940 /// Helper class to manage the addition of builtin operator overload
7941 /// candidates. It provides shared state and utility methods used throughout
7942 /// the process, as well as a helper method to add each group of builtin
7943 /// operator overloads from the standard to a candidate set.
7944 class BuiltinOperatorOverloadBuilder {
7945   // Common instance state available to all overload candidate addition methods.
7946   Sema &S;
7947   ArrayRef<Expr *> Args;
7948   Qualifiers VisibleTypeConversionsQuals;
7949   bool HasArithmeticOrEnumeralCandidateType;
7950   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7951   OverloadCandidateSet &CandidateSet;
7952 
7953   static constexpr int ArithmeticTypesCap = 24;
7954   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
7955 
7956   // Define some indices used to iterate over the arithmetic types in
7957   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
7958   // types are that preserved by promotion (C++ [over.built]p2).
7959   unsigned FirstIntegralType,
7960            LastIntegralType;
7961   unsigned FirstPromotedIntegralType,
7962            LastPromotedIntegralType;
7963   unsigned FirstPromotedArithmeticType,
7964            LastPromotedArithmeticType;
7965   unsigned NumArithmeticTypes;
7966 
7967   void InitArithmeticTypes() {
7968     // Start of promoted types.
7969     FirstPromotedArithmeticType = 0;
7970     ArithmeticTypes.push_back(S.Context.FloatTy);
7971     ArithmeticTypes.push_back(S.Context.DoubleTy);
7972     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7973     if (S.Context.getTargetInfo().hasFloat128Type())
7974       ArithmeticTypes.push_back(S.Context.Float128Ty);
7975 
7976     // Start of integral types.
7977     FirstIntegralType = ArithmeticTypes.size();
7978     FirstPromotedIntegralType = ArithmeticTypes.size();
7979     ArithmeticTypes.push_back(S.Context.IntTy);
7980     ArithmeticTypes.push_back(S.Context.LongTy);
7981     ArithmeticTypes.push_back(S.Context.LongLongTy);
7982     if (S.Context.getTargetInfo().hasInt128Type())
7983       ArithmeticTypes.push_back(S.Context.Int128Ty);
7984     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7985     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7986     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7987     if (S.Context.getTargetInfo().hasInt128Type())
7988       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7989     LastPromotedIntegralType = ArithmeticTypes.size();
7990     LastPromotedArithmeticType = ArithmeticTypes.size();
7991     // End of promoted types.
7992 
7993     ArithmeticTypes.push_back(S.Context.BoolTy);
7994     ArithmeticTypes.push_back(S.Context.CharTy);
7995     ArithmeticTypes.push_back(S.Context.WCharTy);
7996     if (S.Context.getLangOpts().Char8)
7997       ArithmeticTypes.push_back(S.Context.Char8Ty);
7998     ArithmeticTypes.push_back(S.Context.Char16Ty);
7999     ArithmeticTypes.push_back(S.Context.Char32Ty);
8000     ArithmeticTypes.push_back(S.Context.SignedCharTy);
8001     ArithmeticTypes.push_back(S.Context.ShortTy);
8002     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8003     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8004     LastIntegralType = ArithmeticTypes.size();
8005     NumArithmeticTypes = ArithmeticTypes.size();
8006     // End of integral types.
8007     // FIXME: What about complex? What about half?
8008 
8009     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
8010            "Enough inline storage for all arithmetic types.");
8011   }
8012 
8013   /// Helper method to factor out the common pattern of adding overloads
8014   /// for '++' and '--' builtin operators.
8015   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8016                                            bool HasVolatile,
8017                                            bool HasRestrict) {
8018     QualType ParamTypes[2] = {
8019       S.Context.getLValueReferenceType(CandidateTy),
8020       S.Context.IntTy
8021     };
8022 
8023     // Non-volatile version.
8024     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8025 
8026     // Use a heuristic to reduce number of builtin candidates in the set:
8027     // add volatile version only if there are conversions to a volatile type.
8028     if (HasVolatile) {
8029       ParamTypes[0] =
8030         S.Context.getLValueReferenceType(
8031           S.Context.getVolatileType(CandidateTy));
8032       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8033     }
8034 
8035     // Add restrict version only if there are conversions to a restrict type
8036     // and our candidate type is a non-restrict-qualified pointer.
8037     if (HasRestrict && CandidateTy->isAnyPointerType() &&
8038         !CandidateTy.isRestrictQualified()) {
8039       ParamTypes[0]
8040         = S.Context.getLValueReferenceType(
8041             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8042       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8043 
8044       if (HasVolatile) {
8045         ParamTypes[0]
8046           = S.Context.getLValueReferenceType(
8047               S.Context.getCVRQualifiedType(CandidateTy,
8048                                             (Qualifiers::Volatile |
8049                                              Qualifiers::Restrict)));
8050         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8051       }
8052     }
8053 
8054   }
8055 
8056 public:
8057   BuiltinOperatorOverloadBuilder(
8058     Sema &S, ArrayRef<Expr *> Args,
8059     Qualifiers VisibleTypeConversionsQuals,
8060     bool HasArithmeticOrEnumeralCandidateType,
8061     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8062     OverloadCandidateSet &CandidateSet)
8063     : S(S), Args(Args),
8064       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8065       HasArithmeticOrEnumeralCandidateType(
8066         HasArithmeticOrEnumeralCandidateType),
8067       CandidateTypes(CandidateTypes),
8068       CandidateSet(CandidateSet) {
8069 
8070     InitArithmeticTypes();
8071   }
8072 
8073   // Increment is deprecated for bool since C++17.
8074   //
8075   // C++ [over.built]p3:
8076   //
8077   //   For every pair (T, VQ), where T is an arithmetic type other
8078   //   than bool, and VQ is either volatile or empty, there exist
8079   //   candidate operator functions of the form
8080   //
8081   //       VQ T&      operator++(VQ T&);
8082   //       T          operator++(VQ T&, int);
8083   //
8084   // C++ [over.built]p4:
8085   //
8086   //   For every pair (T, VQ), where T is an arithmetic type other
8087   //   than bool, and VQ is either volatile or empty, there exist
8088   //   candidate operator functions of the form
8089   //
8090   //       VQ T&      operator--(VQ T&);
8091   //       T          operator--(VQ T&, int);
8092   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8093     if (!HasArithmeticOrEnumeralCandidateType)
8094       return;
8095 
8096     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8097       const auto TypeOfT = ArithmeticTypes[Arith];
8098       if (TypeOfT == S.Context.BoolTy) {
8099         if (Op == OO_MinusMinus)
8100           continue;
8101         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8102           continue;
8103       }
8104       addPlusPlusMinusMinusStyleOverloads(
8105         TypeOfT,
8106         VisibleTypeConversionsQuals.hasVolatile(),
8107         VisibleTypeConversionsQuals.hasRestrict());
8108     }
8109   }
8110 
8111   // C++ [over.built]p5:
8112   //
8113   //   For every pair (T, VQ), where T is a cv-qualified or
8114   //   cv-unqualified object type, and VQ is either volatile or
8115   //   empty, there exist candidate operator functions of the form
8116   //
8117   //       T*VQ&      operator++(T*VQ&);
8118   //       T*VQ&      operator--(T*VQ&);
8119   //       T*         operator++(T*VQ&, int);
8120   //       T*         operator--(T*VQ&, int);
8121   void addPlusPlusMinusMinusPointerOverloads() {
8122     for (BuiltinCandidateTypeSet::iterator
8123               Ptr = CandidateTypes[0].pointer_begin(),
8124            PtrEnd = CandidateTypes[0].pointer_end();
8125          Ptr != PtrEnd; ++Ptr) {
8126       // Skip pointer types that aren't pointers to object types.
8127       if (!(*Ptr)->getPointeeType()->isObjectType())
8128         continue;
8129 
8130       addPlusPlusMinusMinusStyleOverloads(*Ptr,
8131         (!(*Ptr).isVolatileQualified() &&
8132          VisibleTypeConversionsQuals.hasVolatile()),
8133         (!(*Ptr).isRestrictQualified() &&
8134          VisibleTypeConversionsQuals.hasRestrict()));
8135     }
8136   }
8137 
8138   // C++ [over.built]p6:
8139   //   For every cv-qualified or cv-unqualified object type T, there
8140   //   exist candidate operator functions of the form
8141   //
8142   //       T&         operator*(T*);
8143   //
8144   // C++ [over.built]p7:
8145   //   For every function type T that does not have cv-qualifiers or a
8146   //   ref-qualifier, there exist candidate operator functions of the form
8147   //       T&         operator*(T*);
8148   void addUnaryStarPointerOverloads() {
8149     for (BuiltinCandidateTypeSet::iterator
8150               Ptr = CandidateTypes[0].pointer_begin(),
8151            PtrEnd = CandidateTypes[0].pointer_end();
8152          Ptr != PtrEnd; ++Ptr) {
8153       QualType ParamTy = *Ptr;
8154       QualType PointeeTy = ParamTy->getPointeeType();
8155       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8156         continue;
8157 
8158       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8159         if (Proto->getMethodQuals() || Proto->getRefQualifier())
8160           continue;
8161 
8162       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8163     }
8164   }
8165 
8166   // C++ [over.built]p9:
8167   //  For every promoted arithmetic type T, there exist candidate
8168   //  operator functions of the form
8169   //
8170   //       T         operator+(T);
8171   //       T         operator-(T);
8172   void addUnaryPlusOrMinusArithmeticOverloads() {
8173     if (!HasArithmeticOrEnumeralCandidateType)
8174       return;
8175 
8176     for (unsigned Arith = FirstPromotedArithmeticType;
8177          Arith < LastPromotedArithmeticType; ++Arith) {
8178       QualType ArithTy = ArithmeticTypes[Arith];
8179       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8180     }
8181 
8182     // Extension: We also add these operators for vector types.
8183     for (BuiltinCandidateTypeSet::iterator
8184               Vec = CandidateTypes[0].vector_begin(),
8185            VecEnd = CandidateTypes[0].vector_end();
8186          Vec != VecEnd; ++Vec) {
8187       QualType VecTy = *Vec;
8188       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8189     }
8190   }
8191 
8192   // C++ [over.built]p8:
8193   //   For every type T, there exist candidate operator functions of
8194   //   the form
8195   //
8196   //       T*         operator+(T*);
8197   void addUnaryPlusPointerOverloads() {
8198     for (BuiltinCandidateTypeSet::iterator
8199               Ptr = CandidateTypes[0].pointer_begin(),
8200            PtrEnd = CandidateTypes[0].pointer_end();
8201          Ptr != PtrEnd; ++Ptr) {
8202       QualType ParamTy = *Ptr;
8203       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8204     }
8205   }
8206 
8207   // C++ [over.built]p10:
8208   //   For every promoted integral type T, there exist candidate
8209   //   operator functions of the form
8210   //
8211   //        T         operator~(T);
8212   void addUnaryTildePromotedIntegralOverloads() {
8213     if (!HasArithmeticOrEnumeralCandidateType)
8214       return;
8215 
8216     for (unsigned Int = FirstPromotedIntegralType;
8217          Int < LastPromotedIntegralType; ++Int) {
8218       QualType IntTy = ArithmeticTypes[Int];
8219       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8220     }
8221 
8222     // Extension: We also add this operator for vector types.
8223     for (BuiltinCandidateTypeSet::iterator
8224               Vec = CandidateTypes[0].vector_begin(),
8225            VecEnd = CandidateTypes[0].vector_end();
8226          Vec != VecEnd; ++Vec) {
8227       QualType VecTy = *Vec;
8228       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8229     }
8230   }
8231 
8232   // C++ [over.match.oper]p16:
8233   //   For every pointer to member type T or type std::nullptr_t, there
8234   //   exist candidate operator functions of the form
8235   //
8236   //        bool operator==(T,T);
8237   //        bool operator!=(T,T);
8238   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8239     /// Set of (canonical) types that we've already handled.
8240     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8241 
8242     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8243       for (BuiltinCandidateTypeSet::iterator
8244                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8245              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8246            MemPtr != MemPtrEnd;
8247            ++MemPtr) {
8248         // Don't add the same builtin candidate twice.
8249         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8250           continue;
8251 
8252         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8253         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8254       }
8255 
8256       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8257         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8258         if (AddedTypes.insert(NullPtrTy).second) {
8259           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8260           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8261         }
8262       }
8263     }
8264   }
8265 
8266   // C++ [over.built]p15:
8267   //
8268   //   For every T, where T is an enumeration type or a pointer type,
8269   //   there exist candidate operator functions of the form
8270   //
8271   //        bool       operator<(T, T);
8272   //        bool       operator>(T, T);
8273   //        bool       operator<=(T, T);
8274   //        bool       operator>=(T, T);
8275   //        bool       operator==(T, T);
8276   //        bool       operator!=(T, T);
8277   //           R       operator<=>(T, T)
8278   void addGenericBinaryPointerOrEnumeralOverloads() {
8279     // C++ [over.match.oper]p3:
8280     //   [...]the built-in candidates include all of the candidate operator
8281     //   functions defined in 13.6 that, compared to the given operator, [...]
8282     //   do not have the same parameter-type-list as any non-template non-member
8283     //   candidate.
8284     //
8285     // Note that in practice, this only affects enumeration types because there
8286     // aren't any built-in candidates of record type, and a user-defined operator
8287     // must have an operand of record or enumeration type. Also, the only other
8288     // overloaded operator with enumeration arguments, operator=,
8289     // cannot be overloaded for enumeration types, so this is the only place
8290     // where we must suppress candidates like this.
8291     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8292       UserDefinedBinaryOperators;
8293 
8294     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8295       if (CandidateTypes[ArgIdx].enumeration_begin() !=
8296           CandidateTypes[ArgIdx].enumeration_end()) {
8297         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8298                                          CEnd = CandidateSet.end();
8299              C != CEnd; ++C) {
8300           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8301             continue;
8302 
8303           if (C->Function->isFunctionTemplateSpecialization())
8304             continue;
8305 
8306           // We interpret "same parameter-type-list" as applying to the
8307           // "synthesized candidate, with the order of the two parameters
8308           // reversed", not to the original function.
8309           bool Reversed = C->RewriteKind & CRK_Reversed;
8310           QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
8311                                         ->getType()
8312                                         .getUnqualifiedType();
8313           QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
8314                                          ->getType()
8315                                          .getUnqualifiedType();
8316 
8317           // Skip if either parameter isn't of enumeral type.
8318           if (!FirstParamType->isEnumeralType() ||
8319               !SecondParamType->isEnumeralType())
8320             continue;
8321 
8322           // Add this operator to the set of known user-defined operators.
8323           UserDefinedBinaryOperators.insert(
8324             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8325                            S.Context.getCanonicalType(SecondParamType)));
8326         }
8327       }
8328     }
8329 
8330     /// Set of (canonical) types that we've already handled.
8331     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8332 
8333     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8334       for (BuiltinCandidateTypeSet::iterator
8335                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8336              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8337            Ptr != PtrEnd; ++Ptr) {
8338         // Don't add the same builtin candidate twice.
8339         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8340           continue;
8341 
8342         QualType ParamTypes[2] = { *Ptr, *Ptr };
8343         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8344       }
8345       for (BuiltinCandidateTypeSet::iterator
8346                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8347              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8348            Enum != EnumEnd; ++Enum) {
8349         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8350 
8351         // Don't add the same builtin candidate twice, or if a user defined
8352         // candidate exists.
8353         if (!AddedTypes.insert(CanonType).second ||
8354             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8355                                                             CanonType)))
8356           continue;
8357         QualType ParamTypes[2] = { *Enum, *Enum };
8358         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8359       }
8360     }
8361   }
8362 
8363   // C++ [over.built]p13:
8364   //
8365   //   For every cv-qualified or cv-unqualified object type T
8366   //   there exist candidate operator functions of the form
8367   //
8368   //      T*         operator+(T*, ptrdiff_t);
8369   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8370   //      T*         operator-(T*, ptrdiff_t);
8371   //      T*         operator+(ptrdiff_t, T*);
8372   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8373   //
8374   // C++ [over.built]p14:
8375   //
8376   //   For every T, where T is a pointer to object type, there
8377   //   exist candidate operator functions of the form
8378   //
8379   //      ptrdiff_t  operator-(T, T);
8380   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8381     /// Set of (canonical) types that we've already handled.
8382     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8383 
8384     for (int Arg = 0; Arg < 2; ++Arg) {
8385       QualType AsymmetricParamTypes[2] = {
8386         S.Context.getPointerDiffType(),
8387         S.Context.getPointerDiffType(),
8388       };
8389       for (BuiltinCandidateTypeSet::iterator
8390                 Ptr = CandidateTypes[Arg].pointer_begin(),
8391              PtrEnd = CandidateTypes[Arg].pointer_end();
8392            Ptr != PtrEnd; ++Ptr) {
8393         QualType PointeeTy = (*Ptr)->getPointeeType();
8394         if (!PointeeTy->isObjectType())
8395           continue;
8396 
8397         AsymmetricParamTypes[Arg] = *Ptr;
8398         if (Arg == 0 || Op == OO_Plus) {
8399           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8400           // T* operator+(ptrdiff_t, T*);
8401           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8402         }
8403         if (Op == OO_Minus) {
8404           // ptrdiff_t operator-(T, T);
8405           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8406             continue;
8407 
8408           QualType ParamTypes[2] = { *Ptr, *Ptr };
8409           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8410         }
8411       }
8412     }
8413   }
8414 
8415   // C++ [over.built]p12:
8416   //
8417   //   For every pair of promoted arithmetic types L and R, there
8418   //   exist candidate operator functions of the form
8419   //
8420   //        LR         operator*(L, R);
8421   //        LR         operator/(L, R);
8422   //        LR         operator+(L, R);
8423   //        LR         operator-(L, R);
8424   //        bool       operator<(L, R);
8425   //        bool       operator>(L, R);
8426   //        bool       operator<=(L, R);
8427   //        bool       operator>=(L, R);
8428   //        bool       operator==(L, R);
8429   //        bool       operator!=(L, R);
8430   //
8431   //   where LR is the result of the usual arithmetic conversions
8432   //   between types L and R.
8433   //
8434   // C++ [over.built]p24:
8435   //
8436   //   For every pair of promoted arithmetic types L and R, there exist
8437   //   candidate operator functions of the form
8438   //
8439   //        LR       operator?(bool, L, R);
8440   //
8441   //   where LR is the result of the usual arithmetic conversions
8442   //   between types L and R.
8443   // Our candidates ignore the first parameter.
8444   void addGenericBinaryArithmeticOverloads() {
8445     if (!HasArithmeticOrEnumeralCandidateType)
8446       return;
8447 
8448     for (unsigned Left = FirstPromotedArithmeticType;
8449          Left < LastPromotedArithmeticType; ++Left) {
8450       for (unsigned Right = FirstPromotedArithmeticType;
8451            Right < LastPromotedArithmeticType; ++Right) {
8452         QualType LandR[2] = { ArithmeticTypes[Left],
8453                               ArithmeticTypes[Right] };
8454         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8455       }
8456     }
8457 
8458     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8459     // conditional operator for vector types.
8460     for (BuiltinCandidateTypeSet::iterator
8461               Vec1 = CandidateTypes[0].vector_begin(),
8462            Vec1End = CandidateTypes[0].vector_end();
8463          Vec1 != Vec1End; ++Vec1) {
8464       for (BuiltinCandidateTypeSet::iterator
8465                 Vec2 = CandidateTypes[1].vector_begin(),
8466              Vec2End = CandidateTypes[1].vector_end();
8467            Vec2 != Vec2End; ++Vec2) {
8468         QualType LandR[2] = { *Vec1, *Vec2 };
8469         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8470       }
8471     }
8472   }
8473 
8474   // C++2a [over.built]p14:
8475   //
8476   //   For every integral type T there exists a candidate operator function
8477   //   of the form
8478   //
8479   //        std::strong_ordering operator<=>(T, T)
8480   //
8481   // C++2a [over.built]p15:
8482   //
8483   //   For every pair of floating-point types L and R, there exists a candidate
8484   //   operator function of the form
8485   //
8486   //       std::partial_ordering operator<=>(L, R);
8487   //
8488   // FIXME: The current specification for integral types doesn't play nice with
8489   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8490   // comparisons. Under the current spec this can lead to ambiguity during
8491   // overload resolution. For example:
8492   //
8493   //   enum A : int {a};
8494   //   auto x = (a <=> (long)42);
8495   //
8496   //   error: call is ambiguous for arguments 'A' and 'long'.
8497   //   note: candidate operator<=>(int, int)
8498   //   note: candidate operator<=>(long, long)
8499   //
8500   // To avoid this error, this function deviates from the specification and adds
8501   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8502   // arithmetic types (the same as the generic relational overloads).
8503   //
8504   // For now this function acts as a placeholder.
8505   void addThreeWayArithmeticOverloads() {
8506     addGenericBinaryArithmeticOverloads();
8507   }
8508 
8509   // C++ [over.built]p17:
8510   //
8511   //   For every pair of promoted integral types L and R, there
8512   //   exist candidate operator functions of the form
8513   //
8514   //      LR         operator%(L, R);
8515   //      LR         operator&(L, R);
8516   //      LR         operator^(L, R);
8517   //      LR         operator|(L, R);
8518   //      L          operator<<(L, R);
8519   //      L          operator>>(L, R);
8520   //
8521   //   where LR is the result of the usual arithmetic conversions
8522   //   between types L and R.
8523   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8524     if (!HasArithmeticOrEnumeralCandidateType)
8525       return;
8526 
8527     for (unsigned Left = FirstPromotedIntegralType;
8528          Left < LastPromotedIntegralType; ++Left) {
8529       for (unsigned Right = FirstPromotedIntegralType;
8530            Right < LastPromotedIntegralType; ++Right) {
8531         QualType LandR[2] = { ArithmeticTypes[Left],
8532                               ArithmeticTypes[Right] };
8533         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8534       }
8535     }
8536   }
8537 
8538   // C++ [over.built]p20:
8539   //
8540   //   For every pair (T, VQ), where T is an enumeration or
8541   //   pointer to member type and VQ is either volatile or
8542   //   empty, there exist candidate operator functions of the form
8543   //
8544   //        VQ T&      operator=(VQ T&, T);
8545   void addAssignmentMemberPointerOrEnumeralOverloads() {
8546     /// Set of (canonical) types that we've already handled.
8547     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8548 
8549     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8550       for (BuiltinCandidateTypeSet::iterator
8551                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8552              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8553            Enum != EnumEnd; ++Enum) {
8554         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8555           continue;
8556 
8557         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8558       }
8559 
8560       for (BuiltinCandidateTypeSet::iterator
8561                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8562              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8563            MemPtr != MemPtrEnd; ++MemPtr) {
8564         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8565           continue;
8566 
8567         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8568       }
8569     }
8570   }
8571 
8572   // C++ [over.built]p19:
8573   //
8574   //   For every pair (T, VQ), where T is any type and VQ is either
8575   //   volatile or empty, there exist candidate operator functions
8576   //   of the form
8577   //
8578   //        T*VQ&      operator=(T*VQ&, T*);
8579   //
8580   // C++ [over.built]p21:
8581   //
8582   //   For every pair (T, VQ), where T is a cv-qualified or
8583   //   cv-unqualified object type and VQ is either volatile or
8584   //   empty, there exist candidate operator functions of the form
8585   //
8586   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8587   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8588   void addAssignmentPointerOverloads(bool isEqualOp) {
8589     /// Set of (canonical) types that we've already handled.
8590     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8591 
8592     for (BuiltinCandidateTypeSet::iterator
8593               Ptr = CandidateTypes[0].pointer_begin(),
8594            PtrEnd = CandidateTypes[0].pointer_end();
8595          Ptr != PtrEnd; ++Ptr) {
8596       // If this is operator=, keep track of the builtin candidates we added.
8597       if (isEqualOp)
8598         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8599       else if (!(*Ptr)->getPointeeType()->isObjectType())
8600         continue;
8601 
8602       // non-volatile version
8603       QualType ParamTypes[2] = {
8604         S.Context.getLValueReferenceType(*Ptr),
8605         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8606       };
8607       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8608                             /*IsAssignmentOperator=*/ isEqualOp);
8609 
8610       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8611                           VisibleTypeConversionsQuals.hasVolatile();
8612       if (NeedVolatile) {
8613         // volatile version
8614         ParamTypes[0] =
8615           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8616         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8617                               /*IsAssignmentOperator=*/isEqualOp);
8618       }
8619 
8620       if (!(*Ptr).isRestrictQualified() &&
8621           VisibleTypeConversionsQuals.hasRestrict()) {
8622         // restrict version
8623         ParamTypes[0]
8624           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8625         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8626                               /*IsAssignmentOperator=*/isEqualOp);
8627 
8628         if (NeedVolatile) {
8629           // volatile restrict version
8630           ParamTypes[0]
8631             = S.Context.getLValueReferenceType(
8632                 S.Context.getCVRQualifiedType(*Ptr,
8633                                               (Qualifiers::Volatile |
8634                                                Qualifiers::Restrict)));
8635           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8636                                 /*IsAssignmentOperator=*/isEqualOp);
8637         }
8638       }
8639     }
8640 
8641     if (isEqualOp) {
8642       for (BuiltinCandidateTypeSet::iterator
8643                 Ptr = CandidateTypes[1].pointer_begin(),
8644              PtrEnd = CandidateTypes[1].pointer_end();
8645            Ptr != PtrEnd; ++Ptr) {
8646         // Make sure we don't add the same candidate twice.
8647         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8648           continue;
8649 
8650         QualType ParamTypes[2] = {
8651           S.Context.getLValueReferenceType(*Ptr),
8652           *Ptr,
8653         };
8654 
8655         // non-volatile version
8656         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8657                               /*IsAssignmentOperator=*/true);
8658 
8659         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8660                            VisibleTypeConversionsQuals.hasVolatile();
8661         if (NeedVolatile) {
8662           // volatile version
8663           ParamTypes[0] =
8664             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8665           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8666                                 /*IsAssignmentOperator=*/true);
8667         }
8668 
8669         if (!(*Ptr).isRestrictQualified() &&
8670             VisibleTypeConversionsQuals.hasRestrict()) {
8671           // restrict version
8672           ParamTypes[0]
8673             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8674           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8675                                 /*IsAssignmentOperator=*/true);
8676 
8677           if (NeedVolatile) {
8678             // volatile restrict version
8679             ParamTypes[0]
8680               = S.Context.getLValueReferenceType(
8681                   S.Context.getCVRQualifiedType(*Ptr,
8682                                                 (Qualifiers::Volatile |
8683                                                  Qualifiers::Restrict)));
8684             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8685                                   /*IsAssignmentOperator=*/true);
8686           }
8687         }
8688       }
8689     }
8690   }
8691 
8692   // C++ [over.built]p18:
8693   //
8694   //   For every triple (L, VQ, R), where L is an arithmetic type,
8695   //   VQ is either volatile or empty, and R is a promoted
8696   //   arithmetic type, there exist candidate operator functions of
8697   //   the form
8698   //
8699   //        VQ L&      operator=(VQ L&, R);
8700   //        VQ L&      operator*=(VQ L&, R);
8701   //        VQ L&      operator/=(VQ L&, R);
8702   //        VQ L&      operator+=(VQ L&, R);
8703   //        VQ L&      operator-=(VQ L&, R);
8704   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8705     if (!HasArithmeticOrEnumeralCandidateType)
8706       return;
8707 
8708     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8709       for (unsigned Right = FirstPromotedArithmeticType;
8710            Right < LastPromotedArithmeticType; ++Right) {
8711         QualType ParamTypes[2];
8712         ParamTypes[1] = ArithmeticTypes[Right];
8713         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8714             S, ArithmeticTypes[Left], Args[0]);
8715         // Add this built-in operator as a candidate (VQ is empty).
8716         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8717         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8718                               /*IsAssignmentOperator=*/isEqualOp);
8719 
8720         // Add this built-in operator as a candidate (VQ is 'volatile').
8721         if (VisibleTypeConversionsQuals.hasVolatile()) {
8722           ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy);
8723           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8724           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8725                                 /*IsAssignmentOperator=*/isEqualOp);
8726         }
8727       }
8728     }
8729 
8730     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8731     for (BuiltinCandidateTypeSet::iterator
8732               Vec1 = CandidateTypes[0].vector_begin(),
8733            Vec1End = CandidateTypes[0].vector_end();
8734          Vec1 != Vec1End; ++Vec1) {
8735       for (BuiltinCandidateTypeSet::iterator
8736                 Vec2 = CandidateTypes[1].vector_begin(),
8737              Vec2End = CandidateTypes[1].vector_end();
8738            Vec2 != Vec2End; ++Vec2) {
8739         QualType ParamTypes[2];
8740         ParamTypes[1] = *Vec2;
8741         // Add this built-in operator as a candidate (VQ is empty).
8742         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8743         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8744                               /*IsAssignmentOperator=*/isEqualOp);
8745 
8746         // Add this built-in operator as a candidate (VQ is 'volatile').
8747         if (VisibleTypeConversionsQuals.hasVolatile()) {
8748           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8749           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8750           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8751                                 /*IsAssignmentOperator=*/isEqualOp);
8752         }
8753       }
8754     }
8755   }
8756 
8757   // C++ [over.built]p22:
8758   //
8759   //   For every triple (L, VQ, R), where L is an integral type, VQ
8760   //   is either volatile or empty, and R is a promoted integral
8761   //   type, there exist candidate operator functions of the form
8762   //
8763   //        VQ L&       operator%=(VQ L&, R);
8764   //        VQ L&       operator<<=(VQ L&, R);
8765   //        VQ L&       operator>>=(VQ L&, R);
8766   //        VQ L&       operator&=(VQ L&, R);
8767   //        VQ L&       operator^=(VQ L&, R);
8768   //        VQ L&       operator|=(VQ L&, R);
8769   void addAssignmentIntegralOverloads() {
8770     if (!HasArithmeticOrEnumeralCandidateType)
8771       return;
8772 
8773     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8774       for (unsigned Right = FirstPromotedIntegralType;
8775            Right < LastPromotedIntegralType; ++Right) {
8776         QualType ParamTypes[2];
8777         ParamTypes[1] = ArithmeticTypes[Right];
8778         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8779             S, ArithmeticTypes[Left], Args[0]);
8780         // Add this built-in operator as a candidate (VQ is empty).
8781         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8782         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8783         if (VisibleTypeConversionsQuals.hasVolatile()) {
8784           // Add this built-in operator as a candidate (VQ is 'volatile').
8785           ParamTypes[0] = LeftBaseTy;
8786           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8787           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8788           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8789         }
8790       }
8791     }
8792   }
8793 
8794   // C++ [over.operator]p23:
8795   //
8796   //   There also exist candidate operator functions of the form
8797   //
8798   //        bool        operator!(bool);
8799   //        bool        operator&&(bool, bool);
8800   //        bool        operator||(bool, bool);
8801   void addExclaimOverload() {
8802     QualType ParamTy = S.Context.BoolTy;
8803     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8804                           /*IsAssignmentOperator=*/false,
8805                           /*NumContextualBoolArguments=*/1);
8806   }
8807   void addAmpAmpOrPipePipeOverload() {
8808     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8809     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8810                           /*IsAssignmentOperator=*/false,
8811                           /*NumContextualBoolArguments=*/2);
8812   }
8813 
8814   // C++ [over.built]p13:
8815   //
8816   //   For every cv-qualified or cv-unqualified object type T there
8817   //   exist candidate operator functions of the form
8818   //
8819   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8820   //        T&         operator[](T*, ptrdiff_t);
8821   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8822   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8823   //        T&         operator[](ptrdiff_t, T*);
8824   void addSubscriptOverloads() {
8825     for (BuiltinCandidateTypeSet::iterator
8826               Ptr = CandidateTypes[0].pointer_begin(),
8827            PtrEnd = CandidateTypes[0].pointer_end();
8828          Ptr != PtrEnd; ++Ptr) {
8829       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8830       QualType PointeeType = (*Ptr)->getPointeeType();
8831       if (!PointeeType->isObjectType())
8832         continue;
8833 
8834       // T& operator[](T*, ptrdiff_t)
8835       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8836     }
8837 
8838     for (BuiltinCandidateTypeSet::iterator
8839               Ptr = CandidateTypes[1].pointer_begin(),
8840            PtrEnd = CandidateTypes[1].pointer_end();
8841          Ptr != PtrEnd; ++Ptr) {
8842       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8843       QualType PointeeType = (*Ptr)->getPointeeType();
8844       if (!PointeeType->isObjectType())
8845         continue;
8846 
8847       // T& operator[](ptrdiff_t, T*)
8848       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8849     }
8850   }
8851 
8852   // C++ [over.built]p11:
8853   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8854   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8855   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8856   //    there exist candidate operator functions of the form
8857   //
8858   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8859   //
8860   //    where CV12 is the union of CV1 and CV2.
8861   void addArrowStarOverloads() {
8862     for (BuiltinCandidateTypeSet::iterator
8863              Ptr = CandidateTypes[0].pointer_begin(),
8864            PtrEnd = CandidateTypes[0].pointer_end();
8865          Ptr != PtrEnd; ++Ptr) {
8866       QualType C1Ty = (*Ptr);
8867       QualType C1;
8868       QualifierCollector Q1;
8869       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8870       if (!isa<RecordType>(C1))
8871         continue;
8872       // heuristic to reduce number of builtin candidates in the set.
8873       // Add volatile/restrict version only if there are conversions to a
8874       // volatile/restrict type.
8875       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8876         continue;
8877       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8878         continue;
8879       for (BuiltinCandidateTypeSet::iterator
8880                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8881              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8882            MemPtr != MemPtrEnd; ++MemPtr) {
8883         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8884         QualType C2 = QualType(mptr->getClass(), 0);
8885         C2 = C2.getUnqualifiedType();
8886         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8887           break;
8888         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8889         // build CV12 T&
8890         QualType T = mptr->getPointeeType();
8891         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8892             T.isVolatileQualified())
8893           continue;
8894         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8895             T.isRestrictQualified())
8896           continue;
8897         T = Q1.apply(S.Context, T);
8898         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8899       }
8900     }
8901   }
8902 
8903   // Note that we don't consider the first argument, since it has been
8904   // contextually converted to bool long ago. The candidates below are
8905   // therefore added as binary.
8906   //
8907   // C++ [over.built]p25:
8908   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8909   //   enumeration type, there exist candidate operator functions of the form
8910   //
8911   //        T        operator?(bool, T, T);
8912   //
8913   void addConditionalOperatorOverloads() {
8914     /// Set of (canonical) types that we've already handled.
8915     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8916 
8917     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8918       for (BuiltinCandidateTypeSet::iterator
8919                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8920              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8921            Ptr != PtrEnd; ++Ptr) {
8922         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8923           continue;
8924 
8925         QualType ParamTypes[2] = { *Ptr, *Ptr };
8926         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8927       }
8928 
8929       for (BuiltinCandidateTypeSet::iterator
8930                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8931              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8932            MemPtr != MemPtrEnd; ++MemPtr) {
8933         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8934           continue;
8935 
8936         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8937         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8938       }
8939 
8940       if (S.getLangOpts().CPlusPlus11) {
8941         for (BuiltinCandidateTypeSet::iterator
8942                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8943                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8944              Enum != EnumEnd; ++Enum) {
8945           if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped())
8946             continue;
8947 
8948           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8949             continue;
8950 
8951           QualType ParamTypes[2] = { *Enum, *Enum };
8952           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8953         }
8954       }
8955     }
8956   }
8957 };
8958 
8959 } // end anonymous namespace
8960 
8961 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8962 /// operator overloads to the candidate set (C++ [over.built]), based
8963 /// on the operator @p Op and the arguments given. For example, if the
8964 /// operator is a binary '+', this routine might add "int
8965 /// operator+(int, int)" to cover integer addition.
8966 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8967                                         SourceLocation OpLoc,
8968                                         ArrayRef<Expr *> Args,
8969                                         OverloadCandidateSet &CandidateSet) {
8970   // Find all of the types that the arguments can convert to, but only
8971   // if the operator we're looking at has built-in operator candidates
8972   // that make use of these types. Also record whether we encounter non-record
8973   // candidate types or either arithmetic or enumeral candidate types.
8974   Qualifiers VisibleTypeConversionsQuals;
8975   VisibleTypeConversionsQuals.addConst();
8976   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8977     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8978 
8979   bool HasNonRecordCandidateType = false;
8980   bool HasArithmeticOrEnumeralCandidateType = false;
8981   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8982   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8983     CandidateTypes.emplace_back(*this);
8984     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8985                                                  OpLoc,
8986                                                  true,
8987                                                  (Op == OO_Exclaim ||
8988                                                   Op == OO_AmpAmp ||
8989                                                   Op == OO_PipePipe),
8990                                                  VisibleTypeConversionsQuals);
8991     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8992         CandidateTypes[ArgIdx].hasNonRecordTypes();
8993     HasArithmeticOrEnumeralCandidateType =
8994         HasArithmeticOrEnumeralCandidateType ||
8995         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8996   }
8997 
8998   // Exit early when no non-record types have been added to the candidate set
8999   // for any of the arguments to the operator.
9000   //
9001   // We can't exit early for !, ||, or &&, since there we have always have
9002   // 'bool' overloads.
9003   if (!HasNonRecordCandidateType &&
9004       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9005     return;
9006 
9007   // Setup an object to manage the common state for building overloads.
9008   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9009                                            VisibleTypeConversionsQuals,
9010                                            HasArithmeticOrEnumeralCandidateType,
9011                                            CandidateTypes, CandidateSet);
9012 
9013   // Dispatch over the operation to add in only those overloads which apply.
9014   switch (Op) {
9015   case OO_None:
9016   case NUM_OVERLOADED_OPERATORS:
9017     llvm_unreachable("Expected an overloaded operator");
9018 
9019   case OO_New:
9020   case OO_Delete:
9021   case OO_Array_New:
9022   case OO_Array_Delete:
9023   case OO_Call:
9024     llvm_unreachable(
9025                     "Special operators don't use AddBuiltinOperatorCandidates");
9026 
9027   case OO_Comma:
9028   case OO_Arrow:
9029   case OO_Coawait:
9030     // C++ [over.match.oper]p3:
9031     //   -- For the operator ',', the unary operator '&', the
9032     //      operator '->', or the operator 'co_await', the
9033     //      built-in candidates set is empty.
9034     break;
9035 
9036   case OO_Plus: // '+' is either unary or binary
9037     if (Args.size() == 1)
9038       OpBuilder.addUnaryPlusPointerOverloads();
9039     LLVM_FALLTHROUGH;
9040 
9041   case OO_Minus: // '-' is either unary or binary
9042     if (Args.size() == 1) {
9043       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9044     } else {
9045       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9046       OpBuilder.addGenericBinaryArithmeticOverloads();
9047     }
9048     break;
9049 
9050   case OO_Star: // '*' is either unary or binary
9051     if (Args.size() == 1)
9052       OpBuilder.addUnaryStarPointerOverloads();
9053     else
9054       OpBuilder.addGenericBinaryArithmeticOverloads();
9055     break;
9056 
9057   case OO_Slash:
9058     OpBuilder.addGenericBinaryArithmeticOverloads();
9059     break;
9060 
9061   case OO_PlusPlus:
9062   case OO_MinusMinus:
9063     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9064     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9065     break;
9066 
9067   case OO_EqualEqual:
9068   case OO_ExclaimEqual:
9069     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9070     LLVM_FALLTHROUGH;
9071 
9072   case OO_Less:
9073   case OO_Greater:
9074   case OO_LessEqual:
9075   case OO_GreaterEqual:
9076     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9077     OpBuilder.addGenericBinaryArithmeticOverloads();
9078     break;
9079 
9080   case OO_Spaceship:
9081     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9082     OpBuilder.addThreeWayArithmeticOverloads();
9083     break;
9084 
9085   case OO_Percent:
9086   case OO_Caret:
9087   case OO_Pipe:
9088   case OO_LessLess:
9089   case OO_GreaterGreater:
9090     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9091     break;
9092 
9093   case OO_Amp: // '&' is either unary or binary
9094     if (Args.size() == 1)
9095       // C++ [over.match.oper]p3:
9096       //   -- For the operator ',', the unary operator '&', or the
9097       //      operator '->', the built-in candidates set is empty.
9098       break;
9099 
9100     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9101     break;
9102 
9103   case OO_Tilde:
9104     OpBuilder.addUnaryTildePromotedIntegralOverloads();
9105     break;
9106 
9107   case OO_Equal:
9108     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9109     LLVM_FALLTHROUGH;
9110 
9111   case OO_PlusEqual:
9112   case OO_MinusEqual:
9113     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9114     LLVM_FALLTHROUGH;
9115 
9116   case OO_StarEqual:
9117   case OO_SlashEqual:
9118     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9119     break;
9120 
9121   case OO_PercentEqual:
9122   case OO_LessLessEqual:
9123   case OO_GreaterGreaterEqual:
9124   case OO_AmpEqual:
9125   case OO_CaretEqual:
9126   case OO_PipeEqual:
9127     OpBuilder.addAssignmentIntegralOverloads();
9128     break;
9129 
9130   case OO_Exclaim:
9131     OpBuilder.addExclaimOverload();
9132     break;
9133 
9134   case OO_AmpAmp:
9135   case OO_PipePipe:
9136     OpBuilder.addAmpAmpOrPipePipeOverload();
9137     break;
9138 
9139   case OO_Subscript:
9140     OpBuilder.addSubscriptOverloads();
9141     break;
9142 
9143   case OO_ArrowStar:
9144     OpBuilder.addArrowStarOverloads();
9145     break;
9146 
9147   case OO_Conditional:
9148     OpBuilder.addConditionalOperatorOverloads();
9149     OpBuilder.addGenericBinaryArithmeticOverloads();
9150     break;
9151   }
9152 }
9153 
9154 /// Add function candidates found via argument-dependent lookup
9155 /// to the set of overloading candidates.
9156 ///
9157 /// This routine performs argument-dependent name lookup based on the
9158 /// given function name (which may also be an operator name) and adds
9159 /// all of the overload candidates found by ADL to the overload
9160 /// candidate set (C++ [basic.lookup.argdep]).
9161 void
9162 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9163                                            SourceLocation Loc,
9164                                            ArrayRef<Expr *> Args,
9165                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
9166                                            OverloadCandidateSet& CandidateSet,
9167                                            bool PartialOverloading) {
9168   ADLResult Fns;
9169 
9170   // FIXME: This approach for uniquing ADL results (and removing
9171   // redundant candidates from the set) relies on pointer-equality,
9172   // which means we need to key off the canonical decl.  However,
9173   // always going back to the canonical decl might not get us the
9174   // right set of default arguments.  What default arguments are
9175   // we supposed to consider on ADL candidates, anyway?
9176 
9177   // FIXME: Pass in the explicit template arguments?
9178   ArgumentDependentLookup(Name, Loc, Args, Fns);
9179 
9180   // Erase all of the candidates we already knew about.
9181   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9182                                    CandEnd = CandidateSet.end();
9183        Cand != CandEnd; ++Cand)
9184     if (Cand->Function) {
9185       Fns.erase(Cand->Function);
9186       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9187         Fns.erase(FunTmpl);
9188     }
9189 
9190   // For each of the ADL candidates we found, add it to the overload
9191   // set.
9192   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9193     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9194 
9195     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9196       if (ExplicitTemplateArgs)
9197         continue;
9198 
9199       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet,
9200                            /*SuppressUserConversions=*/false, PartialOverloading,
9201                            /*AllowExplicit*/ true,
9202                            /*AllowExplicitConversions*/ false,
9203                            ADLCallKind::UsesADL);
9204     } else {
9205       AddTemplateOverloadCandidate(
9206           cast<FunctionTemplateDecl>(*I), FoundDecl, ExplicitTemplateArgs, Args,
9207           CandidateSet,
9208           /*SuppressUserConversions=*/false, PartialOverloading,
9209           /*AllowExplicit*/true, ADLCallKind::UsesADL);
9210     }
9211   }
9212 }
9213 
9214 namespace {
9215 enum class Comparison { Equal, Better, Worse };
9216 }
9217 
9218 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9219 /// overload resolution.
9220 ///
9221 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9222 /// Cand1's first N enable_if attributes have precisely the same conditions as
9223 /// Cand2's first N enable_if attributes (where N = the number of enable_if
9224 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9225 ///
9226 /// Note that you can have a pair of candidates such that Cand1's enable_if
9227 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9228 /// worse than Cand1's.
9229 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9230                                        const FunctionDecl *Cand2) {
9231   // Common case: One (or both) decls don't have enable_if attrs.
9232   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9233   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9234   if (!Cand1Attr || !Cand2Attr) {
9235     if (Cand1Attr == Cand2Attr)
9236       return Comparison::Equal;
9237     return Cand1Attr ? Comparison::Better : Comparison::Worse;
9238   }
9239 
9240   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9241   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9242 
9243   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9244   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9245     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9246     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9247 
9248     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9249     // has fewer enable_if attributes than Cand2, and vice versa.
9250     if (!Cand1A)
9251       return Comparison::Worse;
9252     if (!Cand2A)
9253       return Comparison::Better;
9254 
9255     Cand1ID.clear();
9256     Cand2ID.clear();
9257 
9258     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9259     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9260     if (Cand1ID != Cand2ID)
9261       return Comparison::Worse;
9262   }
9263 
9264   return Comparison::Equal;
9265 }
9266 
9267 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9268                                           const OverloadCandidate &Cand2) {
9269   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9270       !Cand2.Function->isMultiVersion())
9271     return false;
9272 
9273   // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this
9274   // is obviously better.
9275   if (Cand1.Function->isInvalidDecl()) return false;
9276   if (Cand2.Function->isInvalidDecl()) return true;
9277 
9278   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9279   // cpu_dispatch, else arbitrarily based on the identifiers.
9280   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9281   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9282   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9283   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9284 
9285   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9286     return false;
9287 
9288   if (Cand1CPUDisp && !Cand2CPUDisp)
9289     return true;
9290   if (Cand2CPUDisp && !Cand1CPUDisp)
9291     return false;
9292 
9293   if (Cand1CPUSpec && Cand2CPUSpec) {
9294     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9295       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size();
9296 
9297     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9298         FirstDiff = std::mismatch(
9299             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9300             Cand2CPUSpec->cpus_begin(),
9301             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9302               return LHS->getName() == RHS->getName();
9303             });
9304 
9305     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9306            "Two different cpu-specific versions should not have the same "
9307            "identifier list, otherwise they'd be the same decl!");
9308     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName();
9309   }
9310   llvm_unreachable("No way to get here unless both had cpu_dispatch");
9311 }
9312 
9313 /// isBetterOverloadCandidate - Determines whether the first overload
9314 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9315 bool clang::isBetterOverloadCandidate(
9316     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9317     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9318   // Define viable functions to be better candidates than non-viable
9319   // functions.
9320   if (!Cand2.Viable)
9321     return Cand1.Viable;
9322   else if (!Cand1.Viable)
9323     return false;
9324 
9325   // C++ [over.match.best]p1:
9326   //
9327   //   -- if F is a static member function, ICS1(F) is defined such
9328   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9329   //      any function G, and, symmetrically, ICS1(G) is neither
9330   //      better nor worse than ICS1(F).
9331   unsigned StartArg = 0;
9332   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9333     StartArg = 1;
9334 
9335   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9336     // We don't allow incompatible pointer conversions in C++.
9337     if (!S.getLangOpts().CPlusPlus)
9338       return ICS.isStandard() &&
9339              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9340 
9341     // The only ill-formed conversion we allow in C++ is the string literal to
9342     // char* conversion, which is only considered ill-formed after C++11.
9343     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9344            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9345   };
9346 
9347   // Define functions that don't require ill-formed conversions for a given
9348   // argument to be better candidates than functions that do.
9349   unsigned NumArgs = Cand1.Conversions.size();
9350   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9351   bool HasBetterConversion = false;
9352   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9353     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9354     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9355     if (Cand1Bad != Cand2Bad) {
9356       if (Cand1Bad)
9357         return false;
9358       HasBetterConversion = true;
9359     }
9360   }
9361 
9362   if (HasBetterConversion)
9363     return true;
9364 
9365   // C++ [over.match.best]p1:
9366   //   A viable function F1 is defined to be a better function than another
9367   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9368   //   conversion sequence than ICSi(F2), and then...
9369   bool HasWorseConversion = false;
9370   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9371     switch (CompareImplicitConversionSequences(S, Loc,
9372                                                Cand1.Conversions[ArgIdx],
9373                                                Cand2.Conversions[ArgIdx])) {
9374     case ImplicitConversionSequence::Better:
9375       // Cand1 has a better conversion sequence.
9376       HasBetterConversion = true;
9377       break;
9378 
9379     case ImplicitConversionSequence::Worse:
9380       if (Cand1.Function && Cand1.Function == Cand2.Function &&
9381           (Cand2.RewriteKind & CRK_Reversed) != 0) {
9382         // Work around large-scale breakage caused by considering reversed
9383         // forms of operator== in C++20:
9384         //
9385         // When comparing a function against its reversed form, if we have a
9386         // better conversion for one argument and a worse conversion for the
9387         // other, we prefer the non-reversed form.
9388         //
9389         // This prevents a conversion function from being considered ambiguous
9390         // with its own reversed form in various where it's only incidentally
9391         // heterogeneous.
9392         //
9393         // We diagnose this as an extension from CreateOverloadedBinOp.
9394         HasWorseConversion = true;
9395         break;
9396       }
9397 
9398       // Cand1 can't be better than Cand2.
9399       return false;
9400 
9401     case ImplicitConversionSequence::Indistinguishable:
9402       // Do nothing.
9403       break;
9404     }
9405   }
9406 
9407   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9408   //       ICSj(F2), or, if not that,
9409   if (HasBetterConversion)
9410     return true;
9411   if (HasWorseConversion)
9412     return false;
9413 
9414   //   -- the context is an initialization by user-defined conversion
9415   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9416   //      from the return type of F1 to the destination type (i.e.,
9417   //      the type of the entity being initialized) is a better
9418   //      conversion sequence than the standard conversion sequence
9419   //      from the return type of F2 to the destination type.
9420   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9421       Cand1.Function && Cand2.Function &&
9422       isa<CXXConversionDecl>(Cand1.Function) &&
9423       isa<CXXConversionDecl>(Cand2.Function)) {
9424     // First check whether we prefer one of the conversion functions over the
9425     // other. This only distinguishes the results in non-standard, extension
9426     // cases such as the conversion from a lambda closure type to a function
9427     // pointer or block.
9428     ImplicitConversionSequence::CompareKind Result =
9429         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9430     if (Result == ImplicitConversionSequence::Indistinguishable)
9431       Result = CompareStandardConversionSequences(S, Loc,
9432                                                   Cand1.FinalConversion,
9433                                                   Cand2.FinalConversion);
9434 
9435     if (Result != ImplicitConversionSequence::Indistinguishable)
9436       return Result == ImplicitConversionSequence::Better;
9437 
9438     // FIXME: Compare kind of reference binding if conversion functions
9439     // convert to a reference type used in direct reference binding, per
9440     // C++14 [over.match.best]p1 section 2 bullet 3.
9441   }
9442 
9443   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9444   // as combined with the resolution to CWG issue 243.
9445   //
9446   // When the context is initialization by constructor ([over.match.ctor] or
9447   // either phase of [over.match.list]), a constructor is preferred over
9448   // a conversion function.
9449   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9450       Cand1.Function && Cand2.Function &&
9451       isa<CXXConstructorDecl>(Cand1.Function) !=
9452           isa<CXXConstructorDecl>(Cand2.Function))
9453     return isa<CXXConstructorDecl>(Cand1.Function);
9454 
9455   //    -- F1 is a non-template function and F2 is a function template
9456   //       specialization, or, if not that,
9457   bool Cand1IsSpecialization = Cand1.Function &&
9458                                Cand1.Function->getPrimaryTemplate();
9459   bool Cand2IsSpecialization = Cand2.Function &&
9460                                Cand2.Function->getPrimaryTemplate();
9461   if (Cand1IsSpecialization != Cand2IsSpecialization)
9462     return Cand2IsSpecialization;
9463 
9464   //   -- F1 and F2 are function template specializations, and the function
9465   //      template for F1 is more specialized than the template for F2
9466   //      according to the partial ordering rules described in 14.5.5.2, or,
9467   //      if not that,
9468   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9469     if (FunctionTemplateDecl *BetterTemplate
9470           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9471                                          Cand2.Function->getPrimaryTemplate(),
9472                                          Loc,
9473                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9474                                                              : TPOC_Call,
9475                                          Cand1.ExplicitCallArguments,
9476                                          Cand2.ExplicitCallArguments))
9477       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9478   }
9479 
9480   //   -- F1 is a constructor for a class D, F2 is a constructor for a base
9481   //      class B of D, and for all arguments the corresponding parameters of
9482   //      F1 and F2 have the same type.
9483   // FIXME: Implement the "all parameters have the same type" check.
9484   bool Cand1IsInherited =
9485       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9486   bool Cand2IsInherited =
9487       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9488   if (Cand1IsInherited != Cand2IsInherited)
9489     return Cand2IsInherited;
9490   else if (Cand1IsInherited) {
9491     assert(Cand2IsInherited);
9492     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9493     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9494     if (Cand1Class->isDerivedFrom(Cand2Class))
9495       return true;
9496     if (Cand2Class->isDerivedFrom(Cand1Class))
9497       return false;
9498     // Inherited from sibling base classes: still ambiguous.
9499   }
9500 
9501   //   -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
9502   //   -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
9503   //      with reversed order of parameters and F1 is not
9504   //
9505   // We rank reversed + different operator as worse than just reversed, but
9506   // that comparison can never happen, because we only consider reversing for
9507   // the maximally-rewritten operator (== or <=>).
9508   if (Cand1.RewriteKind != Cand2.RewriteKind)
9509     return Cand1.RewriteKind < Cand2.RewriteKind;
9510 
9511   // Check C++17 tie-breakers for deduction guides.
9512   {
9513     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9514     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9515     if (Guide1 && Guide2) {
9516       //  -- F1 is generated from a deduction-guide and F2 is not
9517       if (Guide1->isImplicit() != Guide2->isImplicit())
9518         return Guide2->isImplicit();
9519 
9520       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9521       if (Guide1->isCopyDeductionCandidate())
9522         return true;
9523     }
9524   }
9525 
9526   // Check for enable_if value-based overload resolution.
9527   if (Cand1.Function && Cand2.Function) {
9528     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9529     if (Cmp != Comparison::Equal)
9530       return Cmp == Comparison::Better;
9531   }
9532 
9533   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9534     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9535     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9536            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9537   }
9538 
9539   bool HasPS1 = Cand1.Function != nullptr &&
9540                 functionHasPassObjectSizeParams(Cand1.Function);
9541   bool HasPS2 = Cand2.Function != nullptr &&
9542                 functionHasPassObjectSizeParams(Cand2.Function);
9543   if (HasPS1 != HasPS2 && HasPS1)
9544     return true;
9545 
9546   return isBetterMultiversionCandidate(Cand1, Cand2);
9547 }
9548 
9549 /// Determine whether two declarations are "equivalent" for the purposes of
9550 /// name lookup and overload resolution. This applies when the same internal/no
9551 /// linkage entity is defined by two modules (probably by textually including
9552 /// the same header). In such a case, we don't consider the declarations to
9553 /// declare the same entity, but we also don't want lookups with both
9554 /// declarations visible to be ambiguous in some cases (this happens when using
9555 /// a modularized libstdc++).
9556 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9557                                                   const NamedDecl *B) {
9558   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9559   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9560   if (!VA || !VB)
9561     return false;
9562 
9563   // The declarations must be declaring the same name as an internal linkage
9564   // entity in different modules.
9565   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9566           VB->getDeclContext()->getRedeclContext()) ||
9567       getOwningModule(const_cast<ValueDecl *>(VA)) ==
9568           getOwningModule(const_cast<ValueDecl *>(VB)) ||
9569       VA->isExternallyVisible() || VB->isExternallyVisible())
9570     return false;
9571 
9572   // Check that the declarations appear to be equivalent.
9573   //
9574   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9575   // For constants and functions, we should check the initializer or body is
9576   // the same. For non-constant variables, we shouldn't allow it at all.
9577   if (Context.hasSameType(VA->getType(), VB->getType()))
9578     return true;
9579 
9580   // Enum constants within unnamed enumerations will have different types, but
9581   // may still be similar enough to be interchangeable for our purposes.
9582   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9583     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9584       // Only handle anonymous enums. If the enumerations were named and
9585       // equivalent, they would have been merged to the same type.
9586       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9587       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9588       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9589           !Context.hasSameType(EnumA->getIntegerType(),
9590                                EnumB->getIntegerType()))
9591         return false;
9592       // Allow this only if the value is the same for both enumerators.
9593       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9594     }
9595   }
9596 
9597   // Nothing else is sufficiently similar.
9598   return false;
9599 }
9600 
9601 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9602     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9603   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9604 
9605   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9606   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9607       << !M << (M ? M->getFullModuleName() : "");
9608 
9609   for (auto *E : Equiv) {
9610     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9611     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9612         << !M << (M ? M->getFullModuleName() : "");
9613   }
9614 }
9615 
9616 /// Computes the best viable function (C++ 13.3.3)
9617 /// within an overload candidate set.
9618 ///
9619 /// \param Loc The location of the function name (or operator symbol) for
9620 /// which overload resolution occurs.
9621 ///
9622 /// \param Best If overload resolution was successful or found a deleted
9623 /// function, \p Best points to the candidate function found.
9624 ///
9625 /// \returns The result of overload resolution.
9626 OverloadingResult
9627 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9628                                          iterator &Best) {
9629   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9630   std::transform(begin(), end(), std::back_inserter(Candidates),
9631                  [](OverloadCandidate &Cand) { return &Cand; });
9632 
9633   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9634   // are accepted by both clang and NVCC. However, during a particular
9635   // compilation mode only one call variant is viable. We need to
9636   // exclude non-viable overload candidates from consideration based
9637   // only on their host/device attributes. Specifically, if one
9638   // candidate call is WrongSide and the other is SameSide, we ignore
9639   // the WrongSide candidate.
9640   if (S.getLangOpts().CUDA) {
9641     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9642     bool ContainsSameSideCandidate =
9643         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9644           // Check viable function only.
9645           return Cand->Viable && Cand->Function &&
9646                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9647                      Sema::CFP_SameSide;
9648         });
9649     if (ContainsSameSideCandidate) {
9650       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9651         // Check viable function only to avoid unnecessary data copying/moving.
9652         return Cand->Viable && Cand->Function &&
9653                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9654                    Sema::CFP_WrongSide;
9655       };
9656       llvm::erase_if(Candidates, IsWrongSideCandidate);
9657     }
9658   }
9659 
9660   // Find the best viable function.
9661   Best = end();
9662   for (auto *Cand : Candidates) {
9663     Cand->Best = false;
9664     if (Cand->Viable)
9665       if (Best == end() ||
9666           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9667         Best = Cand;
9668   }
9669 
9670   // If we didn't find any viable functions, abort.
9671   if (Best == end())
9672     return OR_No_Viable_Function;
9673 
9674   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9675 
9676   llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
9677   PendingBest.push_back(&*Best);
9678   Best->Best = true;
9679 
9680   // Make sure that this function is better than every other viable
9681   // function. If not, we have an ambiguity.
9682   while (!PendingBest.empty()) {
9683     auto *Curr = PendingBest.pop_back_val();
9684     for (auto *Cand : Candidates) {
9685       if (Cand->Viable && !Cand->Best &&
9686           !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
9687         PendingBest.push_back(Cand);
9688         Cand->Best = true;
9689 
9690         if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
9691                                                      Curr->Function))
9692           EquivalentCands.push_back(Cand->Function);
9693         else
9694           Best = end();
9695       }
9696     }
9697   }
9698 
9699   // If we found more than one best candidate, this is ambiguous.
9700   if (Best == end())
9701     return OR_Ambiguous;
9702 
9703   // Best is the best viable function.
9704   if (Best->Function && Best->Function->isDeleted())
9705     return OR_Deleted;
9706 
9707   if (!EquivalentCands.empty())
9708     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9709                                                     EquivalentCands);
9710 
9711   return OR_Success;
9712 }
9713 
9714 namespace {
9715 
9716 enum OverloadCandidateKind {
9717   oc_function,
9718   oc_method,
9719   oc_reversed_binary_operator,
9720   oc_constructor,
9721   oc_implicit_default_constructor,
9722   oc_implicit_copy_constructor,
9723   oc_implicit_move_constructor,
9724   oc_implicit_copy_assignment,
9725   oc_implicit_move_assignment,
9726   oc_inherited_constructor
9727 };
9728 
9729 enum OverloadCandidateSelect {
9730   ocs_non_template,
9731   ocs_template,
9732   ocs_described_template,
9733 };
9734 
9735 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
9736 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9737                           OverloadCandidateRewriteKind CRK,
9738                           std::string &Description) {
9739 
9740   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9741   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9742     isTemplate = true;
9743     Description = S.getTemplateArgumentBindingsText(
9744         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9745   }
9746 
9747   OverloadCandidateSelect Select = [&]() {
9748     if (!Description.empty())
9749       return ocs_described_template;
9750     return isTemplate ? ocs_template : ocs_non_template;
9751   }();
9752 
9753   OverloadCandidateKind Kind = [&]() {
9754     if (CRK & CRK_Reversed)
9755       return oc_reversed_binary_operator;
9756 
9757     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9758       if (!Ctor->isImplicit()) {
9759         if (isa<ConstructorUsingShadowDecl>(Found))
9760           return oc_inherited_constructor;
9761         else
9762           return oc_constructor;
9763       }
9764 
9765       if (Ctor->isDefaultConstructor())
9766         return oc_implicit_default_constructor;
9767 
9768       if (Ctor->isMoveConstructor())
9769         return oc_implicit_move_constructor;
9770 
9771       assert(Ctor->isCopyConstructor() &&
9772              "unexpected sort of implicit constructor");
9773       return oc_implicit_copy_constructor;
9774     }
9775 
9776     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9777       // This actually gets spelled 'candidate function' for now, but
9778       // it doesn't hurt to split it out.
9779       if (!Meth->isImplicit())
9780         return oc_method;
9781 
9782       if (Meth->isMoveAssignmentOperator())
9783         return oc_implicit_move_assignment;
9784 
9785       if (Meth->isCopyAssignmentOperator())
9786         return oc_implicit_copy_assignment;
9787 
9788       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9789       return oc_method;
9790     }
9791 
9792     return oc_function;
9793   }();
9794 
9795   return std::make_pair(Kind, Select);
9796 }
9797 
9798 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9799   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9800   // set.
9801   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9802     S.Diag(FoundDecl->getLocation(),
9803            diag::note_ovl_candidate_inherited_constructor)
9804       << Shadow->getNominatedBaseClass();
9805 }
9806 
9807 } // end anonymous namespace
9808 
9809 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9810                                     const FunctionDecl *FD) {
9811   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9812     bool AlwaysTrue;
9813     if (EnableIf->getCond()->isValueDependent() ||
9814         !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9815       return false;
9816     if (!AlwaysTrue)
9817       return false;
9818   }
9819   return true;
9820 }
9821 
9822 /// Returns true if we can take the address of the function.
9823 ///
9824 /// \param Complain - If true, we'll emit a diagnostic
9825 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9826 ///   we in overload resolution?
9827 /// \param Loc - The location of the statement we're complaining about. Ignored
9828 ///   if we're not complaining, or if we're in overload resolution.
9829 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9830                                               bool Complain,
9831                                               bool InOverloadResolution,
9832                                               SourceLocation Loc) {
9833   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9834     if (Complain) {
9835       if (InOverloadResolution)
9836         S.Diag(FD->getBeginLoc(),
9837                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9838       else
9839         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9840     }
9841     return false;
9842   }
9843 
9844   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9845     return P->hasAttr<PassObjectSizeAttr>();
9846   });
9847   if (I == FD->param_end())
9848     return true;
9849 
9850   if (Complain) {
9851     // Add one to ParamNo because it's user-facing
9852     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9853     if (InOverloadResolution)
9854       S.Diag(FD->getLocation(),
9855              diag::note_ovl_candidate_has_pass_object_size_params)
9856           << ParamNo;
9857     else
9858       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9859           << FD << ParamNo;
9860   }
9861   return false;
9862 }
9863 
9864 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9865                                                const FunctionDecl *FD) {
9866   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9867                                            /*InOverloadResolution=*/true,
9868                                            /*Loc=*/SourceLocation());
9869 }
9870 
9871 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9872                                              bool Complain,
9873                                              SourceLocation Loc) {
9874   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9875                                              /*InOverloadResolution=*/false,
9876                                              Loc);
9877 }
9878 
9879 // Notes the location of an overload candidate.
9880 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9881                                  OverloadCandidateRewriteKind RewriteKind,
9882                                  QualType DestType, bool TakingAddress) {
9883   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9884     return;
9885   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
9886       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
9887     return;
9888 
9889   std::string FnDesc;
9890   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
9891       ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
9892   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9893                          << (unsigned)KSPair.first << (unsigned)KSPair.second
9894                          << Fn << FnDesc;
9895 
9896   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9897   Diag(Fn->getLocation(), PD);
9898   MaybeEmitInheritedConstructorNote(*this, Found);
9899 }
9900 
9901 // Notes the location of all overload candidates designated through
9902 // OverloadedExpr
9903 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9904                                      bool TakingAddress) {
9905   assert(OverloadedExpr->getType() == Context.OverloadTy);
9906 
9907   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9908   OverloadExpr *OvlExpr = Ovl.Expression;
9909 
9910   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9911                             IEnd = OvlExpr->decls_end();
9912        I != IEnd; ++I) {
9913     if (FunctionTemplateDecl *FunTmpl =
9914                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9915       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
9916                             TakingAddress);
9917     } else if (FunctionDecl *Fun
9918                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9919       NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
9920     }
9921   }
9922 }
9923 
9924 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9925 /// "lead" diagnostic; it will be given two arguments, the source and
9926 /// target types of the conversion.
9927 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9928                                  Sema &S,
9929                                  SourceLocation CaretLoc,
9930                                  const PartialDiagnostic &PDiag) const {
9931   S.Diag(CaretLoc, PDiag)
9932     << Ambiguous.getFromType() << Ambiguous.getToType();
9933   // FIXME: The note limiting machinery is borrowed from
9934   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9935   // refactoring here.
9936   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9937   unsigned CandsShown = 0;
9938   AmbiguousConversionSequence::const_iterator I, E;
9939   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9940     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9941       break;
9942     ++CandsShown;
9943     S.NoteOverloadCandidate(I->first, I->second);
9944   }
9945   if (I != E)
9946     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9947 }
9948 
9949 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9950                                   unsigned I, bool TakingCandidateAddress) {
9951   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9952   assert(Conv.isBad());
9953   assert(Cand->Function && "for now, candidate must be a function");
9954   FunctionDecl *Fn = Cand->Function;
9955 
9956   // There's a conversion slot for the object argument if this is a
9957   // non-constructor method.  Note that 'I' corresponds the
9958   // conversion-slot index.
9959   bool isObjectArgument = false;
9960   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9961     if (I == 0)
9962       isObjectArgument = true;
9963     else
9964       I--;
9965   }
9966 
9967   std::string FnDesc;
9968   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
9969       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
9970                                 FnDesc);
9971 
9972   Expr *FromExpr = Conv.Bad.FromExpr;
9973   QualType FromTy = Conv.Bad.getFromType();
9974   QualType ToTy = Conv.Bad.getToType();
9975 
9976   if (FromTy == S.Context.OverloadTy) {
9977     assert(FromExpr && "overload set argument came from implicit argument?");
9978     Expr *E = FromExpr->IgnoreParens();
9979     if (isa<UnaryOperator>(E))
9980       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9981     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9982 
9983     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9984         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9985         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
9986         << Name << I + 1;
9987     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9988     return;
9989   }
9990 
9991   // Do some hand-waving analysis to see if the non-viability is due
9992   // to a qualifier mismatch.
9993   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9994   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9995   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9996     CToTy = RT->getPointeeType();
9997   else {
9998     // TODO: detect and diagnose the full richness of const mismatches.
9999     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
10000       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
10001         CFromTy = FromPT->getPointeeType();
10002         CToTy = ToPT->getPointeeType();
10003       }
10004   }
10005 
10006   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
10007       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
10008     Qualifiers FromQs = CFromTy.getQualifiers();
10009     Qualifiers ToQs = CToTy.getQualifiers();
10010 
10011     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
10012       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
10013           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10014           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10015           << ToTy << (unsigned)isObjectArgument << I + 1;
10016       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10017       return;
10018     }
10019 
10020     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10021       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
10022           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10023           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10024           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
10025           << (unsigned)isObjectArgument << I + 1;
10026       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10027       return;
10028     }
10029 
10030     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
10031       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
10032           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10033           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10034           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
10035           << (unsigned)isObjectArgument << I + 1;
10036       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10037       return;
10038     }
10039 
10040     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
10041       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
10042           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10043           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10044           << FromQs.hasUnaligned() << I + 1;
10045       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10046       return;
10047     }
10048 
10049     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
10050     assert(CVR && "unexpected qualifiers mismatch");
10051 
10052     if (isObjectArgument) {
10053       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
10054           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10055           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10056           << (CVR - 1);
10057     } else {
10058       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
10059           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10060           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10061           << (CVR - 1) << I + 1;
10062     }
10063     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10064     return;
10065   }
10066 
10067   // Special diagnostic for failure to convert an initializer list, since
10068   // telling the user that it has type void is not useful.
10069   if (FromExpr && isa<InitListExpr>(FromExpr)) {
10070     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
10071         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10072         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10073         << ToTy << (unsigned)isObjectArgument << I + 1;
10074     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10075     return;
10076   }
10077 
10078   // Diagnose references or pointers to incomplete types differently,
10079   // since it's far from impossible that the incompleteness triggered
10080   // the failure.
10081   QualType TempFromTy = FromTy.getNonReferenceType();
10082   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
10083     TempFromTy = PTy->getPointeeType();
10084   if (TempFromTy->isIncompleteType()) {
10085     // Emit the generic diagnostic and, optionally, add the hints to it.
10086     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
10087         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10088         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10089         << ToTy << (unsigned)isObjectArgument << I + 1
10090         << (unsigned)(Cand->Fix.Kind);
10091 
10092     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10093     return;
10094   }
10095 
10096   // Diagnose base -> derived pointer conversions.
10097   unsigned BaseToDerivedConversion = 0;
10098   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
10099     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
10100       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10101                                                FromPtrTy->getPointeeType()) &&
10102           !FromPtrTy->getPointeeType()->isIncompleteType() &&
10103           !ToPtrTy->getPointeeType()->isIncompleteType() &&
10104           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
10105                           FromPtrTy->getPointeeType()))
10106         BaseToDerivedConversion = 1;
10107     }
10108   } else if (const ObjCObjectPointerType *FromPtrTy
10109                                     = FromTy->getAs<ObjCObjectPointerType>()) {
10110     if (const ObjCObjectPointerType *ToPtrTy
10111                                         = ToTy->getAs<ObjCObjectPointerType>())
10112       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
10113         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
10114           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10115                                                 FromPtrTy->getPointeeType()) &&
10116               FromIface->isSuperClassOf(ToIface))
10117             BaseToDerivedConversion = 2;
10118   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
10119     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
10120         !FromTy->isIncompleteType() &&
10121         !ToRefTy->getPointeeType()->isIncompleteType() &&
10122         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
10123       BaseToDerivedConversion = 3;
10124     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
10125                ToTy.getNonReferenceType().getCanonicalType() ==
10126                FromTy.getNonReferenceType().getCanonicalType()) {
10127       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
10128           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10129           << (unsigned)isObjectArgument << I + 1
10130           << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
10131       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10132       return;
10133     }
10134   }
10135 
10136   if (BaseToDerivedConversion) {
10137     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
10138         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10139         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10140         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
10141     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10142     return;
10143   }
10144 
10145   if (isa<ObjCObjectPointerType>(CFromTy) &&
10146       isa<PointerType>(CToTy)) {
10147       Qualifiers FromQs = CFromTy.getQualifiers();
10148       Qualifiers ToQs = CToTy.getQualifiers();
10149       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10150         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
10151             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10152             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10153             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
10154         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10155         return;
10156       }
10157   }
10158 
10159   if (TakingCandidateAddress &&
10160       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
10161     return;
10162 
10163   // Emit the generic diagnostic and, optionally, add the hints to it.
10164   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
10165   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10166         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10167         << ToTy << (unsigned)isObjectArgument << I + 1
10168         << (unsigned)(Cand->Fix.Kind);
10169 
10170   // If we can fix the conversion, suggest the FixIts.
10171   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
10172        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
10173     FDiag << *HI;
10174   S.Diag(Fn->getLocation(), FDiag);
10175 
10176   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10177 }
10178 
10179 /// Additional arity mismatch diagnosis specific to a function overload
10180 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
10181 /// over a candidate in any candidate set.
10182 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
10183                                unsigned NumArgs) {
10184   FunctionDecl *Fn = Cand->Function;
10185   unsigned MinParams = Fn->getMinRequiredArguments();
10186 
10187   // With invalid overloaded operators, it's possible that we think we
10188   // have an arity mismatch when in fact it looks like we have the
10189   // right number of arguments, because only overloaded operators have
10190   // the weird behavior of overloading member and non-member functions.
10191   // Just don't report anything.
10192   if (Fn->isInvalidDecl() &&
10193       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
10194     return true;
10195 
10196   if (NumArgs < MinParams) {
10197     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
10198            (Cand->FailureKind == ovl_fail_bad_deduction &&
10199             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
10200   } else {
10201     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
10202            (Cand->FailureKind == ovl_fail_bad_deduction &&
10203             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
10204   }
10205 
10206   return false;
10207 }
10208 
10209 /// General arity mismatch diagnosis over a candidate in a candidate set.
10210 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
10211                                   unsigned NumFormalArgs) {
10212   assert(isa<FunctionDecl>(D) &&
10213       "The templated declaration should at least be a function"
10214       " when diagnosing bad template argument deduction due to too many"
10215       " or too few arguments");
10216 
10217   FunctionDecl *Fn = cast<FunctionDecl>(D);
10218 
10219   // TODO: treat calls to a missing default constructor as a special case
10220   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
10221   unsigned MinParams = Fn->getMinRequiredArguments();
10222 
10223   // at least / at most / exactly
10224   unsigned mode, modeCount;
10225   if (NumFormalArgs < MinParams) {
10226     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
10227         FnTy->isTemplateVariadic())
10228       mode = 0; // "at least"
10229     else
10230       mode = 2; // "exactly"
10231     modeCount = MinParams;
10232   } else {
10233     if (MinParams != FnTy->getNumParams())
10234       mode = 1; // "at most"
10235     else
10236       mode = 2; // "exactly"
10237     modeCount = FnTy->getNumParams();
10238   }
10239 
10240   std::string Description;
10241   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10242       ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
10243 
10244   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10245     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10246         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10247         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
10248   else
10249     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
10250         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10251         << Description << mode << modeCount << NumFormalArgs;
10252 
10253   MaybeEmitInheritedConstructorNote(S, Found);
10254 }
10255 
10256 /// Arity mismatch diagnosis specific to a function overload candidate.
10257 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
10258                                   unsigned NumFormalArgs) {
10259   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
10260     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10261 }
10262 
10263 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10264   if (TemplateDecl *TD = Templated->getDescribedTemplate())
10265     return TD;
10266   llvm_unreachable("Unsupported: Getting the described template declaration"
10267                    " for bad deduction diagnosis");
10268 }
10269 
10270 /// Diagnose a failed template-argument deduction.
10271 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10272                                  DeductionFailureInfo &DeductionFailure,
10273                                  unsigned NumArgs,
10274                                  bool TakingCandidateAddress) {
10275   TemplateParameter Param = DeductionFailure.getTemplateParameter();
10276   NamedDecl *ParamD;
10277   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10278   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10279   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10280   switch (DeductionFailure.Result) {
10281   case Sema::TDK_Success:
10282     llvm_unreachable("TDK_success while diagnosing bad deduction");
10283 
10284   case Sema::TDK_Incomplete: {
10285     assert(ParamD && "no parameter found for incomplete deduction result");
10286     S.Diag(Templated->getLocation(),
10287            diag::note_ovl_candidate_incomplete_deduction)
10288         << ParamD->getDeclName();
10289     MaybeEmitInheritedConstructorNote(S, Found);
10290     return;
10291   }
10292 
10293   case Sema::TDK_IncompletePack: {
10294     assert(ParamD && "no parameter found for incomplete deduction result");
10295     S.Diag(Templated->getLocation(),
10296            diag::note_ovl_candidate_incomplete_deduction_pack)
10297         << ParamD->getDeclName()
10298         << (DeductionFailure.getFirstArg()->pack_size() + 1)
10299         << *DeductionFailure.getFirstArg();
10300     MaybeEmitInheritedConstructorNote(S, Found);
10301     return;
10302   }
10303 
10304   case Sema::TDK_Underqualified: {
10305     assert(ParamD && "no parameter found for bad qualifiers deduction result");
10306     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10307 
10308     QualType Param = DeductionFailure.getFirstArg()->getAsType();
10309 
10310     // Param will have been canonicalized, but it should just be a
10311     // qualified version of ParamD, so move the qualifiers to that.
10312     QualifierCollector Qs;
10313     Qs.strip(Param);
10314     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10315     assert(S.Context.hasSameType(Param, NonCanonParam));
10316 
10317     // Arg has also been canonicalized, but there's nothing we can do
10318     // about that.  It also doesn't matter as much, because it won't
10319     // have any template parameters in it (because deduction isn't
10320     // done on dependent types).
10321     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10322 
10323     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10324         << ParamD->getDeclName() << Arg << NonCanonParam;
10325     MaybeEmitInheritedConstructorNote(S, Found);
10326     return;
10327   }
10328 
10329   case Sema::TDK_Inconsistent: {
10330     assert(ParamD && "no parameter found for inconsistent deduction result");
10331     int which = 0;
10332     if (isa<TemplateTypeParmDecl>(ParamD))
10333       which = 0;
10334     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10335       // Deduction might have failed because we deduced arguments of two
10336       // different types for a non-type template parameter.
10337       // FIXME: Use a different TDK value for this.
10338       QualType T1 =
10339           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10340       QualType T2 =
10341           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10342       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10343         S.Diag(Templated->getLocation(),
10344                diag::note_ovl_candidate_inconsistent_deduction_types)
10345           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10346           << *DeductionFailure.getSecondArg() << T2;
10347         MaybeEmitInheritedConstructorNote(S, Found);
10348         return;
10349       }
10350 
10351       which = 1;
10352     } else {
10353       which = 2;
10354     }
10355 
10356     S.Diag(Templated->getLocation(),
10357            diag::note_ovl_candidate_inconsistent_deduction)
10358         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10359         << *DeductionFailure.getSecondArg();
10360     MaybeEmitInheritedConstructorNote(S, Found);
10361     return;
10362   }
10363 
10364   case Sema::TDK_InvalidExplicitArguments:
10365     assert(ParamD && "no parameter found for invalid explicit arguments");
10366     if (ParamD->getDeclName())
10367       S.Diag(Templated->getLocation(),
10368              diag::note_ovl_candidate_explicit_arg_mismatch_named)
10369           << ParamD->getDeclName();
10370     else {
10371       int index = 0;
10372       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10373         index = TTP->getIndex();
10374       else if (NonTypeTemplateParmDecl *NTTP
10375                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10376         index = NTTP->getIndex();
10377       else
10378         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10379       S.Diag(Templated->getLocation(),
10380              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10381           << (index + 1);
10382     }
10383     MaybeEmitInheritedConstructorNote(S, Found);
10384     return;
10385 
10386   case Sema::TDK_ConstraintsNotSatisfied: {
10387     // Format the template argument list into the argument string.
10388     SmallString<128> TemplateArgString;
10389     TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
10390     TemplateArgString = " ";
10391     TemplateArgString += S.getTemplateArgumentBindingsText(
10392         getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10393     S.Diag(Templated->getLocation(),
10394            diag::note_ovl_candidate_unsatisfied_constraints)
10395         << TemplateArgString;
10396 
10397     S.DiagnoseUnsatisfiedConstraint(
10398         static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
10399     return;
10400   }
10401   case Sema::TDK_TooManyArguments:
10402   case Sema::TDK_TooFewArguments:
10403     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10404     return;
10405 
10406   case Sema::TDK_InstantiationDepth:
10407     S.Diag(Templated->getLocation(),
10408            diag::note_ovl_candidate_instantiation_depth);
10409     MaybeEmitInheritedConstructorNote(S, Found);
10410     return;
10411 
10412   case Sema::TDK_SubstitutionFailure: {
10413     // Format the template argument list into the argument string.
10414     SmallString<128> TemplateArgString;
10415     if (TemplateArgumentList *Args =
10416             DeductionFailure.getTemplateArgumentList()) {
10417       TemplateArgString = " ";
10418       TemplateArgString += S.getTemplateArgumentBindingsText(
10419           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10420     }
10421 
10422     // If this candidate was disabled by enable_if, say so.
10423     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10424     if (PDiag && PDiag->second.getDiagID() ==
10425           diag::err_typename_nested_not_found_enable_if) {
10426       // FIXME: Use the source range of the condition, and the fully-qualified
10427       //        name of the enable_if template. These are both present in PDiag.
10428       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10429         << "'enable_if'" << TemplateArgString;
10430       return;
10431     }
10432 
10433     // We found a specific requirement that disabled the enable_if.
10434     if (PDiag && PDiag->second.getDiagID() ==
10435         diag::err_typename_nested_not_found_requirement) {
10436       S.Diag(Templated->getLocation(),
10437              diag::note_ovl_candidate_disabled_by_requirement)
10438         << PDiag->second.getStringArg(0) << TemplateArgString;
10439       return;
10440     }
10441 
10442     // Format the SFINAE diagnostic into the argument string.
10443     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10444     //        formatted message in another diagnostic.
10445     SmallString<128> SFINAEArgString;
10446     SourceRange R;
10447     if (PDiag) {
10448       SFINAEArgString = ": ";
10449       R = SourceRange(PDiag->first, PDiag->first);
10450       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10451     }
10452 
10453     S.Diag(Templated->getLocation(),
10454            diag::note_ovl_candidate_substitution_failure)
10455         << TemplateArgString << SFINAEArgString << R;
10456     MaybeEmitInheritedConstructorNote(S, Found);
10457     return;
10458   }
10459 
10460   case Sema::TDK_DeducedMismatch:
10461   case Sema::TDK_DeducedMismatchNested: {
10462     // Format the template argument list into the argument string.
10463     SmallString<128> TemplateArgString;
10464     if (TemplateArgumentList *Args =
10465             DeductionFailure.getTemplateArgumentList()) {
10466       TemplateArgString = " ";
10467       TemplateArgString += S.getTemplateArgumentBindingsText(
10468           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10469     }
10470 
10471     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10472         << (*DeductionFailure.getCallArgIndex() + 1)
10473         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10474         << TemplateArgString
10475         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10476     break;
10477   }
10478 
10479   case Sema::TDK_NonDeducedMismatch: {
10480     // FIXME: Provide a source location to indicate what we couldn't match.
10481     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10482     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10483     if (FirstTA.getKind() == TemplateArgument::Template &&
10484         SecondTA.getKind() == TemplateArgument::Template) {
10485       TemplateName FirstTN = FirstTA.getAsTemplate();
10486       TemplateName SecondTN = SecondTA.getAsTemplate();
10487       if (FirstTN.getKind() == TemplateName::Template &&
10488           SecondTN.getKind() == TemplateName::Template) {
10489         if (FirstTN.getAsTemplateDecl()->getName() ==
10490             SecondTN.getAsTemplateDecl()->getName()) {
10491           // FIXME: This fixes a bad diagnostic where both templates are named
10492           // the same.  This particular case is a bit difficult since:
10493           // 1) It is passed as a string to the diagnostic printer.
10494           // 2) The diagnostic printer only attempts to find a better
10495           //    name for types, not decls.
10496           // Ideally, this should folded into the diagnostic printer.
10497           S.Diag(Templated->getLocation(),
10498                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10499               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10500           return;
10501         }
10502       }
10503     }
10504 
10505     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10506         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10507       return;
10508 
10509     // FIXME: For generic lambda parameters, check if the function is a lambda
10510     // call operator, and if so, emit a prettier and more informative
10511     // diagnostic that mentions 'auto' and lambda in addition to
10512     // (or instead of?) the canonical template type parameters.
10513     S.Diag(Templated->getLocation(),
10514            diag::note_ovl_candidate_non_deduced_mismatch)
10515         << FirstTA << SecondTA;
10516     return;
10517   }
10518   // TODO: diagnose these individually, then kill off
10519   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10520   case Sema::TDK_MiscellaneousDeductionFailure:
10521     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10522     MaybeEmitInheritedConstructorNote(S, Found);
10523     return;
10524   case Sema::TDK_CUDATargetMismatch:
10525     S.Diag(Templated->getLocation(),
10526            diag::note_cuda_ovl_candidate_target_mismatch);
10527     return;
10528   }
10529 }
10530 
10531 /// Diagnose a failed template-argument deduction, for function calls.
10532 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10533                                  unsigned NumArgs,
10534                                  bool TakingCandidateAddress) {
10535   unsigned TDK = Cand->DeductionFailure.Result;
10536   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10537     if (CheckArityMismatch(S, Cand, NumArgs))
10538       return;
10539   }
10540   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10541                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10542 }
10543 
10544 /// CUDA: diagnose an invalid call across targets.
10545 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10546   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10547   FunctionDecl *Callee = Cand->Function;
10548 
10549   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10550                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10551 
10552   std::string FnDesc;
10553   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10554       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
10555                                 Cand->getRewriteKind(), FnDesc);
10556 
10557   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10558       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10559       << FnDesc /* Ignored */
10560       << CalleeTarget << CallerTarget;
10561 
10562   // This could be an implicit constructor for which we could not infer the
10563   // target due to a collsion. Diagnose that case.
10564   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10565   if (Meth != nullptr && Meth->isImplicit()) {
10566     CXXRecordDecl *ParentClass = Meth->getParent();
10567     Sema::CXXSpecialMember CSM;
10568 
10569     switch (FnKindPair.first) {
10570     default:
10571       return;
10572     case oc_implicit_default_constructor:
10573       CSM = Sema::CXXDefaultConstructor;
10574       break;
10575     case oc_implicit_copy_constructor:
10576       CSM = Sema::CXXCopyConstructor;
10577       break;
10578     case oc_implicit_move_constructor:
10579       CSM = Sema::CXXMoveConstructor;
10580       break;
10581     case oc_implicit_copy_assignment:
10582       CSM = Sema::CXXCopyAssignment;
10583       break;
10584     case oc_implicit_move_assignment:
10585       CSM = Sema::CXXMoveAssignment;
10586       break;
10587     };
10588 
10589     bool ConstRHS = false;
10590     if (Meth->getNumParams()) {
10591       if (const ReferenceType *RT =
10592               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10593         ConstRHS = RT->getPointeeType().isConstQualified();
10594       }
10595     }
10596 
10597     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10598                                               /* ConstRHS */ ConstRHS,
10599                                               /* Diagnose */ true);
10600   }
10601 }
10602 
10603 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10604   FunctionDecl *Callee = Cand->Function;
10605   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10606 
10607   S.Diag(Callee->getLocation(),
10608          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10609       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10610 }
10611 
10612 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
10613   ExplicitSpecifier ES;
10614   const char *DeclName;
10615   switch (Cand->Function->getDeclKind()) {
10616   case Decl::Kind::CXXConstructor:
10617     ES = cast<CXXConstructorDecl>(Cand->Function)->getExplicitSpecifier();
10618     DeclName = "constructor";
10619     break;
10620   case Decl::Kind::CXXConversion:
10621     ES = cast<CXXConversionDecl>(Cand->Function)->getExplicitSpecifier();
10622     DeclName = "conversion operator";
10623     break;
10624   case Decl::Kind::CXXDeductionGuide:
10625     ES = cast<CXXDeductionGuideDecl>(Cand->Function)->getExplicitSpecifier();
10626     DeclName = "deductiong guide";
10627     break;
10628   default:
10629     llvm_unreachable("invalid Decl");
10630   }
10631   assert(ES.getExpr() && "null expression should be handled before");
10632   S.Diag(Cand->Function->getLocation(),
10633          diag::note_ovl_candidate_explicit_forbidden)
10634       << DeclName;
10635   S.Diag(ES.getExpr()->getBeginLoc(),
10636          diag::note_explicit_bool_resolved_to_true);
10637 }
10638 
10639 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10640   FunctionDecl *Callee = Cand->Function;
10641 
10642   S.Diag(Callee->getLocation(),
10643          diag::note_ovl_candidate_disabled_by_extension)
10644     << S.getOpenCLExtensionsFromDeclExtMap(Callee);
10645 }
10646 
10647 /// Generates a 'note' diagnostic for an overload candidate.  We've
10648 /// already generated a primary error at the call site.
10649 ///
10650 /// It really does need to be a single diagnostic with its caret
10651 /// pointed at the candidate declaration.  Yes, this creates some
10652 /// major challenges of technical writing.  Yes, this makes pointing
10653 /// out problems with specific arguments quite awkward.  It's still
10654 /// better than generating twenty screens of text for every failed
10655 /// overload.
10656 ///
10657 /// It would be great to be able to express per-candidate problems
10658 /// more richly for those diagnostic clients that cared, but we'd
10659 /// still have to be just as careful with the default diagnostics.
10660 /// \param CtorDestAS Addr space of object being constructed (for ctor
10661 /// candidates only).
10662 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10663                                   unsigned NumArgs,
10664                                   bool TakingCandidateAddress,
10665                                   LangAS CtorDestAS = LangAS::Default) {
10666   FunctionDecl *Fn = Cand->Function;
10667 
10668   // Note deleted candidates, but only if they're viable.
10669   if (Cand->Viable) {
10670     if (Fn->isDeleted()) {
10671       std::string FnDesc;
10672       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10673           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
10674                                     Cand->getRewriteKind(), FnDesc);
10675 
10676       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10677           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10678           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10679       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10680       return;
10681     }
10682 
10683     // We don't really have anything else to say about viable candidates.
10684     S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10685     return;
10686   }
10687 
10688   switch (Cand->FailureKind) {
10689   case ovl_fail_too_many_arguments:
10690   case ovl_fail_too_few_arguments:
10691     return DiagnoseArityMismatch(S, Cand, NumArgs);
10692 
10693   case ovl_fail_bad_deduction:
10694     return DiagnoseBadDeduction(S, Cand, NumArgs,
10695                                 TakingCandidateAddress);
10696 
10697   case ovl_fail_illegal_constructor: {
10698     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10699       << (Fn->getPrimaryTemplate() ? 1 : 0);
10700     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10701     return;
10702   }
10703 
10704   case ovl_fail_object_addrspace_mismatch: {
10705     Qualifiers QualsForPrinting;
10706     QualsForPrinting.setAddressSpace(CtorDestAS);
10707     S.Diag(Fn->getLocation(),
10708            diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
10709         << QualsForPrinting;
10710     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10711     return;
10712   }
10713 
10714   case ovl_fail_trivial_conversion:
10715   case ovl_fail_bad_final_conversion:
10716   case ovl_fail_final_conversion_not_exact:
10717     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10718 
10719   case ovl_fail_bad_conversion: {
10720     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10721     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10722       if (Cand->Conversions[I].isBad())
10723         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10724 
10725     // FIXME: this currently happens when we're called from SemaInit
10726     // when user-conversion overload fails.  Figure out how to handle
10727     // those conditions and diagnose them well.
10728     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10729   }
10730 
10731   case ovl_fail_bad_target:
10732     return DiagnoseBadTarget(S, Cand);
10733 
10734   case ovl_fail_enable_if:
10735     return DiagnoseFailedEnableIfAttr(S, Cand);
10736 
10737   case ovl_fail_explicit_resolved:
10738     return DiagnoseFailedExplicitSpec(S, Cand);
10739 
10740   case ovl_fail_ext_disabled:
10741     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10742 
10743   case ovl_fail_inhctor_slice:
10744     // It's generally not interesting to note copy/move constructors here.
10745     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10746       return;
10747     S.Diag(Fn->getLocation(),
10748            diag::note_ovl_candidate_inherited_constructor_slice)
10749       << (Fn->getPrimaryTemplate() ? 1 : 0)
10750       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10751     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10752     return;
10753 
10754   case ovl_fail_addr_not_available: {
10755     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10756     (void)Available;
10757     assert(!Available);
10758     break;
10759   }
10760   case ovl_non_default_multiversion_function:
10761     // Do nothing, these should simply be ignored.
10762     break;
10763   }
10764 }
10765 
10766 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10767   // Desugar the type of the surrogate down to a function type,
10768   // retaining as many typedefs as possible while still showing
10769   // the function type (and, therefore, its parameter types).
10770   QualType FnType = Cand->Surrogate->getConversionType();
10771   bool isLValueReference = false;
10772   bool isRValueReference = false;
10773   bool isPointer = false;
10774   if (const LValueReferenceType *FnTypeRef =
10775         FnType->getAs<LValueReferenceType>()) {
10776     FnType = FnTypeRef->getPointeeType();
10777     isLValueReference = true;
10778   } else if (const RValueReferenceType *FnTypeRef =
10779                FnType->getAs<RValueReferenceType>()) {
10780     FnType = FnTypeRef->getPointeeType();
10781     isRValueReference = true;
10782   }
10783   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10784     FnType = FnTypePtr->getPointeeType();
10785     isPointer = true;
10786   }
10787   // Desugar down to a function type.
10788   FnType = QualType(FnType->getAs<FunctionType>(), 0);
10789   // Reconstruct the pointer/reference as appropriate.
10790   if (isPointer) FnType = S.Context.getPointerType(FnType);
10791   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10792   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10793 
10794   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10795     << FnType;
10796 }
10797 
10798 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10799                                          SourceLocation OpLoc,
10800                                          OverloadCandidate *Cand) {
10801   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10802   std::string TypeStr("operator");
10803   TypeStr += Opc;
10804   TypeStr += "(";
10805   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
10806   if (Cand->Conversions.size() == 1) {
10807     TypeStr += ")";
10808     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
10809   } else {
10810     TypeStr += ", ";
10811     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
10812     TypeStr += ")";
10813     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
10814   }
10815 }
10816 
10817 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10818                                          OverloadCandidate *Cand) {
10819   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10820     if (ICS.isBad()) break; // all meaningless after first invalid
10821     if (!ICS.isAmbiguous()) continue;
10822 
10823     ICS.DiagnoseAmbiguousConversion(
10824         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10825   }
10826 }
10827 
10828 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10829   if (Cand->Function)
10830     return Cand->Function->getLocation();
10831   if (Cand->IsSurrogate)
10832     return Cand->Surrogate->getLocation();
10833   return SourceLocation();
10834 }
10835 
10836 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10837   switch ((Sema::TemplateDeductionResult)DFI.Result) {
10838   case Sema::TDK_Success:
10839   case Sema::TDK_NonDependentConversionFailure:
10840     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10841 
10842   case Sema::TDK_Invalid:
10843   case Sema::TDK_Incomplete:
10844   case Sema::TDK_IncompletePack:
10845     return 1;
10846 
10847   case Sema::TDK_Underqualified:
10848   case Sema::TDK_Inconsistent:
10849     return 2;
10850 
10851   case Sema::TDK_SubstitutionFailure:
10852   case Sema::TDK_DeducedMismatch:
10853   case Sema::TDK_ConstraintsNotSatisfied:
10854   case Sema::TDK_DeducedMismatchNested:
10855   case Sema::TDK_NonDeducedMismatch:
10856   case Sema::TDK_MiscellaneousDeductionFailure:
10857   case Sema::TDK_CUDATargetMismatch:
10858     return 3;
10859 
10860   case Sema::TDK_InstantiationDepth:
10861     return 4;
10862 
10863   case Sema::TDK_InvalidExplicitArguments:
10864     return 5;
10865 
10866   case Sema::TDK_TooManyArguments:
10867   case Sema::TDK_TooFewArguments:
10868     return 6;
10869   }
10870   llvm_unreachable("Unhandled deduction result");
10871 }
10872 
10873 namespace {
10874 struct CompareOverloadCandidatesForDisplay {
10875   Sema &S;
10876   SourceLocation Loc;
10877   size_t NumArgs;
10878   OverloadCandidateSet::CandidateSetKind CSK;
10879 
10880   CompareOverloadCandidatesForDisplay(
10881       Sema &S, SourceLocation Loc, size_t NArgs,
10882       OverloadCandidateSet::CandidateSetKind CSK)
10883       : S(S), NumArgs(NArgs), CSK(CSK) {}
10884 
10885   bool operator()(const OverloadCandidate *L,
10886                   const OverloadCandidate *R) {
10887     // Fast-path this check.
10888     if (L == R) return false;
10889 
10890     // Order first by viability.
10891     if (L->Viable) {
10892       if (!R->Viable) return true;
10893 
10894       // TODO: introduce a tri-valued comparison for overload
10895       // candidates.  Would be more worthwhile if we had a sort
10896       // that could exploit it.
10897       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10898         return true;
10899       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10900         return false;
10901     } else if (R->Viable)
10902       return false;
10903 
10904     assert(L->Viable == R->Viable);
10905 
10906     // Criteria by which we can sort non-viable candidates:
10907     if (!L->Viable) {
10908       // 1. Arity mismatches come after other candidates.
10909       if (L->FailureKind == ovl_fail_too_many_arguments ||
10910           L->FailureKind == ovl_fail_too_few_arguments) {
10911         if (R->FailureKind == ovl_fail_too_many_arguments ||
10912             R->FailureKind == ovl_fail_too_few_arguments) {
10913           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10914           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10915           if (LDist == RDist) {
10916             if (L->FailureKind == R->FailureKind)
10917               // Sort non-surrogates before surrogates.
10918               return !L->IsSurrogate && R->IsSurrogate;
10919             // Sort candidates requiring fewer parameters than there were
10920             // arguments given after candidates requiring more parameters
10921             // than there were arguments given.
10922             return L->FailureKind == ovl_fail_too_many_arguments;
10923           }
10924           return LDist < RDist;
10925         }
10926         return false;
10927       }
10928       if (R->FailureKind == ovl_fail_too_many_arguments ||
10929           R->FailureKind == ovl_fail_too_few_arguments)
10930         return true;
10931 
10932       // 2. Bad conversions come first and are ordered by the number
10933       // of bad conversions and quality of good conversions.
10934       if (L->FailureKind == ovl_fail_bad_conversion) {
10935         if (R->FailureKind != ovl_fail_bad_conversion)
10936           return true;
10937 
10938         // The conversion that can be fixed with a smaller number of changes,
10939         // comes first.
10940         unsigned numLFixes = L->Fix.NumConversionsFixed;
10941         unsigned numRFixes = R->Fix.NumConversionsFixed;
10942         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10943         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10944         if (numLFixes != numRFixes) {
10945           return numLFixes < numRFixes;
10946         }
10947 
10948         // If there's any ordering between the defined conversions...
10949         // FIXME: this might not be transitive.
10950         assert(L->Conversions.size() == R->Conversions.size());
10951 
10952         int leftBetter = 0;
10953         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10954         for (unsigned E = L->Conversions.size(); I != E; ++I) {
10955           switch (CompareImplicitConversionSequences(S, Loc,
10956                                                      L->Conversions[I],
10957                                                      R->Conversions[I])) {
10958           case ImplicitConversionSequence::Better:
10959             leftBetter++;
10960             break;
10961 
10962           case ImplicitConversionSequence::Worse:
10963             leftBetter--;
10964             break;
10965 
10966           case ImplicitConversionSequence::Indistinguishable:
10967             break;
10968           }
10969         }
10970         if (leftBetter > 0) return true;
10971         if (leftBetter < 0) return false;
10972 
10973       } else if (R->FailureKind == ovl_fail_bad_conversion)
10974         return false;
10975 
10976       if (L->FailureKind == ovl_fail_bad_deduction) {
10977         if (R->FailureKind != ovl_fail_bad_deduction)
10978           return true;
10979 
10980         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10981           return RankDeductionFailure(L->DeductionFailure)
10982                < RankDeductionFailure(R->DeductionFailure);
10983       } else if (R->FailureKind == ovl_fail_bad_deduction)
10984         return false;
10985 
10986       // TODO: others?
10987     }
10988 
10989     // Sort everything else by location.
10990     SourceLocation LLoc = GetLocationForCandidate(L);
10991     SourceLocation RLoc = GetLocationForCandidate(R);
10992 
10993     // Put candidates without locations (e.g. builtins) at the end.
10994     if (LLoc.isInvalid()) return false;
10995     if (RLoc.isInvalid()) return true;
10996 
10997     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10998   }
10999 };
11000 }
11001 
11002 /// CompleteNonViableCandidate - Normally, overload resolution only
11003 /// computes up to the first bad conversion. Produces the FixIt set if
11004 /// possible.
11005 static void
11006 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
11007                            ArrayRef<Expr *> Args,
11008                            OverloadCandidateSet::CandidateSetKind CSK) {
11009   assert(!Cand->Viable);
11010 
11011   // Don't do anything on failures other than bad conversion.
11012   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
11013 
11014   // We only want the FixIts if all the arguments can be corrected.
11015   bool Unfixable = false;
11016   // Use a implicit copy initialization to check conversion fixes.
11017   Cand->Fix.setConversionChecker(TryCopyInitialization);
11018 
11019   // Attempt to fix the bad conversion.
11020   unsigned ConvCount = Cand->Conversions.size();
11021   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
11022        ++ConvIdx) {
11023     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
11024     if (Cand->Conversions[ConvIdx].isInitialized() &&
11025         Cand->Conversions[ConvIdx].isBad()) {
11026       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11027       break;
11028     }
11029   }
11030 
11031   // FIXME: this should probably be preserved from the overload
11032   // operation somehow.
11033   bool SuppressUserConversions = false;
11034 
11035   unsigned ConvIdx = 0;
11036   unsigned ArgIdx = 0;
11037   ArrayRef<QualType> ParamTypes;
11038   bool Reversed = Cand->RewriteKind & CRK_Reversed;
11039 
11040   if (Cand->IsSurrogate) {
11041     QualType ConvType
11042       = Cand->Surrogate->getConversionType().getNonReferenceType();
11043     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11044       ConvType = ConvPtrType->getPointeeType();
11045     ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
11046     // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11047     ConvIdx = 1;
11048   } else if (Cand->Function) {
11049     ParamTypes =
11050         Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
11051     if (isa<CXXMethodDecl>(Cand->Function) &&
11052         !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
11053       // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11054       ConvIdx = 1;
11055       if (CSK == OverloadCandidateSet::CSK_Operator &&
11056           Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call)
11057         // Argument 0 is 'this', which doesn't have a corresponding parameter.
11058         ArgIdx = 1;
11059     }
11060   } else {
11061     // Builtin operator.
11062     assert(ConvCount <= 3);
11063     ParamTypes = Cand->BuiltinParamTypes;
11064   }
11065 
11066   // Fill in the rest of the conversions.
11067   for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
11068        ConvIdx != ConvCount;
11069        ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
11070     assert(ArgIdx < Args.size() && "no argument for this arg conversion");
11071     if (Cand->Conversions[ConvIdx].isInitialized()) {
11072       // We've already checked this conversion.
11073     } else if (ParamIdx < ParamTypes.size()) {
11074       if (ParamTypes[ParamIdx]->isDependentType())
11075         Cand->Conversions[ConvIdx].setAsIdentityConversion(
11076             Args[ArgIdx]->getType());
11077       else {
11078         Cand->Conversions[ConvIdx] =
11079             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
11080                                   SuppressUserConversions,
11081                                   /*InOverloadResolution=*/true,
11082                                   /*AllowObjCWritebackConversion=*/
11083                                   S.getLangOpts().ObjCAutoRefCount);
11084         // Store the FixIt in the candidate if it exists.
11085         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
11086           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11087       }
11088     } else
11089       Cand->Conversions[ConvIdx].setEllipsis();
11090   }
11091 }
11092 
11093 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
11094     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11095     SourceLocation OpLoc,
11096     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11097   // Sort the candidates by viability and position.  Sorting directly would
11098   // be prohibitive, so we make a set of pointers and sort those.
11099   SmallVector<OverloadCandidate*, 32> Cands;
11100   if (OCD == OCD_AllCandidates) Cands.reserve(size());
11101   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11102     if (!Filter(*Cand))
11103       continue;
11104     switch (OCD) {
11105     case OCD_AllCandidates:
11106       if (!Cand->Viable) {
11107         if (!Cand->Function && !Cand->IsSurrogate) {
11108           // This a non-viable builtin candidate.  We do not, in general,
11109           // want to list every possible builtin candidate.
11110           continue;
11111         }
11112         CompleteNonViableCandidate(S, Cand, Args, Kind);
11113       }
11114       break;
11115 
11116     case OCD_ViableCandidates:
11117       if (!Cand->Viable)
11118         continue;
11119       break;
11120 
11121     case OCD_AmbiguousCandidates:
11122       if (!Cand->Best)
11123         continue;
11124       break;
11125     }
11126 
11127     Cands.push_back(Cand);
11128   }
11129 
11130   llvm::stable_sort(
11131       Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
11132 
11133   return Cands;
11134 }
11135 
11136 /// When overload resolution fails, prints diagnostic messages containing the
11137 /// candidates in the candidate set.
11138 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD,
11139     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11140     StringRef Opc, SourceLocation OpLoc,
11141     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11142 
11143   auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
11144 
11145   S.Diag(PD.first, PD.second);
11146 
11147   NoteCandidates(S, Args, Cands, Opc, OpLoc);
11148 }
11149 
11150 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
11151                                           ArrayRef<OverloadCandidate *> Cands,
11152                                           StringRef Opc, SourceLocation OpLoc) {
11153   bool ReportedAmbiguousConversions = false;
11154 
11155   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11156   unsigned CandsShown = 0;
11157   auto I = Cands.begin(), E = Cands.end();
11158   for (; I != E; ++I) {
11159     OverloadCandidate *Cand = *I;
11160 
11161     // Set an arbitrary limit on the number of candidate functions we'll spam
11162     // the user with.  FIXME: This limit should depend on details of the
11163     // candidate list.
11164     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
11165       break;
11166     }
11167     ++CandsShown;
11168 
11169     if (Cand->Function)
11170       NoteFunctionCandidate(S, Cand, Args.size(),
11171                             /*TakingCandidateAddress=*/false, DestAS);
11172     else if (Cand->IsSurrogate)
11173       NoteSurrogateCandidate(S, Cand);
11174     else {
11175       assert(Cand->Viable &&
11176              "Non-viable built-in candidates are not added to Cands.");
11177       // Generally we only see ambiguities including viable builtin
11178       // operators if overload resolution got screwed up by an
11179       // ambiguous user-defined conversion.
11180       //
11181       // FIXME: It's quite possible for different conversions to see
11182       // different ambiguities, though.
11183       if (!ReportedAmbiguousConversions) {
11184         NoteAmbiguousUserConversions(S, OpLoc, Cand);
11185         ReportedAmbiguousConversions = true;
11186       }
11187 
11188       // If this is a viable builtin, print it.
11189       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
11190     }
11191   }
11192 
11193   if (I != E)
11194     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
11195 }
11196 
11197 static SourceLocation
11198 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
11199   return Cand->Specialization ? Cand->Specialization->getLocation()
11200                               : SourceLocation();
11201 }
11202 
11203 namespace {
11204 struct CompareTemplateSpecCandidatesForDisplay {
11205   Sema &S;
11206   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
11207 
11208   bool operator()(const TemplateSpecCandidate *L,
11209                   const TemplateSpecCandidate *R) {
11210     // Fast-path this check.
11211     if (L == R)
11212       return false;
11213 
11214     // Assuming that both candidates are not matches...
11215 
11216     // Sort by the ranking of deduction failures.
11217     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11218       return RankDeductionFailure(L->DeductionFailure) <
11219              RankDeductionFailure(R->DeductionFailure);
11220 
11221     // Sort everything else by location.
11222     SourceLocation LLoc = GetLocationForCandidate(L);
11223     SourceLocation RLoc = GetLocationForCandidate(R);
11224 
11225     // Put candidates without locations (e.g. builtins) at the end.
11226     if (LLoc.isInvalid())
11227       return false;
11228     if (RLoc.isInvalid())
11229       return true;
11230 
11231     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11232   }
11233 };
11234 }
11235 
11236 /// Diagnose a template argument deduction failure.
11237 /// We are treating these failures as overload failures due to bad
11238 /// deductions.
11239 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
11240                                                  bool ForTakingAddress) {
11241   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
11242                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
11243 }
11244 
11245 void TemplateSpecCandidateSet::destroyCandidates() {
11246   for (iterator i = begin(), e = end(); i != e; ++i) {
11247     i->DeductionFailure.Destroy();
11248   }
11249 }
11250 
11251 void TemplateSpecCandidateSet::clear() {
11252   destroyCandidates();
11253   Candidates.clear();
11254 }
11255 
11256 /// NoteCandidates - When no template specialization match is found, prints
11257 /// diagnostic messages containing the non-matching specializations that form
11258 /// the candidate set.
11259 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
11260 /// OCD == OCD_AllCandidates and Cand->Viable == false.
11261 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
11262   // Sort the candidates by position (assuming no candidate is a match).
11263   // Sorting directly would be prohibitive, so we make a set of pointers
11264   // and sort those.
11265   SmallVector<TemplateSpecCandidate *, 32> Cands;
11266   Cands.reserve(size());
11267   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11268     if (Cand->Specialization)
11269       Cands.push_back(Cand);
11270     // Otherwise, this is a non-matching builtin candidate.  We do not,
11271     // in general, want to list every possible builtin candidate.
11272   }
11273 
11274   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
11275 
11276   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
11277   // for generalization purposes (?).
11278   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11279 
11280   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
11281   unsigned CandsShown = 0;
11282   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11283     TemplateSpecCandidate *Cand = *I;
11284 
11285     // Set an arbitrary limit on the number of candidates we'll spam
11286     // the user with.  FIXME: This limit should depend on details of the
11287     // candidate list.
11288     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
11289       break;
11290     ++CandsShown;
11291 
11292     assert(Cand->Specialization &&
11293            "Non-matching built-in candidates are not added to Cands.");
11294     Cand->NoteDeductionFailure(S, ForTakingAddress);
11295   }
11296 
11297   if (I != E)
11298     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
11299 }
11300 
11301 // [PossiblyAFunctionType]  -->   [Return]
11302 // NonFunctionType --> NonFunctionType
11303 // R (A) --> R(A)
11304 // R (*)(A) --> R (A)
11305 // R (&)(A) --> R (A)
11306 // R (S::*)(A) --> R (A)
11307 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
11308   QualType Ret = PossiblyAFunctionType;
11309   if (const PointerType *ToTypePtr =
11310     PossiblyAFunctionType->getAs<PointerType>())
11311     Ret = ToTypePtr->getPointeeType();
11312   else if (const ReferenceType *ToTypeRef =
11313     PossiblyAFunctionType->getAs<ReferenceType>())
11314     Ret = ToTypeRef->getPointeeType();
11315   else if (const MemberPointerType *MemTypePtr =
11316     PossiblyAFunctionType->getAs<MemberPointerType>())
11317     Ret = MemTypePtr->getPointeeType();
11318   Ret =
11319     Context.getCanonicalType(Ret).getUnqualifiedType();
11320   return Ret;
11321 }
11322 
11323 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
11324                                  bool Complain = true) {
11325   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
11326       S.DeduceReturnType(FD, Loc, Complain))
11327     return true;
11328 
11329   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
11330   if (S.getLangOpts().CPlusPlus17 &&
11331       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
11332       !S.ResolveExceptionSpec(Loc, FPT))
11333     return true;
11334 
11335   return false;
11336 }
11337 
11338 namespace {
11339 // A helper class to help with address of function resolution
11340 // - allows us to avoid passing around all those ugly parameters
11341 class AddressOfFunctionResolver {
11342   Sema& S;
11343   Expr* SourceExpr;
11344   const QualType& TargetType;
11345   QualType TargetFunctionType; // Extracted function type from target type
11346 
11347   bool Complain;
11348   //DeclAccessPair& ResultFunctionAccessPair;
11349   ASTContext& Context;
11350 
11351   bool TargetTypeIsNonStaticMemberFunction;
11352   bool FoundNonTemplateFunction;
11353   bool StaticMemberFunctionFromBoundPointer;
11354   bool HasComplained;
11355 
11356   OverloadExpr::FindResult OvlExprInfo;
11357   OverloadExpr *OvlExpr;
11358   TemplateArgumentListInfo OvlExplicitTemplateArgs;
11359   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
11360   TemplateSpecCandidateSet FailedCandidates;
11361 
11362 public:
11363   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
11364                             const QualType &TargetType, bool Complain)
11365       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
11366         Complain(Complain), Context(S.getASTContext()),
11367         TargetTypeIsNonStaticMemberFunction(
11368             !!TargetType->getAs<MemberPointerType>()),
11369         FoundNonTemplateFunction(false),
11370         StaticMemberFunctionFromBoundPointer(false),
11371         HasComplained(false),
11372         OvlExprInfo(OverloadExpr::find(SourceExpr)),
11373         OvlExpr(OvlExprInfo.Expression),
11374         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
11375     ExtractUnqualifiedFunctionTypeFromTargetType();
11376 
11377     if (TargetFunctionType->isFunctionType()) {
11378       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
11379         if (!UME->isImplicitAccess() &&
11380             !S.ResolveSingleFunctionTemplateSpecialization(UME))
11381           StaticMemberFunctionFromBoundPointer = true;
11382     } else if (OvlExpr->hasExplicitTemplateArgs()) {
11383       DeclAccessPair dap;
11384       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
11385               OvlExpr, false, &dap)) {
11386         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
11387           if (!Method->isStatic()) {
11388             // If the target type is a non-function type and the function found
11389             // is a non-static member function, pretend as if that was the
11390             // target, it's the only possible type to end up with.
11391             TargetTypeIsNonStaticMemberFunction = true;
11392 
11393             // And skip adding the function if its not in the proper form.
11394             // We'll diagnose this due to an empty set of functions.
11395             if (!OvlExprInfo.HasFormOfMemberPointer)
11396               return;
11397           }
11398 
11399         Matches.push_back(std::make_pair(dap, Fn));
11400       }
11401       return;
11402     }
11403 
11404     if (OvlExpr->hasExplicitTemplateArgs())
11405       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
11406 
11407     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
11408       // C++ [over.over]p4:
11409       //   If more than one function is selected, [...]
11410       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
11411         if (FoundNonTemplateFunction)
11412           EliminateAllTemplateMatches();
11413         else
11414           EliminateAllExceptMostSpecializedTemplate();
11415       }
11416     }
11417 
11418     if (S.getLangOpts().CUDA && Matches.size() > 1)
11419       EliminateSuboptimalCudaMatches();
11420   }
11421 
11422   bool hasComplained() const { return HasComplained; }
11423 
11424 private:
11425   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
11426     QualType Discard;
11427     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
11428            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
11429   }
11430 
11431   /// \return true if A is considered a better overload candidate for the
11432   /// desired type than B.
11433   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
11434     // If A doesn't have exactly the correct type, we don't want to classify it
11435     // as "better" than anything else. This way, the user is required to
11436     // disambiguate for us if there are multiple candidates and no exact match.
11437     return candidateHasExactlyCorrectType(A) &&
11438            (!candidateHasExactlyCorrectType(B) ||
11439             compareEnableIfAttrs(S, A, B) == Comparison::Better);
11440   }
11441 
11442   /// \return true if we were able to eliminate all but one overload candidate,
11443   /// false otherwise.
11444   bool eliminiateSuboptimalOverloadCandidates() {
11445     // Same algorithm as overload resolution -- one pass to pick the "best",
11446     // another pass to be sure that nothing is better than the best.
11447     auto Best = Matches.begin();
11448     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11449       if (isBetterCandidate(I->second, Best->second))
11450         Best = I;
11451 
11452     const FunctionDecl *BestFn = Best->second;
11453     auto IsBestOrInferiorToBest = [this, BestFn](
11454         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11455       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11456     };
11457 
11458     // Note: We explicitly leave Matches unmodified if there isn't a clear best
11459     // option, so we can potentially give the user a better error
11460     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
11461       return false;
11462     Matches[0] = *Best;
11463     Matches.resize(1);
11464     return true;
11465   }
11466 
11467   bool isTargetTypeAFunction() const {
11468     return TargetFunctionType->isFunctionType();
11469   }
11470 
11471   // [ToType]     [Return]
11472 
11473   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11474   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11475   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11476   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11477     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11478   }
11479 
11480   // return true if any matching specializations were found
11481   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
11482                                    const DeclAccessPair& CurAccessFunPair) {
11483     if (CXXMethodDecl *Method
11484               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11485       // Skip non-static function templates when converting to pointer, and
11486       // static when converting to member pointer.
11487       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11488         return false;
11489     }
11490     else if (TargetTypeIsNonStaticMemberFunction)
11491       return false;
11492 
11493     // C++ [over.over]p2:
11494     //   If the name is a function template, template argument deduction is
11495     //   done (14.8.2.2), and if the argument deduction succeeds, the
11496     //   resulting template argument list is used to generate a single
11497     //   function template specialization, which is added to the set of
11498     //   overloaded functions considered.
11499     FunctionDecl *Specialization = nullptr;
11500     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11501     if (Sema::TemplateDeductionResult Result
11502           = S.DeduceTemplateArguments(FunctionTemplate,
11503                                       &OvlExplicitTemplateArgs,
11504                                       TargetFunctionType, Specialization,
11505                                       Info, /*IsAddressOfFunction*/true)) {
11506       // Make a note of the failed deduction for diagnostics.
11507       FailedCandidates.addCandidate()
11508           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
11509                MakeDeductionFailureInfo(Context, Result, Info));
11510       return false;
11511     }
11512 
11513     // Template argument deduction ensures that we have an exact match or
11514     // compatible pointer-to-function arguments that would be adjusted by ICS.
11515     // This function template specicalization works.
11516     assert(S.isSameOrCompatibleFunctionType(
11517               Context.getCanonicalType(Specialization->getType()),
11518               Context.getCanonicalType(TargetFunctionType)));
11519 
11520     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11521       return false;
11522 
11523     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11524     return true;
11525   }
11526 
11527   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11528                                       const DeclAccessPair& CurAccessFunPair) {
11529     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11530       // Skip non-static functions when converting to pointer, and static
11531       // when converting to member pointer.
11532       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11533         return false;
11534     }
11535     else if (TargetTypeIsNonStaticMemberFunction)
11536       return false;
11537 
11538     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11539       if (S.getLangOpts().CUDA)
11540         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11541           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11542             return false;
11543       if (FunDecl->isMultiVersion()) {
11544         const auto *TA = FunDecl->getAttr<TargetAttr>();
11545         if (TA && !TA->isDefaultVersion())
11546           return false;
11547       }
11548 
11549       // If any candidate has a placeholder return type, trigger its deduction
11550       // now.
11551       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
11552                                Complain)) {
11553         HasComplained |= Complain;
11554         return false;
11555       }
11556 
11557       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11558         return false;
11559 
11560       // If we're in C, we need to support types that aren't exactly identical.
11561       if (!S.getLangOpts().CPlusPlus ||
11562           candidateHasExactlyCorrectType(FunDecl)) {
11563         Matches.push_back(std::make_pair(
11564             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11565         FoundNonTemplateFunction = true;
11566         return true;
11567       }
11568     }
11569 
11570     return false;
11571   }
11572 
11573   bool FindAllFunctionsThatMatchTargetTypeExactly() {
11574     bool Ret = false;
11575 
11576     // If the overload expression doesn't have the form of a pointer to
11577     // member, don't try to convert it to a pointer-to-member type.
11578     if (IsInvalidFormOfPointerToMemberFunction())
11579       return false;
11580 
11581     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11582                                E = OvlExpr->decls_end();
11583          I != E; ++I) {
11584       // Look through any using declarations to find the underlying function.
11585       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11586 
11587       // C++ [over.over]p3:
11588       //   Non-member functions and static member functions match
11589       //   targets of type "pointer-to-function" or "reference-to-function."
11590       //   Nonstatic member functions match targets of
11591       //   type "pointer-to-member-function."
11592       // Note that according to DR 247, the containing class does not matter.
11593       if (FunctionTemplateDecl *FunctionTemplate
11594                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11595         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11596           Ret = true;
11597       }
11598       // If we have explicit template arguments supplied, skip non-templates.
11599       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11600                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11601         Ret = true;
11602     }
11603     assert(Ret || Matches.empty());
11604     return Ret;
11605   }
11606 
11607   void EliminateAllExceptMostSpecializedTemplate() {
11608     //   [...] and any given function template specialization F1 is
11609     //   eliminated if the set contains a second function template
11610     //   specialization whose function template is more specialized
11611     //   than the function template of F1 according to the partial
11612     //   ordering rules of 14.5.5.2.
11613 
11614     // The algorithm specified above is quadratic. We instead use a
11615     // two-pass algorithm (similar to the one used to identify the
11616     // best viable function in an overload set) that identifies the
11617     // best function template (if it exists).
11618 
11619     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11620     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11621       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11622 
11623     // TODO: It looks like FailedCandidates does not serve much purpose
11624     // here, since the no_viable diagnostic has index 0.
11625     UnresolvedSetIterator Result = S.getMostSpecialized(
11626         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11627         SourceExpr->getBeginLoc(), S.PDiag(),
11628         S.PDiag(diag::err_addr_ovl_ambiguous)
11629             << Matches[0].second->getDeclName(),
11630         S.PDiag(diag::note_ovl_candidate)
11631             << (unsigned)oc_function << (unsigned)ocs_described_template,
11632         Complain, TargetFunctionType);
11633 
11634     if (Result != MatchesCopy.end()) {
11635       // Make it the first and only element
11636       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11637       Matches[0].second = cast<FunctionDecl>(*Result);
11638       Matches.resize(1);
11639     } else
11640       HasComplained |= Complain;
11641   }
11642 
11643   void EliminateAllTemplateMatches() {
11644     //   [...] any function template specializations in the set are
11645     //   eliminated if the set also contains a non-template function, [...]
11646     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11647       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11648         ++I;
11649       else {
11650         Matches[I] = Matches[--N];
11651         Matches.resize(N);
11652       }
11653     }
11654   }
11655 
11656   void EliminateSuboptimalCudaMatches() {
11657     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11658   }
11659 
11660 public:
11661   void ComplainNoMatchesFound() const {
11662     assert(Matches.empty());
11663     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
11664         << OvlExpr->getName() << TargetFunctionType
11665         << OvlExpr->getSourceRange();
11666     if (FailedCandidates.empty())
11667       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11668                                   /*TakingAddress=*/true);
11669     else {
11670       // We have some deduction failure messages. Use them to diagnose
11671       // the function templates, and diagnose the non-template candidates
11672       // normally.
11673       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11674                                  IEnd = OvlExpr->decls_end();
11675            I != IEnd; ++I)
11676         if (FunctionDecl *Fun =
11677                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11678           if (!functionHasPassObjectSizeParams(Fun))
11679             S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
11680                                     /*TakingAddress=*/true);
11681       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
11682     }
11683   }
11684 
11685   bool IsInvalidFormOfPointerToMemberFunction() const {
11686     return TargetTypeIsNonStaticMemberFunction &&
11687       !OvlExprInfo.HasFormOfMemberPointer;
11688   }
11689 
11690   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11691       // TODO: Should we condition this on whether any functions might
11692       // have matched, or is it more appropriate to do that in callers?
11693       // TODO: a fixit wouldn't hurt.
11694       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11695         << TargetType << OvlExpr->getSourceRange();
11696   }
11697 
11698   bool IsStaticMemberFunctionFromBoundPointer() const {
11699     return StaticMemberFunctionFromBoundPointer;
11700   }
11701 
11702   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11703     S.Diag(OvlExpr->getBeginLoc(),
11704            diag::err_invalid_form_pointer_member_function)
11705         << OvlExpr->getSourceRange();
11706   }
11707 
11708   void ComplainOfInvalidConversion() const {
11709     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
11710         << OvlExpr->getName() << TargetType;
11711   }
11712 
11713   void ComplainMultipleMatchesFound() const {
11714     assert(Matches.size() > 1);
11715     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
11716         << OvlExpr->getName() << OvlExpr->getSourceRange();
11717     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11718                                 /*TakingAddress=*/true);
11719   }
11720 
11721   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11722 
11723   int getNumMatches() const { return Matches.size(); }
11724 
11725   FunctionDecl* getMatchingFunctionDecl() const {
11726     if (Matches.size() != 1) return nullptr;
11727     return Matches[0].second;
11728   }
11729 
11730   const DeclAccessPair* getMatchingFunctionAccessPair() const {
11731     if (Matches.size() != 1) return nullptr;
11732     return &Matches[0].first;
11733   }
11734 };
11735 }
11736 
11737 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11738 /// an overloaded function (C++ [over.over]), where @p From is an
11739 /// expression with overloaded function type and @p ToType is the type
11740 /// we're trying to resolve to. For example:
11741 ///
11742 /// @code
11743 /// int f(double);
11744 /// int f(int);
11745 ///
11746 /// int (*pfd)(double) = f; // selects f(double)
11747 /// @endcode
11748 ///
11749 /// This routine returns the resulting FunctionDecl if it could be
11750 /// resolved, and NULL otherwise. When @p Complain is true, this
11751 /// routine will emit diagnostics if there is an error.
11752 FunctionDecl *
11753 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11754                                          QualType TargetType,
11755                                          bool Complain,
11756                                          DeclAccessPair &FoundResult,
11757                                          bool *pHadMultipleCandidates) {
11758   assert(AddressOfExpr->getType() == Context.OverloadTy);
11759 
11760   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11761                                      Complain);
11762   int NumMatches = Resolver.getNumMatches();
11763   FunctionDecl *Fn = nullptr;
11764   bool ShouldComplain = Complain && !Resolver.hasComplained();
11765   if (NumMatches == 0 && ShouldComplain) {
11766     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11767       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11768     else
11769       Resolver.ComplainNoMatchesFound();
11770   }
11771   else if (NumMatches > 1 && ShouldComplain)
11772     Resolver.ComplainMultipleMatchesFound();
11773   else if (NumMatches == 1) {
11774     Fn = Resolver.getMatchingFunctionDecl();
11775     assert(Fn);
11776     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11777       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11778     FoundResult = *Resolver.getMatchingFunctionAccessPair();
11779     if (Complain) {
11780       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11781         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11782       else
11783         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11784     }
11785   }
11786 
11787   if (pHadMultipleCandidates)
11788     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11789   return Fn;
11790 }
11791 
11792 /// Given an expression that refers to an overloaded function, try to
11793 /// resolve that function to a single function that can have its address taken.
11794 /// This will modify `Pair` iff it returns non-null.
11795 ///
11796 /// This routine can only realistically succeed if all but one candidates in the
11797 /// overload set for SrcExpr cannot have their addresses taken.
11798 FunctionDecl *
11799 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11800                                                   DeclAccessPair &Pair) {
11801   OverloadExpr::FindResult R = OverloadExpr::find(E);
11802   OverloadExpr *Ovl = R.Expression;
11803   FunctionDecl *Result = nullptr;
11804   DeclAccessPair DAP;
11805   // Don't use the AddressOfResolver because we're specifically looking for
11806   // cases where we have one overload candidate that lacks
11807   // enable_if/pass_object_size/...
11808   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11809     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11810     if (!FD)
11811       return nullptr;
11812 
11813     if (!checkAddressOfFunctionIsAvailable(FD))
11814       continue;
11815 
11816     // We have more than one result; quit.
11817     if (Result)
11818       return nullptr;
11819     DAP = I.getPair();
11820     Result = FD;
11821   }
11822 
11823   if (Result)
11824     Pair = DAP;
11825   return Result;
11826 }
11827 
11828 /// Given an overloaded function, tries to turn it into a non-overloaded
11829 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11830 /// will perform access checks, diagnose the use of the resultant decl, and, if
11831 /// requested, potentially perform a function-to-pointer decay.
11832 ///
11833 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11834 /// Otherwise, returns true. This may emit diagnostics and return true.
11835 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11836     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
11837   Expr *E = SrcExpr.get();
11838   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11839 
11840   DeclAccessPair DAP;
11841   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11842   if (!Found || Found->isCPUDispatchMultiVersion() ||
11843       Found->isCPUSpecificMultiVersion())
11844     return false;
11845 
11846   // Emitting multiple diagnostics for a function that is both inaccessible and
11847   // unavailable is consistent with our behavior elsewhere. So, always check
11848   // for both.
11849   DiagnoseUseOfDecl(Found, E->getExprLoc());
11850   CheckAddressOfMemberAccess(E, DAP);
11851   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11852   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
11853     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11854   else
11855     SrcExpr = Fixed;
11856   return true;
11857 }
11858 
11859 /// Given an expression that refers to an overloaded function, try to
11860 /// resolve that overloaded function expression down to a single function.
11861 ///
11862 /// This routine can only resolve template-ids that refer to a single function
11863 /// template, where that template-id refers to a single template whose template
11864 /// arguments are either provided by the template-id or have defaults,
11865 /// as described in C++0x [temp.arg.explicit]p3.
11866 ///
11867 /// If no template-ids are found, no diagnostics are emitted and NULL is
11868 /// returned.
11869 FunctionDecl *
11870 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11871                                                   bool Complain,
11872                                                   DeclAccessPair *FoundResult) {
11873   // C++ [over.over]p1:
11874   //   [...] [Note: any redundant set of parentheses surrounding the
11875   //   overloaded function name is ignored (5.1). ]
11876   // C++ [over.over]p1:
11877   //   [...] The overloaded function name can be preceded by the &
11878   //   operator.
11879 
11880   // If we didn't actually find any template-ids, we're done.
11881   if (!ovl->hasExplicitTemplateArgs())
11882     return nullptr;
11883 
11884   TemplateArgumentListInfo ExplicitTemplateArgs;
11885   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11886   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11887 
11888   // Look through all of the overloaded functions, searching for one
11889   // whose type matches exactly.
11890   FunctionDecl *Matched = nullptr;
11891   for (UnresolvedSetIterator I = ovl->decls_begin(),
11892          E = ovl->decls_end(); I != E; ++I) {
11893     // C++0x [temp.arg.explicit]p3:
11894     //   [...] In contexts where deduction is done and fails, or in contexts
11895     //   where deduction is not done, if a template argument list is
11896     //   specified and it, along with any default template arguments,
11897     //   identifies a single function template specialization, then the
11898     //   template-id is an lvalue for the function template specialization.
11899     FunctionTemplateDecl *FunctionTemplate
11900       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11901 
11902     // C++ [over.over]p2:
11903     //   If the name is a function template, template argument deduction is
11904     //   done (14.8.2.2), and if the argument deduction succeeds, the
11905     //   resulting template argument list is used to generate a single
11906     //   function template specialization, which is added to the set of
11907     //   overloaded functions considered.
11908     FunctionDecl *Specialization = nullptr;
11909     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11910     if (TemplateDeductionResult Result
11911           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11912                                     Specialization, Info,
11913                                     /*IsAddressOfFunction*/true)) {
11914       // Make a note of the failed deduction for diagnostics.
11915       // TODO: Actually use the failed-deduction info?
11916       FailedCandidates.addCandidate()
11917           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11918                MakeDeductionFailureInfo(Context, Result, Info));
11919       continue;
11920     }
11921 
11922     assert(Specialization && "no specialization and no error?");
11923 
11924     // Multiple matches; we can't resolve to a single declaration.
11925     if (Matched) {
11926       if (Complain) {
11927         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11928           << ovl->getName();
11929         NoteAllOverloadCandidates(ovl);
11930       }
11931       return nullptr;
11932     }
11933 
11934     Matched = Specialization;
11935     if (FoundResult) *FoundResult = I.getPair();
11936   }
11937 
11938   if (Matched &&
11939       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11940     return nullptr;
11941 
11942   return Matched;
11943 }
11944 
11945 // Resolve and fix an overloaded expression that can be resolved
11946 // because it identifies a single function template specialization.
11947 //
11948 // Last three arguments should only be supplied if Complain = true
11949 //
11950 // Return true if it was logically possible to so resolve the
11951 // expression, regardless of whether or not it succeeded.  Always
11952 // returns true if 'complain' is set.
11953 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11954                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
11955                       bool complain, SourceRange OpRangeForComplaining,
11956                                            QualType DestTypeForComplaining,
11957                                             unsigned DiagIDForComplaining) {
11958   assert(SrcExpr.get()->getType() == Context.OverloadTy);
11959 
11960   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11961 
11962   DeclAccessPair found;
11963   ExprResult SingleFunctionExpression;
11964   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11965                            ovl.Expression, /*complain*/ false, &found)) {
11966     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
11967       SrcExpr = ExprError();
11968       return true;
11969     }
11970 
11971     // It is only correct to resolve to an instance method if we're
11972     // resolving a form that's permitted to be a pointer to member.
11973     // Otherwise we'll end up making a bound member expression, which
11974     // is illegal in all the contexts we resolve like this.
11975     if (!ovl.HasFormOfMemberPointer &&
11976         isa<CXXMethodDecl>(fn) &&
11977         cast<CXXMethodDecl>(fn)->isInstance()) {
11978       if (!complain) return false;
11979 
11980       Diag(ovl.Expression->getExprLoc(),
11981            diag::err_bound_member_function)
11982         << 0 << ovl.Expression->getSourceRange();
11983 
11984       // TODO: I believe we only end up here if there's a mix of
11985       // static and non-static candidates (otherwise the expression
11986       // would have 'bound member' type, not 'overload' type).
11987       // Ideally we would note which candidate was chosen and why
11988       // the static candidates were rejected.
11989       SrcExpr = ExprError();
11990       return true;
11991     }
11992 
11993     // Fix the expression to refer to 'fn'.
11994     SingleFunctionExpression =
11995         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11996 
11997     // If desired, do function-to-pointer decay.
11998     if (doFunctionPointerConverion) {
11999       SingleFunctionExpression =
12000         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
12001       if (SingleFunctionExpression.isInvalid()) {
12002         SrcExpr = ExprError();
12003         return true;
12004       }
12005     }
12006   }
12007 
12008   if (!SingleFunctionExpression.isUsable()) {
12009     if (complain) {
12010       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
12011         << ovl.Expression->getName()
12012         << DestTypeForComplaining
12013         << OpRangeForComplaining
12014         << ovl.Expression->getQualifierLoc().getSourceRange();
12015       NoteAllOverloadCandidates(SrcExpr.get());
12016 
12017       SrcExpr = ExprError();
12018       return true;
12019     }
12020 
12021     return false;
12022   }
12023 
12024   SrcExpr = SingleFunctionExpression;
12025   return true;
12026 }
12027 
12028 /// Add a single candidate to the overload set.
12029 static void AddOverloadedCallCandidate(Sema &S,
12030                                        DeclAccessPair FoundDecl,
12031                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
12032                                        ArrayRef<Expr *> Args,
12033                                        OverloadCandidateSet &CandidateSet,
12034                                        bool PartialOverloading,
12035                                        bool KnownValid) {
12036   NamedDecl *Callee = FoundDecl.getDecl();
12037   if (isa<UsingShadowDecl>(Callee))
12038     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
12039 
12040   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
12041     if (ExplicitTemplateArgs) {
12042       assert(!KnownValid && "Explicit template arguments?");
12043       return;
12044     }
12045     // Prevent ill-formed function decls to be added as overload candidates.
12046     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
12047       return;
12048 
12049     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
12050                            /*SuppressUserConversions=*/false,
12051                            PartialOverloading);
12052     return;
12053   }
12054 
12055   if (FunctionTemplateDecl *FuncTemplate
12056       = dyn_cast<FunctionTemplateDecl>(Callee)) {
12057     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
12058                                    ExplicitTemplateArgs, Args, CandidateSet,
12059                                    /*SuppressUserConversions=*/false,
12060                                    PartialOverloading);
12061     return;
12062   }
12063 
12064   assert(!KnownValid && "unhandled case in overloaded call candidate");
12065 }
12066 
12067 /// Add the overload candidates named by callee and/or found by argument
12068 /// dependent lookup to the given overload set.
12069 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
12070                                        ArrayRef<Expr *> Args,
12071                                        OverloadCandidateSet &CandidateSet,
12072                                        bool PartialOverloading) {
12073 
12074 #ifndef NDEBUG
12075   // Verify that ArgumentDependentLookup is consistent with the rules
12076   // in C++0x [basic.lookup.argdep]p3:
12077   //
12078   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
12079   //   and let Y be the lookup set produced by argument dependent
12080   //   lookup (defined as follows). If X contains
12081   //
12082   //     -- a declaration of a class member, or
12083   //
12084   //     -- a block-scope function declaration that is not a
12085   //        using-declaration, or
12086   //
12087   //     -- a declaration that is neither a function or a function
12088   //        template
12089   //
12090   //   then Y is empty.
12091 
12092   if (ULE->requiresADL()) {
12093     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12094            E = ULE->decls_end(); I != E; ++I) {
12095       assert(!(*I)->getDeclContext()->isRecord());
12096       assert(isa<UsingShadowDecl>(*I) ||
12097              !(*I)->getDeclContext()->isFunctionOrMethod());
12098       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
12099     }
12100   }
12101 #endif
12102 
12103   // It would be nice to avoid this copy.
12104   TemplateArgumentListInfo TABuffer;
12105   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12106   if (ULE->hasExplicitTemplateArgs()) {
12107     ULE->copyTemplateArgumentsInto(TABuffer);
12108     ExplicitTemplateArgs = &TABuffer;
12109   }
12110 
12111   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12112          E = ULE->decls_end(); I != E; ++I)
12113     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12114                                CandidateSet, PartialOverloading,
12115                                /*KnownValid*/ true);
12116 
12117   if (ULE->requiresADL())
12118     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
12119                                          Args, ExplicitTemplateArgs,
12120                                          CandidateSet, PartialOverloading);
12121 }
12122 
12123 /// Determine whether a declaration with the specified name could be moved into
12124 /// a different namespace.
12125 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
12126   switch (Name.getCXXOverloadedOperator()) {
12127   case OO_New: case OO_Array_New:
12128   case OO_Delete: case OO_Array_Delete:
12129     return false;
12130 
12131   default:
12132     return true;
12133   }
12134 }
12135 
12136 /// Attempt to recover from an ill-formed use of a non-dependent name in a
12137 /// template, where the non-dependent name was declared after the template
12138 /// was defined. This is common in code written for a compilers which do not
12139 /// correctly implement two-stage name lookup.
12140 ///
12141 /// Returns true if a viable candidate was found and a diagnostic was issued.
12142 static bool
12143 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
12144                        const CXXScopeSpec &SS, LookupResult &R,
12145                        OverloadCandidateSet::CandidateSetKind CSK,
12146                        TemplateArgumentListInfo *ExplicitTemplateArgs,
12147                        ArrayRef<Expr *> Args,
12148                        bool *DoDiagnoseEmptyLookup = nullptr) {
12149   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
12150     return false;
12151 
12152   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
12153     if (DC->isTransparentContext())
12154       continue;
12155 
12156     SemaRef.LookupQualifiedName(R, DC);
12157 
12158     if (!R.empty()) {
12159       R.suppressDiagnostics();
12160 
12161       if (isa<CXXRecordDecl>(DC)) {
12162         // Don't diagnose names we find in classes; we get much better
12163         // diagnostics for these from DiagnoseEmptyLookup.
12164         R.clear();
12165         if (DoDiagnoseEmptyLookup)
12166           *DoDiagnoseEmptyLookup = true;
12167         return false;
12168       }
12169 
12170       OverloadCandidateSet Candidates(FnLoc, CSK);
12171       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12172         AddOverloadedCallCandidate(SemaRef, I.getPair(),
12173                                    ExplicitTemplateArgs, Args,
12174                                    Candidates, false, /*KnownValid*/ false);
12175 
12176       OverloadCandidateSet::iterator Best;
12177       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
12178         // No viable functions. Don't bother the user with notes for functions
12179         // which don't work and shouldn't be found anyway.
12180         R.clear();
12181         return false;
12182       }
12183 
12184       // Find the namespaces where ADL would have looked, and suggest
12185       // declaring the function there instead.
12186       Sema::AssociatedNamespaceSet AssociatedNamespaces;
12187       Sema::AssociatedClassSet AssociatedClasses;
12188       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
12189                                                  AssociatedNamespaces,
12190                                                  AssociatedClasses);
12191       Sema::AssociatedNamespaceSet SuggestedNamespaces;
12192       if (canBeDeclaredInNamespace(R.getLookupName())) {
12193         DeclContext *Std = SemaRef.getStdNamespace();
12194         for (Sema::AssociatedNamespaceSet::iterator
12195                it = AssociatedNamespaces.begin(),
12196                end = AssociatedNamespaces.end(); it != end; ++it) {
12197           // Never suggest declaring a function within namespace 'std'.
12198           if (Std && Std->Encloses(*it))
12199             continue;
12200 
12201           // Never suggest declaring a function within a namespace with a
12202           // reserved name, like __gnu_cxx.
12203           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
12204           if (NS &&
12205               NS->getQualifiedNameAsString().find("__") != std::string::npos)
12206             continue;
12207 
12208           SuggestedNamespaces.insert(*it);
12209         }
12210       }
12211 
12212       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
12213         << R.getLookupName();
12214       if (SuggestedNamespaces.empty()) {
12215         SemaRef.Diag(Best->Function->getLocation(),
12216                      diag::note_not_found_by_two_phase_lookup)
12217           << R.getLookupName() << 0;
12218       } else if (SuggestedNamespaces.size() == 1) {
12219         SemaRef.Diag(Best->Function->getLocation(),
12220                      diag::note_not_found_by_two_phase_lookup)
12221           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
12222       } else {
12223         // FIXME: It would be useful to list the associated namespaces here,
12224         // but the diagnostics infrastructure doesn't provide a way to produce
12225         // a localized representation of a list of items.
12226         SemaRef.Diag(Best->Function->getLocation(),
12227                      diag::note_not_found_by_two_phase_lookup)
12228           << R.getLookupName() << 2;
12229       }
12230 
12231       // Try to recover by calling this function.
12232       return true;
12233     }
12234 
12235     R.clear();
12236   }
12237 
12238   return false;
12239 }
12240 
12241 /// Attempt to recover from ill-formed use of a non-dependent operator in a
12242 /// template, where the non-dependent operator was declared after the template
12243 /// was defined.
12244 ///
12245 /// Returns true if a viable candidate was found and a diagnostic was issued.
12246 static bool
12247 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
12248                                SourceLocation OpLoc,
12249                                ArrayRef<Expr *> Args) {
12250   DeclarationName OpName =
12251     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
12252   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
12253   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
12254                                 OverloadCandidateSet::CSK_Operator,
12255                                 /*ExplicitTemplateArgs=*/nullptr, Args);
12256 }
12257 
12258 namespace {
12259 class BuildRecoveryCallExprRAII {
12260   Sema &SemaRef;
12261 public:
12262   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
12263     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
12264     SemaRef.IsBuildingRecoveryCallExpr = true;
12265   }
12266 
12267   ~BuildRecoveryCallExprRAII() {
12268     SemaRef.IsBuildingRecoveryCallExpr = false;
12269   }
12270 };
12271 
12272 }
12273 
12274 /// Attempts to recover from a call where no functions were found.
12275 ///
12276 /// Returns true if new candidates were found.
12277 static ExprResult
12278 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12279                       UnresolvedLookupExpr *ULE,
12280                       SourceLocation LParenLoc,
12281                       MutableArrayRef<Expr *> Args,
12282                       SourceLocation RParenLoc,
12283                       bool EmptyLookup, bool AllowTypoCorrection) {
12284   // Do not try to recover if it is already building a recovery call.
12285   // This stops infinite loops for template instantiations like
12286   //
12287   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
12288   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
12289   //
12290   if (SemaRef.IsBuildingRecoveryCallExpr)
12291     return ExprError();
12292   BuildRecoveryCallExprRAII RCE(SemaRef);
12293 
12294   CXXScopeSpec SS;
12295   SS.Adopt(ULE->getQualifierLoc());
12296   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
12297 
12298   TemplateArgumentListInfo TABuffer;
12299   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12300   if (ULE->hasExplicitTemplateArgs()) {
12301     ULE->copyTemplateArgumentsInto(TABuffer);
12302     ExplicitTemplateArgs = &TABuffer;
12303   }
12304 
12305   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
12306                  Sema::LookupOrdinaryName);
12307   bool DoDiagnoseEmptyLookup = EmptyLookup;
12308   if (!DiagnoseTwoPhaseLookup(
12309           SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal,
12310           ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) {
12311     NoTypoCorrectionCCC NoTypoValidator{};
12312     FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
12313                                                 ExplicitTemplateArgs != nullptr,
12314                                                 dyn_cast<MemberExpr>(Fn));
12315     CorrectionCandidateCallback &Validator =
12316         AllowTypoCorrection
12317             ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
12318             : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
12319     if (!DoDiagnoseEmptyLookup ||
12320         SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
12321                                     Args))
12322       return ExprError();
12323   }
12324 
12325   assert(!R.empty() && "lookup results empty despite recovery");
12326 
12327   // If recovery created an ambiguity, just bail out.
12328   if (R.isAmbiguous()) {
12329     R.suppressDiagnostics();
12330     return ExprError();
12331   }
12332 
12333   // Build an implicit member call if appropriate.  Just drop the
12334   // casts and such from the call, we don't really care.
12335   ExprResult NewFn = ExprError();
12336   if ((*R.begin())->isCXXClassMember())
12337     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12338                                                     ExplicitTemplateArgs, S);
12339   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
12340     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
12341                                         ExplicitTemplateArgs);
12342   else
12343     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
12344 
12345   if (NewFn.isInvalid())
12346     return ExprError();
12347 
12348   // This shouldn't cause an infinite loop because we're giving it
12349   // an expression with viable lookup results, which should never
12350   // end up here.
12351   return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
12352                                MultiExprArg(Args.data(), Args.size()),
12353                                RParenLoc);
12354 }
12355 
12356 /// Constructs and populates an OverloadedCandidateSet from
12357 /// the given function.
12358 /// \returns true when an the ExprResult output parameter has been set.
12359 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
12360                                   UnresolvedLookupExpr *ULE,
12361                                   MultiExprArg Args,
12362                                   SourceLocation RParenLoc,
12363                                   OverloadCandidateSet *CandidateSet,
12364                                   ExprResult *Result) {
12365 #ifndef NDEBUG
12366   if (ULE->requiresADL()) {
12367     // To do ADL, we must have found an unqualified name.
12368     assert(!ULE->getQualifier() && "qualified name with ADL");
12369 
12370     // We don't perform ADL for implicit declarations of builtins.
12371     // Verify that this was correctly set up.
12372     FunctionDecl *F;
12373     if (ULE->decls_begin() != ULE->decls_end() &&
12374         ULE->decls_begin() + 1 == ULE->decls_end() &&
12375         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
12376         F->getBuiltinID() && F->isImplicit())
12377       llvm_unreachable("performing ADL for builtin");
12378 
12379     // We don't perform ADL in C.
12380     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
12381   }
12382 #endif
12383 
12384   UnbridgedCastsSet UnbridgedCasts;
12385   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
12386     *Result = ExprError();
12387     return true;
12388   }
12389 
12390   // Add the functions denoted by the callee to the set of candidate
12391   // functions, including those from argument-dependent lookup.
12392   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
12393 
12394   if (getLangOpts().MSVCCompat &&
12395       CurContext->isDependentContext() && !isSFINAEContext() &&
12396       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
12397 
12398     OverloadCandidateSet::iterator Best;
12399     if (CandidateSet->empty() ||
12400         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
12401             OR_No_Viable_Function) {
12402       // In Microsoft mode, if we are inside a template class member function
12403       // then create a type dependent CallExpr. The goal is to postpone name
12404       // lookup to instantiation time to be able to search into type dependent
12405       // base classes.
12406       CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy,
12407                                       VK_RValue, RParenLoc);
12408       CE->setTypeDependent(true);
12409       CE->setValueDependent(true);
12410       CE->setInstantiationDependent(true);
12411       *Result = CE;
12412       return true;
12413     }
12414   }
12415 
12416   if (CandidateSet->empty())
12417     return false;
12418 
12419   UnbridgedCasts.restore();
12420   return false;
12421 }
12422 
12423 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
12424 /// the completed call expression. If overload resolution fails, emits
12425 /// diagnostics and returns ExprError()
12426 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12427                                            UnresolvedLookupExpr *ULE,
12428                                            SourceLocation LParenLoc,
12429                                            MultiExprArg Args,
12430                                            SourceLocation RParenLoc,
12431                                            Expr *ExecConfig,
12432                                            OverloadCandidateSet *CandidateSet,
12433                                            OverloadCandidateSet::iterator *Best,
12434                                            OverloadingResult OverloadResult,
12435                                            bool AllowTypoCorrection) {
12436   if (CandidateSet->empty())
12437     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
12438                                  RParenLoc, /*EmptyLookup=*/true,
12439                                  AllowTypoCorrection);
12440 
12441   switch (OverloadResult) {
12442   case OR_Success: {
12443     FunctionDecl *FDecl = (*Best)->Function;
12444     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
12445     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
12446       return ExprError();
12447     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12448     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12449                                          ExecConfig, /*IsExecConfig=*/false,
12450                                          (*Best)->IsADLCandidate);
12451   }
12452 
12453   case OR_No_Viable_Function: {
12454     // Try to recover by looking for viable functions which the user might
12455     // have meant to call.
12456     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
12457                                                 Args, RParenLoc,
12458                                                 /*EmptyLookup=*/false,
12459                                                 AllowTypoCorrection);
12460     if (!Recovery.isInvalid())
12461       return Recovery;
12462 
12463     // If the user passes in a function that we can't take the address of, we
12464     // generally end up emitting really bad error messages. Here, we attempt to
12465     // emit better ones.
12466     for (const Expr *Arg : Args) {
12467       if (!Arg->getType()->isFunctionType())
12468         continue;
12469       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12470         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12471         if (FD &&
12472             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12473                                                        Arg->getExprLoc()))
12474           return ExprError();
12475       }
12476     }
12477 
12478     CandidateSet->NoteCandidates(
12479         PartialDiagnosticAt(
12480             Fn->getBeginLoc(),
12481             SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
12482                 << ULE->getName() << Fn->getSourceRange()),
12483         SemaRef, OCD_AllCandidates, Args);
12484     break;
12485   }
12486 
12487   case OR_Ambiguous:
12488     CandidateSet->NoteCandidates(
12489         PartialDiagnosticAt(Fn->getBeginLoc(),
12490                             SemaRef.PDiag(diag::err_ovl_ambiguous_call)
12491                                 << ULE->getName() << Fn->getSourceRange()),
12492         SemaRef, OCD_AmbiguousCandidates, Args);
12493     break;
12494 
12495   case OR_Deleted: {
12496     CandidateSet->NoteCandidates(
12497         PartialDiagnosticAt(Fn->getBeginLoc(),
12498                             SemaRef.PDiag(diag::err_ovl_deleted_call)
12499                                 << ULE->getName() << Fn->getSourceRange()),
12500         SemaRef, OCD_AllCandidates, Args);
12501 
12502     // We emitted an error for the unavailable/deleted function call but keep
12503     // the call in the AST.
12504     FunctionDecl *FDecl = (*Best)->Function;
12505     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12506     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12507                                          ExecConfig, /*IsExecConfig=*/false,
12508                                          (*Best)->IsADLCandidate);
12509   }
12510   }
12511 
12512   // Overload resolution failed.
12513   return ExprError();
12514 }
12515 
12516 static void markUnaddressableCandidatesUnviable(Sema &S,
12517                                                 OverloadCandidateSet &CS) {
12518   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12519     if (I->Viable &&
12520         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12521       I->Viable = false;
12522       I->FailureKind = ovl_fail_addr_not_available;
12523     }
12524   }
12525 }
12526 
12527 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
12528 /// (which eventually refers to the declaration Func) and the call
12529 /// arguments Args/NumArgs, attempt to resolve the function call down
12530 /// to a specific function. If overload resolution succeeds, returns
12531 /// the call expression produced by overload resolution.
12532 /// Otherwise, emits diagnostics and returns ExprError.
12533 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12534                                          UnresolvedLookupExpr *ULE,
12535                                          SourceLocation LParenLoc,
12536                                          MultiExprArg Args,
12537                                          SourceLocation RParenLoc,
12538                                          Expr *ExecConfig,
12539                                          bool AllowTypoCorrection,
12540                                          bool CalleesAddressIsTaken) {
12541   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12542                                     OverloadCandidateSet::CSK_Normal);
12543   ExprResult result;
12544 
12545   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12546                              &result))
12547     return result;
12548 
12549   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12550   // functions that aren't addressible are considered unviable.
12551   if (CalleesAddressIsTaken)
12552     markUnaddressableCandidatesUnviable(*this, CandidateSet);
12553 
12554   OverloadCandidateSet::iterator Best;
12555   OverloadingResult OverloadResult =
12556       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
12557 
12558   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
12559                                   ExecConfig, &CandidateSet, &Best,
12560                                   OverloadResult, AllowTypoCorrection);
12561 }
12562 
12563 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
12564   return Functions.size() > 1 ||
12565     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12566 }
12567 
12568 /// Create a unary operation that may resolve to an overloaded
12569 /// operator.
12570 ///
12571 /// \param OpLoc The location of the operator itself (e.g., '*').
12572 ///
12573 /// \param Opc The UnaryOperatorKind that describes this operator.
12574 ///
12575 /// \param Fns The set of non-member functions that will be
12576 /// considered by overload resolution. The caller needs to build this
12577 /// set based on the context using, e.g.,
12578 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12579 /// set should not contain any member functions; those will be added
12580 /// by CreateOverloadedUnaryOp().
12581 ///
12582 /// \param Input The input argument.
12583 ExprResult
12584 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12585                               const UnresolvedSetImpl &Fns,
12586                               Expr *Input, bool PerformADL) {
12587   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12588   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12589   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12590   // TODO: provide better source location info.
12591   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12592 
12593   if (checkPlaceholderForOverload(*this, Input))
12594     return ExprError();
12595 
12596   Expr *Args[2] = { Input, nullptr };
12597   unsigned NumArgs = 1;
12598 
12599   // For post-increment and post-decrement, add the implicit '0' as
12600   // the second argument, so that we know this is a post-increment or
12601   // post-decrement.
12602   if (Opc == UO_PostInc || Opc == UO_PostDec) {
12603     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12604     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12605                                      SourceLocation());
12606     NumArgs = 2;
12607   }
12608 
12609   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12610 
12611   if (Input->isTypeDependent()) {
12612     if (Fns.empty())
12613       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12614                                          VK_RValue, OK_Ordinary, OpLoc, false);
12615 
12616     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12617     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
12618         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
12619         /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end());
12620     return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray,
12621                                        Context.DependentTy, VK_RValue, OpLoc,
12622                                        FPOptions());
12623   }
12624 
12625   // Build an empty overload set.
12626   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12627 
12628   // Add the candidates from the given function set.
12629   AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
12630 
12631   // Add operator candidates that are member functions.
12632   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12633 
12634   // Add candidates from ADL.
12635   if (PerformADL) {
12636     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12637                                          /*ExplicitTemplateArgs*/nullptr,
12638                                          CandidateSet);
12639   }
12640 
12641   // Add builtin operator candidates.
12642   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12643 
12644   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12645 
12646   // Perform overload resolution.
12647   OverloadCandidateSet::iterator Best;
12648   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12649   case OR_Success: {
12650     // We found a built-in operator or an overloaded operator.
12651     FunctionDecl *FnDecl = Best->Function;
12652 
12653     if (FnDecl) {
12654       Expr *Base = nullptr;
12655       // We matched an overloaded operator. Build a call to that
12656       // operator.
12657 
12658       // Convert the arguments.
12659       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12660         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12661 
12662         ExprResult InputRes =
12663           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12664                                               Best->FoundDecl, Method);
12665         if (InputRes.isInvalid())
12666           return ExprError();
12667         Base = Input = InputRes.get();
12668       } else {
12669         // Convert the arguments.
12670         ExprResult InputInit
12671           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12672                                                       Context,
12673                                                       FnDecl->getParamDecl(0)),
12674                                       SourceLocation(),
12675                                       Input);
12676         if (InputInit.isInvalid())
12677           return ExprError();
12678         Input = InputInit.get();
12679       }
12680 
12681       // Build the actual expression node.
12682       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12683                                                 Base, HadMultipleCandidates,
12684                                                 OpLoc);
12685       if (FnExpr.isInvalid())
12686         return ExprError();
12687 
12688       // Determine the result type.
12689       QualType ResultTy = FnDecl->getReturnType();
12690       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12691       ResultTy = ResultTy.getNonLValueExprType(Context);
12692 
12693       Args[0] = Input;
12694       CallExpr *TheCall = CXXOperatorCallExpr::Create(
12695           Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
12696           FPOptions(), Best->IsADLCandidate);
12697 
12698       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12699         return ExprError();
12700 
12701       if (CheckFunctionCall(FnDecl, TheCall,
12702                             FnDecl->getType()->castAs<FunctionProtoType>()))
12703         return ExprError();
12704 
12705       return MaybeBindToTemporary(TheCall);
12706     } else {
12707       // We matched a built-in operator. Convert the arguments, then
12708       // break out so that we will build the appropriate built-in
12709       // operator node.
12710       ExprResult InputRes = PerformImplicitConversion(
12711           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
12712           CCK_ForBuiltinOverloadedOp);
12713       if (InputRes.isInvalid())
12714         return ExprError();
12715       Input = InputRes.get();
12716       break;
12717     }
12718   }
12719 
12720   case OR_No_Viable_Function:
12721     // This is an erroneous use of an operator which can be overloaded by
12722     // a non-member function. Check for non-member operators which were
12723     // defined too late to be candidates.
12724     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12725       // FIXME: Recover by calling the found function.
12726       return ExprError();
12727 
12728     // No viable function; fall through to handling this as a
12729     // built-in operator, which will produce an error message for us.
12730     break;
12731 
12732   case OR_Ambiguous:
12733     CandidateSet.NoteCandidates(
12734         PartialDiagnosticAt(OpLoc,
12735                             PDiag(diag::err_ovl_ambiguous_oper_unary)
12736                                 << UnaryOperator::getOpcodeStr(Opc)
12737                                 << Input->getType() << Input->getSourceRange()),
12738         *this, OCD_AmbiguousCandidates, ArgsArray,
12739         UnaryOperator::getOpcodeStr(Opc), OpLoc);
12740     return ExprError();
12741 
12742   case OR_Deleted:
12743     CandidateSet.NoteCandidates(
12744         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
12745                                        << UnaryOperator::getOpcodeStr(Opc)
12746                                        << Input->getSourceRange()),
12747         *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
12748         OpLoc);
12749     return ExprError();
12750   }
12751 
12752   // Either we found no viable overloaded operator or we matched a
12753   // built-in operator. In either case, fall through to trying to
12754   // build a built-in operation.
12755   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12756 }
12757 
12758 /// Perform lookup for an overloaded binary operator.
12759 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
12760                                  OverloadedOperatorKind Op,
12761                                  const UnresolvedSetImpl &Fns,
12762                                  ArrayRef<Expr *> Args, bool PerformADL) {
12763   SourceLocation OpLoc = CandidateSet.getLocation();
12764 
12765   OverloadedOperatorKind ExtraOp =
12766       CandidateSet.getRewriteInfo().AllowRewrittenCandidates
12767           ? getRewrittenOverloadedOperator(Op)
12768           : OO_None;
12769 
12770   // Add the candidates from the given function set. This also adds the
12771   // rewritten candidates using these functions if necessary.
12772   AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
12773 
12774   // Add operator candidates that are member functions.
12775   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12776   if (CandidateSet.getRewriteInfo().shouldAddReversed(Op))
12777     AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
12778                                 OverloadCandidateParamOrder::Reversed);
12779 
12780   // In C++20, also add any rewritten member candidates.
12781   if (ExtraOp) {
12782     AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
12783     if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp))
12784       AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
12785                                   CandidateSet,
12786                                   OverloadCandidateParamOrder::Reversed);
12787   }
12788 
12789   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12790   // performed for an assignment operator (nor for operator[] nor operator->,
12791   // which don't get here).
12792   if (Op != OO_Equal && PerformADL) {
12793     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12794     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12795                                          /*ExplicitTemplateArgs*/ nullptr,
12796                                          CandidateSet);
12797     if (ExtraOp) {
12798       DeclarationName ExtraOpName =
12799           Context.DeclarationNames.getCXXOperatorName(ExtraOp);
12800       AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
12801                                            /*ExplicitTemplateArgs*/ nullptr,
12802                                            CandidateSet);
12803     }
12804   }
12805 
12806   // Add builtin operator candidates.
12807   //
12808   // FIXME: We don't add any rewritten candidates here. This is strictly
12809   // incorrect; a builtin candidate could be hidden by a non-viable candidate,
12810   // resulting in our selecting a rewritten builtin candidate. For example:
12811   //
12812   //   enum class E { e };
12813   //   bool operator!=(E, E) requires false;
12814   //   bool k = E::e != E::e;
12815   //
12816   // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
12817   // it seems unreasonable to consider rewritten builtin candidates. A core
12818   // issue has been filed proposing to removed this requirement.
12819   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12820 }
12821 
12822 /// Create a binary operation that may resolve to an overloaded
12823 /// operator.
12824 ///
12825 /// \param OpLoc The location of the operator itself (e.g., '+').
12826 ///
12827 /// \param Opc The BinaryOperatorKind that describes this operator.
12828 ///
12829 /// \param Fns The set of non-member functions that will be
12830 /// considered by overload resolution. The caller needs to build this
12831 /// set based on the context using, e.g.,
12832 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12833 /// set should not contain any member functions; those will be added
12834 /// by CreateOverloadedBinOp().
12835 ///
12836 /// \param LHS Left-hand argument.
12837 /// \param RHS Right-hand argument.
12838 /// \param PerformADL Whether to consider operator candidates found by ADL.
12839 /// \param AllowRewrittenCandidates Whether to consider candidates found by
12840 ///        C++20 operator rewrites.
12841 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
12842 ///        the function in question. Such a function is never a candidate in
12843 ///        our overload resolution. This also enables synthesizing a three-way
12844 ///        comparison from < and == as described in C++20 [class.spaceship]p1.
12845 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12846                                        BinaryOperatorKind Opc,
12847                                        const UnresolvedSetImpl &Fns, Expr *LHS,
12848                                        Expr *RHS, bool PerformADL,
12849                                        bool AllowRewrittenCandidates,
12850                                        FunctionDecl *DefaultedFn) {
12851   Expr *Args[2] = { LHS, RHS };
12852   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12853 
12854   if (!getLangOpts().CPlusPlus2a)
12855     AllowRewrittenCandidates = false;
12856 
12857   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12858 
12859   // If either side is type-dependent, create an appropriate dependent
12860   // expression.
12861   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12862     if (Fns.empty()) {
12863       // If there are no functions to store, just build a dependent
12864       // BinaryOperator or CompoundAssignment.
12865       if (Opc <= BO_Assign || Opc > BO_OrAssign)
12866         return new (Context) BinaryOperator(
12867             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12868             OpLoc, FPFeatures);
12869 
12870       return new (Context) CompoundAssignOperator(
12871           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12872           Context.DependentTy, Context.DependentTy, OpLoc,
12873           FPFeatures);
12874     }
12875 
12876     // FIXME: save results of ADL from here?
12877     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12878     // TODO: provide better source location info in DNLoc component.
12879     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12880     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12881     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
12882         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
12883         /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end());
12884     return CXXOperatorCallExpr::Create(Context, Op, Fn, Args,
12885                                        Context.DependentTy, VK_RValue, OpLoc,
12886                                        FPFeatures);
12887   }
12888 
12889   // Always do placeholder-like conversions on the RHS.
12890   if (checkPlaceholderForOverload(*this, Args[1]))
12891     return ExprError();
12892 
12893   // Do placeholder-like conversion on the LHS; note that we should
12894   // not get here with a PseudoObject LHS.
12895   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12896   if (checkPlaceholderForOverload(*this, Args[0]))
12897     return ExprError();
12898 
12899   // If this is the assignment operator, we only perform overload resolution
12900   // if the left-hand side is a class or enumeration type. This is actually
12901   // a hack. The standard requires that we do overload resolution between the
12902   // various built-in candidates, but as DR507 points out, this can lead to
12903   // problems. So we do it this way, which pretty much follows what GCC does.
12904   // Note that we go the traditional code path for compound assignment forms.
12905   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12906     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12907 
12908   // If this is the .* operator, which is not overloadable, just
12909   // create a built-in binary operator.
12910   if (Opc == BO_PtrMemD)
12911     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12912 
12913   // Build the overload set.
12914   OverloadCandidateSet CandidateSet(
12915       OpLoc, OverloadCandidateSet::CSK_Operator,
12916       OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates));
12917   if (DefaultedFn)
12918     CandidateSet.exclude(DefaultedFn);
12919   LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
12920 
12921   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12922 
12923   // Perform overload resolution.
12924   OverloadCandidateSet::iterator Best;
12925   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12926     case OR_Success: {
12927       // We found a built-in operator or an overloaded operator.
12928       FunctionDecl *FnDecl = Best->Function;
12929 
12930       bool IsReversed = (Best->RewriteKind & CRK_Reversed);
12931       if (IsReversed)
12932         std::swap(Args[0], Args[1]);
12933 
12934       if (FnDecl) {
12935         Expr *Base = nullptr;
12936         // We matched an overloaded operator. Build a call to that
12937         // operator.
12938 
12939         OverloadedOperatorKind ChosenOp =
12940             FnDecl->getDeclName().getCXXOverloadedOperator();
12941 
12942         // C++2a [over.match.oper]p9:
12943         //   If a rewritten operator== candidate is selected by overload
12944         //   resolution for an operator@, its return type shall be cv bool
12945         if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
12946             !FnDecl->getReturnType()->isBooleanType()) {
12947           Diag(OpLoc, diag::err_ovl_rewrite_equalequal_not_bool)
12948               << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
12949               << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12950           Diag(FnDecl->getLocation(), diag::note_declared_at);
12951           return ExprError();
12952         }
12953 
12954         if (AllowRewrittenCandidates && !IsReversed &&
12955             CandidateSet.getRewriteInfo().shouldAddReversed(ChosenOp)) {
12956           // We could have reversed this operator, but didn't. Check if the
12957           // reversed form was a viable candidate, and if so, if it had a
12958           // better conversion for either parameter. If so, this call is
12959           // formally ambiguous, and allowing it is an extension.
12960           for (OverloadCandidate &Cand : CandidateSet) {
12961             if (Cand.Viable && Cand.Function == FnDecl &&
12962                 Cand.RewriteKind & CRK_Reversed) {
12963               for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
12964                 if (CompareImplicitConversionSequences(
12965                         *this, OpLoc, Cand.Conversions[ArgIdx],
12966                         Best->Conversions[ArgIdx]) ==
12967                     ImplicitConversionSequence::Better) {
12968                   Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
12969                       << BinaryOperator::getOpcodeStr(Opc)
12970                       << Args[0]->getType() << Args[1]->getType()
12971                       << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12972                   Diag(FnDecl->getLocation(),
12973                        diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
12974                 }
12975               }
12976               break;
12977             }
12978           }
12979         }
12980 
12981         // Convert the arguments.
12982         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12983           // Best->Access is only meaningful for class members.
12984           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12985 
12986           ExprResult Arg1 =
12987             PerformCopyInitialization(
12988               InitializedEntity::InitializeParameter(Context,
12989                                                      FnDecl->getParamDecl(0)),
12990               SourceLocation(), Args[1]);
12991           if (Arg1.isInvalid())
12992             return ExprError();
12993 
12994           ExprResult Arg0 =
12995             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12996                                                 Best->FoundDecl, Method);
12997           if (Arg0.isInvalid())
12998             return ExprError();
12999           Base = Args[0] = Arg0.getAs<Expr>();
13000           Args[1] = RHS = Arg1.getAs<Expr>();
13001         } else {
13002           // Convert the arguments.
13003           ExprResult Arg0 = PerformCopyInitialization(
13004             InitializedEntity::InitializeParameter(Context,
13005                                                    FnDecl->getParamDecl(0)),
13006             SourceLocation(), Args[0]);
13007           if (Arg0.isInvalid())
13008             return ExprError();
13009 
13010           ExprResult Arg1 =
13011             PerformCopyInitialization(
13012               InitializedEntity::InitializeParameter(Context,
13013                                                      FnDecl->getParamDecl(1)),
13014               SourceLocation(), Args[1]);
13015           if (Arg1.isInvalid())
13016             return ExprError();
13017           Args[0] = LHS = Arg0.getAs<Expr>();
13018           Args[1] = RHS = Arg1.getAs<Expr>();
13019         }
13020 
13021         // Build the actual expression node.
13022         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13023                                                   Best->FoundDecl, Base,
13024                                                   HadMultipleCandidates, OpLoc);
13025         if (FnExpr.isInvalid())
13026           return ExprError();
13027 
13028         // Determine the result type.
13029         QualType ResultTy = FnDecl->getReturnType();
13030         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13031         ResultTy = ResultTy.getNonLValueExprType(Context);
13032 
13033         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13034             Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
13035             FPFeatures, Best->IsADLCandidate);
13036 
13037         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
13038                                 FnDecl))
13039           return ExprError();
13040 
13041         ArrayRef<const Expr *> ArgsArray(Args, 2);
13042         const Expr *ImplicitThis = nullptr;
13043         // Cut off the implicit 'this'.
13044         if (isa<CXXMethodDecl>(FnDecl)) {
13045           ImplicitThis = ArgsArray[0];
13046           ArgsArray = ArgsArray.slice(1);
13047         }
13048 
13049         // Check for a self move.
13050         if (Op == OO_Equal)
13051           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
13052 
13053         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
13054                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
13055                   VariadicDoesNotApply);
13056 
13057         ExprResult R = MaybeBindToTemporary(TheCall);
13058         if (R.isInvalid())
13059           return ExprError();
13060 
13061         // For a rewritten candidate, we've already reversed the arguments
13062         // if needed. Perform the rest of the rewrite now.
13063         if ((Best->RewriteKind & CRK_DifferentOperator) ||
13064             (Op == OO_Spaceship && IsReversed)) {
13065           if (Op == OO_ExclaimEqual) {
13066             assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
13067             R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
13068           } else {
13069             assert(ChosenOp == OO_Spaceship && "unexpected operator name");
13070             llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13071             Expr *ZeroLiteral =
13072                 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
13073 
13074             Sema::CodeSynthesisContext Ctx;
13075             Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
13076             Ctx.Entity = FnDecl;
13077             pushCodeSynthesisContext(Ctx);
13078 
13079             R = CreateOverloadedBinOp(
13080                 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
13081                 IsReversed ? R.get() : ZeroLiteral, PerformADL,
13082                 /*AllowRewrittenCandidates=*/false);
13083 
13084             popCodeSynthesisContext();
13085           }
13086           if (R.isInvalid())
13087             return ExprError();
13088         } else {
13089           assert(ChosenOp == Op && "unexpected operator name");
13090         }
13091 
13092         // Make a note in the AST if we did any rewriting.
13093         if (Best->RewriteKind != CRK_None)
13094           R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
13095 
13096         return R;
13097       } else {
13098         // We matched a built-in operator. Convert the arguments, then
13099         // break out so that we will build the appropriate built-in
13100         // operator node.
13101         ExprResult ArgsRes0 = PerformImplicitConversion(
13102             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13103             AA_Passing, CCK_ForBuiltinOverloadedOp);
13104         if (ArgsRes0.isInvalid())
13105           return ExprError();
13106         Args[0] = ArgsRes0.get();
13107 
13108         ExprResult ArgsRes1 = PerformImplicitConversion(
13109             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13110             AA_Passing, CCK_ForBuiltinOverloadedOp);
13111         if (ArgsRes1.isInvalid())
13112           return ExprError();
13113         Args[1] = ArgsRes1.get();
13114         break;
13115       }
13116     }
13117 
13118     case OR_No_Viable_Function: {
13119       // C++ [over.match.oper]p9:
13120       //   If the operator is the operator , [...] and there are no
13121       //   viable functions, then the operator is assumed to be the
13122       //   built-in operator and interpreted according to clause 5.
13123       if (Opc == BO_Comma)
13124         break;
13125 
13126       // When defaulting an 'operator<=>', we can try to synthesize a three-way
13127       // compare result using '==' and '<'.
13128       if (DefaultedFn && Opc == BO_Cmp) {
13129         ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
13130                                                           Args[1], DefaultedFn);
13131         if (E.isInvalid() || E.isUsable())
13132           return E;
13133       }
13134 
13135       // For class as left operand for assignment or compound assignment
13136       // operator do not fall through to handling in built-in, but report that
13137       // no overloaded assignment operator found
13138       ExprResult Result = ExprError();
13139       StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
13140       auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
13141                                                    Args, OpLoc);
13142       if (Args[0]->getType()->isRecordType() &&
13143           Opc >= BO_Assign && Opc <= BO_OrAssign) {
13144         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
13145              << BinaryOperator::getOpcodeStr(Opc)
13146              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13147         if (Args[0]->getType()->isIncompleteType()) {
13148           Diag(OpLoc, diag::note_assign_lhs_incomplete)
13149             << Args[0]->getType()
13150             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13151         }
13152       } else {
13153         // This is an erroneous use of an operator which can be overloaded by
13154         // a non-member function. Check for non-member operators which were
13155         // defined too late to be candidates.
13156         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
13157           // FIXME: Recover by calling the found function.
13158           return ExprError();
13159 
13160         // No viable function; try to create a built-in operation, which will
13161         // produce an error. Then, show the non-viable candidates.
13162         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13163       }
13164       assert(Result.isInvalid() &&
13165              "C++ binary operator overloading is missing candidates!");
13166       CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
13167       return Result;
13168     }
13169 
13170     case OR_Ambiguous:
13171       CandidateSet.NoteCandidates(
13172           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13173                                          << BinaryOperator::getOpcodeStr(Opc)
13174                                          << Args[0]->getType()
13175                                          << Args[1]->getType()
13176                                          << Args[0]->getSourceRange()
13177                                          << Args[1]->getSourceRange()),
13178           *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13179           OpLoc);
13180       return ExprError();
13181 
13182     case OR_Deleted:
13183       if (isImplicitlyDeleted(Best->Function)) {
13184         FunctionDecl *DeletedFD = Best->Function;
13185         DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
13186         if (DFK.isSpecialMember()) {
13187           Diag(OpLoc, diag::err_ovl_deleted_special_oper)
13188             << Args[0]->getType() << DFK.asSpecialMember();
13189         } else {
13190           assert(DFK.isComparison());
13191           Diag(OpLoc, diag::err_ovl_deleted_comparison)
13192             << Args[0]->getType() << DeletedFD;
13193         }
13194 
13195         // The user probably meant to call this special member. Just
13196         // explain why it's deleted.
13197         NoteDeletedFunction(DeletedFD);
13198         return ExprError();
13199       }
13200       CandidateSet.NoteCandidates(
13201           PartialDiagnosticAt(
13202               OpLoc, PDiag(diag::err_ovl_deleted_oper)
13203                          << getOperatorSpelling(Best->Function->getDeclName()
13204                                                     .getCXXOverloadedOperator())
13205                          << Args[0]->getSourceRange()
13206                          << Args[1]->getSourceRange()),
13207           *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13208           OpLoc);
13209       return ExprError();
13210   }
13211 
13212   // We matched a built-in operator; build it.
13213   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13214 }
13215 
13216 ExprResult Sema::BuildSynthesizedThreeWayComparison(
13217     SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
13218     FunctionDecl *DefaultedFn) {
13219   const ComparisonCategoryInfo *Info =
13220       Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
13221   // If we're not producing a known comparison category type, we can't
13222   // synthesize a three-way comparison. Let the caller diagnose this.
13223   if (!Info)
13224     return ExprResult((Expr*)nullptr);
13225 
13226   // If we ever want to perform this synthesis more generally, we will need to
13227   // apply the temporary materialization conversion to the operands.
13228   assert(LHS->isGLValue() && RHS->isGLValue() &&
13229          "cannot use prvalue expressions more than once");
13230   Expr *OrigLHS = LHS;
13231   Expr *OrigRHS = RHS;
13232 
13233   // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
13234   // each of them multiple times below.
13235   LHS = new (Context)
13236       OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
13237                       LHS->getObjectKind(), LHS);
13238   RHS = new (Context)
13239       OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
13240                       RHS->getObjectKind(), RHS);
13241 
13242   ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
13243                                         DefaultedFn);
13244   if (Eq.isInvalid())
13245     return ExprError();
13246 
13247   ExprResult Less;
13248   if (Info->isOrdered()) {
13249     Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true, true,
13250                                  DefaultedFn);
13251     if (Less.isInvalid())
13252       return ExprError();
13253   }
13254 
13255   ExprResult Greater;
13256   if (Info->isOrdered()) {
13257     Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
13258                                     DefaultedFn);
13259     if (Greater.isInvalid())
13260       return ExprError();
13261   }
13262 
13263   // Form the list of comparisons we're going to perform.
13264   struct Comparison {
13265     ExprResult Cmp;
13266     ComparisonCategoryResult Result;
13267   } Comparisons[4] =
13268   { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
13269                           : ComparisonCategoryResult::Equivalent},
13270     {Less, ComparisonCategoryResult::Less},
13271     {Greater, ComparisonCategoryResult::Greater},
13272     {ExprResult(), ComparisonCategoryResult::Unordered},
13273   };
13274 
13275   int I;
13276   if (Info->isEquality()) {
13277     Comparisons[1].Result = Info->isStrong()
13278                                 ? ComparisonCategoryResult::Nonequal
13279                                 : ComparisonCategoryResult::Nonequivalent;
13280     I = 1;
13281   } else if (!Info->isPartial()) {
13282     I = 2;
13283   } else {
13284     I = 3;
13285   }
13286 
13287   // Combine the comparisons with suitable conditional expressions.
13288   ExprResult Result;
13289   for (; I >= 0; --I) {
13290     // Build a reference to the comparison category constant.
13291     auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
13292     // FIXME: Missing a constant for a comparison category. Diagnose this?
13293     if (!VI)
13294       return ExprResult((Expr*)nullptr);
13295     ExprResult ThisResult =
13296         BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
13297     if (ThisResult.isInvalid())
13298       return ExprError();
13299 
13300     // Build a conditional unless this is the final case.
13301     if (Result.get()) {
13302       Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
13303                                   ThisResult.get(), Result.get());
13304       if (Result.isInvalid())
13305         return ExprError();
13306     } else {
13307       Result = ThisResult;
13308     }
13309   }
13310 
13311   // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
13312   // bind the OpaqueValueExprs before they're (repeatedly) used.
13313   Expr *SyntacticForm = new (Context)
13314       BinaryOperator(OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
13315                      Result.get()->getValueKind(),
13316                      Result.get()->getObjectKind(), OpLoc, FPFeatures);
13317   Expr *SemanticForm[] = {LHS, RHS, Result.get()};
13318   return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
13319 }
13320 
13321 ExprResult
13322 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
13323                                          SourceLocation RLoc,
13324                                          Expr *Base, Expr *Idx) {
13325   Expr *Args[2] = { Base, Idx };
13326   DeclarationName OpName =
13327       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
13328 
13329   // If either side is type-dependent, create an appropriate dependent
13330   // expression.
13331   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13332 
13333     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13334     // CHECKME: no 'operator' keyword?
13335     DeclarationNameInfo OpNameInfo(OpName, LLoc);
13336     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13337     UnresolvedLookupExpr *Fn
13338       = UnresolvedLookupExpr::Create(Context, NamingClass,
13339                                      NestedNameSpecifierLoc(), OpNameInfo,
13340                                      /*ADL*/ true, /*Overloaded*/ false,
13341                                      UnresolvedSetIterator(),
13342                                      UnresolvedSetIterator());
13343     // Can't add any actual overloads yet
13344 
13345     return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args,
13346                                        Context.DependentTy, VK_RValue, RLoc,
13347                                        FPOptions());
13348   }
13349 
13350   // Handle placeholders on both operands.
13351   if (checkPlaceholderForOverload(*this, Args[0]))
13352     return ExprError();
13353   if (checkPlaceholderForOverload(*this, Args[1]))
13354     return ExprError();
13355 
13356   // Build an empty overload set.
13357   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
13358 
13359   // Subscript can only be overloaded as a member function.
13360 
13361   // Add operator candidates that are member functions.
13362   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13363 
13364   // Add builtin operator candidates.
13365   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13366 
13367   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13368 
13369   // Perform overload resolution.
13370   OverloadCandidateSet::iterator Best;
13371   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
13372     case OR_Success: {
13373       // We found a built-in operator or an overloaded operator.
13374       FunctionDecl *FnDecl = Best->Function;
13375 
13376       if (FnDecl) {
13377         // We matched an overloaded operator. Build a call to that
13378         // operator.
13379 
13380         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
13381 
13382         // Convert the arguments.
13383         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
13384         ExprResult Arg0 =
13385           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13386                                               Best->FoundDecl, Method);
13387         if (Arg0.isInvalid())
13388           return ExprError();
13389         Args[0] = Arg0.get();
13390 
13391         // Convert the arguments.
13392         ExprResult InputInit
13393           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13394                                                       Context,
13395                                                       FnDecl->getParamDecl(0)),
13396                                       SourceLocation(),
13397                                       Args[1]);
13398         if (InputInit.isInvalid())
13399           return ExprError();
13400 
13401         Args[1] = InputInit.getAs<Expr>();
13402 
13403         // Build the actual expression node.
13404         DeclarationNameInfo OpLocInfo(OpName, LLoc);
13405         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13406         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13407                                                   Best->FoundDecl,
13408                                                   Base,
13409                                                   HadMultipleCandidates,
13410                                                   OpLocInfo.getLoc(),
13411                                                   OpLocInfo.getInfo());
13412         if (FnExpr.isInvalid())
13413           return ExprError();
13414 
13415         // Determine the result type
13416         QualType ResultTy = FnDecl->getReturnType();
13417         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13418         ResultTy = ResultTy.getNonLValueExprType(Context);
13419 
13420         CXXOperatorCallExpr *TheCall =
13421             CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(),
13422                                         Args, ResultTy, VK, RLoc, FPOptions());
13423 
13424         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
13425           return ExprError();
13426 
13427         if (CheckFunctionCall(Method, TheCall,
13428                               Method->getType()->castAs<FunctionProtoType>()))
13429           return ExprError();
13430 
13431         return MaybeBindToTemporary(TheCall);
13432       } else {
13433         // We matched a built-in operator. Convert the arguments, then
13434         // break out so that we will build the appropriate built-in
13435         // operator node.
13436         ExprResult ArgsRes0 = PerformImplicitConversion(
13437             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13438             AA_Passing, CCK_ForBuiltinOverloadedOp);
13439         if (ArgsRes0.isInvalid())
13440           return ExprError();
13441         Args[0] = ArgsRes0.get();
13442 
13443         ExprResult ArgsRes1 = PerformImplicitConversion(
13444             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13445             AA_Passing, CCK_ForBuiltinOverloadedOp);
13446         if (ArgsRes1.isInvalid())
13447           return ExprError();
13448         Args[1] = ArgsRes1.get();
13449 
13450         break;
13451       }
13452     }
13453 
13454     case OR_No_Viable_Function: {
13455       PartialDiagnostic PD = CandidateSet.empty()
13456           ? (PDiag(diag::err_ovl_no_oper)
13457              << Args[0]->getType() << /*subscript*/ 0
13458              << Args[0]->getSourceRange() << Args[1]->getSourceRange())
13459           : (PDiag(diag::err_ovl_no_viable_subscript)
13460              << Args[0]->getType() << Args[0]->getSourceRange()
13461              << Args[1]->getSourceRange());
13462       CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
13463                                   OCD_AllCandidates, Args, "[]", LLoc);
13464       return ExprError();
13465     }
13466 
13467     case OR_Ambiguous:
13468       CandidateSet.NoteCandidates(
13469           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13470                                         << "[]" << Args[0]->getType()
13471                                         << Args[1]->getType()
13472                                         << Args[0]->getSourceRange()
13473                                         << Args[1]->getSourceRange()),
13474           *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
13475       return ExprError();
13476 
13477     case OR_Deleted:
13478       CandidateSet.NoteCandidates(
13479           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
13480                                         << "[]" << Args[0]->getSourceRange()
13481                                         << Args[1]->getSourceRange()),
13482           *this, OCD_AllCandidates, Args, "[]", LLoc);
13483       return ExprError();
13484     }
13485 
13486   // We matched a built-in operator; build it.
13487   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
13488 }
13489 
13490 /// BuildCallToMemberFunction - Build a call to a member
13491 /// function. MemExpr is the expression that refers to the member
13492 /// function (and includes the object parameter), Args/NumArgs are the
13493 /// arguments to the function call (not including the object
13494 /// parameter). The caller needs to validate that the member
13495 /// expression refers to a non-static member function or an overloaded
13496 /// member function.
13497 ExprResult
13498 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
13499                                 SourceLocation LParenLoc,
13500                                 MultiExprArg Args,
13501                                 SourceLocation RParenLoc) {
13502   assert(MemExprE->getType() == Context.BoundMemberTy ||
13503          MemExprE->getType() == Context.OverloadTy);
13504 
13505   // Dig out the member expression. This holds both the object
13506   // argument and the member function we're referring to.
13507   Expr *NakedMemExpr = MemExprE->IgnoreParens();
13508 
13509   // Determine whether this is a call to a pointer-to-member function.
13510   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
13511     assert(op->getType() == Context.BoundMemberTy);
13512     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
13513 
13514     QualType fnType =
13515       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
13516 
13517     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
13518     QualType resultType = proto->getCallResultType(Context);
13519     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
13520 
13521     // Check that the object type isn't more qualified than the
13522     // member function we're calling.
13523     Qualifiers funcQuals = proto->getMethodQuals();
13524 
13525     QualType objectType = op->getLHS()->getType();
13526     if (op->getOpcode() == BO_PtrMemI)
13527       objectType = objectType->castAs<PointerType>()->getPointeeType();
13528     Qualifiers objectQuals = objectType.getQualifiers();
13529 
13530     Qualifiers difference = objectQuals - funcQuals;
13531     difference.removeObjCGCAttr();
13532     difference.removeAddressSpace();
13533     if (difference) {
13534       std::string qualsString = difference.getAsString();
13535       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
13536         << fnType.getUnqualifiedType()
13537         << qualsString
13538         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
13539     }
13540 
13541     CXXMemberCallExpr *call =
13542         CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType,
13543                                   valueKind, RParenLoc, proto->getNumParams());
13544 
13545     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
13546                             call, nullptr))
13547       return ExprError();
13548 
13549     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
13550       return ExprError();
13551 
13552     if (CheckOtherCall(call, proto))
13553       return ExprError();
13554 
13555     return MaybeBindToTemporary(call);
13556   }
13557 
13558   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
13559     return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue,
13560                             RParenLoc);
13561 
13562   UnbridgedCastsSet UnbridgedCasts;
13563   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13564     return ExprError();
13565 
13566   MemberExpr *MemExpr;
13567   CXXMethodDecl *Method = nullptr;
13568   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
13569   NestedNameSpecifier *Qualifier = nullptr;
13570   if (isa<MemberExpr>(NakedMemExpr)) {
13571     MemExpr = cast<MemberExpr>(NakedMemExpr);
13572     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
13573     FoundDecl = MemExpr->getFoundDecl();
13574     Qualifier = MemExpr->getQualifier();
13575     UnbridgedCasts.restore();
13576   } else {
13577     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
13578     Qualifier = UnresExpr->getQualifier();
13579 
13580     QualType ObjectType = UnresExpr->getBaseType();
13581     Expr::Classification ObjectClassification
13582       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
13583                             : UnresExpr->getBase()->Classify(Context);
13584 
13585     // Add overload candidates
13586     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
13587                                       OverloadCandidateSet::CSK_Normal);
13588 
13589     // FIXME: avoid copy.
13590     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13591     if (UnresExpr->hasExplicitTemplateArgs()) {
13592       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13593       TemplateArgs = &TemplateArgsBuffer;
13594     }
13595 
13596     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
13597            E = UnresExpr->decls_end(); I != E; ++I) {
13598 
13599       NamedDecl *Func = *I;
13600       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
13601       if (isa<UsingShadowDecl>(Func))
13602         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
13603 
13604 
13605       // Microsoft supports direct constructor calls.
13606       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
13607         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
13608                              CandidateSet,
13609                              /*SuppressUserConversions*/ false);
13610       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
13611         // If explicit template arguments were provided, we can't call a
13612         // non-template member function.
13613         if (TemplateArgs)
13614           continue;
13615 
13616         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
13617                            ObjectClassification, Args, CandidateSet,
13618                            /*SuppressUserConversions=*/false);
13619       } else {
13620         AddMethodTemplateCandidate(
13621             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
13622             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
13623             /*SuppressUserConversions=*/false);
13624       }
13625     }
13626 
13627     DeclarationName DeclName = UnresExpr->getMemberName();
13628 
13629     UnbridgedCasts.restore();
13630 
13631     OverloadCandidateSet::iterator Best;
13632     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
13633                                             Best)) {
13634     case OR_Success:
13635       Method = cast<CXXMethodDecl>(Best->Function);
13636       FoundDecl = Best->FoundDecl;
13637       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
13638       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
13639         return ExprError();
13640       // If FoundDecl is different from Method (such as if one is a template
13641       // and the other a specialization), make sure DiagnoseUseOfDecl is
13642       // called on both.
13643       // FIXME: This would be more comprehensively addressed by modifying
13644       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
13645       // being used.
13646       if (Method != FoundDecl.getDecl() &&
13647                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
13648         return ExprError();
13649       break;
13650 
13651     case OR_No_Viable_Function:
13652       CandidateSet.NoteCandidates(
13653           PartialDiagnosticAt(
13654               UnresExpr->getMemberLoc(),
13655               PDiag(diag::err_ovl_no_viable_member_function_in_call)
13656                   << DeclName << MemExprE->getSourceRange()),
13657           *this, OCD_AllCandidates, Args);
13658       // FIXME: Leaking incoming expressions!
13659       return ExprError();
13660 
13661     case OR_Ambiguous:
13662       CandidateSet.NoteCandidates(
13663           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
13664                               PDiag(diag::err_ovl_ambiguous_member_call)
13665                                   << DeclName << MemExprE->getSourceRange()),
13666           *this, OCD_AmbiguousCandidates, Args);
13667       // FIXME: Leaking incoming expressions!
13668       return ExprError();
13669 
13670     case OR_Deleted:
13671       CandidateSet.NoteCandidates(
13672           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
13673                               PDiag(diag::err_ovl_deleted_member_call)
13674                                   << DeclName << MemExprE->getSourceRange()),
13675           *this, OCD_AllCandidates, Args);
13676       // FIXME: Leaking incoming expressions!
13677       return ExprError();
13678     }
13679 
13680     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
13681 
13682     // If overload resolution picked a static member, build a
13683     // non-member call based on that function.
13684     if (Method->isStatic()) {
13685       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
13686                                    RParenLoc);
13687     }
13688 
13689     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
13690   }
13691 
13692   QualType ResultType = Method->getReturnType();
13693   ExprValueKind VK = Expr::getValueKindForType(ResultType);
13694   ResultType = ResultType.getNonLValueExprType(Context);
13695 
13696   assert(Method && "Member call to something that isn't a method?");
13697   const auto *Proto = Method->getType()->getAs<FunctionProtoType>();
13698   CXXMemberCallExpr *TheCall =
13699       CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
13700                                 RParenLoc, Proto->getNumParams());
13701 
13702   // Check for a valid return type.
13703   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
13704                           TheCall, Method))
13705     return ExprError();
13706 
13707   // Convert the object argument (for a non-static member function call).
13708   // We only need to do this if there was actually an overload; otherwise
13709   // it was done at lookup.
13710   if (!Method->isStatic()) {
13711     ExprResult ObjectArg =
13712       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
13713                                           FoundDecl, Method);
13714     if (ObjectArg.isInvalid())
13715       return ExprError();
13716     MemExpr->setBase(ObjectArg.get());
13717   }
13718 
13719   // Convert the rest of the arguments
13720   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
13721                               RParenLoc))
13722     return ExprError();
13723 
13724   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13725 
13726   if (CheckFunctionCall(Method, TheCall, Proto))
13727     return ExprError();
13728 
13729   // In the case the method to call was not selected by the overloading
13730   // resolution process, we still need to handle the enable_if attribute. Do
13731   // that here, so it will not hide previous -- and more relevant -- errors.
13732   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
13733     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
13734       Diag(MemE->getMemberLoc(),
13735            diag::err_ovl_no_viable_member_function_in_call)
13736           << Method << Method->getSourceRange();
13737       Diag(Method->getLocation(),
13738            diag::note_ovl_candidate_disabled_by_function_cond_attr)
13739           << Attr->getCond()->getSourceRange() << Attr->getMessage();
13740       return ExprError();
13741     }
13742   }
13743 
13744   if ((isa<CXXConstructorDecl>(CurContext) ||
13745        isa<CXXDestructorDecl>(CurContext)) &&
13746       TheCall->getMethodDecl()->isPure()) {
13747     const CXXMethodDecl *MD = TheCall->getMethodDecl();
13748 
13749     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
13750         MemExpr->performsVirtualDispatch(getLangOpts())) {
13751       Diag(MemExpr->getBeginLoc(),
13752            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
13753           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
13754           << MD->getParent()->getDeclName();
13755 
13756       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
13757       if (getLangOpts().AppleKext)
13758         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
13759             << MD->getParent()->getDeclName() << MD->getDeclName();
13760     }
13761   }
13762 
13763   if (CXXDestructorDecl *DD =
13764           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
13765     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
13766     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
13767     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
13768                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
13769                          MemExpr->getMemberLoc());
13770   }
13771 
13772   return MaybeBindToTemporary(TheCall);
13773 }
13774 
13775 /// BuildCallToObjectOfClassType - Build a call to an object of class
13776 /// type (C++ [over.call.object]), which can end up invoking an
13777 /// overloaded function call operator (@c operator()) or performing a
13778 /// user-defined conversion on the object argument.
13779 ExprResult
13780 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
13781                                    SourceLocation LParenLoc,
13782                                    MultiExprArg Args,
13783                                    SourceLocation RParenLoc) {
13784   if (checkPlaceholderForOverload(*this, Obj))
13785     return ExprError();
13786   ExprResult Object = Obj;
13787 
13788   UnbridgedCastsSet UnbridgedCasts;
13789   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13790     return ExprError();
13791 
13792   assert(Object.get()->getType()->isRecordType() &&
13793          "Requires object type argument");
13794   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
13795 
13796   // C++ [over.call.object]p1:
13797   //  If the primary-expression E in the function call syntax
13798   //  evaluates to a class object of type "cv T", then the set of
13799   //  candidate functions includes at least the function call
13800   //  operators of T. The function call operators of T are obtained by
13801   //  ordinary lookup of the name operator() in the context of
13802   //  (E).operator().
13803   OverloadCandidateSet CandidateSet(LParenLoc,
13804                                     OverloadCandidateSet::CSK_Operator);
13805   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
13806 
13807   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
13808                           diag::err_incomplete_object_call, Object.get()))
13809     return true;
13810 
13811   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
13812   LookupQualifiedName(R, Record->getDecl());
13813   R.suppressDiagnostics();
13814 
13815   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13816        Oper != OperEnd; ++Oper) {
13817     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
13818                        Object.get()->Classify(Context), Args, CandidateSet,
13819                        /*SuppressUserConversion=*/false);
13820   }
13821 
13822   // C++ [over.call.object]p2:
13823   //   In addition, for each (non-explicit in C++0x) conversion function
13824   //   declared in T of the form
13825   //
13826   //        operator conversion-type-id () cv-qualifier;
13827   //
13828   //   where cv-qualifier is the same cv-qualification as, or a
13829   //   greater cv-qualification than, cv, and where conversion-type-id
13830   //   denotes the type "pointer to function of (P1,...,Pn) returning
13831   //   R", or the type "reference to pointer to function of
13832   //   (P1,...,Pn) returning R", or the type "reference to function
13833   //   of (P1,...,Pn) returning R", a surrogate call function [...]
13834   //   is also considered as a candidate function. Similarly,
13835   //   surrogate call functions are added to the set of candidate
13836   //   functions for each conversion function declared in an
13837   //   accessible base class provided the function is not hidden
13838   //   within T by another intervening declaration.
13839   const auto &Conversions =
13840       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
13841   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
13842     NamedDecl *D = *I;
13843     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
13844     if (isa<UsingShadowDecl>(D))
13845       D = cast<UsingShadowDecl>(D)->getTargetDecl();
13846 
13847     // Skip over templated conversion functions; they aren't
13848     // surrogates.
13849     if (isa<FunctionTemplateDecl>(D))
13850       continue;
13851 
13852     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
13853     if (!Conv->isExplicit()) {
13854       // Strip the reference type (if any) and then the pointer type (if
13855       // any) to get down to what might be a function type.
13856       QualType ConvType = Conv->getConversionType().getNonReferenceType();
13857       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13858         ConvType = ConvPtrType->getPointeeType();
13859 
13860       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13861       {
13862         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
13863                               Object.get(), Args, CandidateSet);
13864       }
13865     }
13866   }
13867 
13868   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13869 
13870   // Perform overload resolution.
13871   OverloadCandidateSet::iterator Best;
13872   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
13873                                           Best)) {
13874   case OR_Success:
13875     // Overload resolution succeeded; we'll build the appropriate call
13876     // below.
13877     break;
13878 
13879   case OR_No_Viable_Function: {
13880     PartialDiagnostic PD =
13881         CandidateSet.empty()
13882             ? (PDiag(diag::err_ovl_no_oper)
13883                << Object.get()->getType() << /*call*/ 1
13884                << Object.get()->getSourceRange())
13885             : (PDiag(diag::err_ovl_no_viable_object_call)
13886                << Object.get()->getType() << Object.get()->getSourceRange());
13887     CandidateSet.NoteCandidates(
13888         PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
13889         OCD_AllCandidates, Args);
13890     break;
13891   }
13892   case OR_Ambiguous:
13893     CandidateSet.NoteCandidates(
13894         PartialDiagnosticAt(Object.get()->getBeginLoc(),
13895                             PDiag(diag::err_ovl_ambiguous_object_call)
13896                                 << Object.get()->getType()
13897                                 << Object.get()->getSourceRange()),
13898         *this, OCD_AmbiguousCandidates, Args);
13899     break;
13900 
13901   case OR_Deleted:
13902     CandidateSet.NoteCandidates(
13903         PartialDiagnosticAt(Object.get()->getBeginLoc(),
13904                             PDiag(diag::err_ovl_deleted_object_call)
13905                                 << Object.get()->getType()
13906                                 << Object.get()->getSourceRange()),
13907         *this, OCD_AllCandidates, Args);
13908     break;
13909   }
13910 
13911   if (Best == CandidateSet.end())
13912     return true;
13913 
13914   UnbridgedCasts.restore();
13915 
13916   if (Best->Function == nullptr) {
13917     // Since there is no function declaration, this is one of the
13918     // surrogate candidates. Dig out the conversion function.
13919     CXXConversionDecl *Conv
13920       = cast<CXXConversionDecl>(
13921                          Best->Conversions[0].UserDefined.ConversionFunction);
13922 
13923     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13924                               Best->FoundDecl);
13925     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13926       return ExprError();
13927     assert(Conv == Best->FoundDecl.getDecl() &&
13928              "Found Decl & conversion-to-functionptr should be same, right?!");
13929     // We selected one of the surrogate functions that converts the
13930     // object parameter to a function pointer. Perform the conversion
13931     // on the object argument, then let BuildCallExpr finish the job.
13932 
13933     // Create an implicit member expr to refer to the conversion operator.
13934     // and then call it.
13935     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13936                                              Conv, HadMultipleCandidates);
13937     if (Call.isInvalid())
13938       return ExprError();
13939     // Record usage of conversion in an implicit cast.
13940     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13941                                     CK_UserDefinedConversion, Call.get(),
13942                                     nullptr, VK_RValue);
13943 
13944     return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13945   }
13946 
13947   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13948 
13949   // We found an overloaded operator(). Build a CXXOperatorCallExpr
13950   // that calls this method, using Object for the implicit object
13951   // parameter and passing along the remaining arguments.
13952   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13953 
13954   // An error diagnostic has already been printed when parsing the declaration.
13955   if (Method->isInvalidDecl())
13956     return ExprError();
13957 
13958   const FunctionProtoType *Proto =
13959     Method->getType()->getAs<FunctionProtoType>();
13960 
13961   unsigned NumParams = Proto->getNumParams();
13962 
13963   DeclarationNameInfo OpLocInfo(
13964                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13965   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13966   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13967                                            Obj, HadMultipleCandidates,
13968                                            OpLocInfo.getLoc(),
13969                                            OpLocInfo.getInfo());
13970   if (NewFn.isInvalid())
13971     return true;
13972 
13973   // The number of argument slots to allocate in the call. If we have default
13974   // arguments we need to allocate space for them as well. We additionally
13975   // need one more slot for the object parameter.
13976   unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
13977 
13978   // Build the full argument list for the method call (the implicit object
13979   // parameter is placed at the beginning of the list).
13980   SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
13981 
13982   bool IsError = false;
13983 
13984   // Initialize the implicit object parameter.
13985   ExprResult ObjRes =
13986     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13987                                         Best->FoundDecl, Method);
13988   if (ObjRes.isInvalid())
13989     IsError = true;
13990   else
13991     Object = ObjRes;
13992   MethodArgs[0] = Object.get();
13993 
13994   // Check the argument types.
13995   for (unsigned i = 0; i != NumParams; i++) {
13996     Expr *Arg;
13997     if (i < Args.size()) {
13998       Arg = Args[i];
13999 
14000       // Pass the argument.
14001 
14002       ExprResult InputInit
14003         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14004                                                     Context,
14005                                                     Method->getParamDecl(i)),
14006                                     SourceLocation(), Arg);
14007 
14008       IsError |= InputInit.isInvalid();
14009       Arg = InputInit.getAs<Expr>();
14010     } else {
14011       ExprResult DefArg
14012         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14013       if (DefArg.isInvalid()) {
14014         IsError = true;
14015         break;
14016       }
14017 
14018       Arg = DefArg.getAs<Expr>();
14019     }
14020 
14021     MethodArgs[i + 1] = Arg;
14022   }
14023 
14024   // If this is a variadic call, handle args passed through "...".
14025   if (Proto->isVariadic()) {
14026     // Promote the arguments (C99 6.5.2.2p7).
14027     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
14028       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
14029                                                         nullptr);
14030       IsError |= Arg.isInvalid();
14031       MethodArgs[i + 1] = Arg.get();
14032     }
14033   }
14034 
14035   if (IsError)
14036     return true;
14037 
14038   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14039 
14040   // Once we've built TheCall, all of the expressions are properly owned.
14041   QualType ResultTy = Method->getReturnType();
14042   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14043   ResultTy = ResultTy.getNonLValueExprType(Context);
14044 
14045   CXXOperatorCallExpr *TheCall =
14046       CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs,
14047                                   ResultTy, VK, RParenLoc, FPOptions());
14048 
14049   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
14050     return true;
14051 
14052   if (CheckFunctionCall(Method, TheCall, Proto))
14053     return true;
14054 
14055   return MaybeBindToTemporary(TheCall);
14056 }
14057 
14058 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
14059 ///  (if one exists), where @c Base is an expression of class type and
14060 /// @c Member is the name of the member we're trying to find.
14061 ExprResult
14062 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
14063                                bool *NoArrowOperatorFound) {
14064   assert(Base->getType()->isRecordType() &&
14065          "left-hand side must have class type");
14066 
14067   if (checkPlaceholderForOverload(*this, Base))
14068     return ExprError();
14069 
14070   SourceLocation Loc = Base->getExprLoc();
14071 
14072   // C++ [over.ref]p1:
14073   //
14074   //   [...] An expression x->m is interpreted as (x.operator->())->m
14075   //   for a class object x of type T if T::operator->() exists and if
14076   //   the operator is selected as the best match function by the
14077   //   overload resolution mechanism (13.3).
14078   DeclarationName OpName =
14079     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
14080   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
14081   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
14082 
14083   if (RequireCompleteType(Loc, Base->getType(),
14084                           diag::err_typecheck_incomplete_tag, Base))
14085     return ExprError();
14086 
14087   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
14088   LookupQualifiedName(R, BaseRecord->getDecl());
14089   R.suppressDiagnostics();
14090 
14091   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14092        Oper != OperEnd; ++Oper) {
14093     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
14094                        None, CandidateSet, /*SuppressUserConversion=*/false);
14095   }
14096 
14097   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14098 
14099   // Perform overload resolution.
14100   OverloadCandidateSet::iterator Best;
14101   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14102   case OR_Success:
14103     // Overload resolution succeeded; we'll build the call below.
14104     break;
14105 
14106   case OR_No_Viable_Function: {
14107     auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
14108     if (CandidateSet.empty()) {
14109       QualType BaseType = Base->getType();
14110       if (NoArrowOperatorFound) {
14111         // Report this specific error to the caller instead of emitting a
14112         // diagnostic, as requested.
14113         *NoArrowOperatorFound = true;
14114         return ExprError();
14115       }
14116       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
14117         << BaseType << Base->getSourceRange();
14118       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
14119         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
14120           << FixItHint::CreateReplacement(OpLoc, ".");
14121       }
14122     } else
14123       Diag(OpLoc, diag::err_ovl_no_viable_oper)
14124         << "operator->" << Base->getSourceRange();
14125     CandidateSet.NoteCandidates(*this, Base, Cands);
14126     return ExprError();
14127   }
14128   case OR_Ambiguous:
14129     CandidateSet.NoteCandidates(
14130         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
14131                                        << "->" << Base->getType()
14132                                        << Base->getSourceRange()),
14133         *this, OCD_AmbiguousCandidates, Base);
14134     return ExprError();
14135 
14136   case OR_Deleted:
14137     CandidateSet.NoteCandidates(
14138         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14139                                        << "->" << Base->getSourceRange()),
14140         *this, OCD_AllCandidates, Base);
14141     return ExprError();
14142   }
14143 
14144   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
14145 
14146   // Convert the object parameter.
14147   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14148   ExprResult BaseResult =
14149     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
14150                                         Best->FoundDecl, Method);
14151   if (BaseResult.isInvalid())
14152     return ExprError();
14153   Base = BaseResult.get();
14154 
14155   // Build the operator call.
14156   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14157                                             Base, HadMultipleCandidates, OpLoc);
14158   if (FnExpr.isInvalid())
14159     return ExprError();
14160 
14161   QualType ResultTy = Method->getReturnType();
14162   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14163   ResultTy = ResultTy.getNonLValueExprType(Context);
14164   CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14165       Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions());
14166 
14167   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
14168     return ExprError();
14169 
14170   if (CheckFunctionCall(Method, TheCall,
14171                         Method->getType()->castAs<FunctionProtoType>()))
14172     return ExprError();
14173 
14174   return MaybeBindToTemporary(TheCall);
14175 }
14176 
14177 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
14178 /// a literal operator described by the provided lookup results.
14179 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
14180                                           DeclarationNameInfo &SuffixInfo,
14181                                           ArrayRef<Expr*> Args,
14182                                           SourceLocation LitEndLoc,
14183                                        TemplateArgumentListInfo *TemplateArgs) {
14184   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
14185 
14186   OverloadCandidateSet CandidateSet(UDSuffixLoc,
14187                                     OverloadCandidateSet::CSK_Normal);
14188   AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
14189                                  TemplateArgs);
14190 
14191   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14192 
14193   // Perform overload resolution. This will usually be trivial, but might need
14194   // to perform substitutions for a literal operator template.
14195   OverloadCandidateSet::iterator Best;
14196   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
14197   case OR_Success:
14198   case OR_Deleted:
14199     break;
14200 
14201   case OR_No_Viable_Function:
14202     CandidateSet.NoteCandidates(
14203         PartialDiagnosticAt(UDSuffixLoc,
14204                             PDiag(diag::err_ovl_no_viable_function_in_call)
14205                                 << R.getLookupName()),
14206         *this, OCD_AllCandidates, Args);
14207     return ExprError();
14208 
14209   case OR_Ambiguous:
14210     CandidateSet.NoteCandidates(
14211         PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
14212                                                 << R.getLookupName()),
14213         *this, OCD_AmbiguousCandidates, Args);
14214     return ExprError();
14215   }
14216 
14217   FunctionDecl *FD = Best->Function;
14218   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
14219                                         nullptr, HadMultipleCandidates,
14220                                         SuffixInfo.getLoc(),
14221                                         SuffixInfo.getInfo());
14222   if (Fn.isInvalid())
14223     return true;
14224 
14225   // Check the argument types. This should almost always be a no-op, except
14226   // that array-to-pointer decay is applied to string literals.
14227   Expr *ConvArgs[2];
14228   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
14229     ExprResult InputInit = PerformCopyInitialization(
14230       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
14231       SourceLocation(), Args[ArgIdx]);
14232     if (InputInit.isInvalid())
14233       return true;
14234     ConvArgs[ArgIdx] = InputInit.get();
14235   }
14236 
14237   QualType ResultTy = FD->getReturnType();
14238   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14239   ResultTy = ResultTy.getNonLValueExprType(Context);
14240 
14241   UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
14242       Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
14243       VK, LitEndLoc, UDSuffixLoc);
14244 
14245   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
14246     return ExprError();
14247 
14248   if (CheckFunctionCall(FD, UDL, nullptr))
14249     return ExprError();
14250 
14251   return MaybeBindToTemporary(UDL);
14252 }
14253 
14254 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
14255 /// given LookupResult is non-empty, it is assumed to describe a member which
14256 /// will be invoked. Otherwise, the function will be found via argument
14257 /// dependent lookup.
14258 /// CallExpr is set to a valid expression and FRS_Success returned on success,
14259 /// otherwise CallExpr is set to ExprError() and some non-success value
14260 /// is returned.
14261 Sema::ForRangeStatus
14262 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
14263                                 SourceLocation RangeLoc,
14264                                 const DeclarationNameInfo &NameInfo,
14265                                 LookupResult &MemberLookup,
14266                                 OverloadCandidateSet *CandidateSet,
14267                                 Expr *Range, ExprResult *CallExpr) {
14268   Scope *S = nullptr;
14269 
14270   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
14271   if (!MemberLookup.empty()) {
14272     ExprResult MemberRef =
14273         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
14274                                  /*IsPtr=*/false, CXXScopeSpec(),
14275                                  /*TemplateKWLoc=*/SourceLocation(),
14276                                  /*FirstQualifierInScope=*/nullptr,
14277                                  MemberLookup,
14278                                  /*TemplateArgs=*/nullptr, S);
14279     if (MemberRef.isInvalid()) {
14280       *CallExpr = ExprError();
14281       return FRS_DiagnosticIssued;
14282     }
14283     *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
14284     if (CallExpr->isInvalid()) {
14285       *CallExpr = ExprError();
14286       return FRS_DiagnosticIssued;
14287     }
14288   } else {
14289     UnresolvedSet<0> FoundNames;
14290     UnresolvedLookupExpr *Fn =
14291       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
14292                                    NestedNameSpecifierLoc(), NameInfo,
14293                                    /*NeedsADL=*/true, /*Overloaded=*/false,
14294                                    FoundNames.begin(), FoundNames.end());
14295 
14296     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
14297                                                     CandidateSet, CallExpr);
14298     if (CandidateSet->empty() || CandidateSetError) {
14299       *CallExpr = ExprError();
14300       return FRS_NoViableFunction;
14301     }
14302     OverloadCandidateSet::iterator Best;
14303     OverloadingResult OverloadResult =
14304         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
14305 
14306     if (OverloadResult == OR_No_Viable_Function) {
14307       *CallExpr = ExprError();
14308       return FRS_NoViableFunction;
14309     }
14310     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
14311                                          Loc, nullptr, CandidateSet, &Best,
14312                                          OverloadResult,
14313                                          /*AllowTypoCorrection=*/false);
14314     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
14315       *CallExpr = ExprError();
14316       return FRS_DiagnosticIssued;
14317     }
14318   }
14319   return FRS_Success;
14320 }
14321 
14322 
14323 /// FixOverloadedFunctionReference - E is an expression that refers to
14324 /// a C++ overloaded function (possibly with some parentheses and
14325 /// perhaps a '&' around it). We have resolved the overloaded function
14326 /// to the function declaration Fn, so patch up the expression E to
14327 /// refer (possibly indirectly) to Fn. Returns the new expr.
14328 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
14329                                            FunctionDecl *Fn) {
14330   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
14331     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
14332                                                    Found, Fn);
14333     if (SubExpr == PE->getSubExpr())
14334       return PE;
14335 
14336     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
14337   }
14338 
14339   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
14340     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
14341                                                    Found, Fn);
14342     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
14343                                SubExpr->getType()) &&
14344            "Implicit cast type cannot be determined from overload");
14345     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
14346     if (SubExpr == ICE->getSubExpr())
14347       return ICE;
14348 
14349     return ImplicitCastExpr::Create(Context, ICE->getType(),
14350                                     ICE->getCastKind(),
14351                                     SubExpr, nullptr,
14352                                     ICE->getValueKind());
14353   }
14354 
14355   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
14356     if (!GSE->isResultDependent()) {
14357       Expr *SubExpr =
14358           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
14359       if (SubExpr == GSE->getResultExpr())
14360         return GSE;
14361 
14362       // Replace the resulting type information before rebuilding the generic
14363       // selection expression.
14364       ArrayRef<Expr *> A = GSE->getAssocExprs();
14365       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
14366       unsigned ResultIdx = GSE->getResultIndex();
14367       AssocExprs[ResultIdx] = SubExpr;
14368 
14369       return GenericSelectionExpr::Create(
14370           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
14371           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
14372           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
14373           ResultIdx);
14374     }
14375     // Rather than fall through to the unreachable, return the original generic
14376     // selection expression.
14377     return GSE;
14378   }
14379 
14380   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
14381     assert(UnOp->getOpcode() == UO_AddrOf &&
14382            "Can only take the address of an overloaded function");
14383     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
14384       if (Method->isStatic()) {
14385         // Do nothing: static member functions aren't any different
14386         // from non-member functions.
14387       } else {
14388         // Fix the subexpression, which really has to be an
14389         // UnresolvedLookupExpr holding an overloaded member function
14390         // or template.
14391         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14392                                                        Found, Fn);
14393         if (SubExpr == UnOp->getSubExpr())
14394           return UnOp;
14395 
14396         assert(isa<DeclRefExpr>(SubExpr)
14397                && "fixed to something other than a decl ref");
14398         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
14399                && "fixed to a member ref with no nested name qualifier");
14400 
14401         // We have taken the address of a pointer to member
14402         // function. Perform the computation here so that we get the
14403         // appropriate pointer to member type.
14404         QualType ClassType
14405           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
14406         QualType MemPtrType
14407           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
14408         // Under the MS ABI, lock down the inheritance model now.
14409         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14410           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
14411 
14412         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
14413                                            VK_RValue, OK_Ordinary,
14414                                            UnOp->getOperatorLoc(), false);
14415       }
14416     }
14417     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14418                                                    Found, Fn);
14419     if (SubExpr == UnOp->getSubExpr())
14420       return UnOp;
14421 
14422     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
14423                                      Context.getPointerType(SubExpr->getType()),
14424                                        VK_RValue, OK_Ordinary,
14425                                        UnOp->getOperatorLoc(), false);
14426   }
14427 
14428   // C++ [except.spec]p17:
14429   //   An exception-specification is considered to be needed when:
14430   //   - in an expression the function is the unique lookup result or the
14431   //     selected member of a set of overloaded functions
14432   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
14433     ResolveExceptionSpec(E->getExprLoc(), FPT);
14434 
14435   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14436     // FIXME: avoid copy.
14437     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14438     if (ULE->hasExplicitTemplateArgs()) {
14439       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
14440       TemplateArgs = &TemplateArgsBuffer;
14441     }
14442 
14443     DeclRefExpr *DRE =
14444         BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(),
14445                          ULE->getQualifierLoc(), Found.getDecl(),
14446                          ULE->getTemplateKeywordLoc(), TemplateArgs);
14447     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
14448     return DRE;
14449   }
14450 
14451   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
14452     // FIXME: avoid copy.
14453     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14454     if (MemExpr->hasExplicitTemplateArgs()) {
14455       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14456       TemplateArgs = &TemplateArgsBuffer;
14457     }
14458 
14459     Expr *Base;
14460 
14461     // If we're filling in a static method where we used to have an
14462     // implicit member access, rewrite to a simple decl ref.
14463     if (MemExpr->isImplicitAccess()) {
14464       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14465         DeclRefExpr *DRE = BuildDeclRefExpr(
14466             Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
14467             MemExpr->getQualifierLoc(), Found.getDecl(),
14468             MemExpr->getTemplateKeywordLoc(), TemplateArgs);
14469         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
14470         return DRE;
14471       } else {
14472         SourceLocation Loc = MemExpr->getMemberLoc();
14473         if (MemExpr->getQualifier())
14474           Loc = MemExpr->getQualifierLoc().getBeginLoc();
14475         Base =
14476             BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
14477       }
14478     } else
14479       Base = MemExpr->getBase();
14480 
14481     ExprValueKind valueKind;
14482     QualType type;
14483     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14484       valueKind = VK_LValue;
14485       type = Fn->getType();
14486     } else {
14487       valueKind = VK_RValue;
14488       type = Context.BoundMemberTy;
14489     }
14490 
14491     return BuildMemberExpr(
14492         Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
14493         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
14494         /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
14495         type, valueKind, OK_Ordinary, TemplateArgs);
14496   }
14497 
14498   llvm_unreachable("Invalid reference to overloaded function");
14499 }
14500 
14501 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
14502                                                 DeclAccessPair Found,
14503                                                 FunctionDecl *Fn) {
14504   return FixOverloadedFunctionReference(E.get(), Found, Fn);
14505 }
14506