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_implicit_equality_comparison,
9727   oc_inherited_constructor
9728 };
9729 
9730 enum OverloadCandidateSelect {
9731   ocs_non_template,
9732   ocs_template,
9733   ocs_described_template,
9734 };
9735 
9736 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
9737 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9738                           OverloadCandidateRewriteKind CRK,
9739                           std::string &Description) {
9740 
9741   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9742   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9743     isTemplate = true;
9744     Description = S.getTemplateArgumentBindingsText(
9745         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9746   }
9747 
9748   OverloadCandidateSelect Select = [&]() {
9749     if (!Description.empty())
9750       return ocs_described_template;
9751     return isTemplate ? ocs_template : ocs_non_template;
9752   }();
9753 
9754   OverloadCandidateKind Kind = [&]() {
9755     if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
9756       return oc_implicit_equality_comparison;
9757 
9758     if (CRK & CRK_Reversed)
9759       return oc_reversed_binary_operator;
9760 
9761     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9762       if (!Ctor->isImplicit()) {
9763         if (isa<ConstructorUsingShadowDecl>(Found))
9764           return oc_inherited_constructor;
9765         else
9766           return oc_constructor;
9767       }
9768 
9769       if (Ctor->isDefaultConstructor())
9770         return oc_implicit_default_constructor;
9771 
9772       if (Ctor->isMoveConstructor())
9773         return oc_implicit_move_constructor;
9774 
9775       assert(Ctor->isCopyConstructor() &&
9776              "unexpected sort of implicit constructor");
9777       return oc_implicit_copy_constructor;
9778     }
9779 
9780     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9781       // This actually gets spelled 'candidate function' for now, but
9782       // it doesn't hurt to split it out.
9783       if (!Meth->isImplicit())
9784         return oc_method;
9785 
9786       if (Meth->isMoveAssignmentOperator())
9787         return oc_implicit_move_assignment;
9788 
9789       if (Meth->isCopyAssignmentOperator())
9790         return oc_implicit_copy_assignment;
9791 
9792       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9793       return oc_method;
9794     }
9795 
9796     return oc_function;
9797   }();
9798 
9799   return std::make_pair(Kind, Select);
9800 }
9801 
9802 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9803   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9804   // set.
9805   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9806     S.Diag(FoundDecl->getLocation(),
9807            diag::note_ovl_candidate_inherited_constructor)
9808       << Shadow->getNominatedBaseClass();
9809 }
9810 
9811 } // end anonymous namespace
9812 
9813 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9814                                     const FunctionDecl *FD) {
9815   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9816     bool AlwaysTrue;
9817     if (EnableIf->getCond()->isValueDependent() ||
9818         !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9819       return false;
9820     if (!AlwaysTrue)
9821       return false;
9822   }
9823   return true;
9824 }
9825 
9826 /// Returns true if we can take the address of the function.
9827 ///
9828 /// \param Complain - If true, we'll emit a diagnostic
9829 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9830 ///   we in overload resolution?
9831 /// \param Loc - The location of the statement we're complaining about. Ignored
9832 ///   if we're not complaining, or if we're in overload resolution.
9833 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9834                                               bool Complain,
9835                                               bool InOverloadResolution,
9836                                               SourceLocation Loc) {
9837   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9838     if (Complain) {
9839       if (InOverloadResolution)
9840         S.Diag(FD->getBeginLoc(),
9841                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9842       else
9843         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9844     }
9845     return false;
9846   }
9847 
9848   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9849     return P->hasAttr<PassObjectSizeAttr>();
9850   });
9851   if (I == FD->param_end())
9852     return true;
9853 
9854   if (Complain) {
9855     // Add one to ParamNo because it's user-facing
9856     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9857     if (InOverloadResolution)
9858       S.Diag(FD->getLocation(),
9859              diag::note_ovl_candidate_has_pass_object_size_params)
9860           << ParamNo;
9861     else
9862       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9863           << FD << ParamNo;
9864   }
9865   return false;
9866 }
9867 
9868 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9869                                                const FunctionDecl *FD) {
9870   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9871                                            /*InOverloadResolution=*/true,
9872                                            /*Loc=*/SourceLocation());
9873 }
9874 
9875 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9876                                              bool Complain,
9877                                              SourceLocation Loc) {
9878   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9879                                              /*InOverloadResolution=*/false,
9880                                              Loc);
9881 }
9882 
9883 // Notes the location of an overload candidate.
9884 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9885                                  OverloadCandidateRewriteKind RewriteKind,
9886                                  QualType DestType, bool TakingAddress) {
9887   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9888     return;
9889   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
9890       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
9891     return;
9892 
9893   std::string FnDesc;
9894   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
9895       ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
9896   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9897                          << (unsigned)KSPair.first << (unsigned)KSPair.second
9898                          << Fn << FnDesc;
9899 
9900   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9901   Diag(Fn->getLocation(), PD);
9902   MaybeEmitInheritedConstructorNote(*this, Found);
9903 }
9904 
9905 // Notes the location of all overload candidates designated through
9906 // OverloadedExpr
9907 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9908                                      bool TakingAddress) {
9909   assert(OverloadedExpr->getType() == Context.OverloadTy);
9910 
9911   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9912   OverloadExpr *OvlExpr = Ovl.Expression;
9913 
9914   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9915                             IEnd = OvlExpr->decls_end();
9916        I != IEnd; ++I) {
9917     if (FunctionTemplateDecl *FunTmpl =
9918                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9919       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
9920                             TakingAddress);
9921     } else if (FunctionDecl *Fun
9922                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9923       NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
9924     }
9925   }
9926 }
9927 
9928 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9929 /// "lead" diagnostic; it will be given two arguments, the source and
9930 /// target types of the conversion.
9931 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9932                                  Sema &S,
9933                                  SourceLocation CaretLoc,
9934                                  const PartialDiagnostic &PDiag) const {
9935   S.Diag(CaretLoc, PDiag)
9936     << Ambiguous.getFromType() << Ambiguous.getToType();
9937   // FIXME: The note limiting machinery is borrowed from
9938   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9939   // refactoring here.
9940   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9941   unsigned CandsShown = 0;
9942   AmbiguousConversionSequence::const_iterator I, E;
9943   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9944     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9945       break;
9946     ++CandsShown;
9947     S.NoteOverloadCandidate(I->first, I->second);
9948   }
9949   if (I != E)
9950     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9951 }
9952 
9953 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9954                                   unsigned I, bool TakingCandidateAddress) {
9955   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9956   assert(Conv.isBad());
9957   assert(Cand->Function && "for now, candidate must be a function");
9958   FunctionDecl *Fn = Cand->Function;
9959 
9960   // There's a conversion slot for the object argument if this is a
9961   // non-constructor method.  Note that 'I' corresponds the
9962   // conversion-slot index.
9963   bool isObjectArgument = false;
9964   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9965     if (I == 0)
9966       isObjectArgument = true;
9967     else
9968       I--;
9969   }
9970 
9971   std::string FnDesc;
9972   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
9973       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
9974                                 FnDesc);
9975 
9976   Expr *FromExpr = Conv.Bad.FromExpr;
9977   QualType FromTy = Conv.Bad.getFromType();
9978   QualType ToTy = Conv.Bad.getToType();
9979 
9980   if (FromTy == S.Context.OverloadTy) {
9981     assert(FromExpr && "overload set argument came from implicit argument?");
9982     Expr *E = FromExpr->IgnoreParens();
9983     if (isa<UnaryOperator>(E))
9984       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9985     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9986 
9987     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9988         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9989         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
9990         << Name << I + 1;
9991     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9992     return;
9993   }
9994 
9995   // Do some hand-waving analysis to see if the non-viability is due
9996   // to a qualifier mismatch.
9997   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9998   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9999   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
10000     CToTy = RT->getPointeeType();
10001   else {
10002     // TODO: detect and diagnose the full richness of const mismatches.
10003     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
10004       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
10005         CFromTy = FromPT->getPointeeType();
10006         CToTy = ToPT->getPointeeType();
10007       }
10008   }
10009 
10010   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
10011       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
10012     Qualifiers FromQs = CFromTy.getQualifiers();
10013     Qualifiers ToQs = CToTy.getQualifiers();
10014 
10015     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
10016       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
10017           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10018           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10019           << ToTy << (unsigned)isObjectArgument << I + 1;
10020       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10021       return;
10022     }
10023 
10024     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10025       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
10026           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10027           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10028           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
10029           << (unsigned)isObjectArgument << I + 1;
10030       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10031       return;
10032     }
10033 
10034     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
10035       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
10036           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10037           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10038           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
10039           << (unsigned)isObjectArgument << I + 1;
10040       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10041       return;
10042     }
10043 
10044     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
10045       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
10046           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10047           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10048           << FromQs.hasUnaligned() << I + 1;
10049       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10050       return;
10051     }
10052 
10053     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
10054     assert(CVR && "unexpected qualifiers mismatch");
10055 
10056     if (isObjectArgument) {
10057       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
10058           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10059           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10060           << (CVR - 1);
10061     } else {
10062       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
10063           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10064           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10065           << (CVR - 1) << I + 1;
10066     }
10067     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10068     return;
10069   }
10070 
10071   // Special diagnostic for failure to convert an initializer list, since
10072   // telling the user that it has type void is not useful.
10073   if (FromExpr && isa<InitListExpr>(FromExpr)) {
10074     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
10075         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10076         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10077         << ToTy << (unsigned)isObjectArgument << I + 1;
10078     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10079     return;
10080   }
10081 
10082   // Diagnose references or pointers to incomplete types differently,
10083   // since it's far from impossible that the incompleteness triggered
10084   // the failure.
10085   QualType TempFromTy = FromTy.getNonReferenceType();
10086   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
10087     TempFromTy = PTy->getPointeeType();
10088   if (TempFromTy->isIncompleteType()) {
10089     // Emit the generic diagnostic and, optionally, add the hints to it.
10090     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
10091         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10092         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10093         << ToTy << (unsigned)isObjectArgument << I + 1
10094         << (unsigned)(Cand->Fix.Kind);
10095 
10096     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10097     return;
10098   }
10099 
10100   // Diagnose base -> derived pointer conversions.
10101   unsigned BaseToDerivedConversion = 0;
10102   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
10103     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
10104       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10105                                                FromPtrTy->getPointeeType()) &&
10106           !FromPtrTy->getPointeeType()->isIncompleteType() &&
10107           !ToPtrTy->getPointeeType()->isIncompleteType() &&
10108           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
10109                           FromPtrTy->getPointeeType()))
10110         BaseToDerivedConversion = 1;
10111     }
10112   } else if (const ObjCObjectPointerType *FromPtrTy
10113                                     = FromTy->getAs<ObjCObjectPointerType>()) {
10114     if (const ObjCObjectPointerType *ToPtrTy
10115                                         = ToTy->getAs<ObjCObjectPointerType>())
10116       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
10117         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
10118           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10119                                                 FromPtrTy->getPointeeType()) &&
10120               FromIface->isSuperClassOf(ToIface))
10121             BaseToDerivedConversion = 2;
10122   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
10123     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
10124         !FromTy->isIncompleteType() &&
10125         !ToRefTy->getPointeeType()->isIncompleteType() &&
10126         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
10127       BaseToDerivedConversion = 3;
10128     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
10129                ToTy.getNonReferenceType().getCanonicalType() ==
10130                FromTy.getNonReferenceType().getCanonicalType()) {
10131       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
10132           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10133           << (unsigned)isObjectArgument << I + 1
10134           << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
10135       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10136       return;
10137     }
10138   }
10139 
10140   if (BaseToDerivedConversion) {
10141     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
10142         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10143         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10144         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
10145     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10146     return;
10147   }
10148 
10149   if (isa<ObjCObjectPointerType>(CFromTy) &&
10150       isa<PointerType>(CToTy)) {
10151       Qualifiers FromQs = CFromTy.getQualifiers();
10152       Qualifiers ToQs = CToTy.getQualifiers();
10153       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10154         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
10155             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10156             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10157             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
10158         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10159         return;
10160       }
10161   }
10162 
10163   if (TakingCandidateAddress &&
10164       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
10165     return;
10166 
10167   // Emit the generic diagnostic and, optionally, add the hints to it.
10168   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
10169   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10170         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10171         << ToTy << (unsigned)isObjectArgument << I + 1
10172         << (unsigned)(Cand->Fix.Kind);
10173 
10174   // If we can fix the conversion, suggest the FixIts.
10175   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
10176        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
10177     FDiag << *HI;
10178   S.Diag(Fn->getLocation(), FDiag);
10179 
10180   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10181 }
10182 
10183 /// Additional arity mismatch diagnosis specific to a function overload
10184 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
10185 /// over a candidate in any candidate set.
10186 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
10187                                unsigned NumArgs) {
10188   FunctionDecl *Fn = Cand->Function;
10189   unsigned MinParams = Fn->getMinRequiredArguments();
10190 
10191   // With invalid overloaded operators, it's possible that we think we
10192   // have an arity mismatch when in fact it looks like we have the
10193   // right number of arguments, because only overloaded operators have
10194   // the weird behavior of overloading member and non-member functions.
10195   // Just don't report anything.
10196   if (Fn->isInvalidDecl() &&
10197       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
10198     return true;
10199 
10200   if (NumArgs < MinParams) {
10201     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
10202            (Cand->FailureKind == ovl_fail_bad_deduction &&
10203             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
10204   } else {
10205     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
10206            (Cand->FailureKind == ovl_fail_bad_deduction &&
10207             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
10208   }
10209 
10210   return false;
10211 }
10212 
10213 /// General arity mismatch diagnosis over a candidate in a candidate set.
10214 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
10215                                   unsigned NumFormalArgs) {
10216   assert(isa<FunctionDecl>(D) &&
10217       "The templated declaration should at least be a function"
10218       " when diagnosing bad template argument deduction due to too many"
10219       " or too few arguments");
10220 
10221   FunctionDecl *Fn = cast<FunctionDecl>(D);
10222 
10223   // TODO: treat calls to a missing default constructor as a special case
10224   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
10225   unsigned MinParams = Fn->getMinRequiredArguments();
10226 
10227   // at least / at most / exactly
10228   unsigned mode, modeCount;
10229   if (NumFormalArgs < MinParams) {
10230     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
10231         FnTy->isTemplateVariadic())
10232       mode = 0; // "at least"
10233     else
10234       mode = 2; // "exactly"
10235     modeCount = MinParams;
10236   } else {
10237     if (MinParams != FnTy->getNumParams())
10238       mode = 1; // "at most"
10239     else
10240       mode = 2; // "exactly"
10241     modeCount = FnTy->getNumParams();
10242   }
10243 
10244   std::string Description;
10245   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10246       ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
10247 
10248   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10249     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10250         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10251         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
10252   else
10253     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
10254         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10255         << Description << mode << modeCount << NumFormalArgs;
10256 
10257   MaybeEmitInheritedConstructorNote(S, Found);
10258 }
10259 
10260 /// Arity mismatch diagnosis specific to a function overload candidate.
10261 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
10262                                   unsigned NumFormalArgs) {
10263   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
10264     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10265 }
10266 
10267 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10268   if (TemplateDecl *TD = Templated->getDescribedTemplate())
10269     return TD;
10270   llvm_unreachable("Unsupported: Getting the described template declaration"
10271                    " for bad deduction diagnosis");
10272 }
10273 
10274 /// Diagnose a failed template-argument deduction.
10275 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10276                                  DeductionFailureInfo &DeductionFailure,
10277                                  unsigned NumArgs,
10278                                  bool TakingCandidateAddress) {
10279   TemplateParameter Param = DeductionFailure.getTemplateParameter();
10280   NamedDecl *ParamD;
10281   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10282   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10283   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10284   switch (DeductionFailure.Result) {
10285   case Sema::TDK_Success:
10286     llvm_unreachable("TDK_success while diagnosing bad deduction");
10287 
10288   case Sema::TDK_Incomplete: {
10289     assert(ParamD && "no parameter found for incomplete deduction result");
10290     S.Diag(Templated->getLocation(),
10291            diag::note_ovl_candidate_incomplete_deduction)
10292         << ParamD->getDeclName();
10293     MaybeEmitInheritedConstructorNote(S, Found);
10294     return;
10295   }
10296 
10297   case Sema::TDK_IncompletePack: {
10298     assert(ParamD && "no parameter found for incomplete deduction result");
10299     S.Diag(Templated->getLocation(),
10300            diag::note_ovl_candidate_incomplete_deduction_pack)
10301         << ParamD->getDeclName()
10302         << (DeductionFailure.getFirstArg()->pack_size() + 1)
10303         << *DeductionFailure.getFirstArg();
10304     MaybeEmitInheritedConstructorNote(S, Found);
10305     return;
10306   }
10307 
10308   case Sema::TDK_Underqualified: {
10309     assert(ParamD && "no parameter found for bad qualifiers deduction result");
10310     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10311 
10312     QualType Param = DeductionFailure.getFirstArg()->getAsType();
10313 
10314     // Param will have been canonicalized, but it should just be a
10315     // qualified version of ParamD, so move the qualifiers to that.
10316     QualifierCollector Qs;
10317     Qs.strip(Param);
10318     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10319     assert(S.Context.hasSameType(Param, NonCanonParam));
10320 
10321     // Arg has also been canonicalized, but there's nothing we can do
10322     // about that.  It also doesn't matter as much, because it won't
10323     // have any template parameters in it (because deduction isn't
10324     // done on dependent types).
10325     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10326 
10327     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10328         << ParamD->getDeclName() << Arg << NonCanonParam;
10329     MaybeEmitInheritedConstructorNote(S, Found);
10330     return;
10331   }
10332 
10333   case Sema::TDK_Inconsistent: {
10334     assert(ParamD && "no parameter found for inconsistent deduction result");
10335     int which = 0;
10336     if (isa<TemplateTypeParmDecl>(ParamD))
10337       which = 0;
10338     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10339       // Deduction might have failed because we deduced arguments of two
10340       // different types for a non-type template parameter.
10341       // FIXME: Use a different TDK value for this.
10342       QualType T1 =
10343           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10344       QualType T2 =
10345           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10346       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10347         S.Diag(Templated->getLocation(),
10348                diag::note_ovl_candidate_inconsistent_deduction_types)
10349           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10350           << *DeductionFailure.getSecondArg() << T2;
10351         MaybeEmitInheritedConstructorNote(S, Found);
10352         return;
10353       }
10354 
10355       which = 1;
10356     } else {
10357       which = 2;
10358     }
10359 
10360     S.Diag(Templated->getLocation(),
10361            diag::note_ovl_candidate_inconsistent_deduction)
10362         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10363         << *DeductionFailure.getSecondArg();
10364     MaybeEmitInheritedConstructorNote(S, Found);
10365     return;
10366   }
10367 
10368   case Sema::TDK_InvalidExplicitArguments:
10369     assert(ParamD && "no parameter found for invalid explicit arguments");
10370     if (ParamD->getDeclName())
10371       S.Diag(Templated->getLocation(),
10372              diag::note_ovl_candidate_explicit_arg_mismatch_named)
10373           << ParamD->getDeclName();
10374     else {
10375       int index = 0;
10376       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10377         index = TTP->getIndex();
10378       else if (NonTypeTemplateParmDecl *NTTP
10379                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10380         index = NTTP->getIndex();
10381       else
10382         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10383       S.Diag(Templated->getLocation(),
10384              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10385           << (index + 1);
10386     }
10387     MaybeEmitInheritedConstructorNote(S, Found);
10388     return;
10389 
10390   case Sema::TDK_ConstraintsNotSatisfied: {
10391     // Format the template argument list into the argument string.
10392     SmallString<128> TemplateArgString;
10393     TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
10394     TemplateArgString = " ";
10395     TemplateArgString += S.getTemplateArgumentBindingsText(
10396         getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10397     S.Diag(Templated->getLocation(),
10398            diag::note_ovl_candidate_unsatisfied_constraints)
10399         << TemplateArgString;
10400 
10401     S.DiagnoseUnsatisfiedConstraint(
10402         static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
10403     return;
10404   }
10405   case Sema::TDK_TooManyArguments:
10406   case Sema::TDK_TooFewArguments:
10407     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10408     return;
10409 
10410   case Sema::TDK_InstantiationDepth:
10411     S.Diag(Templated->getLocation(),
10412            diag::note_ovl_candidate_instantiation_depth);
10413     MaybeEmitInheritedConstructorNote(S, Found);
10414     return;
10415 
10416   case Sema::TDK_SubstitutionFailure: {
10417     // Format the template argument list into the argument string.
10418     SmallString<128> TemplateArgString;
10419     if (TemplateArgumentList *Args =
10420             DeductionFailure.getTemplateArgumentList()) {
10421       TemplateArgString = " ";
10422       TemplateArgString += S.getTemplateArgumentBindingsText(
10423           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10424     }
10425 
10426     // If this candidate was disabled by enable_if, say so.
10427     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10428     if (PDiag && PDiag->second.getDiagID() ==
10429           diag::err_typename_nested_not_found_enable_if) {
10430       // FIXME: Use the source range of the condition, and the fully-qualified
10431       //        name of the enable_if template. These are both present in PDiag.
10432       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10433         << "'enable_if'" << TemplateArgString;
10434       return;
10435     }
10436 
10437     // We found a specific requirement that disabled the enable_if.
10438     if (PDiag && PDiag->second.getDiagID() ==
10439         diag::err_typename_nested_not_found_requirement) {
10440       S.Diag(Templated->getLocation(),
10441              diag::note_ovl_candidate_disabled_by_requirement)
10442         << PDiag->second.getStringArg(0) << TemplateArgString;
10443       return;
10444     }
10445 
10446     // Format the SFINAE diagnostic into the argument string.
10447     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10448     //        formatted message in another diagnostic.
10449     SmallString<128> SFINAEArgString;
10450     SourceRange R;
10451     if (PDiag) {
10452       SFINAEArgString = ": ";
10453       R = SourceRange(PDiag->first, PDiag->first);
10454       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10455     }
10456 
10457     S.Diag(Templated->getLocation(),
10458            diag::note_ovl_candidate_substitution_failure)
10459         << TemplateArgString << SFINAEArgString << R;
10460     MaybeEmitInheritedConstructorNote(S, Found);
10461     return;
10462   }
10463 
10464   case Sema::TDK_DeducedMismatch:
10465   case Sema::TDK_DeducedMismatchNested: {
10466     // Format the template argument list into the argument string.
10467     SmallString<128> TemplateArgString;
10468     if (TemplateArgumentList *Args =
10469             DeductionFailure.getTemplateArgumentList()) {
10470       TemplateArgString = " ";
10471       TemplateArgString += S.getTemplateArgumentBindingsText(
10472           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10473     }
10474 
10475     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10476         << (*DeductionFailure.getCallArgIndex() + 1)
10477         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10478         << TemplateArgString
10479         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10480     break;
10481   }
10482 
10483   case Sema::TDK_NonDeducedMismatch: {
10484     // FIXME: Provide a source location to indicate what we couldn't match.
10485     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10486     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10487     if (FirstTA.getKind() == TemplateArgument::Template &&
10488         SecondTA.getKind() == TemplateArgument::Template) {
10489       TemplateName FirstTN = FirstTA.getAsTemplate();
10490       TemplateName SecondTN = SecondTA.getAsTemplate();
10491       if (FirstTN.getKind() == TemplateName::Template &&
10492           SecondTN.getKind() == TemplateName::Template) {
10493         if (FirstTN.getAsTemplateDecl()->getName() ==
10494             SecondTN.getAsTemplateDecl()->getName()) {
10495           // FIXME: This fixes a bad diagnostic where both templates are named
10496           // the same.  This particular case is a bit difficult since:
10497           // 1) It is passed as a string to the diagnostic printer.
10498           // 2) The diagnostic printer only attempts to find a better
10499           //    name for types, not decls.
10500           // Ideally, this should folded into the diagnostic printer.
10501           S.Diag(Templated->getLocation(),
10502                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10503               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10504           return;
10505         }
10506       }
10507     }
10508 
10509     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10510         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10511       return;
10512 
10513     // FIXME: For generic lambda parameters, check if the function is a lambda
10514     // call operator, and if so, emit a prettier and more informative
10515     // diagnostic that mentions 'auto' and lambda in addition to
10516     // (or instead of?) the canonical template type parameters.
10517     S.Diag(Templated->getLocation(),
10518            diag::note_ovl_candidate_non_deduced_mismatch)
10519         << FirstTA << SecondTA;
10520     return;
10521   }
10522   // TODO: diagnose these individually, then kill off
10523   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10524   case Sema::TDK_MiscellaneousDeductionFailure:
10525     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10526     MaybeEmitInheritedConstructorNote(S, Found);
10527     return;
10528   case Sema::TDK_CUDATargetMismatch:
10529     S.Diag(Templated->getLocation(),
10530            diag::note_cuda_ovl_candidate_target_mismatch);
10531     return;
10532   }
10533 }
10534 
10535 /// Diagnose a failed template-argument deduction, for function calls.
10536 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10537                                  unsigned NumArgs,
10538                                  bool TakingCandidateAddress) {
10539   unsigned TDK = Cand->DeductionFailure.Result;
10540   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10541     if (CheckArityMismatch(S, Cand, NumArgs))
10542       return;
10543   }
10544   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10545                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10546 }
10547 
10548 /// CUDA: diagnose an invalid call across targets.
10549 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10550   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10551   FunctionDecl *Callee = Cand->Function;
10552 
10553   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10554                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10555 
10556   std::string FnDesc;
10557   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10558       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
10559                                 Cand->getRewriteKind(), FnDesc);
10560 
10561   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10562       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10563       << FnDesc /* Ignored */
10564       << CalleeTarget << CallerTarget;
10565 
10566   // This could be an implicit constructor for which we could not infer the
10567   // target due to a collsion. Diagnose that case.
10568   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10569   if (Meth != nullptr && Meth->isImplicit()) {
10570     CXXRecordDecl *ParentClass = Meth->getParent();
10571     Sema::CXXSpecialMember CSM;
10572 
10573     switch (FnKindPair.first) {
10574     default:
10575       return;
10576     case oc_implicit_default_constructor:
10577       CSM = Sema::CXXDefaultConstructor;
10578       break;
10579     case oc_implicit_copy_constructor:
10580       CSM = Sema::CXXCopyConstructor;
10581       break;
10582     case oc_implicit_move_constructor:
10583       CSM = Sema::CXXMoveConstructor;
10584       break;
10585     case oc_implicit_copy_assignment:
10586       CSM = Sema::CXXCopyAssignment;
10587       break;
10588     case oc_implicit_move_assignment:
10589       CSM = Sema::CXXMoveAssignment;
10590       break;
10591     };
10592 
10593     bool ConstRHS = false;
10594     if (Meth->getNumParams()) {
10595       if (const ReferenceType *RT =
10596               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10597         ConstRHS = RT->getPointeeType().isConstQualified();
10598       }
10599     }
10600 
10601     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10602                                               /* ConstRHS */ ConstRHS,
10603                                               /* Diagnose */ true);
10604   }
10605 }
10606 
10607 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10608   FunctionDecl *Callee = Cand->Function;
10609   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10610 
10611   S.Diag(Callee->getLocation(),
10612          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10613       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10614 }
10615 
10616 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
10617   ExplicitSpecifier ES;
10618   const char *DeclName;
10619   switch (Cand->Function->getDeclKind()) {
10620   case Decl::Kind::CXXConstructor:
10621     ES = cast<CXXConstructorDecl>(Cand->Function)->getExplicitSpecifier();
10622     DeclName = "constructor";
10623     break;
10624   case Decl::Kind::CXXConversion:
10625     ES = cast<CXXConversionDecl>(Cand->Function)->getExplicitSpecifier();
10626     DeclName = "conversion operator";
10627     break;
10628   case Decl::Kind::CXXDeductionGuide:
10629     ES = cast<CXXDeductionGuideDecl>(Cand->Function)->getExplicitSpecifier();
10630     DeclName = "deductiong guide";
10631     break;
10632   default:
10633     llvm_unreachable("invalid Decl");
10634   }
10635   assert(ES.getExpr() && "null expression should be handled before");
10636   S.Diag(Cand->Function->getLocation(),
10637          diag::note_ovl_candidate_explicit_forbidden)
10638       << DeclName;
10639   S.Diag(ES.getExpr()->getBeginLoc(),
10640          diag::note_explicit_bool_resolved_to_true);
10641 }
10642 
10643 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10644   FunctionDecl *Callee = Cand->Function;
10645 
10646   S.Diag(Callee->getLocation(),
10647          diag::note_ovl_candidate_disabled_by_extension)
10648     << S.getOpenCLExtensionsFromDeclExtMap(Callee);
10649 }
10650 
10651 /// Generates a 'note' diagnostic for an overload candidate.  We've
10652 /// already generated a primary error at the call site.
10653 ///
10654 /// It really does need to be a single diagnostic with its caret
10655 /// pointed at the candidate declaration.  Yes, this creates some
10656 /// major challenges of technical writing.  Yes, this makes pointing
10657 /// out problems with specific arguments quite awkward.  It's still
10658 /// better than generating twenty screens of text for every failed
10659 /// overload.
10660 ///
10661 /// It would be great to be able to express per-candidate problems
10662 /// more richly for those diagnostic clients that cared, but we'd
10663 /// still have to be just as careful with the default diagnostics.
10664 /// \param CtorDestAS Addr space of object being constructed (for ctor
10665 /// candidates only).
10666 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10667                                   unsigned NumArgs,
10668                                   bool TakingCandidateAddress,
10669                                   LangAS CtorDestAS = LangAS::Default) {
10670   FunctionDecl *Fn = Cand->Function;
10671 
10672   // Note deleted candidates, but only if they're viable.
10673   if (Cand->Viable) {
10674     if (Fn->isDeleted()) {
10675       std::string FnDesc;
10676       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10677           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
10678                                     Cand->getRewriteKind(), FnDesc);
10679 
10680       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10681           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10682           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10683       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10684       return;
10685     }
10686 
10687     // We don't really have anything else to say about viable candidates.
10688     S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10689     return;
10690   }
10691 
10692   switch (Cand->FailureKind) {
10693   case ovl_fail_too_many_arguments:
10694   case ovl_fail_too_few_arguments:
10695     return DiagnoseArityMismatch(S, Cand, NumArgs);
10696 
10697   case ovl_fail_bad_deduction:
10698     return DiagnoseBadDeduction(S, Cand, NumArgs,
10699                                 TakingCandidateAddress);
10700 
10701   case ovl_fail_illegal_constructor: {
10702     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10703       << (Fn->getPrimaryTemplate() ? 1 : 0);
10704     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10705     return;
10706   }
10707 
10708   case ovl_fail_object_addrspace_mismatch: {
10709     Qualifiers QualsForPrinting;
10710     QualsForPrinting.setAddressSpace(CtorDestAS);
10711     S.Diag(Fn->getLocation(),
10712            diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
10713         << QualsForPrinting;
10714     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10715     return;
10716   }
10717 
10718   case ovl_fail_trivial_conversion:
10719   case ovl_fail_bad_final_conversion:
10720   case ovl_fail_final_conversion_not_exact:
10721     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10722 
10723   case ovl_fail_bad_conversion: {
10724     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10725     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10726       if (Cand->Conversions[I].isBad())
10727         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10728 
10729     // FIXME: this currently happens when we're called from SemaInit
10730     // when user-conversion overload fails.  Figure out how to handle
10731     // those conditions and diagnose them well.
10732     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10733   }
10734 
10735   case ovl_fail_bad_target:
10736     return DiagnoseBadTarget(S, Cand);
10737 
10738   case ovl_fail_enable_if:
10739     return DiagnoseFailedEnableIfAttr(S, Cand);
10740 
10741   case ovl_fail_explicit_resolved:
10742     return DiagnoseFailedExplicitSpec(S, Cand);
10743 
10744   case ovl_fail_ext_disabled:
10745     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10746 
10747   case ovl_fail_inhctor_slice:
10748     // It's generally not interesting to note copy/move constructors here.
10749     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10750       return;
10751     S.Diag(Fn->getLocation(),
10752            diag::note_ovl_candidate_inherited_constructor_slice)
10753       << (Fn->getPrimaryTemplate() ? 1 : 0)
10754       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10755     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10756     return;
10757 
10758   case ovl_fail_addr_not_available: {
10759     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10760     (void)Available;
10761     assert(!Available);
10762     break;
10763   }
10764   case ovl_non_default_multiversion_function:
10765     // Do nothing, these should simply be ignored.
10766     break;
10767   }
10768 }
10769 
10770 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10771   // Desugar the type of the surrogate down to a function type,
10772   // retaining as many typedefs as possible while still showing
10773   // the function type (and, therefore, its parameter types).
10774   QualType FnType = Cand->Surrogate->getConversionType();
10775   bool isLValueReference = false;
10776   bool isRValueReference = false;
10777   bool isPointer = false;
10778   if (const LValueReferenceType *FnTypeRef =
10779         FnType->getAs<LValueReferenceType>()) {
10780     FnType = FnTypeRef->getPointeeType();
10781     isLValueReference = true;
10782   } else if (const RValueReferenceType *FnTypeRef =
10783                FnType->getAs<RValueReferenceType>()) {
10784     FnType = FnTypeRef->getPointeeType();
10785     isRValueReference = true;
10786   }
10787   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10788     FnType = FnTypePtr->getPointeeType();
10789     isPointer = true;
10790   }
10791   // Desugar down to a function type.
10792   FnType = QualType(FnType->getAs<FunctionType>(), 0);
10793   // Reconstruct the pointer/reference as appropriate.
10794   if (isPointer) FnType = S.Context.getPointerType(FnType);
10795   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10796   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10797 
10798   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10799     << FnType;
10800 }
10801 
10802 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10803                                          SourceLocation OpLoc,
10804                                          OverloadCandidate *Cand) {
10805   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10806   std::string TypeStr("operator");
10807   TypeStr += Opc;
10808   TypeStr += "(";
10809   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
10810   if (Cand->Conversions.size() == 1) {
10811     TypeStr += ")";
10812     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
10813   } else {
10814     TypeStr += ", ";
10815     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
10816     TypeStr += ")";
10817     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
10818   }
10819 }
10820 
10821 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10822                                          OverloadCandidate *Cand) {
10823   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10824     if (ICS.isBad()) break; // all meaningless after first invalid
10825     if (!ICS.isAmbiguous()) continue;
10826 
10827     ICS.DiagnoseAmbiguousConversion(
10828         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10829   }
10830 }
10831 
10832 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10833   if (Cand->Function)
10834     return Cand->Function->getLocation();
10835   if (Cand->IsSurrogate)
10836     return Cand->Surrogate->getLocation();
10837   return SourceLocation();
10838 }
10839 
10840 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10841   switch ((Sema::TemplateDeductionResult)DFI.Result) {
10842   case Sema::TDK_Success:
10843   case Sema::TDK_NonDependentConversionFailure:
10844     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10845 
10846   case Sema::TDK_Invalid:
10847   case Sema::TDK_Incomplete:
10848   case Sema::TDK_IncompletePack:
10849     return 1;
10850 
10851   case Sema::TDK_Underqualified:
10852   case Sema::TDK_Inconsistent:
10853     return 2;
10854 
10855   case Sema::TDK_SubstitutionFailure:
10856   case Sema::TDK_DeducedMismatch:
10857   case Sema::TDK_ConstraintsNotSatisfied:
10858   case Sema::TDK_DeducedMismatchNested:
10859   case Sema::TDK_NonDeducedMismatch:
10860   case Sema::TDK_MiscellaneousDeductionFailure:
10861   case Sema::TDK_CUDATargetMismatch:
10862     return 3;
10863 
10864   case Sema::TDK_InstantiationDepth:
10865     return 4;
10866 
10867   case Sema::TDK_InvalidExplicitArguments:
10868     return 5;
10869 
10870   case Sema::TDK_TooManyArguments:
10871   case Sema::TDK_TooFewArguments:
10872     return 6;
10873   }
10874   llvm_unreachable("Unhandled deduction result");
10875 }
10876 
10877 namespace {
10878 struct CompareOverloadCandidatesForDisplay {
10879   Sema &S;
10880   SourceLocation Loc;
10881   size_t NumArgs;
10882   OverloadCandidateSet::CandidateSetKind CSK;
10883 
10884   CompareOverloadCandidatesForDisplay(
10885       Sema &S, SourceLocation Loc, size_t NArgs,
10886       OverloadCandidateSet::CandidateSetKind CSK)
10887       : S(S), NumArgs(NArgs), CSK(CSK) {}
10888 
10889   bool operator()(const OverloadCandidate *L,
10890                   const OverloadCandidate *R) {
10891     // Fast-path this check.
10892     if (L == R) return false;
10893 
10894     // Order first by viability.
10895     if (L->Viable) {
10896       if (!R->Viable) return true;
10897 
10898       // TODO: introduce a tri-valued comparison for overload
10899       // candidates.  Would be more worthwhile if we had a sort
10900       // that could exploit it.
10901       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10902         return true;
10903       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10904         return false;
10905     } else if (R->Viable)
10906       return false;
10907 
10908     assert(L->Viable == R->Viable);
10909 
10910     // Criteria by which we can sort non-viable candidates:
10911     if (!L->Viable) {
10912       // 1. Arity mismatches come after other candidates.
10913       if (L->FailureKind == ovl_fail_too_many_arguments ||
10914           L->FailureKind == ovl_fail_too_few_arguments) {
10915         if (R->FailureKind == ovl_fail_too_many_arguments ||
10916             R->FailureKind == ovl_fail_too_few_arguments) {
10917           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10918           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10919           if (LDist == RDist) {
10920             if (L->FailureKind == R->FailureKind)
10921               // Sort non-surrogates before surrogates.
10922               return !L->IsSurrogate && R->IsSurrogate;
10923             // Sort candidates requiring fewer parameters than there were
10924             // arguments given after candidates requiring more parameters
10925             // than there were arguments given.
10926             return L->FailureKind == ovl_fail_too_many_arguments;
10927           }
10928           return LDist < RDist;
10929         }
10930         return false;
10931       }
10932       if (R->FailureKind == ovl_fail_too_many_arguments ||
10933           R->FailureKind == ovl_fail_too_few_arguments)
10934         return true;
10935 
10936       // 2. Bad conversions come first and are ordered by the number
10937       // of bad conversions and quality of good conversions.
10938       if (L->FailureKind == ovl_fail_bad_conversion) {
10939         if (R->FailureKind != ovl_fail_bad_conversion)
10940           return true;
10941 
10942         // The conversion that can be fixed with a smaller number of changes,
10943         // comes first.
10944         unsigned numLFixes = L->Fix.NumConversionsFixed;
10945         unsigned numRFixes = R->Fix.NumConversionsFixed;
10946         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10947         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10948         if (numLFixes != numRFixes) {
10949           return numLFixes < numRFixes;
10950         }
10951 
10952         // If there's any ordering between the defined conversions...
10953         // FIXME: this might not be transitive.
10954         assert(L->Conversions.size() == R->Conversions.size());
10955 
10956         int leftBetter = 0;
10957         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10958         for (unsigned E = L->Conversions.size(); I != E; ++I) {
10959           switch (CompareImplicitConversionSequences(S, Loc,
10960                                                      L->Conversions[I],
10961                                                      R->Conversions[I])) {
10962           case ImplicitConversionSequence::Better:
10963             leftBetter++;
10964             break;
10965 
10966           case ImplicitConversionSequence::Worse:
10967             leftBetter--;
10968             break;
10969 
10970           case ImplicitConversionSequence::Indistinguishable:
10971             break;
10972           }
10973         }
10974         if (leftBetter > 0) return true;
10975         if (leftBetter < 0) return false;
10976 
10977       } else if (R->FailureKind == ovl_fail_bad_conversion)
10978         return false;
10979 
10980       if (L->FailureKind == ovl_fail_bad_deduction) {
10981         if (R->FailureKind != ovl_fail_bad_deduction)
10982           return true;
10983 
10984         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10985           return RankDeductionFailure(L->DeductionFailure)
10986                < RankDeductionFailure(R->DeductionFailure);
10987       } else if (R->FailureKind == ovl_fail_bad_deduction)
10988         return false;
10989 
10990       // TODO: others?
10991     }
10992 
10993     // Sort everything else by location.
10994     SourceLocation LLoc = GetLocationForCandidate(L);
10995     SourceLocation RLoc = GetLocationForCandidate(R);
10996 
10997     // Put candidates without locations (e.g. builtins) at the end.
10998     if (LLoc.isInvalid()) return false;
10999     if (RLoc.isInvalid()) return true;
11000 
11001     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11002   }
11003 };
11004 }
11005 
11006 /// CompleteNonViableCandidate - Normally, overload resolution only
11007 /// computes up to the first bad conversion. Produces the FixIt set if
11008 /// possible.
11009 static void
11010 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
11011                            ArrayRef<Expr *> Args,
11012                            OverloadCandidateSet::CandidateSetKind CSK) {
11013   assert(!Cand->Viable);
11014 
11015   // Don't do anything on failures other than bad conversion.
11016   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
11017 
11018   // We only want the FixIts if all the arguments can be corrected.
11019   bool Unfixable = false;
11020   // Use a implicit copy initialization to check conversion fixes.
11021   Cand->Fix.setConversionChecker(TryCopyInitialization);
11022 
11023   // Attempt to fix the bad conversion.
11024   unsigned ConvCount = Cand->Conversions.size();
11025   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
11026        ++ConvIdx) {
11027     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
11028     if (Cand->Conversions[ConvIdx].isInitialized() &&
11029         Cand->Conversions[ConvIdx].isBad()) {
11030       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11031       break;
11032     }
11033   }
11034 
11035   // FIXME: this should probably be preserved from the overload
11036   // operation somehow.
11037   bool SuppressUserConversions = false;
11038 
11039   unsigned ConvIdx = 0;
11040   unsigned ArgIdx = 0;
11041   ArrayRef<QualType> ParamTypes;
11042   bool Reversed = Cand->RewriteKind & CRK_Reversed;
11043 
11044   if (Cand->IsSurrogate) {
11045     QualType ConvType
11046       = Cand->Surrogate->getConversionType().getNonReferenceType();
11047     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11048       ConvType = ConvPtrType->getPointeeType();
11049     ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
11050     // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11051     ConvIdx = 1;
11052   } else if (Cand->Function) {
11053     ParamTypes =
11054         Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
11055     if (isa<CXXMethodDecl>(Cand->Function) &&
11056         !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
11057       // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11058       ConvIdx = 1;
11059       if (CSK == OverloadCandidateSet::CSK_Operator &&
11060           Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call)
11061         // Argument 0 is 'this', which doesn't have a corresponding parameter.
11062         ArgIdx = 1;
11063     }
11064   } else {
11065     // Builtin operator.
11066     assert(ConvCount <= 3);
11067     ParamTypes = Cand->BuiltinParamTypes;
11068   }
11069 
11070   // Fill in the rest of the conversions.
11071   for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
11072        ConvIdx != ConvCount;
11073        ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
11074     assert(ArgIdx < Args.size() && "no argument for this arg conversion");
11075     if (Cand->Conversions[ConvIdx].isInitialized()) {
11076       // We've already checked this conversion.
11077     } else if (ParamIdx < ParamTypes.size()) {
11078       if (ParamTypes[ParamIdx]->isDependentType())
11079         Cand->Conversions[ConvIdx].setAsIdentityConversion(
11080             Args[ArgIdx]->getType());
11081       else {
11082         Cand->Conversions[ConvIdx] =
11083             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
11084                                   SuppressUserConversions,
11085                                   /*InOverloadResolution=*/true,
11086                                   /*AllowObjCWritebackConversion=*/
11087                                   S.getLangOpts().ObjCAutoRefCount);
11088         // Store the FixIt in the candidate if it exists.
11089         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
11090           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11091       }
11092     } else
11093       Cand->Conversions[ConvIdx].setEllipsis();
11094   }
11095 }
11096 
11097 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
11098     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11099     SourceLocation OpLoc,
11100     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11101   // Sort the candidates by viability and position.  Sorting directly would
11102   // be prohibitive, so we make a set of pointers and sort those.
11103   SmallVector<OverloadCandidate*, 32> Cands;
11104   if (OCD == OCD_AllCandidates) Cands.reserve(size());
11105   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11106     if (!Filter(*Cand))
11107       continue;
11108     switch (OCD) {
11109     case OCD_AllCandidates:
11110       if (!Cand->Viable) {
11111         if (!Cand->Function && !Cand->IsSurrogate) {
11112           // This a non-viable builtin candidate.  We do not, in general,
11113           // want to list every possible builtin candidate.
11114           continue;
11115         }
11116         CompleteNonViableCandidate(S, Cand, Args, Kind);
11117       }
11118       break;
11119 
11120     case OCD_ViableCandidates:
11121       if (!Cand->Viable)
11122         continue;
11123       break;
11124 
11125     case OCD_AmbiguousCandidates:
11126       if (!Cand->Best)
11127         continue;
11128       break;
11129     }
11130 
11131     Cands.push_back(Cand);
11132   }
11133 
11134   llvm::stable_sort(
11135       Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
11136 
11137   return Cands;
11138 }
11139 
11140 /// When overload resolution fails, prints diagnostic messages containing the
11141 /// candidates in the candidate set.
11142 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD,
11143     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11144     StringRef Opc, SourceLocation OpLoc,
11145     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11146 
11147   auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
11148 
11149   S.Diag(PD.first, PD.second);
11150 
11151   NoteCandidates(S, Args, Cands, Opc, OpLoc);
11152 }
11153 
11154 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
11155                                           ArrayRef<OverloadCandidate *> Cands,
11156                                           StringRef Opc, SourceLocation OpLoc) {
11157   bool ReportedAmbiguousConversions = false;
11158 
11159   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11160   unsigned CandsShown = 0;
11161   auto I = Cands.begin(), E = Cands.end();
11162   for (; I != E; ++I) {
11163     OverloadCandidate *Cand = *I;
11164 
11165     // Set an arbitrary limit on the number of candidate functions we'll spam
11166     // the user with.  FIXME: This limit should depend on details of the
11167     // candidate list.
11168     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
11169       break;
11170     }
11171     ++CandsShown;
11172 
11173     if (Cand->Function)
11174       NoteFunctionCandidate(S, Cand, Args.size(),
11175                             /*TakingCandidateAddress=*/false, DestAS);
11176     else if (Cand->IsSurrogate)
11177       NoteSurrogateCandidate(S, Cand);
11178     else {
11179       assert(Cand->Viable &&
11180              "Non-viable built-in candidates are not added to Cands.");
11181       // Generally we only see ambiguities including viable builtin
11182       // operators if overload resolution got screwed up by an
11183       // ambiguous user-defined conversion.
11184       //
11185       // FIXME: It's quite possible for different conversions to see
11186       // different ambiguities, though.
11187       if (!ReportedAmbiguousConversions) {
11188         NoteAmbiguousUserConversions(S, OpLoc, Cand);
11189         ReportedAmbiguousConversions = true;
11190       }
11191 
11192       // If this is a viable builtin, print it.
11193       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
11194     }
11195   }
11196 
11197   if (I != E)
11198     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
11199 }
11200 
11201 static SourceLocation
11202 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
11203   return Cand->Specialization ? Cand->Specialization->getLocation()
11204                               : SourceLocation();
11205 }
11206 
11207 namespace {
11208 struct CompareTemplateSpecCandidatesForDisplay {
11209   Sema &S;
11210   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
11211 
11212   bool operator()(const TemplateSpecCandidate *L,
11213                   const TemplateSpecCandidate *R) {
11214     // Fast-path this check.
11215     if (L == R)
11216       return false;
11217 
11218     // Assuming that both candidates are not matches...
11219 
11220     // Sort by the ranking of deduction failures.
11221     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11222       return RankDeductionFailure(L->DeductionFailure) <
11223              RankDeductionFailure(R->DeductionFailure);
11224 
11225     // Sort everything else by location.
11226     SourceLocation LLoc = GetLocationForCandidate(L);
11227     SourceLocation RLoc = GetLocationForCandidate(R);
11228 
11229     // Put candidates without locations (e.g. builtins) at the end.
11230     if (LLoc.isInvalid())
11231       return false;
11232     if (RLoc.isInvalid())
11233       return true;
11234 
11235     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11236   }
11237 };
11238 }
11239 
11240 /// Diagnose a template argument deduction failure.
11241 /// We are treating these failures as overload failures due to bad
11242 /// deductions.
11243 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
11244                                                  bool ForTakingAddress) {
11245   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
11246                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
11247 }
11248 
11249 void TemplateSpecCandidateSet::destroyCandidates() {
11250   for (iterator i = begin(), e = end(); i != e; ++i) {
11251     i->DeductionFailure.Destroy();
11252   }
11253 }
11254 
11255 void TemplateSpecCandidateSet::clear() {
11256   destroyCandidates();
11257   Candidates.clear();
11258 }
11259 
11260 /// NoteCandidates - When no template specialization match is found, prints
11261 /// diagnostic messages containing the non-matching specializations that form
11262 /// the candidate set.
11263 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
11264 /// OCD == OCD_AllCandidates and Cand->Viable == false.
11265 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
11266   // Sort the candidates by position (assuming no candidate is a match).
11267   // Sorting directly would be prohibitive, so we make a set of pointers
11268   // and sort those.
11269   SmallVector<TemplateSpecCandidate *, 32> Cands;
11270   Cands.reserve(size());
11271   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11272     if (Cand->Specialization)
11273       Cands.push_back(Cand);
11274     // Otherwise, this is a non-matching builtin candidate.  We do not,
11275     // in general, want to list every possible builtin candidate.
11276   }
11277 
11278   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
11279 
11280   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
11281   // for generalization purposes (?).
11282   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11283 
11284   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
11285   unsigned CandsShown = 0;
11286   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11287     TemplateSpecCandidate *Cand = *I;
11288 
11289     // Set an arbitrary limit on the number of candidates we'll spam
11290     // the user with.  FIXME: This limit should depend on details of the
11291     // candidate list.
11292     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
11293       break;
11294     ++CandsShown;
11295 
11296     assert(Cand->Specialization &&
11297            "Non-matching built-in candidates are not added to Cands.");
11298     Cand->NoteDeductionFailure(S, ForTakingAddress);
11299   }
11300 
11301   if (I != E)
11302     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
11303 }
11304 
11305 // [PossiblyAFunctionType]  -->   [Return]
11306 // NonFunctionType --> NonFunctionType
11307 // R (A) --> R(A)
11308 // R (*)(A) --> R (A)
11309 // R (&)(A) --> R (A)
11310 // R (S::*)(A) --> R (A)
11311 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
11312   QualType Ret = PossiblyAFunctionType;
11313   if (const PointerType *ToTypePtr =
11314     PossiblyAFunctionType->getAs<PointerType>())
11315     Ret = ToTypePtr->getPointeeType();
11316   else if (const ReferenceType *ToTypeRef =
11317     PossiblyAFunctionType->getAs<ReferenceType>())
11318     Ret = ToTypeRef->getPointeeType();
11319   else if (const MemberPointerType *MemTypePtr =
11320     PossiblyAFunctionType->getAs<MemberPointerType>())
11321     Ret = MemTypePtr->getPointeeType();
11322   Ret =
11323     Context.getCanonicalType(Ret).getUnqualifiedType();
11324   return Ret;
11325 }
11326 
11327 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
11328                                  bool Complain = true) {
11329   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
11330       S.DeduceReturnType(FD, Loc, Complain))
11331     return true;
11332 
11333   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
11334   if (S.getLangOpts().CPlusPlus17 &&
11335       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
11336       !S.ResolveExceptionSpec(Loc, FPT))
11337     return true;
11338 
11339   return false;
11340 }
11341 
11342 namespace {
11343 // A helper class to help with address of function resolution
11344 // - allows us to avoid passing around all those ugly parameters
11345 class AddressOfFunctionResolver {
11346   Sema& S;
11347   Expr* SourceExpr;
11348   const QualType& TargetType;
11349   QualType TargetFunctionType; // Extracted function type from target type
11350 
11351   bool Complain;
11352   //DeclAccessPair& ResultFunctionAccessPair;
11353   ASTContext& Context;
11354 
11355   bool TargetTypeIsNonStaticMemberFunction;
11356   bool FoundNonTemplateFunction;
11357   bool StaticMemberFunctionFromBoundPointer;
11358   bool HasComplained;
11359 
11360   OverloadExpr::FindResult OvlExprInfo;
11361   OverloadExpr *OvlExpr;
11362   TemplateArgumentListInfo OvlExplicitTemplateArgs;
11363   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
11364   TemplateSpecCandidateSet FailedCandidates;
11365 
11366 public:
11367   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
11368                             const QualType &TargetType, bool Complain)
11369       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
11370         Complain(Complain), Context(S.getASTContext()),
11371         TargetTypeIsNonStaticMemberFunction(
11372             !!TargetType->getAs<MemberPointerType>()),
11373         FoundNonTemplateFunction(false),
11374         StaticMemberFunctionFromBoundPointer(false),
11375         HasComplained(false),
11376         OvlExprInfo(OverloadExpr::find(SourceExpr)),
11377         OvlExpr(OvlExprInfo.Expression),
11378         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
11379     ExtractUnqualifiedFunctionTypeFromTargetType();
11380 
11381     if (TargetFunctionType->isFunctionType()) {
11382       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
11383         if (!UME->isImplicitAccess() &&
11384             !S.ResolveSingleFunctionTemplateSpecialization(UME))
11385           StaticMemberFunctionFromBoundPointer = true;
11386     } else if (OvlExpr->hasExplicitTemplateArgs()) {
11387       DeclAccessPair dap;
11388       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
11389               OvlExpr, false, &dap)) {
11390         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
11391           if (!Method->isStatic()) {
11392             // If the target type is a non-function type and the function found
11393             // is a non-static member function, pretend as if that was the
11394             // target, it's the only possible type to end up with.
11395             TargetTypeIsNonStaticMemberFunction = true;
11396 
11397             // And skip adding the function if its not in the proper form.
11398             // We'll diagnose this due to an empty set of functions.
11399             if (!OvlExprInfo.HasFormOfMemberPointer)
11400               return;
11401           }
11402 
11403         Matches.push_back(std::make_pair(dap, Fn));
11404       }
11405       return;
11406     }
11407 
11408     if (OvlExpr->hasExplicitTemplateArgs())
11409       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
11410 
11411     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
11412       // C++ [over.over]p4:
11413       //   If more than one function is selected, [...]
11414       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
11415         if (FoundNonTemplateFunction)
11416           EliminateAllTemplateMatches();
11417         else
11418           EliminateAllExceptMostSpecializedTemplate();
11419       }
11420     }
11421 
11422     if (S.getLangOpts().CUDA && Matches.size() > 1)
11423       EliminateSuboptimalCudaMatches();
11424   }
11425 
11426   bool hasComplained() const { return HasComplained; }
11427 
11428 private:
11429   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
11430     QualType Discard;
11431     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
11432            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
11433   }
11434 
11435   /// \return true if A is considered a better overload candidate for the
11436   /// desired type than B.
11437   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
11438     // If A doesn't have exactly the correct type, we don't want to classify it
11439     // as "better" than anything else. This way, the user is required to
11440     // disambiguate for us if there are multiple candidates and no exact match.
11441     return candidateHasExactlyCorrectType(A) &&
11442            (!candidateHasExactlyCorrectType(B) ||
11443             compareEnableIfAttrs(S, A, B) == Comparison::Better);
11444   }
11445 
11446   /// \return true if we were able to eliminate all but one overload candidate,
11447   /// false otherwise.
11448   bool eliminiateSuboptimalOverloadCandidates() {
11449     // Same algorithm as overload resolution -- one pass to pick the "best",
11450     // another pass to be sure that nothing is better than the best.
11451     auto Best = Matches.begin();
11452     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11453       if (isBetterCandidate(I->second, Best->second))
11454         Best = I;
11455 
11456     const FunctionDecl *BestFn = Best->second;
11457     auto IsBestOrInferiorToBest = [this, BestFn](
11458         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11459       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11460     };
11461 
11462     // Note: We explicitly leave Matches unmodified if there isn't a clear best
11463     // option, so we can potentially give the user a better error
11464     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
11465       return false;
11466     Matches[0] = *Best;
11467     Matches.resize(1);
11468     return true;
11469   }
11470 
11471   bool isTargetTypeAFunction() const {
11472     return TargetFunctionType->isFunctionType();
11473   }
11474 
11475   // [ToType]     [Return]
11476 
11477   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11478   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11479   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11480   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11481     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11482   }
11483 
11484   // return true if any matching specializations were found
11485   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
11486                                    const DeclAccessPair& CurAccessFunPair) {
11487     if (CXXMethodDecl *Method
11488               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11489       // Skip non-static function templates when converting to pointer, and
11490       // static when converting to member pointer.
11491       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11492         return false;
11493     }
11494     else if (TargetTypeIsNonStaticMemberFunction)
11495       return false;
11496 
11497     // C++ [over.over]p2:
11498     //   If the name is a function template, template argument deduction is
11499     //   done (14.8.2.2), and if the argument deduction succeeds, the
11500     //   resulting template argument list is used to generate a single
11501     //   function template specialization, which is added to the set of
11502     //   overloaded functions considered.
11503     FunctionDecl *Specialization = nullptr;
11504     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11505     if (Sema::TemplateDeductionResult Result
11506           = S.DeduceTemplateArguments(FunctionTemplate,
11507                                       &OvlExplicitTemplateArgs,
11508                                       TargetFunctionType, Specialization,
11509                                       Info, /*IsAddressOfFunction*/true)) {
11510       // Make a note of the failed deduction for diagnostics.
11511       FailedCandidates.addCandidate()
11512           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
11513                MakeDeductionFailureInfo(Context, Result, Info));
11514       return false;
11515     }
11516 
11517     // Template argument deduction ensures that we have an exact match or
11518     // compatible pointer-to-function arguments that would be adjusted by ICS.
11519     // This function template specicalization works.
11520     assert(S.isSameOrCompatibleFunctionType(
11521               Context.getCanonicalType(Specialization->getType()),
11522               Context.getCanonicalType(TargetFunctionType)));
11523 
11524     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11525       return false;
11526 
11527     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11528     return true;
11529   }
11530 
11531   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11532                                       const DeclAccessPair& CurAccessFunPair) {
11533     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11534       // Skip non-static functions when converting to pointer, and static
11535       // when converting to member pointer.
11536       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11537         return false;
11538     }
11539     else if (TargetTypeIsNonStaticMemberFunction)
11540       return false;
11541 
11542     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11543       if (S.getLangOpts().CUDA)
11544         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11545           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11546             return false;
11547       if (FunDecl->isMultiVersion()) {
11548         const auto *TA = FunDecl->getAttr<TargetAttr>();
11549         if (TA && !TA->isDefaultVersion())
11550           return false;
11551       }
11552 
11553       // If any candidate has a placeholder return type, trigger its deduction
11554       // now.
11555       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
11556                                Complain)) {
11557         HasComplained |= Complain;
11558         return false;
11559       }
11560 
11561       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11562         return false;
11563 
11564       // If we're in C, we need to support types that aren't exactly identical.
11565       if (!S.getLangOpts().CPlusPlus ||
11566           candidateHasExactlyCorrectType(FunDecl)) {
11567         Matches.push_back(std::make_pair(
11568             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11569         FoundNonTemplateFunction = true;
11570         return true;
11571       }
11572     }
11573 
11574     return false;
11575   }
11576 
11577   bool FindAllFunctionsThatMatchTargetTypeExactly() {
11578     bool Ret = false;
11579 
11580     // If the overload expression doesn't have the form of a pointer to
11581     // member, don't try to convert it to a pointer-to-member type.
11582     if (IsInvalidFormOfPointerToMemberFunction())
11583       return false;
11584 
11585     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11586                                E = OvlExpr->decls_end();
11587          I != E; ++I) {
11588       // Look through any using declarations to find the underlying function.
11589       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11590 
11591       // C++ [over.over]p3:
11592       //   Non-member functions and static member functions match
11593       //   targets of type "pointer-to-function" or "reference-to-function."
11594       //   Nonstatic member functions match targets of
11595       //   type "pointer-to-member-function."
11596       // Note that according to DR 247, the containing class does not matter.
11597       if (FunctionTemplateDecl *FunctionTemplate
11598                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11599         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11600           Ret = true;
11601       }
11602       // If we have explicit template arguments supplied, skip non-templates.
11603       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11604                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11605         Ret = true;
11606     }
11607     assert(Ret || Matches.empty());
11608     return Ret;
11609   }
11610 
11611   void EliminateAllExceptMostSpecializedTemplate() {
11612     //   [...] and any given function template specialization F1 is
11613     //   eliminated if the set contains a second function template
11614     //   specialization whose function template is more specialized
11615     //   than the function template of F1 according to the partial
11616     //   ordering rules of 14.5.5.2.
11617 
11618     // The algorithm specified above is quadratic. We instead use a
11619     // two-pass algorithm (similar to the one used to identify the
11620     // best viable function in an overload set) that identifies the
11621     // best function template (if it exists).
11622 
11623     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11624     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11625       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11626 
11627     // TODO: It looks like FailedCandidates does not serve much purpose
11628     // here, since the no_viable diagnostic has index 0.
11629     UnresolvedSetIterator Result = S.getMostSpecialized(
11630         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11631         SourceExpr->getBeginLoc(), S.PDiag(),
11632         S.PDiag(diag::err_addr_ovl_ambiguous)
11633             << Matches[0].second->getDeclName(),
11634         S.PDiag(diag::note_ovl_candidate)
11635             << (unsigned)oc_function << (unsigned)ocs_described_template,
11636         Complain, TargetFunctionType);
11637 
11638     if (Result != MatchesCopy.end()) {
11639       // Make it the first and only element
11640       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11641       Matches[0].second = cast<FunctionDecl>(*Result);
11642       Matches.resize(1);
11643     } else
11644       HasComplained |= Complain;
11645   }
11646 
11647   void EliminateAllTemplateMatches() {
11648     //   [...] any function template specializations in the set are
11649     //   eliminated if the set also contains a non-template function, [...]
11650     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11651       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11652         ++I;
11653       else {
11654         Matches[I] = Matches[--N];
11655         Matches.resize(N);
11656       }
11657     }
11658   }
11659 
11660   void EliminateSuboptimalCudaMatches() {
11661     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11662   }
11663 
11664 public:
11665   void ComplainNoMatchesFound() const {
11666     assert(Matches.empty());
11667     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
11668         << OvlExpr->getName() << TargetFunctionType
11669         << OvlExpr->getSourceRange();
11670     if (FailedCandidates.empty())
11671       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11672                                   /*TakingAddress=*/true);
11673     else {
11674       // We have some deduction failure messages. Use them to diagnose
11675       // the function templates, and diagnose the non-template candidates
11676       // normally.
11677       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11678                                  IEnd = OvlExpr->decls_end();
11679            I != IEnd; ++I)
11680         if (FunctionDecl *Fun =
11681                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11682           if (!functionHasPassObjectSizeParams(Fun))
11683             S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
11684                                     /*TakingAddress=*/true);
11685       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
11686     }
11687   }
11688 
11689   bool IsInvalidFormOfPointerToMemberFunction() const {
11690     return TargetTypeIsNonStaticMemberFunction &&
11691       !OvlExprInfo.HasFormOfMemberPointer;
11692   }
11693 
11694   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11695       // TODO: Should we condition this on whether any functions might
11696       // have matched, or is it more appropriate to do that in callers?
11697       // TODO: a fixit wouldn't hurt.
11698       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11699         << TargetType << OvlExpr->getSourceRange();
11700   }
11701 
11702   bool IsStaticMemberFunctionFromBoundPointer() const {
11703     return StaticMemberFunctionFromBoundPointer;
11704   }
11705 
11706   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11707     S.Diag(OvlExpr->getBeginLoc(),
11708            diag::err_invalid_form_pointer_member_function)
11709         << OvlExpr->getSourceRange();
11710   }
11711 
11712   void ComplainOfInvalidConversion() const {
11713     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
11714         << OvlExpr->getName() << TargetType;
11715   }
11716 
11717   void ComplainMultipleMatchesFound() const {
11718     assert(Matches.size() > 1);
11719     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
11720         << OvlExpr->getName() << OvlExpr->getSourceRange();
11721     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11722                                 /*TakingAddress=*/true);
11723   }
11724 
11725   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11726 
11727   int getNumMatches() const { return Matches.size(); }
11728 
11729   FunctionDecl* getMatchingFunctionDecl() const {
11730     if (Matches.size() != 1) return nullptr;
11731     return Matches[0].second;
11732   }
11733 
11734   const DeclAccessPair* getMatchingFunctionAccessPair() const {
11735     if (Matches.size() != 1) return nullptr;
11736     return &Matches[0].first;
11737   }
11738 };
11739 }
11740 
11741 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11742 /// an overloaded function (C++ [over.over]), where @p From is an
11743 /// expression with overloaded function type and @p ToType is the type
11744 /// we're trying to resolve to. For example:
11745 ///
11746 /// @code
11747 /// int f(double);
11748 /// int f(int);
11749 ///
11750 /// int (*pfd)(double) = f; // selects f(double)
11751 /// @endcode
11752 ///
11753 /// This routine returns the resulting FunctionDecl if it could be
11754 /// resolved, and NULL otherwise. When @p Complain is true, this
11755 /// routine will emit diagnostics if there is an error.
11756 FunctionDecl *
11757 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11758                                          QualType TargetType,
11759                                          bool Complain,
11760                                          DeclAccessPair &FoundResult,
11761                                          bool *pHadMultipleCandidates) {
11762   assert(AddressOfExpr->getType() == Context.OverloadTy);
11763 
11764   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11765                                      Complain);
11766   int NumMatches = Resolver.getNumMatches();
11767   FunctionDecl *Fn = nullptr;
11768   bool ShouldComplain = Complain && !Resolver.hasComplained();
11769   if (NumMatches == 0 && ShouldComplain) {
11770     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11771       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11772     else
11773       Resolver.ComplainNoMatchesFound();
11774   }
11775   else if (NumMatches > 1 && ShouldComplain)
11776     Resolver.ComplainMultipleMatchesFound();
11777   else if (NumMatches == 1) {
11778     Fn = Resolver.getMatchingFunctionDecl();
11779     assert(Fn);
11780     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11781       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11782     FoundResult = *Resolver.getMatchingFunctionAccessPair();
11783     if (Complain) {
11784       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11785         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11786       else
11787         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11788     }
11789   }
11790 
11791   if (pHadMultipleCandidates)
11792     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11793   return Fn;
11794 }
11795 
11796 /// Given an expression that refers to an overloaded function, try to
11797 /// resolve that function to a single function that can have its address taken.
11798 /// This will modify `Pair` iff it returns non-null.
11799 ///
11800 /// This routine can only realistically succeed if all but one candidates in the
11801 /// overload set for SrcExpr cannot have their addresses taken.
11802 FunctionDecl *
11803 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11804                                                   DeclAccessPair &Pair) {
11805   OverloadExpr::FindResult R = OverloadExpr::find(E);
11806   OverloadExpr *Ovl = R.Expression;
11807   FunctionDecl *Result = nullptr;
11808   DeclAccessPair DAP;
11809   // Don't use the AddressOfResolver because we're specifically looking for
11810   // cases where we have one overload candidate that lacks
11811   // enable_if/pass_object_size/...
11812   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11813     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11814     if (!FD)
11815       return nullptr;
11816 
11817     if (!checkAddressOfFunctionIsAvailable(FD))
11818       continue;
11819 
11820     // We have more than one result; quit.
11821     if (Result)
11822       return nullptr;
11823     DAP = I.getPair();
11824     Result = FD;
11825   }
11826 
11827   if (Result)
11828     Pair = DAP;
11829   return Result;
11830 }
11831 
11832 /// Given an overloaded function, tries to turn it into a non-overloaded
11833 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11834 /// will perform access checks, diagnose the use of the resultant decl, and, if
11835 /// requested, potentially perform a function-to-pointer decay.
11836 ///
11837 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11838 /// Otherwise, returns true. This may emit diagnostics and return true.
11839 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11840     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
11841   Expr *E = SrcExpr.get();
11842   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11843 
11844   DeclAccessPair DAP;
11845   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11846   if (!Found || Found->isCPUDispatchMultiVersion() ||
11847       Found->isCPUSpecificMultiVersion())
11848     return false;
11849 
11850   // Emitting multiple diagnostics for a function that is both inaccessible and
11851   // unavailable is consistent with our behavior elsewhere. So, always check
11852   // for both.
11853   DiagnoseUseOfDecl(Found, E->getExprLoc());
11854   CheckAddressOfMemberAccess(E, DAP);
11855   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11856   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
11857     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11858   else
11859     SrcExpr = Fixed;
11860   return true;
11861 }
11862 
11863 /// Given an expression that refers to an overloaded function, try to
11864 /// resolve that overloaded function expression down to a single function.
11865 ///
11866 /// This routine can only resolve template-ids that refer to a single function
11867 /// template, where that template-id refers to a single template whose template
11868 /// arguments are either provided by the template-id or have defaults,
11869 /// as described in C++0x [temp.arg.explicit]p3.
11870 ///
11871 /// If no template-ids are found, no diagnostics are emitted and NULL is
11872 /// returned.
11873 FunctionDecl *
11874 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11875                                                   bool Complain,
11876                                                   DeclAccessPair *FoundResult) {
11877   // C++ [over.over]p1:
11878   //   [...] [Note: any redundant set of parentheses surrounding the
11879   //   overloaded function name is ignored (5.1). ]
11880   // C++ [over.over]p1:
11881   //   [...] The overloaded function name can be preceded by the &
11882   //   operator.
11883 
11884   // If we didn't actually find any template-ids, we're done.
11885   if (!ovl->hasExplicitTemplateArgs())
11886     return nullptr;
11887 
11888   TemplateArgumentListInfo ExplicitTemplateArgs;
11889   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11890   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11891 
11892   // Look through all of the overloaded functions, searching for one
11893   // whose type matches exactly.
11894   FunctionDecl *Matched = nullptr;
11895   for (UnresolvedSetIterator I = ovl->decls_begin(),
11896          E = ovl->decls_end(); I != E; ++I) {
11897     // C++0x [temp.arg.explicit]p3:
11898     //   [...] In contexts where deduction is done and fails, or in contexts
11899     //   where deduction is not done, if a template argument list is
11900     //   specified and it, along with any default template arguments,
11901     //   identifies a single function template specialization, then the
11902     //   template-id is an lvalue for the function template specialization.
11903     FunctionTemplateDecl *FunctionTemplate
11904       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11905 
11906     // C++ [over.over]p2:
11907     //   If the name is a function template, template argument deduction is
11908     //   done (14.8.2.2), and if the argument deduction succeeds, the
11909     //   resulting template argument list is used to generate a single
11910     //   function template specialization, which is added to the set of
11911     //   overloaded functions considered.
11912     FunctionDecl *Specialization = nullptr;
11913     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11914     if (TemplateDeductionResult Result
11915           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11916                                     Specialization, Info,
11917                                     /*IsAddressOfFunction*/true)) {
11918       // Make a note of the failed deduction for diagnostics.
11919       // TODO: Actually use the failed-deduction info?
11920       FailedCandidates.addCandidate()
11921           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11922                MakeDeductionFailureInfo(Context, Result, Info));
11923       continue;
11924     }
11925 
11926     assert(Specialization && "no specialization and no error?");
11927 
11928     // Multiple matches; we can't resolve to a single declaration.
11929     if (Matched) {
11930       if (Complain) {
11931         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11932           << ovl->getName();
11933         NoteAllOverloadCandidates(ovl);
11934       }
11935       return nullptr;
11936     }
11937 
11938     Matched = Specialization;
11939     if (FoundResult) *FoundResult = I.getPair();
11940   }
11941 
11942   if (Matched &&
11943       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11944     return nullptr;
11945 
11946   return Matched;
11947 }
11948 
11949 // Resolve and fix an overloaded expression that can be resolved
11950 // because it identifies a single function template specialization.
11951 //
11952 // Last three arguments should only be supplied if Complain = true
11953 //
11954 // Return true if it was logically possible to so resolve the
11955 // expression, regardless of whether or not it succeeded.  Always
11956 // returns true if 'complain' is set.
11957 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11958                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
11959                       bool complain, SourceRange OpRangeForComplaining,
11960                                            QualType DestTypeForComplaining,
11961                                             unsigned DiagIDForComplaining) {
11962   assert(SrcExpr.get()->getType() == Context.OverloadTy);
11963 
11964   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11965 
11966   DeclAccessPair found;
11967   ExprResult SingleFunctionExpression;
11968   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11969                            ovl.Expression, /*complain*/ false, &found)) {
11970     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
11971       SrcExpr = ExprError();
11972       return true;
11973     }
11974 
11975     // It is only correct to resolve to an instance method if we're
11976     // resolving a form that's permitted to be a pointer to member.
11977     // Otherwise we'll end up making a bound member expression, which
11978     // is illegal in all the contexts we resolve like this.
11979     if (!ovl.HasFormOfMemberPointer &&
11980         isa<CXXMethodDecl>(fn) &&
11981         cast<CXXMethodDecl>(fn)->isInstance()) {
11982       if (!complain) return false;
11983 
11984       Diag(ovl.Expression->getExprLoc(),
11985            diag::err_bound_member_function)
11986         << 0 << ovl.Expression->getSourceRange();
11987 
11988       // TODO: I believe we only end up here if there's a mix of
11989       // static and non-static candidates (otherwise the expression
11990       // would have 'bound member' type, not 'overload' type).
11991       // Ideally we would note which candidate was chosen and why
11992       // the static candidates were rejected.
11993       SrcExpr = ExprError();
11994       return true;
11995     }
11996 
11997     // Fix the expression to refer to 'fn'.
11998     SingleFunctionExpression =
11999         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
12000 
12001     // If desired, do function-to-pointer decay.
12002     if (doFunctionPointerConverion) {
12003       SingleFunctionExpression =
12004         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
12005       if (SingleFunctionExpression.isInvalid()) {
12006         SrcExpr = ExprError();
12007         return true;
12008       }
12009     }
12010   }
12011 
12012   if (!SingleFunctionExpression.isUsable()) {
12013     if (complain) {
12014       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
12015         << ovl.Expression->getName()
12016         << DestTypeForComplaining
12017         << OpRangeForComplaining
12018         << ovl.Expression->getQualifierLoc().getSourceRange();
12019       NoteAllOverloadCandidates(SrcExpr.get());
12020 
12021       SrcExpr = ExprError();
12022       return true;
12023     }
12024 
12025     return false;
12026   }
12027 
12028   SrcExpr = SingleFunctionExpression;
12029   return true;
12030 }
12031 
12032 /// Add a single candidate to the overload set.
12033 static void AddOverloadedCallCandidate(Sema &S,
12034                                        DeclAccessPair FoundDecl,
12035                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
12036                                        ArrayRef<Expr *> Args,
12037                                        OverloadCandidateSet &CandidateSet,
12038                                        bool PartialOverloading,
12039                                        bool KnownValid) {
12040   NamedDecl *Callee = FoundDecl.getDecl();
12041   if (isa<UsingShadowDecl>(Callee))
12042     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
12043 
12044   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
12045     if (ExplicitTemplateArgs) {
12046       assert(!KnownValid && "Explicit template arguments?");
12047       return;
12048     }
12049     // Prevent ill-formed function decls to be added as overload candidates.
12050     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
12051       return;
12052 
12053     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
12054                            /*SuppressUserConversions=*/false,
12055                            PartialOverloading);
12056     return;
12057   }
12058 
12059   if (FunctionTemplateDecl *FuncTemplate
12060       = dyn_cast<FunctionTemplateDecl>(Callee)) {
12061     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
12062                                    ExplicitTemplateArgs, Args, CandidateSet,
12063                                    /*SuppressUserConversions=*/false,
12064                                    PartialOverloading);
12065     return;
12066   }
12067 
12068   assert(!KnownValid && "unhandled case in overloaded call candidate");
12069 }
12070 
12071 /// Add the overload candidates named by callee and/or found by argument
12072 /// dependent lookup to the given overload set.
12073 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
12074                                        ArrayRef<Expr *> Args,
12075                                        OverloadCandidateSet &CandidateSet,
12076                                        bool PartialOverloading) {
12077 
12078 #ifndef NDEBUG
12079   // Verify that ArgumentDependentLookup is consistent with the rules
12080   // in C++0x [basic.lookup.argdep]p3:
12081   //
12082   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
12083   //   and let Y be the lookup set produced by argument dependent
12084   //   lookup (defined as follows). If X contains
12085   //
12086   //     -- a declaration of a class member, or
12087   //
12088   //     -- a block-scope function declaration that is not a
12089   //        using-declaration, or
12090   //
12091   //     -- a declaration that is neither a function or a function
12092   //        template
12093   //
12094   //   then Y is empty.
12095 
12096   if (ULE->requiresADL()) {
12097     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12098            E = ULE->decls_end(); I != E; ++I) {
12099       assert(!(*I)->getDeclContext()->isRecord());
12100       assert(isa<UsingShadowDecl>(*I) ||
12101              !(*I)->getDeclContext()->isFunctionOrMethod());
12102       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
12103     }
12104   }
12105 #endif
12106 
12107   // It would be nice to avoid this copy.
12108   TemplateArgumentListInfo TABuffer;
12109   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12110   if (ULE->hasExplicitTemplateArgs()) {
12111     ULE->copyTemplateArgumentsInto(TABuffer);
12112     ExplicitTemplateArgs = &TABuffer;
12113   }
12114 
12115   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12116          E = ULE->decls_end(); I != E; ++I)
12117     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12118                                CandidateSet, PartialOverloading,
12119                                /*KnownValid*/ true);
12120 
12121   if (ULE->requiresADL())
12122     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
12123                                          Args, ExplicitTemplateArgs,
12124                                          CandidateSet, PartialOverloading);
12125 }
12126 
12127 /// Determine whether a declaration with the specified name could be moved into
12128 /// a different namespace.
12129 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
12130   switch (Name.getCXXOverloadedOperator()) {
12131   case OO_New: case OO_Array_New:
12132   case OO_Delete: case OO_Array_Delete:
12133     return false;
12134 
12135   default:
12136     return true;
12137   }
12138 }
12139 
12140 /// Attempt to recover from an ill-formed use of a non-dependent name in a
12141 /// template, where the non-dependent name was declared after the template
12142 /// was defined. This is common in code written for a compilers which do not
12143 /// correctly implement two-stage name lookup.
12144 ///
12145 /// Returns true if a viable candidate was found and a diagnostic was issued.
12146 static bool
12147 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
12148                        const CXXScopeSpec &SS, LookupResult &R,
12149                        OverloadCandidateSet::CandidateSetKind CSK,
12150                        TemplateArgumentListInfo *ExplicitTemplateArgs,
12151                        ArrayRef<Expr *> Args,
12152                        bool *DoDiagnoseEmptyLookup = nullptr) {
12153   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
12154     return false;
12155 
12156   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
12157     if (DC->isTransparentContext())
12158       continue;
12159 
12160     SemaRef.LookupQualifiedName(R, DC);
12161 
12162     if (!R.empty()) {
12163       R.suppressDiagnostics();
12164 
12165       if (isa<CXXRecordDecl>(DC)) {
12166         // Don't diagnose names we find in classes; we get much better
12167         // diagnostics for these from DiagnoseEmptyLookup.
12168         R.clear();
12169         if (DoDiagnoseEmptyLookup)
12170           *DoDiagnoseEmptyLookup = true;
12171         return false;
12172       }
12173 
12174       OverloadCandidateSet Candidates(FnLoc, CSK);
12175       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12176         AddOverloadedCallCandidate(SemaRef, I.getPair(),
12177                                    ExplicitTemplateArgs, Args,
12178                                    Candidates, false, /*KnownValid*/ false);
12179 
12180       OverloadCandidateSet::iterator Best;
12181       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
12182         // No viable functions. Don't bother the user with notes for functions
12183         // which don't work and shouldn't be found anyway.
12184         R.clear();
12185         return false;
12186       }
12187 
12188       // Find the namespaces where ADL would have looked, and suggest
12189       // declaring the function there instead.
12190       Sema::AssociatedNamespaceSet AssociatedNamespaces;
12191       Sema::AssociatedClassSet AssociatedClasses;
12192       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
12193                                                  AssociatedNamespaces,
12194                                                  AssociatedClasses);
12195       Sema::AssociatedNamespaceSet SuggestedNamespaces;
12196       if (canBeDeclaredInNamespace(R.getLookupName())) {
12197         DeclContext *Std = SemaRef.getStdNamespace();
12198         for (Sema::AssociatedNamespaceSet::iterator
12199                it = AssociatedNamespaces.begin(),
12200                end = AssociatedNamespaces.end(); it != end; ++it) {
12201           // Never suggest declaring a function within namespace 'std'.
12202           if (Std && Std->Encloses(*it))
12203             continue;
12204 
12205           // Never suggest declaring a function within a namespace with a
12206           // reserved name, like __gnu_cxx.
12207           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
12208           if (NS &&
12209               NS->getQualifiedNameAsString().find("__") != std::string::npos)
12210             continue;
12211 
12212           SuggestedNamespaces.insert(*it);
12213         }
12214       }
12215 
12216       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
12217         << R.getLookupName();
12218       if (SuggestedNamespaces.empty()) {
12219         SemaRef.Diag(Best->Function->getLocation(),
12220                      diag::note_not_found_by_two_phase_lookup)
12221           << R.getLookupName() << 0;
12222       } else if (SuggestedNamespaces.size() == 1) {
12223         SemaRef.Diag(Best->Function->getLocation(),
12224                      diag::note_not_found_by_two_phase_lookup)
12225           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
12226       } else {
12227         // FIXME: It would be useful to list the associated namespaces here,
12228         // but the diagnostics infrastructure doesn't provide a way to produce
12229         // a localized representation of a list of items.
12230         SemaRef.Diag(Best->Function->getLocation(),
12231                      diag::note_not_found_by_two_phase_lookup)
12232           << R.getLookupName() << 2;
12233       }
12234 
12235       // Try to recover by calling this function.
12236       return true;
12237     }
12238 
12239     R.clear();
12240   }
12241 
12242   return false;
12243 }
12244 
12245 /// Attempt to recover from ill-formed use of a non-dependent operator in a
12246 /// template, where the non-dependent operator was declared after the template
12247 /// was defined.
12248 ///
12249 /// Returns true if a viable candidate was found and a diagnostic was issued.
12250 static bool
12251 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
12252                                SourceLocation OpLoc,
12253                                ArrayRef<Expr *> Args) {
12254   DeclarationName OpName =
12255     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
12256   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
12257   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
12258                                 OverloadCandidateSet::CSK_Operator,
12259                                 /*ExplicitTemplateArgs=*/nullptr, Args);
12260 }
12261 
12262 namespace {
12263 class BuildRecoveryCallExprRAII {
12264   Sema &SemaRef;
12265 public:
12266   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
12267     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
12268     SemaRef.IsBuildingRecoveryCallExpr = true;
12269   }
12270 
12271   ~BuildRecoveryCallExprRAII() {
12272     SemaRef.IsBuildingRecoveryCallExpr = false;
12273   }
12274 };
12275 
12276 }
12277 
12278 /// Attempts to recover from a call where no functions were found.
12279 ///
12280 /// Returns true if new candidates were found.
12281 static ExprResult
12282 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12283                       UnresolvedLookupExpr *ULE,
12284                       SourceLocation LParenLoc,
12285                       MutableArrayRef<Expr *> Args,
12286                       SourceLocation RParenLoc,
12287                       bool EmptyLookup, bool AllowTypoCorrection) {
12288   // Do not try to recover if it is already building a recovery call.
12289   // This stops infinite loops for template instantiations like
12290   //
12291   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
12292   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
12293   //
12294   if (SemaRef.IsBuildingRecoveryCallExpr)
12295     return ExprError();
12296   BuildRecoveryCallExprRAII RCE(SemaRef);
12297 
12298   CXXScopeSpec SS;
12299   SS.Adopt(ULE->getQualifierLoc());
12300   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
12301 
12302   TemplateArgumentListInfo TABuffer;
12303   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12304   if (ULE->hasExplicitTemplateArgs()) {
12305     ULE->copyTemplateArgumentsInto(TABuffer);
12306     ExplicitTemplateArgs = &TABuffer;
12307   }
12308 
12309   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
12310                  Sema::LookupOrdinaryName);
12311   bool DoDiagnoseEmptyLookup = EmptyLookup;
12312   if (!DiagnoseTwoPhaseLookup(
12313           SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal,
12314           ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) {
12315     NoTypoCorrectionCCC NoTypoValidator{};
12316     FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
12317                                                 ExplicitTemplateArgs != nullptr,
12318                                                 dyn_cast<MemberExpr>(Fn));
12319     CorrectionCandidateCallback &Validator =
12320         AllowTypoCorrection
12321             ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
12322             : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
12323     if (!DoDiagnoseEmptyLookup ||
12324         SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
12325                                     Args))
12326       return ExprError();
12327   }
12328 
12329   assert(!R.empty() && "lookup results empty despite recovery");
12330 
12331   // If recovery created an ambiguity, just bail out.
12332   if (R.isAmbiguous()) {
12333     R.suppressDiagnostics();
12334     return ExprError();
12335   }
12336 
12337   // Build an implicit member call if appropriate.  Just drop the
12338   // casts and such from the call, we don't really care.
12339   ExprResult NewFn = ExprError();
12340   if ((*R.begin())->isCXXClassMember())
12341     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12342                                                     ExplicitTemplateArgs, S);
12343   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
12344     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
12345                                         ExplicitTemplateArgs);
12346   else
12347     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
12348 
12349   if (NewFn.isInvalid())
12350     return ExprError();
12351 
12352   // This shouldn't cause an infinite loop because we're giving it
12353   // an expression with viable lookup results, which should never
12354   // end up here.
12355   return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
12356                                MultiExprArg(Args.data(), Args.size()),
12357                                RParenLoc);
12358 }
12359 
12360 /// Constructs and populates an OverloadedCandidateSet from
12361 /// the given function.
12362 /// \returns true when an the ExprResult output parameter has been set.
12363 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
12364                                   UnresolvedLookupExpr *ULE,
12365                                   MultiExprArg Args,
12366                                   SourceLocation RParenLoc,
12367                                   OverloadCandidateSet *CandidateSet,
12368                                   ExprResult *Result) {
12369 #ifndef NDEBUG
12370   if (ULE->requiresADL()) {
12371     // To do ADL, we must have found an unqualified name.
12372     assert(!ULE->getQualifier() && "qualified name with ADL");
12373 
12374     // We don't perform ADL for implicit declarations of builtins.
12375     // Verify that this was correctly set up.
12376     FunctionDecl *F;
12377     if (ULE->decls_begin() != ULE->decls_end() &&
12378         ULE->decls_begin() + 1 == ULE->decls_end() &&
12379         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
12380         F->getBuiltinID() && F->isImplicit())
12381       llvm_unreachable("performing ADL for builtin");
12382 
12383     // We don't perform ADL in C.
12384     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
12385   }
12386 #endif
12387 
12388   UnbridgedCastsSet UnbridgedCasts;
12389   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
12390     *Result = ExprError();
12391     return true;
12392   }
12393 
12394   // Add the functions denoted by the callee to the set of candidate
12395   // functions, including those from argument-dependent lookup.
12396   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
12397 
12398   if (getLangOpts().MSVCCompat &&
12399       CurContext->isDependentContext() && !isSFINAEContext() &&
12400       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
12401 
12402     OverloadCandidateSet::iterator Best;
12403     if (CandidateSet->empty() ||
12404         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
12405             OR_No_Viable_Function) {
12406       // In Microsoft mode, if we are inside a template class member function
12407       // then create a type dependent CallExpr. The goal is to postpone name
12408       // lookup to instantiation time to be able to search into type dependent
12409       // base classes.
12410       CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy,
12411                                       VK_RValue, RParenLoc);
12412       CE->setTypeDependent(true);
12413       CE->setValueDependent(true);
12414       CE->setInstantiationDependent(true);
12415       *Result = CE;
12416       return true;
12417     }
12418   }
12419 
12420   if (CandidateSet->empty())
12421     return false;
12422 
12423   UnbridgedCasts.restore();
12424   return false;
12425 }
12426 
12427 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
12428 /// the completed call expression. If overload resolution fails, emits
12429 /// diagnostics and returns ExprError()
12430 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12431                                            UnresolvedLookupExpr *ULE,
12432                                            SourceLocation LParenLoc,
12433                                            MultiExprArg Args,
12434                                            SourceLocation RParenLoc,
12435                                            Expr *ExecConfig,
12436                                            OverloadCandidateSet *CandidateSet,
12437                                            OverloadCandidateSet::iterator *Best,
12438                                            OverloadingResult OverloadResult,
12439                                            bool AllowTypoCorrection) {
12440   if (CandidateSet->empty())
12441     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
12442                                  RParenLoc, /*EmptyLookup=*/true,
12443                                  AllowTypoCorrection);
12444 
12445   switch (OverloadResult) {
12446   case OR_Success: {
12447     FunctionDecl *FDecl = (*Best)->Function;
12448     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
12449     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
12450       return ExprError();
12451     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12452     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12453                                          ExecConfig, /*IsExecConfig=*/false,
12454                                          (*Best)->IsADLCandidate);
12455   }
12456 
12457   case OR_No_Viable_Function: {
12458     // Try to recover by looking for viable functions which the user might
12459     // have meant to call.
12460     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
12461                                                 Args, RParenLoc,
12462                                                 /*EmptyLookup=*/false,
12463                                                 AllowTypoCorrection);
12464     if (!Recovery.isInvalid())
12465       return Recovery;
12466 
12467     // If the user passes in a function that we can't take the address of, we
12468     // generally end up emitting really bad error messages. Here, we attempt to
12469     // emit better ones.
12470     for (const Expr *Arg : Args) {
12471       if (!Arg->getType()->isFunctionType())
12472         continue;
12473       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12474         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12475         if (FD &&
12476             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12477                                                        Arg->getExprLoc()))
12478           return ExprError();
12479       }
12480     }
12481 
12482     CandidateSet->NoteCandidates(
12483         PartialDiagnosticAt(
12484             Fn->getBeginLoc(),
12485             SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
12486                 << ULE->getName() << Fn->getSourceRange()),
12487         SemaRef, OCD_AllCandidates, Args);
12488     break;
12489   }
12490 
12491   case OR_Ambiguous:
12492     CandidateSet->NoteCandidates(
12493         PartialDiagnosticAt(Fn->getBeginLoc(),
12494                             SemaRef.PDiag(diag::err_ovl_ambiguous_call)
12495                                 << ULE->getName() << Fn->getSourceRange()),
12496         SemaRef, OCD_AmbiguousCandidates, Args);
12497     break;
12498 
12499   case OR_Deleted: {
12500     CandidateSet->NoteCandidates(
12501         PartialDiagnosticAt(Fn->getBeginLoc(),
12502                             SemaRef.PDiag(diag::err_ovl_deleted_call)
12503                                 << ULE->getName() << Fn->getSourceRange()),
12504         SemaRef, OCD_AllCandidates, Args);
12505 
12506     // We emitted an error for the unavailable/deleted function call but keep
12507     // the call in the AST.
12508     FunctionDecl *FDecl = (*Best)->Function;
12509     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12510     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12511                                          ExecConfig, /*IsExecConfig=*/false,
12512                                          (*Best)->IsADLCandidate);
12513   }
12514   }
12515 
12516   // Overload resolution failed.
12517   return ExprError();
12518 }
12519 
12520 static void markUnaddressableCandidatesUnviable(Sema &S,
12521                                                 OverloadCandidateSet &CS) {
12522   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12523     if (I->Viable &&
12524         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12525       I->Viable = false;
12526       I->FailureKind = ovl_fail_addr_not_available;
12527     }
12528   }
12529 }
12530 
12531 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
12532 /// (which eventually refers to the declaration Func) and the call
12533 /// arguments Args/NumArgs, attempt to resolve the function call down
12534 /// to a specific function. If overload resolution succeeds, returns
12535 /// the call expression produced by overload resolution.
12536 /// Otherwise, emits diagnostics and returns ExprError.
12537 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12538                                          UnresolvedLookupExpr *ULE,
12539                                          SourceLocation LParenLoc,
12540                                          MultiExprArg Args,
12541                                          SourceLocation RParenLoc,
12542                                          Expr *ExecConfig,
12543                                          bool AllowTypoCorrection,
12544                                          bool CalleesAddressIsTaken) {
12545   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12546                                     OverloadCandidateSet::CSK_Normal);
12547   ExprResult result;
12548 
12549   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12550                              &result))
12551     return result;
12552 
12553   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12554   // functions that aren't addressible are considered unviable.
12555   if (CalleesAddressIsTaken)
12556     markUnaddressableCandidatesUnviable(*this, CandidateSet);
12557 
12558   OverloadCandidateSet::iterator Best;
12559   OverloadingResult OverloadResult =
12560       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
12561 
12562   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
12563                                   ExecConfig, &CandidateSet, &Best,
12564                                   OverloadResult, AllowTypoCorrection);
12565 }
12566 
12567 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
12568   return Functions.size() > 1 ||
12569     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12570 }
12571 
12572 /// Create a unary operation that may resolve to an overloaded
12573 /// operator.
12574 ///
12575 /// \param OpLoc The location of the operator itself (e.g., '*').
12576 ///
12577 /// \param Opc The UnaryOperatorKind that describes this operator.
12578 ///
12579 /// \param Fns The set of non-member functions that will be
12580 /// considered by overload resolution. The caller needs to build this
12581 /// set based on the context using, e.g.,
12582 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12583 /// set should not contain any member functions; those will be added
12584 /// by CreateOverloadedUnaryOp().
12585 ///
12586 /// \param Input The input argument.
12587 ExprResult
12588 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12589                               const UnresolvedSetImpl &Fns,
12590                               Expr *Input, bool PerformADL) {
12591   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12592   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12593   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12594   // TODO: provide better source location info.
12595   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12596 
12597   if (checkPlaceholderForOverload(*this, Input))
12598     return ExprError();
12599 
12600   Expr *Args[2] = { Input, nullptr };
12601   unsigned NumArgs = 1;
12602 
12603   // For post-increment and post-decrement, add the implicit '0' as
12604   // the second argument, so that we know this is a post-increment or
12605   // post-decrement.
12606   if (Opc == UO_PostInc || Opc == UO_PostDec) {
12607     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12608     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12609                                      SourceLocation());
12610     NumArgs = 2;
12611   }
12612 
12613   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12614 
12615   if (Input->isTypeDependent()) {
12616     if (Fns.empty())
12617       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12618                                          VK_RValue, OK_Ordinary, OpLoc, false);
12619 
12620     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12621     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
12622         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
12623         /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end());
12624     return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray,
12625                                        Context.DependentTy, VK_RValue, OpLoc,
12626                                        FPOptions());
12627   }
12628 
12629   // Build an empty overload set.
12630   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12631 
12632   // Add the candidates from the given function set.
12633   AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
12634 
12635   // Add operator candidates that are member functions.
12636   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12637 
12638   // Add candidates from ADL.
12639   if (PerformADL) {
12640     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12641                                          /*ExplicitTemplateArgs*/nullptr,
12642                                          CandidateSet);
12643   }
12644 
12645   // Add builtin operator candidates.
12646   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12647 
12648   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12649 
12650   // Perform overload resolution.
12651   OverloadCandidateSet::iterator Best;
12652   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12653   case OR_Success: {
12654     // We found a built-in operator or an overloaded operator.
12655     FunctionDecl *FnDecl = Best->Function;
12656 
12657     if (FnDecl) {
12658       Expr *Base = nullptr;
12659       // We matched an overloaded operator. Build a call to that
12660       // operator.
12661 
12662       // Convert the arguments.
12663       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12664         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12665 
12666         ExprResult InputRes =
12667           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12668                                               Best->FoundDecl, Method);
12669         if (InputRes.isInvalid())
12670           return ExprError();
12671         Base = Input = InputRes.get();
12672       } else {
12673         // Convert the arguments.
12674         ExprResult InputInit
12675           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12676                                                       Context,
12677                                                       FnDecl->getParamDecl(0)),
12678                                       SourceLocation(),
12679                                       Input);
12680         if (InputInit.isInvalid())
12681           return ExprError();
12682         Input = InputInit.get();
12683       }
12684 
12685       // Build the actual expression node.
12686       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12687                                                 Base, HadMultipleCandidates,
12688                                                 OpLoc);
12689       if (FnExpr.isInvalid())
12690         return ExprError();
12691 
12692       // Determine the result type.
12693       QualType ResultTy = FnDecl->getReturnType();
12694       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12695       ResultTy = ResultTy.getNonLValueExprType(Context);
12696 
12697       Args[0] = Input;
12698       CallExpr *TheCall = CXXOperatorCallExpr::Create(
12699           Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
12700           FPOptions(), Best->IsADLCandidate);
12701 
12702       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12703         return ExprError();
12704 
12705       if (CheckFunctionCall(FnDecl, TheCall,
12706                             FnDecl->getType()->castAs<FunctionProtoType>()))
12707         return ExprError();
12708 
12709       return MaybeBindToTemporary(TheCall);
12710     } else {
12711       // We matched a built-in operator. Convert the arguments, then
12712       // break out so that we will build the appropriate built-in
12713       // operator node.
12714       ExprResult InputRes = PerformImplicitConversion(
12715           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
12716           CCK_ForBuiltinOverloadedOp);
12717       if (InputRes.isInvalid())
12718         return ExprError();
12719       Input = InputRes.get();
12720       break;
12721     }
12722   }
12723 
12724   case OR_No_Viable_Function:
12725     // This is an erroneous use of an operator which can be overloaded by
12726     // a non-member function. Check for non-member operators which were
12727     // defined too late to be candidates.
12728     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12729       // FIXME: Recover by calling the found function.
12730       return ExprError();
12731 
12732     // No viable function; fall through to handling this as a
12733     // built-in operator, which will produce an error message for us.
12734     break;
12735 
12736   case OR_Ambiguous:
12737     CandidateSet.NoteCandidates(
12738         PartialDiagnosticAt(OpLoc,
12739                             PDiag(diag::err_ovl_ambiguous_oper_unary)
12740                                 << UnaryOperator::getOpcodeStr(Opc)
12741                                 << Input->getType() << Input->getSourceRange()),
12742         *this, OCD_AmbiguousCandidates, ArgsArray,
12743         UnaryOperator::getOpcodeStr(Opc), OpLoc);
12744     return ExprError();
12745 
12746   case OR_Deleted:
12747     CandidateSet.NoteCandidates(
12748         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
12749                                        << UnaryOperator::getOpcodeStr(Opc)
12750                                        << Input->getSourceRange()),
12751         *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
12752         OpLoc);
12753     return ExprError();
12754   }
12755 
12756   // Either we found no viable overloaded operator or we matched a
12757   // built-in operator. In either case, fall through to trying to
12758   // build a built-in operation.
12759   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12760 }
12761 
12762 /// Perform lookup for an overloaded binary operator.
12763 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
12764                                  OverloadedOperatorKind Op,
12765                                  const UnresolvedSetImpl &Fns,
12766                                  ArrayRef<Expr *> Args, bool PerformADL) {
12767   SourceLocation OpLoc = CandidateSet.getLocation();
12768 
12769   OverloadedOperatorKind ExtraOp =
12770       CandidateSet.getRewriteInfo().AllowRewrittenCandidates
12771           ? getRewrittenOverloadedOperator(Op)
12772           : OO_None;
12773 
12774   // Add the candidates from the given function set. This also adds the
12775   // rewritten candidates using these functions if necessary.
12776   AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
12777 
12778   // Add operator candidates that are member functions.
12779   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12780   if (CandidateSet.getRewriteInfo().shouldAddReversed(Op))
12781     AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
12782                                 OverloadCandidateParamOrder::Reversed);
12783 
12784   // In C++20, also add any rewritten member candidates.
12785   if (ExtraOp) {
12786     AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
12787     if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp))
12788       AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
12789                                   CandidateSet,
12790                                   OverloadCandidateParamOrder::Reversed);
12791   }
12792 
12793   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12794   // performed for an assignment operator (nor for operator[] nor operator->,
12795   // which don't get here).
12796   if (Op != OO_Equal && PerformADL) {
12797     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12798     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12799                                          /*ExplicitTemplateArgs*/ nullptr,
12800                                          CandidateSet);
12801     if (ExtraOp) {
12802       DeclarationName ExtraOpName =
12803           Context.DeclarationNames.getCXXOperatorName(ExtraOp);
12804       AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
12805                                            /*ExplicitTemplateArgs*/ nullptr,
12806                                            CandidateSet);
12807     }
12808   }
12809 
12810   // Add builtin operator candidates.
12811   //
12812   // FIXME: We don't add any rewritten candidates here. This is strictly
12813   // incorrect; a builtin candidate could be hidden by a non-viable candidate,
12814   // resulting in our selecting a rewritten builtin candidate. For example:
12815   //
12816   //   enum class E { e };
12817   //   bool operator!=(E, E) requires false;
12818   //   bool k = E::e != E::e;
12819   //
12820   // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
12821   // it seems unreasonable to consider rewritten builtin candidates. A core
12822   // issue has been filed proposing to removed this requirement.
12823   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12824 }
12825 
12826 /// Create a binary operation that may resolve to an overloaded
12827 /// operator.
12828 ///
12829 /// \param OpLoc The location of the operator itself (e.g., '+').
12830 ///
12831 /// \param Opc The BinaryOperatorKind that describes this operator.
12832 ///
12833 /// \param Fns The set of non-member functions that will be
12834 /// considered by overload resolution. The caller needs to build this
12835 /// set based on the context using, e.g.,
12836 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12837 /// set should not contain any member functions; those will be added
12838 /// by CreateOverloadedBinOp().
12839 ///
12840 /// \param LHS Left-hand argument.
12841 /// \param RHS Right-hand argument.
12842 /// \param PerformADL Whether to consider operator candidates found by ADL.
12843 /// \param AllowRewrittenCandidates Whether to consider candidates found by
12844 ///        C++20 operator rewrites.
12845 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
12846 ///        the function in question. Such a function is never a candidate in
12847 ///        our overload resolution. This also enables synthesizing a three-way
12848 ///        comparison from < and == as described in C++20 [class.spaceship]p1.
12849 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12850                                        BinaryOperatorKind Opc,
12851                                        const UnresolvedSetImpl &Fns, Expr *LHS,
12852                                        Expr *RHS, bool PerformADL,
12853                                        bool AllowRewrittenCandidates,
12854                                        FunctionDecl *DefaultedFn) {
12855   Expr *Args[2] = { LHS, RHS };
12856   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12857 
12858   if (!getLangOpts().CPlusPlus2a)
12859     AllowRewrittenCandidates = false;
12860 
12861   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12862 
12863   // If either side is type-dependent, create an appropriate dependent
12864   // expression.
12865   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12866     if (Fns.empty()) {
12867       // If there are no functions to store, just build a dependent
12868       // BinaryOperator or CompoundAssignment.
12869       if (Opc <= BO_Assign || Opc > BO_OrAssign)
12870         return new (Context) BinaryOperator(
12871             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12872             OpLoc, FPFeatures);
12873 
12874       return new (Context) CompoundAssignOperator(
12875           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12876           Context.DependentTy, Context.DependentTy, OpLoc,
12877           FPFeatures);
12878     }
12879 
12880     // FIXME: save results of ADL from here?
12881     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12882     // TODO: provide better source location info in DNLoc component.
12883     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12884     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12885     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
12886         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
12887         /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end());
12888     return CXXOperatorCallExpr::Create(Context, Op, Fn, Args,
12889                                        Context.DependentTy, VK_RValue, OpLoc,
12890                                        FPFeatures);
12891   }
12892 
12893   // Always do placeholder-like conversions on the RHS.
12894   if (checkPlaceholderForOverload(*this, Args[1]))
12895     return ExprError();
12896 
12897   // Do placeholder-like conversion on the LHS; note that we should
12898   // not get here with a PseudoObject LHS.
12899   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12900   if (checkPlaceholderForOverload(*this, Args[0]))
12901     return ExprError();
12902 
12903   // If this is the assignment operator, we only perform overload resolution
12904   // if the left-hand side is a class or enumeration type. This is actually
12905   // a hack. The standard requires that we do overload resolution between the
12906   // various built-in candidates, but as DR507 points out, this can lead to
12907   // problems. So we do it this way, which pretty much follows what GCC does.
12908   // Note that we go the traditional code path for compound assignment forms.
12909   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12910     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12911 
12912   // If this is the .* operator, which is not overloadable, just
12913   // create a built-in binary operator.
12914   if (Opc == BO_PtrMemD)
12915     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12916 
12917   // Build the overload set.
12918   OverloadCandidateSet CandidateSet(
12919       OpLoc, OverloadCandidateSet::CSK_Operator,
12920       OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates));
12921   if (DefaultedFn)
12922     CandidateSet.exclude(DefaultedFn);
12923   LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
12924 
12925   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12926 
12927   // Perform overload resolution.
12928   OverloadCandidateSet::iterator Best;
12929   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12930     case OR_Success: {
12931       // We found a built-in operator or an overloaded operator.
12932       FunctionDecl *FnDecl = Best->Function;
12933 
12934       bool IsReversed = (Best->RewriteKind & CRK_Reversed);
12935       if (IsReversed)
12936         std::swap(Args[0], Args[1]);
12937 
12938       if (FnDecl) {
12939         Expr *Base = nullptr;
12940         // We matched an overloaded operator. Build a call to that
12941         // operator.
12942 
12943         OverloadedOperatorKind ChosenOp =
12944             FnDecl->getDeclName().getCXXOverloadedOperator();
12945 
12946         // C++2a [over.match.oper]p9:
12947         //   If a rewritten operator== candidate is selected by overload
12948         //   resolution for an operator@, its return type shall be cv bool
12949         if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
12950             !FnDecl->getReturnType()->isBooleanType()) {
12951           Diag(OpLoc, diag::err_ovl_rewrite_equalequal_not_bool)
12952               << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
12953               << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12954           Diag(FnDecl->getLocation(), diag::note_declared_at);
12955           return ExprError();
12956         }
12957 
12958         if (AllowRewrittenCandidates && !IsReversed &&
12959             CandidateSet.getRewriteInfo().shouldAddReversed(ChosenOp)) {
12960           // We could have reversed this operator, but didn't. Check if the
12961           // reversed form was a viable candidate, and if so, if it had a
12962           // better conversion for either parameter. If so, this call is
12963           // formally ambiguous, and allowing it is an extension.
12964           for (OverloadCandidate &Cand : CandidateSet) {
12965             if (Cand.Viable && Cand.Function == FnDecl &&
12966                 Cand.RewriteKind & CRK_Reversed) {
12967               for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
12968                 if (CompareImplicitConversionSequences(
12969                         *this, OpLoc, Cand.Conversions[ArgIdx],
12970                         Best->Conversions[ArgIdx]) ==
12971                     ImplicitConversionSequence::Better) {
12972                   Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
12973                       << BinaryOperator::getOpcodeStr(Opc)
12974                       << Args[0]->getType() << Args[1]->getType()
12975                       << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12976                   Diag(FnDecl->getLocation(),
12977                        diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
12978                 }
12979               }
12980               break;
12981             }
12982           }
12983         }
12984 
12985         // Convert the arguments.
12986         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12987           // Best->Access is only meaningful for class members.
12988           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12989 
12990           ExprResult Arg1 =
12991             PerformCopyInitialization(
12992               InitializedEntity::InitializeParameter(Context,
12993                                                      FnDecl->getParamDecl(0)),
12994               SourceLocation(), Args[1]);
12995           if (Arg1.isInvalid())
12996             return ExprError();
12997 
12998           ExprResult Arg0 =
12999             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13000                                                 Best->FoundDecl, Method);
13001           if (Arg0.isInvalid())
13002             return ExprError();
13003           Base = Args[0] = Arg0.getAs<Expr>();
13004           Args[1] = RHS = Arg1.getAs<Expr>();
13005         } else {
13006           // Convert the arguments.
13007           ExprResult Arg0 = PerformCopyInitialization(
13008             InitializedEntity::InitializeParameter(Context,
13009                                                    FnDecl->getParamDecl(0)),
13010             SourceLocation(), Args[0]);
13011           if (Arg0.isInvalid())
13012             return ExprError();
13013 
13014           ExprResult Arg1 =
13015             PerformCopyInitialization(
13016               InitializedEntity::InitializeParameter(Context,
13017                                                      FnDecl->getParamDecl(1)),
13018               SourceLocation(), Args[1]);
13019           if (Arg1.isInvalid())
13020             return ExprError();
13021           Args[0] = LHS = Arg0.getAs<Expr>();
13022           Args[1] = RHS = Arg1.getAs<Expr>();
13023         }
13024 
13025         // Build the actual expression node.
13026         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13027                                                   Best->FoundDecl, Base,
13028                                                   HadMultipleCandidates, OpLoc);
13029         if (FnExpr.isInvalid())
13030           return ExprError();
13031 
13032         // Determine the result type.
13033         QualType ResultTy = FnDecl->getReturnType();
13034         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13035         ResultTy = ResultTy.getNonLValueExprType(Context);
13036 
13037         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13038             Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
13039             FPFeatures, Best->IsADLCandidate);
13040 
13041         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
13042                                 FnDecl))
13043           return ExprError();
13044 
13045         ArrayRef<const Expr *> ArgsArray(Args, 2);
13046         const Expr *ImplicitThis = nullptr;
13047         // Cut off the implicit 'this'.
13048         if (isa<CXXMethodDecl>(FnDecl)) {
13049           ImplicitThis = ArgsArray[0];
13050           ArgsArray = ArgsArray.slice(1);
13051         }
13052 
13053         // Check for a self move.
13054         if (Op == OO_Equal)
13055           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
13056 
13057         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
13058                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
13059                   VariadicDoesNotApply);
13060 
13061         ExprResult R = MaybeBindToTemporary(TheCall);
13062         if (R.isInvalid())
13063           return ExprError();
13064 
13065         // For a rewritten candidate, we've already reversed the arguments
13066         // if needed. Perform the rest of the rewrite now.
13067         if ((Best->RewriteKind & CRK_DifferentOperator) ||
13068             (Op == OO_Spaceship && IsReversed)) {
13069           if (Op == OO_ExclaimEqual) {
13070             assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
13071             R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
13072           } else {
13073             assert(ChosenOp == OO_Spaceship && "unexpected operator name");
13074             llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13075             Expr *ZeroLiteral =
13076                 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
13077 
13078             Sema::CodeSynthesisContext Ctx;
13079             Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
13080             Ctx.Entity = FnDecl;
13081             pushCodeSynthesisContext(Ctx);
13082 
13083             R = CreateOverloadedBinOp(
13084                 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
13085                 IsReversed ? R.get() : ZeroLiteral, PerformADL,
13086                 /*AllowRewrittenCandidates=*/false);
13087 
13088             popCodeSynthesisContext();
13089           }
13090           if (R.isInvalid())
13091             return ExprError();
13092         } else {
13093           assert(ChosenOp == Op && "unexpected operator name");
13094         }
13095 
13096         // Make a note in the AST if we did any rewriting.
13097         if (Best->RewriteKind != CRK_None)
13098           R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
13099 
13100         return R;
13101       } else {
13102         // We matched a built-in operator. Convert the arguments, then
13103         // break out so that we will build the appropriate built-in
13104         // operator node.
13105         ExprResult ArgsRes0 = PerformImplicitConversion(
13106             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13107             AA_Passing, CCK_ForBuiltinOverloadedOp);
13108         if (ArgsRes0.isInvalid())
13109           return ExprError();
13110         Args[0] = ArgsRes0.get();
13111 
13112         ExprResult ArgsRes1 = PerformImplicitConversion(
13113             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13114             AA_Passing, CCK_ForBuiltinOverloadedOp);
13115         if (ArgsRes1.isInvalid())
13116           return ExprError();
13117         Args[1] = ArgsRes1.get();
13118         break;
13119       }
13120     }
13121 
13122     case OR_No_Viable_Function: {
13123       // C++ [over.match.oper]p9:
13124       //   If the operator is the operator , [...] and there are no
13125       //   viable functions, then the operator is assumed to be the
13126       //   built-in operator and interpreted according to clause 5.
13127       if (Opc == BO_Comma)
13128         break;
13129 
13130       // When defaulting an 'operator<=>', we can try to synthesize a three-way
13131       // compare result using '==' and '<'.
13132       if (DefaultedFn && Opc == BO_Cmp) {
13133         ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
13134                                                           Args[1], DefaultedFn);
13135         if (E.isInvalid() || E.isUsable())
13136           return E;
13137       }
13138 
13139       // For class as left operand for assignment or compound assignment
13140       // operator do not fall through to handling in built-in, but report that
13141       // no overloaded assignment operator found
13142       ExprResult Result = ExprError();
13143       StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
13144       auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
13145                                                    Args, OpLoc);
13146       if (Args[0]->getType()->isRecordType() &&
13147           Opc >= BO_Assign && Opc <= BO_OrAssign) {
13148         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
13149              << BinaryOperator::getOpcodeStr(Opc)
13150              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13151         if (Args[0]->getType()->isIncompleteType()) {
13152           Diag(OpLoc, diag::note_assign_lhs_incomplete)
13153             << Args[0]->getType()
13154             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13155         }
13156       } else {
13157         // This is an erroneous use of an operator which can be overloaded by
13158         // a non-member function. Check for non-member operators which were
13159         // defined too late to be candidates.
13160         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
13161           // FIXME: Recover by calling the found function.
13162           return ExprError();
13163 
13164         // No viable function; try to create a built-in operation, which will
13165         // produce an error. Then, show the non-viable candidates.
13166         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13167       }
13168       assert(Result.isInvalid() &&
13169              "C++ binary operator overloading is missing candidates!");
13170       CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
13171       return Result;
13172     }
13173 
13174     case OR_Ambiguous:
13175       CandidateSet.NoteCandidates(
13176           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13177                                          << BinaryOperator::getOpcodeStr(Opc)
13178                                          << Args[0]->getType()
13179                                          << Args[1]->getType()
13180                                          << Args[0]->getSourceRange()
13181                                          << Args[1]->getSourceRange()),
13182           *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13183           OpLoc);
13184       return ExprError();
13185 
13186     case OR_Deleted:
13187       if (isImplicitlyDeleted(Best->Function)) {
13188         FunctionDecl *DeletedFD = Best->Function;
13189         DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
13190         if (DFK.isSpecialMember()) {
13191           Diag(OpLoc, diag::err_ovl_deleted_special_oper)
13192             << Args[0]->getType() << DFK.asSpecialMember();
13193         } else {
13194           assert(DFK.isComparison());
13195           Diag(OpLoc, diag::err_ovl_deleted_comparison)
13196             << Args[0]->getType() << DeletedFD;
13197         }
13198 
13199         // The user probably meant to call this special member. Just
13200         // explain why it's deleted.
13201         NoteDeletedFunction(DeletedFD);
13202         return ExprError();
13203       }
13204       CandidateSet.NoteCandidates(
13205           PartialDiagnosticAt(
13206               OpLoc, PDiag(diag::err_ovl_deleted_oper)
13207                          << getOperatorSpelling(Best->Function->getDeclName()
13208                                                     .getCXXOverloadedOperator())
13209                          << Args[0]->getSourceRange()
13210                          << Args[1]->getSourceRange()),
13211           *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13212           OpLoc);
13213       return ExprError();
13214   }
13215 
13216   // We matched a built-in operator; build it.
13217   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13218 }
13219 
13220 ExprResult Sema::BuildSynthesizedThreeWayComparison(
13221     SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
13222     FunctionDecl *DefaultedFn) {
13223   const ComparisonCategoryInfo *Info =
13224       Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
13225   // If we're not producing a known comparison category type, we can't
13226   // synthesize a three-way comparison. Let the caller diagnose this.
13227   if (!Info)
13228     return ExprResult((Expr*)nullptr);
13229 
13230   // If we ever want to perform this synthesis more generally, we will need to
13231   // apply the temporary materialization conversion to the operands.
13232   assert(LHS->isGLValue() && RHS->isGLValue() &&
13233          "cannot use prvalue expressions more than once");
13234   Expr *OrigLHS = LHS;
13235   Expr *OrigRHS = RHS;
13236 
13237   // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
13238   // each of them multiple times below.
13239   LHS = new (Context)
13240       OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
13241                       LHS->getObjectKind(), LHS);
13242   RHS = new (Context)
13243       OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
13244                       RHS->getObjectKind(), RHS);
13245 
13246   ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
13247                                         DefaultedFn);
13248   if (Eq.isInvalid())
13249     return ExprError();
13250 
13251   ExprResult Less;
13252   if (Info->isOrdered()) {
13253     Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true, true,
13254                                  DefaultedFn);
13255     if (Less.isInvalid())
13256       return ExprError();
13257   }
13258 
13259   ExprResult Greater;
13260   if (Info->isOrdered()) {
13261     Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
13262                                     DefaultedFn);
13263     if (Greater.isInvalid())
13264       return ExprError();
13265   }
13266 
13267   // Form the list of comparisons we're going to perform.
13268   struct Comparison {
13269     ExprResult Cmp;
13270     ComparisonCategoryResult Result;
13271   } Comparisons[4] =
13272   { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
13273                           : ComparisonCategoryResult::Equivalent},
13274     {Less, ComparisonCategoryResult::Less},
13275     {Greater, ComparisonCategoryResult::Greater},
13276     {ExprResult(), ComparisonCategoryResult::Unordered},
13277   };
13278 
13279   int I;
13280   if (Info->isEquality()) {
13281     Comparisons[1].Result = Info->isStrong()
13282                                 ? ComparisonCategoryResult::Nonequal
13283                                 : ComparisonCategoryResult::Nonequivalent;
13284     I = 1;
13285   } else if (!Info->isPartial()) {
13286     I = 2;
13287   } else {
13288     I = 3;
13289   }
13290 
13291   // Combine the comparisons with suitable conditional expressions.
13292   ExprResult Result;
13293   for (; I >= 0; --I) {
13294     // Build a reference to the comparison category constant.
13295     auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
13296     // FIXME: Missing a constant for a comparison category. Diagnose this?
13297     if (!VI)
13298       return ExprResult((Expr*)nullptr);
13299     ExprResult ThisResult =
13300         BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
13301     if (ThisResult.isInvalid())
13302       return ExprError();
13303 
13304     // Build a conditional unless this is the final case.
13305     if (Result.get()) {
13306       Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
13307                                   ThisResult.get(), Result.get());
13308       if (Result.isInvalid())
13309         return ExprError();
13310     } else {
13311       Result = ThisResult;
13312     }
13313   }
13314 
13315   // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
13316   // bind the OpaqueValueExprs before they're (repeatedly) used.
13317   Expr *SyntacticForm = new (Context)
13318       BinaryOperator(OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
13319                      Result.get()->getValueKind(),
13320                      Result.get()->getObjectKind(), OpLoc, FPFeatures);
13321   Expr *SemanticForm[] = {LHS, RHS, Result.get()};
13322   return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
13323 }
13324 
13325 ExprResult
13326 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
13327                                          SourceLocation RLoc,
13328                                          Expr *Base, Expr *Idx) {
13329   Expr *Args[2] = { Base, Idx };
13330   DeclarationName OpName =
13331       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
13332 
13333   // If either side is type-dependent, create an appropriate dependent
13334   // expression.
13335   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13336 
13337     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13338     // CHECKME: no 'operator' keyword?
13339     DeclarationNameInfo OpNameInfo(OpName, LLoc);
13340     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13341     UnresolvedLookupExpr *Fn
13342       = UnresolvedLookupExpr::Create(Context, NamingClass,
13343                                      NestedNameSpecifierLoc(), OpNameInfo,
13344                                      /*ADL*/ true, /*Overloaded*/ false,
13345                                      UnresolvedSetIterator(),
13346                                      UnresolvedSetIterator());
13347     // Can't add any actual overloads yet
13348 
13349     return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args,
13350                                        Context.DependentTy, VK_RValue, RLoc,
13351                                        FPOptions());
13352   }
13353 
13354   // Handle placeholders on both operands.
13355   if (checkPlaceholderForOverload(*this, Args[0]))
13356     return ExprError();
13357   if (checkPlaceholderForOverload(*this, Args[1]))
13358     return ExprError();
13359 
13360   // Build an empty overload set.
13361   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
13362 
13363   // Subscript can only be overloaded as a member function.
13364 
13365   // Add operator candidates that are member functions.
13366   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13367 
13368   // Add builtin operator candidates.
13369   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13370 
13371   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13372 
13373   // Perform overload resolution.
13374   OverloadCandidateSet::iterator Best;
13375   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
13376     case OR_Success: {
13377       // We found a built-in operator or an overloaded operator.
13378       FunctionDecl *FnDecl = Best->Function;
13379 
13380       if (FnDecl) {
13381         // We matched an overloaded operator. Build a call to that
13382         // operator.
13383 
13384         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
13385 
13386         // Convert the arguments.
13387         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
13388         ExprResult Arg0 =
13389           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13390                                               Best->FoundDecl, Method);
13391         if (Arg0.isInvalid())
13392           return ExprError();
13393         Args[0] = Arg0.get();
13394 
13395         // Convert the arguments.
13396         ExprResult InputInit
13397           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13398                                                       Context,
13399                                                       FnDecl->getParamDecl(0)),
13400                                       SourceLocation(),
13401                                       Args[1]);
13402         if (InputInit.isInvalid())
13403           return ExprError();
13404 
13405         Args[1] = InputInit.getAs<Expr>();
13406 
13407         // Build the actual expression node.
13408         DeclarationNameInfo OpLocInfo(OpName, LLoc);
13409         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13410         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13411                                                   Best->FoundDecl,
13412                                                   Base,
13413                                                   HadMultipleCandidates,
13414                                                   OpLocInfo.getLoc(),
13415                                                   OpLocInfo.getInfo());
13416         if (FnExpr.isInvalid())
13417           return ExprError();
13418 
13419         // Determine the result type
13420         QualType ResultTy = FnDecl->getReturnType();
13421         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13422         ResultTy = ResultTy.getNonLValueExprType(Context);
13423 
13424         CXXOperatorCallExpr *TheCall =
13425             CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(),
13426                                         Args, ResultTy, VK, RLoc, FPOptions());
13427 
13428         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
13429           return ExprError();
13430 
13431         if (CheckFunctionCall(Method, TheCall,
13432                               Method->getType()->castAs<FunctionProtoType>()))
13433           return ExprError();
13434 
13435         return MaybeBindToTemporary(TheCall);
13436       } else {
13437         // We matched a built-in operator. Convert the arguments, then
13438         // break out so that we will build the appropriate built-in
13439         // operator node.
13440         ExprResult ArgsRes0 = PerformImplicitConversion(
13441             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13442             AA_Passing, CCK_ForBuiltinOverloadedOp);
13443         if (ArgsRes0.isInvalid())
13444           return ExprError();
13445         Args[0] = ArgsRes0.get();
13446 
13447         ExprResult ArgsRes1 = PerformImplicitConversion(
13448             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13449             AA_Passing, CCK_ForBuiltinOverloadedOp);
13450         if (ArgsRes1.isInvalid())
13451           return ExprError();
13452         Args[1] = ArgsRes1.get();
13453 
13454         break;
13455       }
13456     }
13457 
13458     case OR_No_Viable_Function: {
13459       PartialDiagnostic PD = CandidateSet.empty()
13460           ? (PDiag(diag::err_ovl_no_oper)
13461              << Args[0]->getType() << /*subscript*/ 0
13462              << Args[0]->getSourceRange() << Args[1]->getSourceRange())
13463           : (PDiag(diag::err_ovl_no_viable_subscript)
13464              << Args[0]->getType() << Args[0]->getSourceRange()
13465              << Args[1]->getSourceRange());
13466       CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
13467                                   OCD_AllCandidates, Args, "[]", LLoc);
13468       return ExprError();
13469     }
13470 
13471     case OR_Ambiguous:
13472       CandidateSet.NoteCandidates(
13473           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13474                                         << "[]" << Args[0]->getType()
13475                                         << Args[1]->getType()
13476                                         << Args[0]->getSourceRange()
13477                                         << Args[1]->getSourceRange()),
13478           *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
13479       return ExprError();
13480 
13481     case OR_Deleted:
13482       CandidateSet.NoteCandidates(
13483           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
13484                                         << "[]" << Args[0]->getSourceRange()
13485                                         << Args[1]->getSourceRange()),
13486           *this, OCD_AllCandidates, Args, "[]", LLoc);
13487       return ExprError();
13488     }
13489 
13490   // We matched a built-in operator; build it.
13491   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
13492 }
13493 
13494 /// BuildCallToMemberFunction - Build a call to a member
13495 /// function. MemExpr is the expression that refers to the member
13496 /// function (and includes the object parameter), Args/NumArgs are the
13497 /// arguments to the function call (not including the object
13498 /// parameter). The caller needs to validate that the member
13499 /// expression refers to a non-static member function or an overloaded
13500 /// member function.
13501 ExprResult
13502 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
13503                                 SourceLocation LParenLoc,
13504                                 MultiExprArg Args,
13505                                 SourceLocation RParenLoc) {
13506   assert(MemExprE->getType() == Context.BoundMemberTy ||
13507          MemExprE->getType() == Context.OverloadTy);
13508 
13509   // Dig out the member expression. This holds both the object
13510   // argument and the member function we're referring to.
13511   Expr *NakedMemExpr = MemExprE->IgnoreParens();
13512 
13513   // Determine whether this is a call to a pointer-to-member function.
13514   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
13515     assert(op->getType() == Context.BoundMemberTy);
13516     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
13517 
13518     QualType fnType =
13519       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
13520 
13521     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
13522     QualType resultType = proto->getCallResultType(Context);
13523     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
13524 
13525     // Check that the object type isn't more qualified than the
13526     // member function we're calling.
13527     Qualifiers funcQuals = proto->getMethodQuals();
13528 
13529     QualType objectType = op->getLHS()->getType();
13530     if (op->getOpcode() == BO_PtrMemI)
13531       objectType = objectType->castAs<PointerType>()->getPointeeType();
13532     Qualifiers objectQuals = objectType.getQualifiers();
13533 
13534     Qualifiers difference = objectQuals - funcQuals;
13535     difference.removeObjCGCAttr();
13536     difference.removeAddressSpace();
13537     if (difference) {
13538       std::string qualsString = difference.getAsString();
13539       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
13540         << fnType.getUnqualifiedType()
13541         << qualsString
13542         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
13543     }
13544 
13545     CXXMemberCallExpr *call =
13546         CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType,
13547                                   valueKind, RParenLoc, proto->getNumParams());
13548 
13549     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
13550                             call, nullptr))
13551       return ExprError();
13552 
13553     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
13554       return ExprError();
13555 
13556     if (CheckOtherCall(call, proto))
13557       return ExprError();
13558 
13559     return MaybeBindToTemporary(call);
13560   }
13561 
13562   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
13563     return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue,
13564                             RParenLoc);
13565 
13566   UnbridgedCastsSet UnbridgedCasts;
13567   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13568     return ExprError();
13569 
13570   MemberExpr *MemExpr;
13571   CXXMethodDecl *Method = nullptr;
13572   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
13573   NestedNameSpecifier *Qualifier = nullptr;
13574   if (isa<MemberExpr>(NakedMemExpr)) {
13575     MemExpr = cast<MemberExpr>(NakedMemExpr);
13576     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
13577     FoundDecl = MemExpr->getFoundDecl();
13578     Qualifier = MemExpr->getQualifier();
13579     UnbridgedCasts.restore();
13580   } else {
13581     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
13582     Qualifier = UnresExpr->getQualifier();
13583 
13584     QualType ObjectType = UnresExpr->getBaseType();
13585     Expr::Classification ObjectClassification
13586       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
13587                             : UnresExpr->getBase()->Classify(Context);
13588 
13589     // Add overload candidates
13590     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
13591                                       OverloadCandidateSet::CSK_Normal);
13592 
13593     // FIXME: avoid copy.
13594     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13595     if (UnresExpr->hasExplicitTemplateArgs()) {
13596       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13597       TemplateArgs = &TemplateArgsBuffer;
13598     }
13599 
13600     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
13601            E = UnresExpr->decls_end(); I != E; ++I) {
13602 
13603       NamedDecl *Func = *I;
13604       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
13605       if (isa<UsingShadowDecl>(Func))
13606         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
13607 
13608 
13609       // Microsoft supports direct constructor calls.
13610       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
13611         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
13612                              CandidateSet,
13613                              /*SuppressUserConversions*/ false);
13614       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
13615         // If explicit template arguments were provided, we can't call a
13616         // non-template member function.
13617         if (TemplateArgs)
13618           continue;
13619 
13620         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
13621                            ObjectClassification, Args, CandidateSet,
13622                            /*SuppressUserConversions=*/false);
13623       } else {
13624         AddMethodTemplateCandidate(
13625             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
13626             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
13627             /*SuppressUserConversions=*/false);
13628       }
13629     }
13630 
13631     DeclarationName DeclName = UnresExpr->getMemberName();
13632 
13633     UnbridgedCasts.restore();
13634 
13635     OverloadCandidateSet::iterator Best;
13636     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
13637                                             Best)) {
13638     case OR_Success:
13639       Method = cast<CXXMethodDecl>(Best->Function);
13640       FoundDecl = Best->FoundDecl;
13641       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
13642       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
13643         return ExprError();
13644       // If FoundDecl is different from Method (such as if one is a template
13645       // and the other a specialization), make sure DiagnoseUseOfDecl is
13646       // called on both.
13647       // FIXME: This would be more comprehensively addressed by modifying
13648       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
13649       // being used.
13650       if (Method != FoundDecl.getDecl() &&
13651                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
13652         return ExprError();
13653       break;
13654 
13655     case OR_No_Viable_Function:
13656       CandidateSet.NoteCandidates(
13657           PartialDiagnosticAt(
13658               UnresExpr->getMemberLoc(),
13659               PDiag(diag::err_ovl_no_viable_member_function_in_call)
13660                   << DeclName << MemExprE->getSourceRange()),
13661           *this, OCD_AllCandidates, Args);
13662       // FIXME: Leaking incoming expressions!
13663       return ExprError();
13664 
13665     case OR_Ambiguous:
13666       CandidateSet.NoteCandidates(
13667           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
13668                               PDiag(diag::err_ovl_ambiguous_member_call)
13669                                   << DeclName << MemExprE->getSourceRange()),
13670           *this, OCD_AmbiguousCandidates, Args);
13671       // FIXME: Leaking incoming expressions!
13672       return ExprError();
13673 
13674     case OR_Deleted:
13675       CandidateSet.NoteCandidates(
13676           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
13677                               PDiag(diag::err_ovl_deleted_member_call)
13678                                   << DeclName << MemExprE->getSourceRange()),
13679           *this, OCD_AllCandidates, Args);
13680       // FIXME: Leaking incoming expressions!
13681       return ExprError();
13682     }
13683 
13684     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
13685 
13686     // If overload resolution picked a static member, build a
13687     // non-member call based on that function.
13688     if (Method->isStatic()) {
13689       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
13690                                    RParenLoc);
13691     }
13692 
13693     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
13694   }
13695 
13696   QualType ResultType = Method->getReturnType();
13697   ExprValueKind VK = Expr::getValueKindForType(ResultType);
13698   ResultType = ResultType.getNonLValueExprType(Context);
13699 
13700   assert(Method && "Member call to something that isn't a method?");
13701   const auto *Proto = Method->getType()->getAs<FunctionProtoType>();
13702   CXXMemberCallExpr *TheCall =
13703       CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
13704                                 RParenLoc, Proto->getNumParams());
13705 
13706   // Check for a valid return type.
13707   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
13708                           TheCall, Method))
13709     return ExprError();
13710 
13711   // Convert the object argument (for a non-static member function call).
13712   // We only need to do this if there was actually an overload; otherwise
13713   // it was done at lookup.
13714   if (!Method->isStatic()) {
13715     ExprResult ObjectArg =
13716       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
13717                                           FoundDecl, Method);
13718     if (ObjectArg.isInvalid())
13719       return ExprError();
13720     MemExpr->setBase(ObjectArg.get());
13721   }
13722 
13723   // Convert the rest of the arguments
13724   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
13725                               RParenLoc))
13726     return ExprError();
13727 
13728   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13729 
13730   if (CheckFunctionCall(Method, TheCall, Proto))
13731     return ExprError();
13732 
13733   // In the case the method to call was not selected by the overloading
13734   // resolution process, we still need to handle the enable_if attribute. Do
13735   // that here, so it will not hide previous -- and more relevant -- errors.
13736   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
13737     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
13738       Diag(MemE->getMemberLoc(),
13739            diag::err_ovl_no_viable_member_function_in_call)
13740           << Method << Method->getSourceRange();
13741       Diag(Method->getLocation(),
13742            diag::note_ovl_candidate_disabled_by_function_cond_attr)
13743           << Attr->getCond()->getSourceRange() << Attr->getMessage();
13744       return ExprError();
13745     }
13746   }
13747 
13748   if ((isa<CXXConstructorDecl>(CurContext) ||
13749        isa<CXXDestructorDecl>(CurContext)) &&
13750       TheCall->getMethodDecl()->isPure()) {
13751     const CXXMethodDecl *MD = TheCall->getMethodDecl();
13752 
13753     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
13754         MemExpr->performsVirtualDispatch(getLangOpts())) {
13755       Diag(MemExpr->getBeginLoc(),
13756            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
13757           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
13758           << MD->getParent()->getDeclName();
13759 
13760       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
13761       if (getLangOpts().AppleKext)
13762         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
13763             << MD->getParent()->getDeclName() << MD->getDeclName();
13764     }
13765   }
13766 
13767   if (CXXDestructorDecl *DD =
13768           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
13769     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
13770     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
13771     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
13772                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
13773                          MemExpr->getMemberLoc());
13774   }
13775 
13776   return MaybeBindToTemporary(TheCall);
13777 }
13778 
13779 /// BuildCallToObjectOfClassType - Build a call to an object of class
13780 /// type (C++ [over.call.object]), which can end up invoking an
13781 /// overloaded function call operator (@c operator()) or performing a
13782 /// user-defined conversion on the object argument.
13783 ExprResult
13784 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
13785                                    SourceLocation LParenLoc,
13786                                    MultiExprArg Args,
13787                                    SourceLocation RParenLoc) {
13788   if (checkPlaceholderForOverload(*this, Obj))
13789     return ExprError();
13790   ExprResult Object = Obj;
13791 
13792   UnbridgedCastsSet UnbridgedCasts;
13793   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13794     return ExprError();
13795 
13796   assert(Object.get()->getType()->isRecordType() &&
13797          "Requires object type argument");
13798   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
13799 
13800   // C++ [over.call.object]p1:
13801   //  If the primary-expression E in the function call syntax
13802   //  evaluates to a class object of type "cv T", then the set of
13803   //  candidate functions includes at least the function call
13804   //  operators of T. The function call operators of T are obtained by
13805   //  ordinary lookup of the name operator() in the context of
13806   //  (E).operator().
13807   OverloadCandidateSet CandidateSet(LParenLoc,
13808                                     OverloadCandidateSet::CSK_Operator);
13809   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
13810 
13811   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
13812                           diag::err_incomplete_object_call, Object.get()))
13813     return true;
13814 
13815   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
13816   LookupQualifiedName(R, Record->getDecl());
13817   R.suppressDiagnostics();
13818 
13819   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13820        Oper != OperEnd; ++Oper) {
13821     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
13822                        Object.get()->Classify(Context), Args, CandidateSet,
13823                        /*SuppressUserConversion=*/false);
13824   }
13825 
13826   // C++ [over.call.object]p2:
13827   //   In addition, for each (non-explicit in C++0x) conversion function
13828   //   declared in T of the form
13829   //
13830   //        operator conversion-type-id () cv-qualifier;
13831   //
13832   //   where cv-qualifier is the same cv-qualification as, or a
13833   //   greater cv-qualification than, cv, and where conversion-type-id
13834   //   denotes the type "pointer to function of (P1,...,Pn) returning
13835   //   R", or the type "reference to pointer to function of
13836   //   (P1,...,Pn) returning R", or the type "reference to function
13837   //   of (P1,...,Pn) returning R", a surrogate call function [...]
13838   //   is also considered as a candidate function. Similarly,
13839   //   surrogate call functions are added to the set of candidate
13840   //   functions for each conversion function declared in an
13841   //   accessible base class provided the function is not hidden
13842   //   within T by another intervening declaration.
13843   const auto &Conversions =
13844       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
13845   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
13846     NamedDecl *D = *I;
13847     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
13848     if (isa<UsingShadowDecl>(D))
13849       D = cast<UsingShadowDecl>(D)->getTargetDecl();
13850 
13851     // Skip over templated conversion functions; they aren't
13852     // surrogates.
13853     if (isa<FunctionTemplateDecl>(D))
13854       continue;
13855 
13856     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
13857     if (!Conv->isExplicit()) {
13858       // Strip the reference type (if any) and then the pointer type (if
13859       // any) to get down to what might be a function type.
13860       QualType ConvType = Conv->getConversionType().getNonReferenceType();
13861       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13862         ConvType = ConvPtrType->getPointeeType();
13863 
13864       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13865       {
13866         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
13867                               Object.get(), Args, CandidateSet);
13868       }
13869     }
13870   }
13871 
13872   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13873 
13874   // Perform overload resolution.
13875   OverloadCandidateSet::iterator Best;
13876   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
13877                                           Best)) {
13878   case OR_Success:
13879     // Overload resolution succeeded; we'll build the appropriate call
13880     // below.
13881     break;
13882 
13883   case OR_No_Viable_Function: {
13884     PartialDiagnostic PD =
13885         CandidateSet.empty()
13886             ? (PDiag(diag::err_ovl_no_oper)
13887                << Object.get()->getType() << /*call*/ 1
13888                << Object.get()->getSourceRange())
13889             : (PDiag(diag::err_ovl_no_viable_object_call)
13890                << Object.get()->getType() << Object.get()->getSourceRange());
13891     CandidateSet.NoteCandidates(
13892         PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
13893         OCD_AllCandidates, Args);
13894     break;
13895   }
13896   case OR_Ambiguous:
13897     CandidateSet.NoteCandidates(
13898         PartialDiagnosticAt(Object.get()->getBeginLoc(),
13899                             PDiag(diag::err_ovl_ambiguous_object_call)
13900                                 << Object.get()->getType()
13901                                 << Object.get()->getSourceRange()),
13902         *this, OCD_AmbiguousCandidates, Args);
13903     break;
13904 
13905   case OR_Deleted:
13906     CandidateSet.NoteCandidates(
13907         PartialDiagnosticAt(Object.get()->getBeginLoc(),
13908                             PDiag(diag::err_ovl_deleted_object_call)
13909                                 << Object.get()->getType()
13910                                 << Object.get()->getSourceRange()),
13911         *this, OCD_AllCandidates, Args);
13912     break;
13913   }
13914 
13915   if (Best == CandidateSet.end())
13916     return true;
13917 
13918   UnbridgedCasts.restore();
13919 
13920   if (Best->Function == nullptr) {
13921     // Since there is no function declaration, this is one of the
13922     // surrogate candidates. Dig out the conversion function.
13923     CXXConversionDecl *Conv
13924       = cast<CXXConversionDecl>(
13925                          Best->Conversions[0].UserDefined.ConversionFunction);
13926 
13927     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13928                               Best->FoundDecl);
13929     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13930       return ExprError();
13931     assert(Conv == Best->FoundDecl.getDecl() &&
13932              "Found Decl & conversion-to-functionptr should be same, right?!");
13933     // We selected one of the surrogate functions that converts the
13934     // object parameter to a function pointer. Perform the conversion
13935     // on the object argument, then let BuildCallExpr finish the job.
13936 
13937     // Create an implicit member expr to refer to the conversion operator.
13938     // and then call it.
13939     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13940                                              Conv, HadMultipleCandidates);
13941     if (Call.isInvalid())
13942       return ExprError();
13943     // Record usage of conversion in an implicit cast.
13944     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13945                                     CK_UserDefinedConversion, Call.get(),
13946                                     nullptr, VK_RValue);
13947 
13948     return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13949   }
13950 
13951   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13952 
13953   // We found an overloaded operator(). Build a CXXOperatorCallExpr
13954   // that calls this method, using Object for the implicit object
13955   // parameter and passing along the remaining arguments.
13956   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13957 
13958   // An error diagnostic has already been printed when parsing the declaration.
13959   if (Method->isInvalidDecl())
13960     return ExprError();
13961 
13962   const FunctionProtoType *Proto =
13963     Method->getType()->getAs<FunctionProtoType>();
13964 
13965   unsigned NumParams = Proto->getNumParams();
13966 
13967   DeclarationNameInfo OpLocInfo(
13968                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13969   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13970   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13971                                            Obj, HadMultipleCandidates,
13972                                            OpLocInfo.getLoc(),
13973                                            OpLocInfo.getInfo());
13974   if (NewFn.isInvalid())
13975     return true;
13976 
13977   // The number of argument slots to allocate in the call. If we have default
13978   // arguments we need to allocate space for them as well. We additionally
13979   // need one more slot for the object parameter.
13980   unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
13981 
13982   // Build the full argument list for the method call (the implicit object
13983   // parameter is placed at the beginning of the list).
13984   SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
13985 
13986   bool IsError = false;
13987 
13988   // Initialize the implicit object parameter.
13989   ExprResult ObjRes =
13990     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13991                                         Best->FoundDecl, Method);
13992   if (ObjRes.isInvalid())
13993     IsError = true;
13994   else
13995     Object = ObjRes;
13996   MethodArgs[0] = Object.get();
13997 
13998   // Check the argument types.
13999   for (unsigned i = 0; i != NumParams; i++) {
14000     Expr *Arg;
14001     if (i < Args.size()) {
14002       Arg = Args[i];
14003 
14004       // Pass the argument.
14005 
14006       ExprResult InputInit
14007         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14008                                                     Context,
14009                                                     Method->getParamDecl(i)),
14010                                     SourceLocation(), Arg);
14011 
14012       IsError |= InputInit.isInvalid();
14013       Arg = InputInit.getAs<Expr>();
14014     } else {
14015       ExprResult DefArg
14016         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14017       if (DefArg.isInvalid()) {
14018         IsError = true;
14019         break;
14020       }
14021 
14022       Arg = DefArg.getAs<Expr>();
14023     }
14024 
14025     MethodArgs[i + 1] = Arg;
14026   }
14027 
14028   // If this is a variadic call, handle args passed through "...".
14029   if (Proto->isVariadic()) {
14030     // Promote the arguments (C99 6.5.2.2p7).
14031     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
14032       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
14033                                                         nullptr);
14034       IsError |= Arg.isInvalid();
14035       MethodArgs[i + 1] = Arg.get();
14036     }
14037   }
14038 
14039   if (IsError)
14040     return true;
14041 
14042   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14043 
14044   // Once we've built TheCall, all of the expressions are properly owned.
14045   QualType ResultTy = Method->getReturnType();
14046   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14047   ResultTy = ResultTy.getNonLValueExprType(Context);
14048 
14049   CXXOperatorCallExpr *TheCall =
14050       CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs,
14051                                   ResultTy, VK, RParenLoc, FPOptions());
14052 
14053   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
14054     return true;
14055 
14056   if (CheckFunctionCall(Method, TheCall, Proto))
14057     return true;
14058 
14059   return MaybeBindToTemporary(TheCall);
14060 }
14061 
14062 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
14063 ///  (if one exists), where @c Base is an expression of class type and
14064 /// @c Member is the name of the member we're trying to find.
14065 ExprResult
14066 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
14067                                bool *NoArrowOperatorFound) {
14068   assert(Base->getType()->isRecordType() &&
14069          "left-hand side must have class type");
14070 
14071   if (checkPlaceholderForOverload(*this, Base))
14072     return ExprError();
14073 
14074   SourceLocation Loc = Base->getExprLoc();
14075 
14076   // C++ [over.ref]p1:
14077   //
14078   //   [...] An expression x->m is interpreted as (x.operator->())->m
14079   //   for a class object x of type T if T::operator->() exists and if
14080   //   the operator is selected as the best match function by the
14081   //   overload resolution mechanism (13.3).
14082   DeclarationName OpName =
14083     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
14084   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
14085   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
14086 
14087   if (RequireCompleteType(Loc, Base->getType(),
14088                           diag::err_typecheck_incomplete_tag, Base))
14089     return ExprError();
14090 
14091   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
14092   LookupQualifiedName(R, BaseRecord->getDecl());
14093   R.suppressDiagnostics();
14094 
14095   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14096        Oper != OperEnd; ++Oper) {
14097     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
14098                        None, CandidateSet, /*SuppressUserConversion=*/false);
14099   }
14100 
14101   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14102 
14103   // Perform overload resolution.
14104   OverloadCandidateSet::iterator Best;
14105   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14106   case OR_Success:
14107     // Overload resolution succeeded; we'll build the call below.
14108     break;
14109 
14110   case OR_No_Viable_Function: {
14111     auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
14112     if (CandidateSet.empty()) {
14113       QualType BaseType = Base->getType();
14114       if (NoArrowOperatorFound) {
14115         // Report this specific error to the caller instead of emitting a
14116         // diagnostic, as requested.
14117         *NoArrowOperatorFound = true;
14118         return ExprError();
14119       }
14120       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
14121         << BaseType << Base->getSourceRange();
14122       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
14123         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
14124           << FixItHint::CreateReplacement(OpLoc, ".");
14125       }
14126     } else
14127       Diag(OpLoc, diag::err_ovl_no_viable_oper)
14128         << "operator->" << Base->getSourceRange();
14129     CandidateSet.NoteCandidates(*this, Base, Cands);
14130     return ExprError();
14131   }
14132   case OR_Ambiguous:
14133     CandidateSet.NoteCandidates(
14134         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
14135                                        << "->" << Base->getType()
14136                                        << Base->getSourceRange()),
14137         *this, OCD_AmbiguousCandidates, Base);
14138     return ExprError();
14139 
14140   case OR_Deleted:
14141     CandidateSet.NoteCandidates(
14142         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14143                                        << "->" << Base->getSourceRange()),
14144         *this, OCD_AllCandidates, Base);
14145     return ExprError();
14146   }
14147 
14148   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
14149 
14150   // Convert the object parameter.
14151   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14152   ExprResult BaseResult =
14153     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
14154                                         Best->FoundDecl, Method);
14155   if (BaseResult.isInvalid())
14156     return ExprError();
14157   Base = BaseResult.get();
14158 
14159   // Build the operator call.
14160   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14161                                             Base, HadMultipleCandidates, OpLoc);
14162   if (FnExpr.isInvalid())
14163     return ExprError();
14164 
14165   QualType ResultTy = Method->getReturnType();
14166   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14167   ResultTy = ResultTy.getNonLValueExprType(Context);
14168   CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14169       Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions());
14170 
14171   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
14172     return ExprError();
14173 
14174   if (CheckFunctionCall(Method, TheCall,
14175                         Method->getType()->castAs<FunctionProtoType>()))
14176     return ExprError();
14177 
14178   return MaybeBindToTemporary(TheCall);
14179 }
14180 
14181 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
14182 /// a literal operator described by the provided lookup results.
14183 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
14184                                           DeclarationNameInfo &SuffixInfo,
14185                                           ArrayRef<Expr*> Args,
14186                                           SourceLocation LitEndLoc,
14187                                        TemplateArgumentListInfo *TemplateArgs) {
14188   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
14189 
14190   OverloadCandidateSet CandidateSet(UDSuffixLoc,
14191                                     OverloadCandidateSet::CSK_Normal);
14192   AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
14193                                  TemplateArgs);
14194 
14195   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14196 
14197   // Perform overload resolution. This will usually be trivial, but might need
14198   // to perform substitutions for a literal operator template.
14199   OverloadCandidateSet::iterator Best;
14200   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
14201   case OR_Success:
14202   case OR_Deleted:
14203     break;
14204 
14205   case OR_No_Viable_Function:
14206     CandidateSet.NoteCandidates(
14207         PartialDiagnosticAt(UDSuffixLoc,
14208                             PDiag(diag::err_ovl_no_viable_function_in_call)
14209                                 << R.getLookupName()),
14210         *this, OCD_AllCandidates, Args);
14211     return ExprError();
14212 
14213   case OR_Ambiguous:
14214     CandidateSet.NoteCandidates(
14215         PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
14216                                                 << R.getLookupName()),
14217         *this, OCD_AmbiguousCandidates, Args);
14218     return ExprError();
14219   }
14220 
14221   FunctionDecl *FD = Best->Function;
14222   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
14223                                         nullptr, HadMultipleCandidates,
14224                                         SuffixInfo.getLoc(),
14225                                         SuffixInfo.getInfo());
14226   if (Fn.isInvalid())
14227     return true;
14228 
14229   // Check the argument types. This should almost always be a no-op, except
14230   // that array-to-pointer decay is applied to string literals.
14231   Expr *ConvArgs[2];
14232   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
14233     ExprResult InputInit = PerformCopyInitialization(
14234       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
14235       SourceLocation(), Args[ArgIdx]);
14236     if (InputInit.isInvalid())
14237       return true;
14238     ConvArgs[ArgIdx] = InputInit.get();
14239   }
14240 
14241   QualType ResultTy = FD->getReturnType();
14242   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14243   ResultTy = ResultTy.getNonLValueExprType(Context);
14244 
14245   UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
14246       Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
14247       VK, LitEndLoc, UDSuffixLoc);
14248 
14249   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
14250     return ExprError();
14251 
14252   if (CheckFunctionCall(FD, UDL, nullptr))
14253     return ExprError();
14254 
14255   return MaybeBindToTemporary(UDL);
14256 }
14257 
14258 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
14259 /// given LookupResult is non-empty, it is assumed to describe a member which
14260 /// will be invoked. Otherwise, the function will be found via argument
14261 /// dependent lookup.
14262 /// CallExpr is set to a valid expression and FRS_Success returned on success,
14263 /// otherwise CallExpr is set to ExprError() and some non-success value
14264 /// is returned.
14265 Sema::ForRangeStatus
14266 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
14267                                 SourceLocation RangeLoc,
14268                                 const DeclarationNameInfo &NameInfo,
14269                                 LookupResult &MemberLookup,
14270                                 OverloadCandidateSet *CandidateSet,
14271                                 Expr *Range, ExprResult *CallExpr) {
14272   Scope *S = nullptr;
14273 
14274   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
14275   if (!MemberLookup.empty()) {
14276     ExprResult MemberRef =
14277         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
14278                                  /*IsPtr=*/false, CXXScopeSpec(),
14279                                  /*TemplateKWLoc=*/SourceLocation(),
14280                                  /*FirstQualifierInScope=*/nullptr,
14281                                  MemberLookup,
14282                                  /*TemplateArgs=*/nullptr, S);
14283     if (MemberRef.isInvalid()) {
14284       *CallExpr = ExprError();
14285       return FRS_DiagnosticIssued;
14286     }
14287     *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
14288     if (CallExpr->isInvalid()) {
14289       *CallExpr = ExprError();
14290       return FRS_DiagnosticIssued;
14291     }
14292   } else {
14293     UnresolvedSet<0> FoundNames;
14294     UnresolvedLookupExpr *Fn =
14295       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
14296                                    NestedNameSpecifierLoc(), NameInfo,
14297                                    /*NeedsADL=*/true, /*Overloaded=*/false,
14298                                    FoundNames.begin(), FoundNames.end());
14299 
14300     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
14301                                                     CandidateSet, CallExpr);
14302     if (CandidateSet->empty() || CandidateSetError) {
14303       *CallExpr = ExprError();
14304       return FRS_NoViableFunction;
14305     }
14306     OverloadCandidateSet::iterator Best;
14307     OverloadingResult OverloadResult =
14308         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
14309 
14310     if (OverloadResult == OR_No_Viable_Function) {
14311       *CallExpr = ExprError();
14312       return FRS_NoViableFunction;
14313     }
14314     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
14315                                          Loc, nullptr, CandidateSet, &Best,
14316                                          OverloadResult,
14317                                          /*AllowTypoCorrection=*/false);
14318     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
14319       *CallExpr = ExprError();
14320       return FRS_DiagnosticIssued;
14321     }
14322   }
14323   return FRS_Success;
14324 }
14325 
14326 
14327 /// FixOverloadedFunctionReference - E is an expression that refers to
14328 /// a C++ overloaded function (possibly with some parentheses and
14329 /// perhaps a '&' around it). We have resolved the overloaded function
14330 /// to the function declaration Fn, so patch up the expression E to
14331 /// refer (possibly indirectly) to Fn. Returns the new expr.
14332 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
14333                                            FunctionDecl *Fn) {
14334   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
14335     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
14336                                                    Found, Fn);
14337     if (SubExpr == PE->getSubExpr())
14338       return PE;
14339 
14340     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
14341   }
14342 
14343   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
14344     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
14345                                                    Found, Fn);
14346     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
14347                                SubExpr->getType()) &&
14348            "Implicit cast type cannot be determined from overload");
14349     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
14350     if (SubExpr == ICE->getSubExpr())
14351       return ICE;
14352 
14353     return ImplicitCastExpr::Create(Context, ICE->getType(),
14354                                     ICE->getCastKind(),
14355                                     SubExpr, nullptr,
14356                                     ICE->getValueKind());
14357   }
14358 
14359   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
14360     if (!GSE->isResultDependent()) {
14361       Expr *SubExpr =
14362           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
14363       if (SubExpr == GSE->getResultExpr())
14364         return GSE;
14365 
14366       // Replace the resulting type information before rebuilding the generic
14367       // selection expression.
14368       ArrayRef<Expr *> A = GSE->getAssocExprs();
14369       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
14370       unsigned ResultIdx = GSE->getResultIndex();
14371       AssocExprs[ResultIdx] = SubExpr;
14372 
14373       return GenericSelectionExpr::Create(
14374           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
14375           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
14376           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
14377           ResultIdx);
14378     }
14379     // Rather than fall through to the unreachable, return the original generic
14380     // selection expression.
14381     return GSE;
14382   }
14383 
14384   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
14385     assert(UnOp->getOpcode() == UO_AddrOf &&
14386            "Can only take the address of an overloaded function");
14387     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
14388       if (Method->isStatic()) {
14389         // Do nothing: static member functions aren't any different
14390         // from non-member functions.
14391       } else {
14392         // Fix the subexpression, which really has to be an
14393         // UnresolvedLookupExpr holding an overloaded member function
14394         // or template.
14395         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14396                                                        Found, Fn);
14397         if (SubExpr == UnOp->getSubExpr())
14398           return UnOp;
14399 
14400         assert(isa<DeclRefExpr>(SubExpr)
14401                && "fixed to something other than a decl ref");
14402         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
14403                && "fixed to a member ref with no nested name qualifier");
14404 
14405         // We have taken the address of a pointer to member
14406         // function. Perform the computation here so that we get the
14407         // appropriate pointer to member type.
14408         QualType ClassType
14409           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
14410         QualType MemPtrType
14411           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
14412         // Under the MS ABI, lock down the inheritance model now.
14413         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14414           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
14415 
14416         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
14417                                            VK_RValue, OK_Ordinary,
14418                                            UnOp->getOperatorLoc(), false);
14419       }
14420     }
14421     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14422                                                    Found, Fn);
14423     if (SubExpr == UnOp->getSubExpr())
14424       return UnOp;
14425 
14426     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
14427                                      Context.getPointerType(SubExpr->getType()),
14428                                        VK_RValue, OK_Ordinary,
14429                                        UnOp->getOperatorLoc(), false);
14430   }
14431 
14432   // C++ [except.spec]p17:
14433   //   An exception-specification is considered to be needed when:
14434   //   - in an expression the function is the unique lookup result or the
14435   //     selected member of a set of overloaded functions
14436   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
14437     ResolveExceptionSpec(E->getExprLoc(), FPT);
14438 
14439   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14440     // FIXME: avoid copy.
14441     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14442     if (ULE->hasExplicitTemplateArgs()) {
14443       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
14444       TemplateArgs = &TemplateArgsBuffer;
14445     }
14446 
14447     DeclRefExpr *DRE =
14448         BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(),
14449                          ULE->getQualifierLoc(), Found.getDecl(),
14450                          ULE->getTemplateKeywordLoc(), TemplateArgs);
14451     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
14452     return DRE;
14453   }
14454 
14455   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
14456     // FIXME: avoid copy.
14457     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14458     if (MemExpr->hasExplicitTemplateArgs()) {
14459       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14460       TemplateArgs = &TemplateArgsBuffer;
14461     }
14462 
14463     Expr *Base;
14464 
14465     // If we're filling in a static method where we used to have an
14466     // implicit member access, rewrite to a simple decl ref.
14467     if (MemExpr->isImplicitAccess()) {
14468       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14469         DeclRefExpr *DRE = BuildDeclRefExpr(
14470             Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
14471             MemExpr->getQualifierLoc(), Found.getDecl(),
14472             MemExpr->getTemplateKeywordLoc(), TemplateArgs);
14473         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
14474         return DRE;
14475       } else {
14476         SourceLocation Loc = MemExpr->getMemberLoc();
14477         if (MemExpr->getQualifier())
14478           Loc = MemExpr->getQualifierLoc().getBeginLoc();
14479         Base =
14480             BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
14481       }
14482     } else
14483       Base = MemExpr->getBase();
14484 
14485     ExprValueKind valueKind;
14486     QualType type;
14487     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14488       valueKind = VK_LValue;
14489       type = Fn->getType();
14490     } else {
14491       valueKind = VK_RValue;
14492       type = Context.BoundMemberTy;
14493     }
14494 
14495     return BuildMemberExpr(
14496         Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
14497         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
14498         /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
14499         type, valueKind, OK_Ordinary, TemplateArgs);
14500   }
14501 
14502   llvm_unreachable("Invalid reference to overloaded function");
14503 }
14504 
14505 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
14506                                                 DeclAccessPair Found,
14507                                                 FunctionDecl *Fn) {
14508   return FixOverloadedFunctionReference(E.get(), Found, Fn);
14509 }
14510