1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file provides Sema routines for C++ overloading.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/Overload.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/TypeOrdering.h"
22 #include "clang/Basic/Diagnostic.h"
23 #include "clang/Basic/DiagnosticOptions.h"
24 #include "clang/Basic/PartialDiagnostic.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/SemaInternal.h"
29 #include "clang/Sema/Template.h"
30 #include "clang/Sema/TemplateDeduction.h"
31 #include "llvm/ADT/DenseSet.h"
32 #include "llvm/ADT/Optional.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/SmallString.h"
36 #include <algorithm>
37 #include <cstdlib>
38 
39 using namespace clang;
40 using namespace sema;
41 
42 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
43   return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
44     return P->hasAttr<PassObjectSizeAttr>();
45   });
46 }
47 
48 /// A convenience routine for creating a decayed reference to a function.
49 static ExprResult
50 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
51                       const Expr *Base, bool HadMultipleCandidates,
52                       SourceLocation Loc = SourceLocation(),
53                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
54   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
55     return ExprError();
56   // If FoundDecl is different from Fn (such as if one is a template
57   // and the other a specialization), make sure DiagnoseUseOfDecl is
58   // called on both.
59   // FIXME: This would be more comprehensively addressed by modifying
60   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
61   // being used.
62   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
63     return ExprError();
64   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
65     S.ResolveExceptionSpec(Loc, FPT);
66   DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
67                                                  VK_LValue, Loc, LocInfo);
68   if (HadMultipleCandidates)
69     DRE->setHadMultipleCandidates(true);
70 
71   S.MarkDeclRefReferenced(DRE, Base);
72   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
73                              CK_FunctionToPointerDecay);
74 }
75 
76 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
77                                  bool InOverloadResolution,
78                                  StandardConversionSequence &SCS,
79                                  bool CStyle,
80                                  bool AllowObjCWritebackConversion);
81 
82 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
83                                                  QualType &ToType,
84                                                  bool InOverloadResolution,
85                                                  StandardConversionSequence &SCS,
86                                                  bool CStyle);
87 static OverloadingResult
88 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
89                         UserDefinedConversionSequence& User,
90                         OverloadCandidateSet& Conversions,
91                         bool AllowExplicit,
92                         bool AllowObjCConversionOnExplicit);
93 
94 
95 static ImplicitConversionSequence::CompareKind
96 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
97                                    const StandardConversionSequence& SCS1,
98                                    const StandardConversionSequence& SCS2);
99 
100 static ImplicitConversionSequence::CompareKind
101 CompareQualificationConversions(Sema &S,
102                                 const StandardConversionSequence& SCS1,
103                                 const StandardConversionSequence& SCS2);
104 
105 static ImplicitConversionSequence::CompareKind
106 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
107                                 const StandardConversionSequence& SCS1,
108                                 const StandardConversionSequence& SCS2);
109 
110 /// GetConversionRank - Retrieve the implicit conversion rank
111 /// corresponding to the given implicit conversion kind.
112 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
113   static const ImplicitConversionRank
114     Rank[(int)ICK_Num_Conversion_Kinds] = {
115     ICR_Exact_Match,
116     ICR_Exact_Match,
117     ICR_Exact_Match,
118     ICR_Exact_Match,
119     ICR_Exact_Match,
120     ICR_Exact_Match,
121     ICR_Promotion,
122     ICR_Promotion,
123     ICR_Promotion,
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_Conversion,
134     ICR_OCL_Scalar_Widening,
135     ICR_Complex_Real_Conversion,
136     ICR_Conversion,
137     ICR_Conversion,
138     ICR_Writeback_Conversion,
139     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
140                      // it was omitted by the patch that added
141                      // ICK_Zero_Event_Conversion
142     ICR_C_Conversion,
143     ICR_C_Conversion_Extension
144   };
145   return Rank[(int)Kind];
146 }
147 
148 /// GetImplicitConversionName - Return the name of this kind of
149 /// implicit conversion.
150 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
151   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
152     "No conversion",
153     "Lvalue-to-rvalue",
154     "Array-to-pointer",
155     "Function-to-pointer",
156     "Function pointer conversion",
157     "Qualification",
158     "Integral promotion",
159     "Floating point promotion",
160     "Complex promotion",
161     "Integral conversion",
162     "Floating conversion",
163     "Complex conversion",
164     "Floating-integral conversion",
165     "Pointer conversion",
166     "Pointer-to-member conversion",
167     "Boolean conversion",
168     "Compatible-types conversion",
169     "Derived-to-base conversion",
170     "Vector conversion",
171     "Vector splat",
172     "Complex-real conversion",
173     "Block Pointer conversion",
174     "Transparent Union Conversion",
175     "Writeback conversion",
176     "OpenCL Zero Event Conversion",
177     "C specific type conversion",
178     "Incompatible pointer conversion"
179   };
180   return Name[Kind];
181 }
182 
183 /// StandardConversionSequence - Set the standard conversion
184 /// sequence to the identity conversion.
185 void StandardConversionSequence::setAsIdentityConversion() {
186   First = ICK_Identity;
187   Second = ICK_Identity;
188   Third = ICK_Identity;
189   DeprecatedStringLiteralToCharPtr = false;
190   QualificationIncludesObjCLifetime = false;
191   ReferenceBinding = false;
192   DirectBinding = false;
193   IsLvalueReference = true;
194   BindsToFunctionLvalue = false;
195   BindsToRvalue = false;
196   BindsImplicitObjectArgumentWithoutRefQualifier = false;
197   ObjCLifetimeConversionBinding = false;
198   CopyConstructor = nullptr;
199 }
200 
201 /// getRank - Retrieve the rank of this standard conversion sequence
202 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
203 /// implicit conversions.
204 ImplicitConversionRank StandardConversionSequence::getRank() const {
205   ImplicitConversionRank Rank = ICR_Exact_Match;
206   if  (GetConversionRank(First) > Rank)
207     Rank = GetConversionRank(First);
208   if  (GetConversionRank(Second) > Rank)
209     Rank = GetConversionRank(Second);
210   if  (GetConversionRank(Third) > Rank)
211     Rank = GetConversionRank(Third);
212   return Rank;
213 }
214 
215 /// isPointerConversionToBool - Determines whether this conversion is
216 /// a conversion of a pointer or pointer-to-member to bool. This is
217 /// used as part of the ranking of standard conversion sequences
218 /// (C++ 13.3.3.2p4).
219 bool StandardConversionSequence::isPointerConversionToBool() const {
220   // Note that FromType has not necessarily been transformed by the
221   // array-to-pointer or function-to-pointer implicit conversions, so
222   // check for their presence as well as checking whether FromType is
223   // a pointer.
224   if (getToType(1)->isBooleanType() &&
225       (getFromType()->isPointerType() ||
226        getFromType()->isMemberPointerType() ||
227        getFromType()->isObjCObjectPointerType() ||
228        getFromType()->isBlockPointerType() ||
229        getFromType()->isNullPtrType() ||
230        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
231     return true;
232 
233   return false;
234 }
235 
236 /// isPointerConversionToVoidPointer - Determines whether this
237 /// conversion is a conversion of a pointer to a void pointer. This is
238 /// used as part of the ranking of standard conversion sequences (C++
239 /// 13.3.3.2p4).
240 bool
241 StandardConversionSequence::
242 isPointerConversionToVoidPointer(ASTContext& Context) const {
243   QualType FromType = getFromType();
244   QualType ToType = getToType(1);
245 
246   // Note that FromType has not necessarily been transformed by the
247   // array-to-pointer implicit conversion, so check for its presence
248   // and redo the conversion to get a pointer.
249   if (First == ICK_Array_To_Pointer)
250     FromType = Context.getArrayDecayedType(FromType);
251 
252   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
253     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
254       return ToPtrType->getPointeeType()->isVoidType();
255 
256   return false;
257 }
258 
259 /// Skip any implicit casts which could be either part of a narrowing conversion
260 /// or after one in an implicit conversion.
261 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
262   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
263     switch (ICE->getCastKind()) {
264     case CK_NoOp:
265     case CK_IntegralCast:
266     case CK_IntegralToBoolean:
267     case CK_IntegralToFloating:
268     case CK_BooleanToSignedIntegral:
269     case CK_FloatingToIntegral:
270     case CK_FloatingToBoolean:
271     case CK_FloatingCast:
272       Converted = ICE->getSubExpr();
273       continue;
274 
275     default:
276       return Converted;
277     }
278   }
279 
280   return Converted;
281 }
282 
283 /// Check if this standard conversion sequence represents a narrowing
284 /// conversion, according to C++11 [dcl.init.list]p7.
285 ///
286 /// \param Ctx  The AST context.
287 /// \param Converted  The result of applying this standard conversion sequence.
288 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
289 ///        value of the expression prior to the narrowing conversion.
290 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
291 ///        type of the expression prior to the narrowing conversion.
292 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
293 ///        from floating point types to integral types should be ignored.
294 NarrowingKind StandardConversionSequence::getNarrowingKind(
295     ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
296     QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
297   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
298 
299   // C++11 [dcl.init.list]p7:
300   //   A narrowing conversion is an implicit conversion ...
301   QualType FromType = getToType(0);
302   QualType ToType = getToType(1);
303 
304   // A conversion to an enumeration type is narrowing if the conversion to
305   // the underlying type is narrowing. This only arises for expressions of
306   // the form 'Enum{init}'.
307   if (auto *ET = ToType->getAs<EnumType>())
308     ToType = ET->getDecl()->getIntegerType();
309 
310   switch (Second) {
311   // 'bool' is an integral type; dispatch to the right place to handle it.
312   case ICK_Boolean_Conversion:
313     if (FromType->isRealFloatingType())
314       goto FloatingIntegralConversion;
315     if (FromType->isIntegralOrUnscopedEnumerationType())
316       goto IntegralConversion;
317     // Boolean conversions can be from pointers and pointers to members
318     // [conv.bool], and those aren't considered narrowing conversions.
319     return NK_Not_Narrowing;
320 
321   // -- from a floating-point type to an integer type, or
322   //
323   // -- from an integer type or unscoped enumeration type to a floating-point
324   //    type, except where the source is a constant expression and the actual
325   //    value after conversion will fit into the target type and will produce
326   //    the original value when converted back to the original type, or
327   case ICK_Floating_Integral:
328   FloatingIntegralConversion:
329     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
330       return NK_Type_Narrowing;
331     } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
332                ToType->isRealFloatingType()) {
333       if (IgnoreFloatToIntegralConversion)
334         return NK_Not_Narrowing;
335       llvm::APSInt IntConstantValue;
336       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
337       assert(Initializer && "Unknown conversion expression");
338 
339       // If it's value-dependent, we can't tell whether it's narrowing.
340       if (Initializer->isValueDependent())
341         return NK_Dependent_Narrowing;
342 
343       if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
344         // Convert the integer to the floating type.
345         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
346         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
347                                 llvm::APFloat::rmNearestTiesToEven);
348         // And back.
349         llvm::APSInt ConvertedValue = IntConstantValue;
350         bool ignored;
351         Result.convertToInteger(ConvertedValue,
352                                 llvm::APFloat::rmTowardZero, &ignored);
353         // If the resulting value is different, this was a narrowing conversion.
354         if (IntConstantValue != ConvertedValue) {
355           ConstantValue = APValue(IntConstantValue);
356           ConstantType = Initializer->getType();
357           return NK_Constant_Narrowing;
358         }
359       } else {
360         // Variables are always narrowings.
361         return NK_Variable_Narrowing;
362       }
363     }
364     return NK_Not_Narrowing;
365 
366   // -- from long double to double or float, or from double to float, except
367   //    where the source is a constant expression and the actual value after
368   //    conversion is within the range of values that can be represented (even
369   //    if it cannot be represented exactly), or
370   case ICK_Floating_Conversion:
371     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
372         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
373       // FromType is larger than ToType.
374       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
375 
376       // If it's value-dependent, we can't tell whether it's narrowing.
377       if (Initializer->isValueDependent())
378         return NK_Dependent_Narrowing;
379 
380       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
381         // Constant!
382         assert(ConstantValue.isFloat());
383         llvm::APFloat FloatVal = ConstantValue.getFloat();
384         // Convert the source value into the target type.
385         bool ignored;
386         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
387           Ctx.getFloatTypeSemantics(ToType),
388           llvm::APFloat::rmNearestTiesToEven, &ignored);
389         // If there was no overflow, the source value is within the range of
390         // values that can be represented.
391         if (ConvertStatus & llvm::APFloat::opOverflow) {
392           ConstantType = Initializer->getType();
393           return NK_Constant_Narrowing;
394         }
395       } else {
396         return NK_Variable_Narrowing;
397       }
398     }
399     return NK_Not_Narrowing;
400 
401   // -- from an integer type or unscoped enumeration type to an integer type
402   //    that cannot represent all the values of the original type, except where
403   //    the source is a constant expression and the actual value after
404   //    conversion will fit into the target type and will produce the original
405   //    value when converted back to the original type.
406   case ICK_Integral_Conversion:
407   IntegralConversion: {
408     assert(FromType->isIntegralOrUnscopedEnumerationType());
409     assert(ToType->isIntegralOrUnscopedEnumerationType());
410     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
411     const unsigned FromWidth = Ctx.getIntWidth(FromType);
412     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
413     const unsigned ToWidth = Ctx.getIntWidth(ToType);
414 
415     if (FromWidth > ToWidth ||
416         (FromWidth == ToWidth && FromSigned != ToSigned) ||
417         (FromSigned && !ToSigned)) {
418       // Not all values of FromType can be represented in ToType.
419       llvm::APSInt InitializerValue;
420       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
421 
422       // If it's value-dependent, we can't tell whether it's narrowing.
423       if (Initializer->isValueDependent())
424         return NK_Dependent_Narrowing;
425 
426       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
427         // Such conversions on variables are always narrowing.
428         return NK_Variable_Narrowing;
429       }
430       bool Narrowing = false;
431       if (FromWidth < ToWidth) {
432         // Negative -> unsigned is narrowing. Otherwise, more bits is never
433         // narrowing.
434         if (InitializerValue.isSigned() && InitializerValue.isNegative())
435           Narrowing = true;
436       } else {
437         // Add a bit to the InitializerValue so we don't have to worry about
438         // signed vs. unsigned comparisons.
439         InitializerValue = InitializerValue.extend(
440           InitializerValue.getBitWidth() + 1);
441         // Convert the initializer to and from the target width and signed-ness.
442         llvm::APSInt ConvertedValue = InitializerValue;
443         ConvertedValue = ConvertedValue.trunc(ToWidth);
444         ConvertedValue.setIsSigned(ToSigned);
445         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
446         ConvertedValue.setIsSigned(InitializerValue.isSigned());
447         // If the result is different, this was a narrowing conversion.
448         if (ConvertedValue != InitializerValue)
449           Narrowing = true;
450       }
451       if (Narrowing) {
452         ConstantType = Initializer->getType();
453         ConstantValue = APValue(InitializerValue);
454         return NK_Constant_Narrowing;
455       }
456     }
457     return NK_Not_Narrowing;
458   }
459 
460   default:
461     // Other kinds of conversions are not narrowings.
462     return NK_Not_Narrowing;
463   }
464 }
465 
466 /// dump - Print this standard conversion sequence to standard
467 /// error. Useful for debugging overloading issues.
468 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
469   raw_ostream &OS = llvm::errs();
470   bool PrintedSomething = false;
471   if (First != ICK_Identity) {
472     OS << GetImplicitConversionName(First);
473     PrintedSomething = true;
474   }
475 
476   if (Second != ICK_Identity) {
477     if (PrintedSomething) {
478       OS << " -> ";
479     }
480     OS << GetImplicitConversionName(Second);
481 
482     if (CopyConstructor) {
483       OS << " (by copy constructor)";
484     } else if (DirectBinding) {
485       OS << " (direct reference binding)";
486     } else if (ReferenceBinding) {
487       OS << " (reference binding)";
488     }
489     PrintedSomething = true;
490   }
491 
492   if (Third != ICK_Identity) {
493     if (PrintedSomething) {
494       OS << " -> ";
495     }
496     OS << GetImplicitConversionName(Third);
497     PrintedSomething = true;
498   }
499 
500   if (!PrintedSomething) {
501     OS << "No conversions required";
502   }
503 }
504 
505 /// dump - Print this user-defined conversion sequence to standard
506 /// error. Useful for debugging overloading issues.
507 void UserDefinedConversionSequence::dump() const {
508   raw_ostream &OS = llvm::errs();
509   if (Before.First || Before.Second || Before.Third) {
510     Before.dump();
511     OS << " -> ";
512   }
513   if (ConversionFunction)
514     OS << '\'' << *ConversionFunction << '\'';
515   else
516     OS << "aggregate initialization";
517   if (After.First || After.Second || After.Third) {
518     OS << " -> ";
519     After.dump();
520   }
521 }
522 
523 /// dump - Print this implicit conversion sequence to standard
524 /// error. Useful for debugging overloading issues.
525 void ImplicitConversionSequence::dump() const {
526   raw_ostream &OS = llvm::errs();
527   if (isStdInitializerListElement())
528     OS << "Worst std::initializer_list element conversion: ";
529   switch (ConversionKind) {
530   case StandardConversion:
531     OS << "Standard conversion: ";
532     Standard.dump();
533     break;
534   case UserDefinedConversion:
535     OS << "User-defined conversion: ";
536     UserDefined.dump();
537     break;
538   case EllipsisConversion:
539     OS << "Ellipsis conversion";
540     break;
541   case AmbiguousConversion:
542     OS << "Ambiguous conversion";
543     break;
544   case BadConversion:
545     OS << "Bad conversion";
546     break;
547   }
548 
549   OS << "\n";
550 }
551 
552 void AmbiguousConversionSequence::construct() {
553   new (&conversions()) ConversionSet();
554 }
555 
556 void AmbiguousConversionSequence::destruct() {
557   conversions().~ConversionSet();
558 }
559 
560 void
561 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
562   FromTypePtr = O.FromTypePtr;
563   ToTypePtr = O.ToTypePtr;
564   new (&conversions()) ConversionSet(O.conversions());
565 }
566 
567 namespace {
568   // Structure used by DeductionFailureInfo to store
569   // template argument information.
570   struct DFIArguments {
571     TemplateArgument FirstArg;
572     TemplateArgument SecondArg;
573   };
574   // Structure used by DeductionFailureInfo to store
575   // template parameter and template argument information.
576   struct DFIParamWithArguments : DFIArguments {
577     TemplateParameter Param;
578   };
579   // Structure used by DeductionFailureInfo to store template argument
580   // information and the index of the problematic call argument.
581   struct DFIDeducedMismatchArgs : DFIArguments {
582     TemplateArgumentList *TemplateArgs;
583     unsigned CallArgIndex;
584   };
585 }
586 
587 /// Convert from Sema's representation of template deduction information
588 /// to the form used in overload-candidate information.
589 DeductionFailureInfo
590 clang::MakeDeductionFailureInfo(ASTContext &Context,
591                                 Sema::TemplateDeductionResult TDK,
592                                 TemplateDeductionInfo &Info) {
593   DeductionFailureInfo Result;
594   Result.Result = static_cast<unsigned>(TDK);
595   Result.HasDiagnostic = false;
596   switch (TDK) {
597   case Sema::TDK_Invalid:
598   case Sema::TDK_InstantiationDepth:
599   case Sema::TDK_TooManyArguments:
600   case Sema::TDK_TooFewArguments:
601   case Sema::TDK_MiscellaneousDeductionFailure:
602   case Sema::TDK_CUDATargetMismatch:
603     Result.Data = nullptr;
604     break;
605 
606   case Sema::TDK_Incomplete:
607   case Sema::TDK_InvalidExplicitArguments:
608     Result.Data = Info.Param.getOpaqueValue();
609     break;
610 
611   case Sema::TDK_DeducedMismatch:
612   case Sema::TDK_DeducedMismatchNested: {
613     // FIXME: Should allocate from normal heap so that we can free this later.
614     auto *Saved = new (Context) DFIDeducedMismatchArgs;
615     Saved->FirstArg = Info.FirstArg;
616     Saved->SecondArg = Info.SecondArg;
617     Saved->TemplateArgs = Info.take();
618     Saved->CallArgIndex = Info.CallArgIndex;
619     Result.Data = Saved;
620     break;
621   }
622 
623   case Sema::TDK_NonDeducedMismatch: {
624     // FIXME: Should allocate from normal heap so that we can free this later.
625     DFIArguments *Saved = new (Context) DFIArguments;
626     Saved->FirstArg = Info.FirstArg;
627     Saved->SecondArg = Info.SecondArg;
628     Result.Data = Saved;
629     break;
630   }
631 
632   case Sema::TDK_IncompletePack:
633     // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
634   case Sema::TDK_Inconsistent:
635   case Sema::TDK_Underqualified: {
636     // FIXME: Should allocate from normal heap so that we can free this later.
637     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
638     Saved->Param = Info.Param;
639     Saved->FirstArg = Info.FirstArg;
640     Saved->SecondArg = Info.SecondArg;
641     Result.Data = Saved;
642     break;
643   }
644 
645   case Sema::TDK_SubstitutionFailure:
646     Result.Data = Info.take();
647     if (Info.hasSFINAEDiagnostic()) {
648       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
649           SourceLocation(), PartialDiagnostic::NullDiagnostic());
650       Info.takeSFINAEDiagnostic(*Diag);
651       Result.HasDiagnostic = true;
652     }
653     break;
654 
655   case Sema::TDK_Success:
656   case Sema::TDK_NonDependentConversionFailure:
657     llvm_unreachable("not a deduction failure");
658   }
659 
660   return Result;
661 }
662 
663 void DeductionFailureInfo::Destroy() {
664   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
665   case Sema::TDK_Success:
666   case Sema::TDK_Invalid:
667   case Sema::TDK_InstantiationDepth:
668   case Sema::TDK_Incomplete:
669   case Sema::TDK_TooManyArguments:
670   case Sema::TDK_TooFewArguments:
671   case Sema::TDK_InvalidExplicitArguments:
672   case Sema::TDK_CUDATargetMismatch:
673   case Sema::TDK_NonDependentConversionFailure:
674     break;
675 
676   case Sema::TDK_IncompletePack:
677   case Sema::TDK_Inconsistent:
678   case Sema::TDK_Underqualified:
679   case Sema::TDK_DeducedMismatch:
680   case Sema::TDK_DeducedMismatchNested:
681   case Sema::TDK_NonDeducedMismatch:
682     // FIXME: Destroy the data?
683     Data = nullptr;
684     break;
685 
686   case Sema::TDK_SubstitutionFailure:
687     // FIXME: Destroy the template argument list?
688     Data = nullptr;
689     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
690       Diag->~PartialDiagnosticAt();
691       HasDiagnostic = false;
692     }
693     break;
694 
695   // Unhandled
696   case Sema::TDK_MiscellaneousDeductionFailure:
697     break;
698   }
699 }
700 
701 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
702   if (HasDiagnostic)
703     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
704   return nullptr;
705 }
706 
707 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
708   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
709   case Sema::TDK_Success:
710   case Sema::TDK_Invalid:
711   case Sema::TDK_InstantiationDepth:
712   case Sema::TDK_TooManyArguments:
713   case Sema::TDK_TooFewArguments:
714   case Sema::TDK_SubstitutionFailure:
715   case Sema::TDK_DeducedMismatch:
716   case Sema::TDK_DeducedMismatchNested:
717   case Sema::TDK_NonDeducedMismatch:
718   case Sema::TDK_CUDATargetMismatch:
719   case Sema::TDK_NonDependentConversionFailure:
720     return TemplateParameter();
721 
722   case Sema::TDK_Incomplete:
723   case Sema::TDK_InvalidExplicitArguments:
724     return TemplateParameter::getFromOpaqueValue(Data);
725 
726   case Sema::TDK_IncompletePack:
727   case Sema::TDK_Inconsistent:
728   case Sema::TDK_Underqualified:
729     return static_cast<DFIParamWithArguments*>(Data)->Param;
730 
731   // Unhandled
732   case Sema::TDK_MiscellaneousDeductionFailure:
733     break;
734   }
735 
736   return TemplateParameter();
737 }
738 
739 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
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_Incomplete:
747   case Sema::TDK_IncompletePack:
748   case Sema::TDK_InvalidExplicitArguments:
749   case Sema::TDK_Inconsistent:
750   case Sema::TDK_Underqualified:
751   case Sema::TDK_NonDeducedMismatch:
752   case Sema::TDK_CUDATargetMismatch:
753   case Sema::TDK_NonDependentConversionFailure:
754     return nullptr;
755 
756   case Sema::TDK_DeducedMismatch:
757   case Sema::TDK_DeducedMismatchNested:
758     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
759 
760   case Sema::TDK_SubstitutionFailure:
761     return static_cast<TemplateArgumentList*>(Data);
762 
763   // Unhandled
764   case Sema::TDK_MiscellaneousDeductionFailure:
765     break;
766   }
767 
768   return nullptr;
769 }
770 
771 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
772   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
773   case Sema::TDK_Success:
774   case Sema::TDK_Invalid:
775   case Sema::TDK_InstantiationDepth:
776   case Sema::TDK_Incomplete:
777   case Sema::TDK_TooManyArguments:
778   case Sema::TDK_TooFewArguments:
779   case Sema::TDK_InvalidExplicitArguments:
780   case Sema::TDK_SubstitutionFailure:
781   case Sema::TDK_CUDATargetMismatch:
782   case Sema::TDK_NonDependentConversionFailure:
783     return nullptr;
784 
785   case Sema::TDK_IncompletePack:
786   case Sema::TDK_Inconsistent:
787   case Sema::TDK_Underqualified:
788   case Sema::TDK_DeducedMismatch:
789   case Sema::TDK_DeducedMismatchNested:
790   case Sema::TDK_NonDeducedMismatch:
791     return &static_cast<DFIArguments*>(Data)->FirstArg;
792 
793   // Unhandled
794   case Sema::TDK_MiscellaneousDeductionFailure:
795     break;
796   }
797 
798   return nullptr;
799 }
800 
801 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
802   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
803   case Sema::TDK_Success:
804   case Sema::TDK_Invalid:
805   case Sema::TDK_InstantiationDepth:
806   case Sema::TDK_Incomplete:
807   case Sema::TDK_IncompletePack:
808   case Sema::TDK_TooManyArguments:
809   case Sema::TDK_TooFewArguments:
810   case Sema::TDK_InvalidExplicitArguments:
811   case Sema::TDK_SubstitutionFailure:
812   case Sema::TDK_CUDATargetMismatch:
813   case Sema::TDK_NonDependentConversionFailure:
814     return nullptr;
815 
816   case Sema::TDK_Inconsistent:
817   case Sema::TDK_Underqualified:
818   case Sema::TDK_DeducedMismatch:
819   case Sema::TDK_DeducedMismatchNested:
820   case Sema::TDK_NonDeducedMismatch:
821     return &static_cast<DFIArguments*>(Data)->SecondArg;
822 
823   // Unhandled
824   case Sema::TDK_MiscellaneousDeductionFailure:
825     break;
826   }
827 
828   return nullptr;
829 }
830 
831 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
832   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
833   case Sema::TDK_DeducedMismatch:
834   case Sema::TDK_DeducedMismatchNested:
835     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
836 
837   default:
838     return llvm::None;
839   }
840 }
841 
842 void OverloadCandidateSet::destroyCandidates() {
843   for (iterator i = begin(), e = end(); i != e; ++i) {
844     for (auto &C : i->Conversions)
845       C.~ImplicitConversionSequence();
846     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
847       i->DeductionFailure.Destroy();
848   }
849 }
850 
851 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
852   destroyCandidates();
853   SlabAllocator.Reset();
854   NumInlineBytesUsed = 0;
855   Candidates.clear();
856   Functions.clear();
857   Kind = CSK;
858 }
859 
860 namespace {
861   class UnbridgedCastsSet {
862     struct Entry {
863       Expr **Addr;
864       Expr *Saved;
865     };
866     SmallVector<Entry, 2> Entries;
867 
868   public:
869     void save(Sema &S, Expr *&E) {
870       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
871       Entry entry = { &E, E };
872       Entries.push_back(entry);
873       E = S.stripARCUnbridgedCast(E);
874     }
875 
876     void restore() {
877       for (SmallVectorImpl<Entry>::iterator
878              i = Entries.begin(), e = Entries.end(); i != e; ++i)
879         *i->Addr = i->Saved;
880     }
881   };
882 }
883 
884 /// checkPlaceholderForOverload - Do any interesting placeholder-like
885 /// preprocessing on the given expression.
886 ///
887 /// \param unbridgedCasts a collection to which to add unbridged casts;
888 ///   without this, they will be immediately diagnosed as errors
889 ///
890 /// Return true on unrecoverable error.
891 static bool
892 checkPlaceholderForOverload(Sema &S, Expr *&E,
893                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
894   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
895     // We can't handle overloaded expressions here because overload
896     // resolution might reasonably tweak them.
897     if (placeholder->getKind() == BuiltinType::Overload) return false;
898 
899     // If the context potentially accepts unbridged ARC casts, strip
900     // the unbridged cast and add it to the collection for later restoration.
901     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
902         unbridgedCasts) {
903       unbridgedCasts->save(S, E);
904       return false;
905     }
906 
907     // Go ahead and check everything else.
908     ExprResult result = S.CheckPlaceholderExpr(E);
909     if (result.isInvalid())
910       return true;
911 
912     E = result.get();
913     return false;
914   }
915 
916   // Nothing to do.
917   return false;
918 }
919 
920 /// checkArgPlaceholdersForOverload - Check a set of call operands for
921 /// placeholders.
922 static bool checkArgPlaceholdersForOverload(Sema &S,
923                                             MultiExprArg Args,
924                                             UnbridgedCastsSet &unbridged) {
925   for (unsigned i = 0, e = Args.size(); i != e; ++i)
926     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
927       return true;
928 
929   return false;
930 }
931 
932 /// Determine whether the given New declaration is an overload of the
933 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
934 /// New and Old cannot be overloaded, e.g., if New has the same signature as
935 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
936 /// functions (or function templates) at all. When it does return Ovl_Match or
937 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
938 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
939 /// declaration.
940 ///
941 /// Example: Given the following input:
942 ///
943 ///   void f(int, float); // #1
944 ///   void f(int, int); // #2
945 ///   int f(int, int); // #3
946 ///
947 /// When we process #1, there is no previous declaration of "f", so IsOverload
948 /// will not be used.
949 ///
950 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
951 /// the parameter types, we see that #1 and #2 are overloaded (since they have
952 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
953 /// unchanged.
954 ///
955 /// When we process #3, Old is an overload set containing #1 and #2. We compare
956 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
957 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
958 /// functions are not part of the signature), IsOverload returns Ovl_Match and
959 /// MatchedDecl will be set to point to the FunctionDecl for #2.
960 ///
961 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
962 /// by a using declaration. The rules for whether to hide shadow declarations
963 /// ignore some properties which otherwise figure into a function template's
964 /// signature.
965 Sema::OverloadKind
966 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
967                     NamedDecl *&Match, bool NewIsUsingDecl) {
968   for (LookupResult::iterator I = Old.begin(), E = Old.end();
969          I != E; ++I) {
970     NamedDecl *OldD = *I;
971 
972     bool OldIsUsingDecl = false;
973     if (isa<UsingShadowDecl>(OldD)) {
974       OldIsUsingDecl = true;
975 
976       // We can always introduce two using declarations into the same
977       // context, even if they have identical signatures.
978       if (NewIsUsingDecl) continue;
979 
980       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
981     }
982 
983     // A using-declaration does not conflict with another declaration
984     // if one of them is hidden.
985     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
986       continue;
987 
988     // If either declaration was introduced by a using declaration,
989     // we'll need to use slightly different rules for matching.
990     // Essentially, these rules are the normal rules, except that
991     // function templates hide function templates with different
992     // return types or template parameter lists.
993     bool UseMemberUsingDeclRules =
994       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
995       !New->getFriendObjectKind();
996 
997     if (FunctionDecl *OldF = OldD->getAsFunction()) {
998       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
999         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1000           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1001           continue;
1002         }
1003 
1004         if (!isa<FunctionTemplateDecl>(OldD) &&
1005             !shouldLinkPossiblyHiddenDecl(*I, New))
1006           continue;
1007 
1008         Match = *I;
1009         return Ovl_Match;
1010       }
1011 
1012       // Builtins that have custom typechecking or have a reference should
1013       // not be overloadable or redeclarable.
1014       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1015         Match = *I;
1016         return Ovl_NonFunction;
1017       }
1018     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1019       // We can overload with these, which can show up when doing
1020       // redeclaration checks for UsingDecls.
1021       assert(Old.getLookupKind() == LookupUsingDeclName);
1022     } else if (isa<TagDecl>(OldD)) {
1023       // We can always overload with tags by hiding them.
1024     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1025       // Optimistically assume that an unresolved using decl will
1026       // overload; if it doesn't, we'll have to diagnose during
1027       // template instantiation.
1028       //
1029       // Exception: if the scope is dependent and this is not a class
1030       // member, the using declaration can only introduce an enumerator.
1031       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1032         Match = *I;
1033         return Ovl_NonFunction;
1034       }
1035     } else {
1036       // (C++ 13p1):
1037       //   Only function declarations can be overloaded; object and type
1038       //   declarations cannot be overloaded.
1039       Match = *I;
1040       return Ovl_NonFunction;
1041     }
1042   }
1043 
1044   return Ovl_Overload;
1045 }
1046 
1047 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1048                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1049   // C++ [basic.start.main]p2: This function shall not be overloaded.
1050   if (New->isMain())
1051     return false;
1052 
1053   // MSVCRT user defined entry points cannot be overloaded.
1054   if (New->isMSVCRTEntryPoint())
1055     return false;
1056 
1057   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1058   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1059 
1060   // C++ [temp.fct]p2:
1061   //   A function template can be overloaded with other function templates
1062   //   and with normal (non-template) functions.
1063   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1064     return true;
1065 
1066   // Is the function New an overload of the function Old?
1067   QualType OldQType = Context.getCanonicalType(Old->getType());
1068   QualType NewQType = Context.getCanonicalType(New->getType());
1069 
1070   // Compare the signatures (C++ 1.3.10) of the two functions to
1071   // determine whether they are overloads. If we find any mismatch
1072   // in the signature, they are overloads.
1073 
1074   // If either of these functions is a K&R-style function (no
1075   // prototype), then we consider them to have matching signatures.
1076   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1077       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1078     return false;
1079 
1080   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1081   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1082 
1083   // The signature of a function includes the types of its
1084   // parameters (C++ 1.3.10), which includes the presence or absence
1085   // of the ellipsis; see C++ DR 357).
1086   if (OldQType != NewQType &&
1087       (OldType->getNumParams() != NewType->getNumParams() ||
1088        OldType->isVariadic() != NewType->isVariadic() ||
1089        !FunctionParamTypesAreEqual(OldType, NewType)))
1090     return true;
1091 
1092   // C++ [temp.over.link]p4:
1093   //   The signature of a function template consists of its function
1094   //   signature, its return type and its template parameter list. The names
1095   //   of the template parameters are significant only for establishing the
1096   //   relationship between the template parameters and the rest of the
1097   //   signature.
1098   //
1099   // We check the return type and template parameter lists for function
1100   // templates first; the remaining checks follow.
1101   //
1102   // However, we don't consider either of these when deciding whether
1103   // a member introduced by a shadow declaration is hidden.
1104   if (!UseMemberUsingDeclRules && NewTemplate &&
1105       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1106                                        OldTemplate->getTemplateParameters(),
1107                                        false, TPL_TemplateMatch) ||
1108        !Context.hasSameType(Old->getDeclaredReturnType(),
1109                             New->getDeclaredReturnType())))
1110     return true;
1111 
1112   // If the function is a class member, its signature includes the
1113   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1114   //
1115   // As part of this, also check whether one of the member functions
1116   // is static, in which case they are not overloads (C++
1117   // 13.1p2). While not part of the definition of the signature,
1118   // this check is important to determine whether these functions
1119   // can be overloaded.
1120   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1121   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1122   if (OldMethod && NewMethod &&
1123       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1124     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1125       if (!UseMemberUsingDeclRules &&
1126           (OldMethod->getRefQualifier() == RQ_None ||
1127            NewMethod->getRefQualifier() == RQ_None)) {
1128         // C++0x [over.load]p2:
1129         //   - Member function declarations with the same name and the same
1130         //     parameter-type-list as well as member function template
1131         //     declarations with the same name, the same parameter-type-list, and
1132         //     the same template parameter lists cannot be overloaded if any of
1133         //     them, but not all, have a ref-qualifier (8.3.5).
1134         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1135           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1136         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1137       }
1138       return true;
1139     }
1140 
1141     // We may not have applied the implicit const for a constexpr member
1142     // function yet (because we haven't yet resolved whether this is a static
1143     // or non-static member function). Add it now, on the assumption that this
1144     // is a redeclaration of OldMethod.
1145     unsigned OldQuals = OldMethod->getTypeQualifiers();
1146     unsigned NewQuals = NewMethod->getTypeQualifiers();
1147     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1148         !isa<CXXConstructorDecl>(NewMethod))
1149       NewQuals |= Qualifiers::Const;
1150 
1151     // We do not allow overloading based off of '__restrict'.
1152     OldQuals &= ~Qualifiers::Restrict;
1153     NewQuals &= ~Qualifiers::Restrict;
1154     if (OldQuals != NewQuals)
1155       return true;
1156   }
1157 
1158   // Though pass_object_size is placed on parameters and takes an argument, we
1159   // consider it to be a function-level modifier for the sake of function
1160   // identity. Either the function has one or more parameters with
1161   // pass_object_size or it doesn't.
1162   if (functionHasPassObjectSizeParams(New) !=
1163       functionHasPassObjectSizeParams(Old))
1164     return true;
1165 
1166   // enable_if attributes are an order-sensitive part of the signature.
1167   for (specific_attr_iterator<EnableIfAttr>
1168          NewI = New->specific_attr_begin<EnableIfAttr>(),
1169          NewE = New->specific_attr_end<EnableIfAttr>(),
1170          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1171          OldE = Old->specific_attr_end<EnableIfAttr>();
1172        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1173     if (NewI == NewE || OldI == OldE)
1174       return true;
1175     llvm::FoldingSetNodeID NewID, OldID;
1176     NewI->getCond()->Profile(NewID, Context, true);
1177     OldI->getCond()->Profile(OldID, Context, true);
1178     if (NewID != OldID)
1179       return true;
1180   }
1181 
1182   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1183     // Don't allow overloading of destructors.  (In theory we could, but it
1184     // would be a giant change to clang.)
1185     if (isa<CXXDestructorDecl>(New))
1186       return false;
1187 
1188     CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1189                        OldTarget = IdentifyCUDATarget(Old);
1190     if (NewTarget == CFT_InvalidTarget)
1191       return false;
1192 
1193     assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1194 
1195     // Allow overloading of functions with same signature and different CUDA
1196     // target attributes.
1197     return NewTarget != OldTarget;
1198   }
1199 
1200   // The signatures match; this is not an overload.
1201   return false;
1202 }
1203 
1204 /// Checks availability of the function depending on the current
1205 /// function context. Inside an unavailable function, unavailability is ignored.
1206 ///
1207 /// \returns true if \arg FD is unavailable and current context is inside
1208 /// an available function, false otherwise.
1209 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1210   if (!FD->isUnavailable())
1211     return false;
1212 
1213   // Walk up the context of the caller.
1214   Decl *C = cast<Decl>(CurContext);
1215   do {
1216     if (C->isUnavailable())
1217       return false;
1218   } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1219   return true;
1220 }
1221 
1222 /// Tries a user-defined conversion from From to ToType.
1223 ///
1224 /// Produces an implicit conversion sequence for when a standard conversion
1225 /// is not an option. See TryImplicitConversion for more information.
1226 static ImplicitConversionSequence
1227 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1228                          bool SuppressUserConversions,
1229                          bool AllowExplicit,
1230                          bool InOverloadResolution,
1231                          bool CStyle,
1232                          bool AllowObjCWritebackConversion,
1233                          bool AllowObjCConversionOnExplicit) {
1234   ImplicitConversionSequence ICS;
1235 
1236   if (SuppressUserConversions) {
1237     // We're not in the case above, so there is no conversion that
1238     // we can perform.
1239     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1240     return ICS;
1241   }
1242 
1243   // Attempt user-defined conversion.
1244   OverloadCandidateSet Conversions(From->getExprLoc(),
1245                                    OverloadCandidateSet::CSK_Normal);
1246   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1247                                   Conversions, AllowExplicit,
1248                                   AllowObjCConversionOnExplicit)) {
1249   case OR_Success:
1250   case OR_Deleted:
1251     ICS.setUserDefined();
1252     // C++ [over.ics.user]p4:
1253     //   A conversion of an expression of class type to the same class
1254     //   type is given Exact Match rank, and a conversion of an
1255     //   expression of class type to a base class of that type is
1256     //   given Conversion rank, in spite of the fact that a copy
1257     //   constructor (i.e., a user-defined conversion function) is
1258     //   called for those cases.
1259     if (CXXConstructorDecl *Constructor
1260           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1261       QualType FromCanon
1262         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1263       QualType ToCanon
1264         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1265       if (Constructor->isCopyConstructor() &&
1266           (FromCanon == ToCanon ||
1267            S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1268         // Turn this into a "standard" conversion sequence, so that it
1269         // gets ranked with standard conversion sequences.
1270         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1271         ICS.setStandard();
1272         ICS.Standard.setAsIdentityConversion();
1273         ICS.Standard.setFromType(From->getType());
1274         ICS.Standard.setAllToTypes(ToType);
1275         ICS.Standard.CopyConstructor = Constructor;
1276         ICS.Standard.FoundCopyConstructor = Found;
1277         if (ToCanon != FromCanon)
1278           ICS.Standard.Second = ICK_Derived_To_Base;
1279       }
1280     }
1281     break;
1282 
1283   case OR_Ambiguous:
1284     ICS.setAmbiguous();
1285     ICS.Ambiguous.setFromType(From->getType());
1286     ICS.Ambiguous.setToType(ToType);
1287     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1288          Cand != Conversions.end(); ++Cand)
1289       if (Cand->Viable)
1290         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1291     break;
1292 
1293     // Fall through.
1294   case OR_No_Viable_Function:
1295     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1296     break;
1297   }
1298 
1299   return ICS;
1300 }
1301 
1302 /// TryImplicitConversion - Attempt to perform an implicit conversion
1303 /// from the given expression (Expr) to the given type (ToType). This
1304 /// function returns an implicit conversion sequence that can be used
1305 /// to perform the initialization. Given
1306 ///
1307 ///   void f(float f);
1308 ///   void g(int i) { f(i); }
1309 ///
1310 /// this routine would produce an implicit conversion sequence to
1311 /// describe the initialization of f from i, which will be a standard
1312 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1313 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1314 //
1315 /// Note that this routine only determines how the conversion can be
1316 /// performed; it does not actually perform the conversion. As such,
1317 /// it will not produce any diagnostics if no conversion is available,
1318 /// but will instead return an implicit conversion sequence of kind
1319 /// "BadConversion".
1320 ///
1321 /// If @p SuppressUserConversions, then user-defined conversions are
1322 /// not permitted.
1323 /// If @p AllowExplicit, then explicit user-defined conversions are
1324 /// permitted.
1325 ///
1326 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1327 /// writeback conversion, which allows __autoreleasing id* parameters to
1328 /// be initialized with __strong id* or __weak id* arguments.
1329 static ImplicitConversionSequence
1330 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1331                       bool SuppressUserConversions,
1332                       bool AllowExplicit,
1333                       bool InOverloadResolution,
1334                       bool CStyle,
1335                       bool AllowObjCWritebackConversion,
1336                       bool AllowObjCConversionOnExplicit) {
1337   ImplicitConversionSequence ICS;
1338   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1339                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1340     ICS.setStandard();
1341     return ICS;
1342   }
1343 
1344   if (!S.getLangOpts().CPlusPlus) {
1345     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1346     return ICS;
1347   }
1348 
1349   // C++ [over.ics.user]p4:
1350   //   A conversion of an expression of class type to the same class
1351   //   type is given Exact Match rank, and a conversion of an
1352   //   expression of class type to a base class of that type is
1353   //   given Conversion rank, in spite of the fact that a copy/move
1354   //   constructor (i.e., a user-defined conversion function) is
1355   //   called for those cases.
1356   QualType FromType = From->getType();
1357   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1358       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1359        S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1360     ICS.setStandard();
1361     ICS.Standard.setAsIdentityConversion();
1362     ICS.Standard.setFromType(FromType);
1363     ICS.Standard.setAllToTypes(ToType);
1364 
1365     // We don't actually check at this point whether there is a valid
1366     // copy/move constructor, since overloading just assumes that it
1367     // exists. When we actually perform initialization, we'll find the
1368     // appropriate constructor to copy the returned object, if needed.
1369     ICS.Standard.CopyConstructor = nullptr;
1370 
1371     // Determine whether this is considered a derived-to-base conversion.
1372     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1373       ICS.Standard.Second = ICK_Derived_To_Base;
1374 
1375     return ICS;
1376   }
1377 
1378   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1379                                   AllowExplicit, InOverloadResolution, CStyle,
1380                                   AllowObjCWritebackConversion,
1381                                   AllowObjCConversionOnExplicit);
1382 }
1383 
1384 ImplicitConversionSequence
1385 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1386                             bool SuppressUserConversions,
1387                             bool AllowExplicit,
1388                             bool InOverloadResolution,
1389                             bool CStyle,
1390                             bool AllowObjCWritebackConversion) {
1391   return ::TryImplicitConversion(*this, From, ToType,
1392                                  SuppressUserConversions, AllowExplicit,
1393                                  InOverloadResolution, CStyle,
1394                                  AllowObjCWritebackConversion,
1395                                  /*AllowObjCConversionOnExplicit=*/false);
1396 }
1397 
1398 /// PerformImplicitConversion - Perform an implicit conversion of the
1399 /// expression From to the type ToType. Returns the
1400 /// converted expression. Flavor is the kind of conversion we're
1401 /// performing, used in the error message. If @p AllowExplicit,
1402 /// explicit user-defined conversions are permitted.
1403 ExprResult
1404 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1405                                 AssignmentAction Action, bool AllowExplicit) {
1406   ImplicitConversionSequence ICS;
1407   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1408 }
1409 
1410 ExprResult
1411 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1412                                 AssignmentAction Action, bool AllowExplicit,
1413                                 ImplicitConversionSequence& ICS) {
1414   if (checkPlaceholderForOverload(*this, From))
1415     return ExprError();
1416 
1417   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1418   bool AllowObjCWritebackConversion
1419     = getLangOpts().ObjCAutoRefCount &&
1420       (Action == AA_Passing || Action == AA_Sending);
1421   if (getLangOpts().ObjC)
1422     CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1423                                       From->getType(), From);
1424   ICS = ::TryImplicitConversion(*this, From, ToType,
1425                                 /*SuppressUserConversions=*/false,
1426                                 AllowExplicit,
1427                                 /*InOverloadResolution=*/false,
1428                                 /*CStyle=*/false,
1429                                 AllowObjCWritebackConversion,
1430                                 /*AllowObjCConversionOnExplicit=*/false);
1431   return PerformImplicitConversion(From, ToType, ICS, Action);
1432 }
1433 
1434 /// Determine whether the conversion from FromType to ToType is a valid
1435 /// conversion that strips "noexcept" or "noreturn" off the nested function
1436 /// type.
1437 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1438                                 QualType &ResultTy) {
1439   if (Context.hasSameUnqualifiedType(FromType, ToType))
1440     return false;
1441 
1442   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1443   //                    or F(t noexcept) -> F(t)
1444   // where F adds one of the following at most once:
1445   //   - a pointer
1446   //   - a member pointer
1447   //   - a block pointer
1448   // Changes here need matching changes in FindCompositePointerType.
1449   CanQualType CanTo = Context.getCanonicalType(ToType);
1450   CanQualType CanFrom = Context.getCanonicalType(FromType);
1451   Type::TypeClass TyClass = CanTo->getTypeClass();
1452   if (TyClass != CanFrom->getTypeClass()) return false;
1453   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1454     if (TyClass == Type::Pointer) {
1455       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1456       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1457     } else if (TyClass == Type::BlockPointer) {
1458       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1459       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1460     } else if (TyClass == Type::MemberPointer) {
1461       auto ToMPT = CanTo.getAs<MemberPointerType>();
1462       auto FromMPT = CanFrom.getAs<MemberPointerType>();
1463       // A function pointer conversion cannot change the class of the function.
1464       if (ToMPT->getClass() != FromMPT->getClass())
1465         return false;
1466       CanTo = ToMPT->getPointeeType();
1467       CanFrom = FromMPT->getPointeeType();
1468     } else {
1469       return false;
1470     }
1471 
1472     TyClass = CanTo->getTypeClass();
1473     if (TyClass != CanFrom->getTypeClass()) return false;
1474     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1475       return false;
1476   }
1477 
1478   const auto *FromFn = cast<FunctionType>(CanFrom);
1479   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1480 
1481   const auto *ToFn = cast<FunctionType>(CanTo);
1482   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1483 
1484   bool Changed = false;
1485 
1486   // Drop 'noreturn' if not present in target type.
1487   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1488     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1489     Changed = true;
1490   }
1491 
1492   // Drop 'noexcept' if not present in target type.
1493   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1494     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1495     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1496       FromFn = cast<FunctionType>(
1497           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1498                                                    EST_None)
1499                  .getTypePtr());
1500       Changed = true;
1501     }
1502 
1503     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1504     // only if the ExtParameterInfo lists of the two function prototypes can be
1505     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1506     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1507     bool CanUseToFPT, CanUseFromFPT;
1508     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1509                                       CanUseFromFPT, NewParamInfos) &&
1510         CanUseToFPT && !CanUseFromFPT) {
1511       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1512       ExtInfo.ExtParameterInfos =
1513           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1514       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1515                                             FromFPT->getParamTypes(), ExtInfo);
1516       FromFn = QT->getAs<FunctionType>();
1517       Changed = true;
1518     }
1519   }
1520 
1521   if (!Changed)
1522     return false;
1523 
1524   assert(QualType(FromFn, 0).isCanonical());
1525   if (QualType(FromFn, 0) != CanTo) return false;
1526 
1527   ResultTy = ToType;
1528   return true;
1529 }
1530 
1531 /// Determine whether the conversion from FromType to ToType is a valid
1532 /// vector conversion.
1533 ///
1534 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1535 /// conversion.
1536 static bool IsVectorConversion(Sema &S, QualType FromType,
1537                                QualType ToType, ImplicitConversionKind &ICK) {
1538   // We need at least one of these types to be a vector type to have a vector
1539   // conversion.
1540   if (!ToType->isVectorType() && !FromType->isVectorType())
1541     return false;
1542 
1543   // Identical types require no conversions.
1544   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1545     return false;
1546 
1547   // There are no conversions between extended vector types, only identity.
1548   if (ToType->isExtVectorType()) {
1549     // There are no conversions between extended vector types other than the
1550     // identity conversion.
1551     if (FromType->isExtVectorType())
1552       return false;
1553 
1554     // Vector splat from any arithmetic type to a vector.
1555     if (FromType->isArithmeticType()) {
1556       ICK = ICK_Vector_Splat;
1557       return true;
1558     }
1559   }
1560 
1561   // We can perform the conversion between vector types in the following cases:
1562   // 1)vector types are equivalent AltiVec and GCC vector types
1563   // 2)lax vector conversions are permitted and the vector types are of the
1564   //   same size
1565   if (ToType->isVectorType() && FromType->isVectorType()) {
1566     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1567         S.isLaxVectorConversion(FromType, ToType)) {
1568       ICK = ICK_Vector_Conversion;
1569       return true;
1570     }
1571   }
1572 
1573   return false;
1574 }
1575 
1576 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1577                                 bool InOverloadResolution,
1578                                 StandardConversionSequence &SCS,
1579                                 bool CStyle);
1580 
1581 /// IsStandardConversion - Determines whether there is a standard
1582 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1583 /// expression From to the type ToType. Standard conversion sequences
1584 /// only consider non-class types; for conversions that involve class
1585 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1586 /// contain the standard conversion sequence required to perform this
1587 /// conversion and this routine will return true. Otherwise, this
1588 /// routine will return false and the value of SCS is unspecified.
1589 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1590                                  bool InOverloadResolution,
1591                                  StandardConversionSequence &SCS,
1592                                  bool CStyle,
1593                                  bool AllowObjCWritebackConversion) {
1594   QualType FromType = From->getType();
1595 
1596   // Standard conversions (C++ [conv])
1597   SCS.setAsIdentityConversion();
1598   SCS.IncompatibleObjC = false;
1599   SCS.setFromType(FromType);
1600   SCS.CopyConstructor = nullptr;
1601 
1602   // There are no standard conversions for class types in C++, so
1603   // abort early. When overloading in C, however, we do permit them.
1604   if (S.getLangOpts().CPlusPlus &&
1605       (FromType->isRecordType() || ToType->isRecordType()))
1606     return false;
1607 
1608   // The first conversion can be an lvalue-to-rvalue conversion,
1609   // array-to-pointer conversion, or function-to-pointer conversion
1610   // (C++ 4p1).
1611 
1612   if (FromType == S.Context.OverloadTy) {
1613     DeclAccessPair AccessPair;
1614     if (FunctionDecl *Fn
1615           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1616                                                  AccessPair)) {
1617       // We were able to resolve the address of the overloaded function,
1618       // so we can convert to the type of that function.
1619       FromType = Fn->getType();
1620       SCS.setFromType(FromType);
1621 
1622       // we can sometimes resolve &foo<int> regardless of ToType, so check
1623       // if the type matches (identity) or we are converting to bool
1624       if (!S.Context.hasSameUnqualifiedType(
1625                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1626         QualType resultTy;
1627         // if the function type matches except for [[noreturn]], it's ok
1628         if (!S.IsFunctionConversion(FromType,
1629               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1630           // otherwise, only a boolean conversion is standard
1631           if (!ToType->isBooleanType())
1632             return false;
1633       }
1634 
1635       // Check if the "from" expression is taking the address of an overloaded
1636       // function and recompute the FromType accordingly. Take advantage of the
1637       // fact that non-static member functions *must* have such an address-of
1638       // expression.
1639       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1640       if (Method && !Method->isStatic()) {
1641         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1642                "Non-unary operator on non-static member address");
1643         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1644                == UO_AddrOf &&
1645                "Non-address-of operator on non-static member address");
1646         const Type *ClassType
1647           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1648         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1649       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1650         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1651                UO_AddrOf &&
1652                "Non-address-of operator for overloaded function expression");
1653         FromType = S.Context.getPointerType(FromType);
1654       }
1655 
1656       // Check that we've computed the proper type after overload resolution.
1657       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1658       // be calling it from within an NDEBUG block.
1659       assert(S.Context.hasSameType(
1660         FromType,
1661         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1662     } else {
1663       return false;
1664     }
1665   }
1666   // Lvalue-to-rvalue conversion (C++11 4.1):
1667   //   A glvalue (3.10) of a non-function, non-array type T can
1668   //   be converted to a prvalue.
1669   bool argIsLValue = From->isGLValue();
1670   if (argIsLValue &&
1671       !FromType->isFunctionType() && !FromType->isArrayType() &&
1672       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1673     SCS.First = ICK_Lvalue_To_Rvalue;
1674 
1675     // C11 6.3.2.1p2:
1676     //   ... if the lvalue has atomic type, the value has the non-atomic version
1677     //   of the type of the lvalue ...
1678     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1679       FromType = Atomic->getValueType();
1680 
1681     // If T is a non-class type, the type of the rvalue is the
1682     // cv-unqualified version of T. Otherwise, the type of the rvalue
1683     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1684     // just strip the qualifiers because they don't matter.
1685     FromType = FromType.getUnqualifiedType();
1686   } else if (FromType->isArrayType()) {
1687     // Array-to-pointer conversion (C++ 4.2)
1688     SCS.First = ICK_Array_To_Pointer;
1689 
1690     // An lvalue or rvalue of type "array of N T" or "array of unknown
1691     // bound of T" can be converted to an rvalue of type "pointer to
1692     // T" (C++ 4.2p1).
1693     FromType = S.Context.getArrayDecayedType(FromType);
1694 
1695     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1696       // This conversion is deprecated in C++03 (D.4)
1697       SCS.DeprecatedStringLiteralToCharPtr = true;
1698 
1699       // For the purpose of ranking in overload resolution
1700       // (13.3.3.1.1), this conversion is considered an
1701       // array-to-pointer conversion followed by a qualification
1702       // conversion (4.4). (C++ 4.2p2)
1703       SCS.Second = ICK_Identity;
1704       SCS.Third = ICK_Qualification;
1705       SCS.QualificationIncludesObjCLifetime = false;
1706       SCS.setAllToTypes(FromType);
1707       return true;
1708     }
1709   } else if (FromType->isFunctionType() && argIsLValue) {
1710     // Function-to-pointer conversion (C++ 4.3).
1711     SCS.First = ICK_Function_To_Pointer;
1712 
1713     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1714       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1715         if (!S.checkAddressOfFunctionIsAvailable(FD))
1716           return false;
1717 
1718     // An lvalue of function type T can be converted to an rvalue of
1719     // type "pointer to T." The result is a pointer to the
1720     // function. (C++ 4.3p1).
1721     FromType = S.Context.getPointerType(FromType);
1722   } else {
1723     // We don't require any conversions for the first step.
1724     SCS.First = ICK_Identity;
1725   }
1726   SCS.setToType(0, FromType);
1727 
1728   // The second conversion can be an integral promotion, floating
1729   // point promotion, integral conversion, floating point conversion,
1730   // floating-integral conversion, pointer conversion,
1731   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1732   // For overloading in C, this can also be a "compatible-type"
1733   // conversion.
1734   bool IncompatibleObjC = false;
1735   ImplicitConversionKind SecondICK = ICK_Identity;
1736   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1737     // The unqualified versions of the types are the same: there's no
1738     // conversion to do.
1739     SCS.Second = ICK_Identity;
1740   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1741     // Integral promotion (C++ 4.5).
1742     SCS.Second = ICK_Integral_Promotion;
1743     FromType = ToType.getUnqualifiedType();
1744   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1745     // Floating point promotion (C++ 4.6).
1746     SCS.Second = ICK_Floating_Promotion;
1747     FromType = ToType.getUnqualifiedType();
1748   } else if (S.IsComplexPromotion(FromType, ToType)) {
1749     // Complex promotion (Clang extension)
1750     SCS.Second = ICK_Complex_Promotion;
1751     FromType = ToType.getUnqualifiedType();
1752   } else if (ToType->isBooleanType() &&
1753              (FromType->isArithmeticType() ||
1754               FromType->isAnyPointerType() ||
1755               FromType->isBlockPointerType() ||
1756               FromType->isMemberPointerType() ||
1757               FromType->isNullPtrType())) {
1758     // Boolean conversions (C++ 4.12).
1759     SCS.Second = ICK_Boolean_Conversion;
1760     FromType = S.Context.BoolTy;
1761   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1762              ToType->isIntegralType(S.Context)) {
1763     // Integral conversions (C++ 4.7).
1764     SCS.Second = ICK_Integral_Conversion;
1765     FromType = ToType.getUnqualifiedType();
1766   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1767     // Complex conversions (C99 6.3.1.6)
1768     SCS.Second = ICK_Complex_Conversion;
1769     FromType = ToType.getUnqualifiedType();
1770   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1771              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1772     // Complex-real conversions (C99 6.3.1.7)
1773     SCS.Second = ICK_Complex_Real;
1774     FromType = ToType.getUnqualifiedType();
1775   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1776     // FIXME: disable conversions between long double and __float128 if
1777     // their representation is different until there is back end support
1778     // We of course allow this conversion if long double is really double.
1779     if (&S.Context.getFloatTypeSemantics(FromType) !=
1780         &S.Context.getFloatTypeSemantics(ToType)) {
1781       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1782                                     ToType == S.Context.LongDoubleTy) ||
1783                                    (FromType == S.Context.LongDoubleTy &&
1784                                     ToType == S.Context.Float128Ty));
1785       if (Float128AndLongDouble &&
1786           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1787            &llvm::APFloat::PPCDoubleDouble()))
1788         return false;
1789     }
1790     // Floating point conversions (C++ 4.8).
1791     SCS.Second = ICK_Floating_Conversion;
1792     FromType = ToType.getUnqualifiedType();
1793   } else if ((FromType->isRealFloatingType() &&
1794               ToType->isIntegralType(S.Context)) ||
1795              (FromType->isIntegralOrUnscopedEnumerationType() &&
1796               ToType->isRealFloatingType())) {
1797     // Floating-integral conversions (C++ 4.9).
1798     SCS.Second = ICK_Floating_Integral;
1799     FromType = ToType.getUnqualifiedType();
1800   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1801     SCS.Second = ICK_Block_Pointer_Conversion;
1802   } else if (AllowObjCWritebackConversion &&
1803              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1804     SCS.Second = ICK_Writeback_Conversion;
1805   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1806                                    FromType, IncompatibleObjC)) {
1807     // Pointer conversions (C++ 4.10).
1808     SCS.Second = ICK_Pointer_Conversion;
1809     SCS.IncompatibleObjC = IncompatibleObjC;
1810     FromType = FromType.getUnqualifiedType();
1811   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1812                                          InOverloadResolution, FromType)) {
1813     // Pointer to member conversions (4.11).
1814     SCS.Second = ICK_Pointer_Member;
1815   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1816     SCS.Second = SecondICK;
1817     FromType = ToType.getUnqualifiedType();
1818   } else if (!S.getLangOpts().CPlusPlus &&
1819              S.Context.typesAreCompatible(ToType, FromType)) {
1820     // Compatible conversions (Clang extension for C function overloading)
1821     SCS.Second = ICK_Compatible_Conversion;
1822     FromType = ToType.getUnqualifiedType();
1823   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1824                                              InOverloadResolution,
1825                                              SCS, CStyle)) {
1826     SCS.Second = ICK_TransparentUnionConversion;
1827     FromType = ToType;
1828   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1829                                  CStyle)) {
1830     // tryAtomicConversion has updated the standard conversion sequence
1831     // appropriately.
1832     return true;
1833   } else if (ToType->isEventT() &&
1834              From->isIntegerConstantExpr(S.getASTContext()) &&
1835              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1836     SCS.Second = ICK_Zero_Event_Conversion;
1837     FromType = ToType;
1838   } else if (ToType->isQueueT() &&
1839              From->isIntegerConstantExpr(S.getASTContext()) &&
1840              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1841     SCS.Second = ICK_Zero_Queue_Conversion;
1842     FromType = ToType;
1843   } else {
1844     // No second conversion required.
1845     SCS.Second = ICK_Identity;
1846   }
1847   SCS.setToType(1, FromType);
1848 
1849   // The third conversion can be a function pointer conversion or a
1850   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1851   bool ObjCLifetimeConversion;
1852   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1853     // Function pointer conversions (removing 'noexcept') including removal of
1854     // 'noreturn' (Clang extension).
1855     SCS.Third = ICK_Function_Conversion;
1856   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1857                                          ObjCLifetimeConversion)) {
1858     SCS.Third = ICK_Qualification;
1859     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1860     FromType = ToType;
1861   } else {
1862     // No conversion required
1863     SCS.Third = ICK_Identity;
1864   }
1865 
1866   // C++ [over.best.ics]p6:
1867   //   [...] Any difference in top-level cv-qualification is
1868   //   subsumed by the initialization itself and does not constitute
1869   //   a conversion. [...]
1870   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1871   QualType CanonTo = S.Context.getCanonicalType(ToType);
1872   if (CanonFrom.getLocalUnqualifiedType()
1873                                      == CanonTo.getLocalUnqualifiedType() &&
1874       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1875     FromType = ToType;
1876     CanonFrom = CanonTo;
1877   }
1878 
1879   SCS.setToType(2, FromType);
1880 
1881   if (CanonFrom == CanonTo)
1882     return true;
1883 
1884   // If we have not converted the argument type to the parameter type,
1885   // this is a bad conversion sequence, unless we're resolving an overload in C.
1886   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1887     return false;
1888 
1889   ExprResult ER = ExprResult{From};
1890   Sema::AssignConvertType Conv =
1891       S.CheckSingleAssignmentConstraints(ToType, ER,
1892                                          /*Diagnose=*/false,
1893                                          /*DiagnoseCFAudited=*/false,
1894                                          /*ConvertRHS=*/false);
1895   ImplicitConversionKind SecondConv;
1896   switch (Conv) {
1897   case Sema::Compatible:
1898     SecondConv = ICK_C_Only_Conversion;
1899     break;
1900   // For our purposes, discarding qualifiers is just as bad as using an
1901   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1902   // qualifiers, as well.
1903   case Sema::CompatiblePointerDiscardsQualifiers:
1904   case Sema::IncompatiblePointer:
1905   case Sema::IncompatiblePointerSign:
1906     SecondConv = ICK_Incompatible_Pointer_Conversion;
1907     break;
1908   default:
1909     return false;
1910   }
1911 
1912   // First can only be an lvalue conversion, so we pretend that this was the
1913   // second conversion. First should already be valid from earlier in the
1914   // function.
1915   SCS.Second = SecondConv;
1916   SCS.setToType(1, ToType);
1917 
1918   // Third is Identity, because Second should rank us worse than any other
1919   // conversion. This could also be ICK_Qualification, but it's simpler to just
1920   // lump everything in with the second conversion, and we don't gain anything
1921   // from making this ICK_Qualification.
1922   SCS.Third = ICK_Identity;
1923   SCS.setToType(2, ToType);
1924   return true;
1925 }
1926 
1927 static bool
1928 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1929                                      QualType &ToType,
1930                                      bool InOverloadResolution,
1931                                      StandardConversionSequence &SCS,
1932                                      bool CStyle) {
1933 
1934   const RecordType *UT = ToType->getAsUnionType();
1935   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1936     return false;
1937   // The field to initialize within the transparent union.
1938   RecordDecl *UD = UT->getDecl();
1939   // It's compatible if the expression matches any of the fields.
1940   for (const auto *it : UD->fields()) {
1941     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1942                              CStyle, /*ObjCWritebackConversion=*/false)) {
1943       ToType = it->getType();
1944       return true;
1945     }
1946   }
1947   return false;
1948 }
1949 
1950 /// IsIntegralPromotion - Determines whether the conversion from the
1951 /// expression From (whose potentially-adjusted type is FromType) to
1952 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1953 /// sets PromotedType to the promoted type.
1954 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1955   const BuiltinType *To = ToType->getAs<BuiltinType>();
1956   // All integers are built-in.
1957   if (!To) {
1958     return false;
1959   }
1960 
1961   // An rvalue of type char, signed char, unsigned char, short int, or
1962   // unsigned short int can be converted to an rvalue of type int if
1963   // int can represent all the values of the source type; otherwise,
1964   // the source rvalue can be converted to an rvalue of type unsigned
1965   // int (C++ 4.5p1).
1966   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1967       !FromType->isEnumeralType()) {
1968     if (// We can promote any signed, promotable integer type to an int
1969         (FromType->isSignedIntegerType() ||
1970          // We can promote any unsigned integer type whose size is
1971          // less than int to an int.
1972          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1973       return To->getKind() == BuiltinType::Int;
1974     }
1975 
1976     return To->getKind() == BuiltinType::UInt;
1977   }
1978 
1979   // C++11 [conv.prom]p3:
1980   //   A prvalue of an unscoped enumeration type whose underlying type is not
1981   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1982   //   following types that can represent all the values of the enumeration
1983   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1984   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1985   //   long long int. If none of the types in that list can represent all the
1986   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1987   //   type can be converted to an rvalue a prvalue of the extended integer type
1988   //   with lowest integer conversion rank (4.13) greater than the rank of long
1989   //   long in which all the values of the enumeration can be represented. If
1990   //   there are two such extended types, the signed one is chosen.
1991   // C++11 [conv.prom]p4:
1992   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1993   //   can be converted to a prvalue of its underlying type. Moreover, if
1994   //   integral promotion can be applied to its underlying type, a prvalue of an
1995   //   unscoped enumeration type whose underlying type is fixed can also be
1996   //   converted to a prvalue of the promoted underlying type.
1997   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1998     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1999     // provided for a scoped enumeration.
2000     if (FromEnumType->getDecl()->isScoped())
2001       return false;
2002 
2003     // We can perform an integral promotion to the underlying type of the enum,
2004     // even if that's not the promoted type. Note that the check for promoting
2005     // the underlying type is based on the type alone, and does not consider
2006     // the bitfield-ness of the actual source expression.
2007     if (FromEnumType->getDecl()->isFixed()) {
2008       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2009       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2010              IsIntegralPromotion(nullptr, Underlying, ToType);
2011     }
2012 
2013     // We have already pre-calculated the promotion type, so this is trivial.
2014     if (ToType->isIntegerType() &&
2015         isCompleteType(From->getBeginLoc(), FromType))
2016       return Context.hasSameUnqualifiedType(
2017           ToType, FromEnumType->getDecl()->getPromotionType());
2018 
2019     // C++ [conv.prom]p5:
2020     //   If the bit-field has an enumerated type, it is treated as any other
2021     //   value of that type for promotion purposes.
2022     //
2023     // ... so do not fall through into the bit-field checks below in C++.
2024     if (getLangOpts().CPlusPlus)
2025       return false;
2026   }
2027 
2028   // C++0x [conv.prom]p2:
2029   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2030   //   to an rvalue a prvalue of the first of the following types that can
2031   //   represent all the values of its underlying type: int, unsigned int,
2032   //   long int, unsigned long int, long long int, or unsigned long long int.
2033   //   If none of the types in that list can represent all the values of its
2034   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2035   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2036   //   type.
2037   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2038       ToType->isIntegerType()) {
2039     // Determine whether the type we're converting from is signed or
2040     // unsigned.
2041     bool FromIsSigned = FromType->isSignedIntegerType();
2042     uint64_t FromSize = Context.getTypeSize(FromType);
2043 
2044     // The types we'll try to promote to, in the appropriate
2045     // order. Try each of these types.
2046     QualType PromoteTypes[6] = {
2047       Context.IntTy, Context.UnsignedIntTy,
2048       Context.LongTy, Context.UnsignedLongTy ,
2049       Context.LongLongTy, Context.UnsignedLongLongTy
2050     };
2051     for (int Idx = 0; Idx < 6; ++Idx) {
2052       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2053       if (FromSize < ToSize ||
2054           (FromSize == ToSize &&
2055            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2056         // We found the type that we can promote to. If this is the
2057         // type we wanted, we have a promotion. Otherwise, no
2058         // promotion.
2059         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2060       }
2061     }
2062   }
2063 
2064   // An rvalue for an integral bit-field (9.6) can be converted to an
2065   // rvalue of type int if int can represent all the values of the
2066   // bit-field; otherwise, it can be converted to unsigned int if
2067   // unsigned int can represent all the values of the bit-field. If
2068   // the bit-field is larger yet, no integral promotion applies to
2069   // it. If the bit-field has an enumerated type, it is treated as any
2070   // other value of that type for promotion purposes (C++ 4.5p3).
2071   // FIXME: We should delay checking of bit-fields until we actually perform the
2072   // conversion.
2073   //
2074   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2075   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2076   // bit-fields and those whose underlying type is larger than int) for GCC
2077   // compatibility.
2078   if (From) {
2079     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2080       llvm::APSInt BitWidth;
2081       if (FromType->isIntegralType(Context) &&
2082           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2083         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2084         ToSize = Context.getTypeSize(ToType);
2085 
2086         // Are we promoting to an int from a bitfield that fits in an int?
2087         if (BitWidth < ToSize ||
2088             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2089           return To->getKind() == BuiltinType::Int;
2090         }
2091 
2092         // Are we promoting to an unsigned int from an unsigned bitfield
2093         // that fits into an unsigned int?
2094         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2095           return To->getKind() == BuiltinType::UInt;
2096         }
2097 
2098         return false;
2099       }
2100     }
2101   }
2102 
2103   // An rvalue of type bool can be converted to an rvalue of type int,
2104   // with false becoming zero and true becoming one (C++ 4.5p4).
2105   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2106     return true;
2107   }
2108 
2109   return false;
2110 }
2111 
2112 /// IsFloatingPointPromotion - Determines whether the conversion from
2113 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2114 /// returns true and sets PromotedType to the promoted type.
2115 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2116   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2117     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2118       /// An rvalue of type float can be converted to an rvalue of type
2119       /// double. (C++ 4.6p1).
2120       if (FromBuiltin->getKind() == BuiltinType::Float &&
2121           ToBuiltin->getKind() == BuiltinType::Double)
2122         return true;
2123 
2124       // C99 6.3.1.5p1:
2125       //   When a float is promoted to double or long double, or a
2126       //   double is promoted to long double [...].
2127       if (!getLangOpts().CPlusPlus &&
2128           (FromBuiltin->getKind() == BuiltinType::Float ||
2129            FromBuiltin->getKind() == BuiltinType::Double) &&
2130           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2131            ToBuiltin->getKind() == BuiltinType::Float128))
2132         return true;
2133 
2134       // Half can be promoted to float.
2135       if (!getLangOpts().NativeHalfType &&
2136            FromBuiltin->getKind() == BuiltinType::Half &&
2137           ToBuiltin->getKind() == BuiltinType::Float)
2138         return true;
2139     }
2140 
2141   return false;
2142 }
2143 
2144 /// Determine if a conversion is a complex promotion.
2145 ///
2146 /// A complex promotion is defined as a complex -> complex conversion
2147 /// where the conversion between the underlying real types is a
2148 /// floating-point or integral promotion.
2149 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2150   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2151   if (!FromComplex)
2152     return false;
2153 
2154   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2155   if (!ToComplex)
2156     return false;
2157 
2158   return IsFloatingPointPromotion(FromComplex->getElementType(),
2159                                   ToComplex->getElementType()) ||
2160     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2161                         ToComplex->getElementType());
2162 }
2163 
2164 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2165 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2166 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2167 /// if non-empty, will be a pointer to ToType that may or may not have
2168 /// the right set of qualifiers on its pointee.
2169 ///
2170 static QualType
2171 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2172                                    QualType ToPointee, QualType ToType,
2173                                    ASTContext &Context,
2174                                    bool StripObjCLifetime = false) {
2175   assert((FromPtr->getTypeClass() == Type::Pointer ||
2176           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2177          "Invalid similarly-qualified pointer type");
2178 
2179   /// Conversions to 'id' subsume cv-qualifier conversions.
2180   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2181     return ToType.getUnqualifiedType();
2182 
2183   QualType CanonFromPointee
2184     = Context.getCanonicalType(FromPtr->getPointeeType());
2185   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2186   Qualifiers Quals = CanonFromPointee.getQualifiers();
2187 
2188   if (StripObjCLifetime)
2189     Quals.removeObjCLifetime();
2190 
2191   // Exact qualifier match -> return the pointer type we're converting to.
2192   if (CanonToPointee.getLocalQualifiers() == Quals) {
2193     // ToType is exactly what we need. Return it.
2194     if (!ToType.isNull())
2195       return ToType.getUnqualifiedType();
2196 
2197     // Build a pointer to ToPointee. It has the right qualifiers
2198     // already.
2199     if (isa<ObjCObjectPointerType>(ToType))
2200       return Context.getObjCObjectPointerType(ToPointee);
2201     return Context.getPointerType(ToPointee);
2202   }
2203 
2204   // Just build a canonical type that has the right qualifiers.
2205   QualType QualifiedCanonToPointee
2206     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2207 
2208   if (isa<ObjCObjectPointerType>(ToType))
2209     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2210   return Context.getPointerType(QualifiedCanonToPointee);
2211 }
2212 
2213 static bool isNullPointerConstantForConversion(Expr *Expr,
2214                                                bool InOverloadResolution,
2215                                                ASTContext &Context) {
2216   // Handle value-dependent integral null pointer constants correctly.
2217   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2218   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2219       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2220     return !InOverloadResolution;
2221 
2222   return Expr->isNullPointerConstant(Context,
2223                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2224                                         : Expr::NPC_ValueDependentIsNull);
2225 }
2226 
2227 /// IsPointerConversion - Determines whether the conversion of the
2228 /// expression From, which has the (possibly adjusted) type FromType,
2229 /// can be converted to the type ToType via a pointer conversion (C++
2230 /// 4.10). If so, returns true and places the converted type (that
2231 /// might differ from ToType in its cv-qualifiers at some level) into
2232 /// ConvertedType.
2233 ///
2234 /// This routine also supports conversions to and from block pointers
2235 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2236 /// pointers to interfaces. FIXME: Once we've determined the
2237 /// appropriate overloading rules for Objective-C, we may want to
2238 /// split the Objective-C checks into a different routine; however,
2239 /// GCC seems to consider all of these conversions to be pointer
2240 /// conversions, so for now they live here. IncompatibleObjC will be
2241 /// set if the conversion is an allowed Objective-C conversion that
2242 /// should result in a warning.
2243 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2244                                bool InOverloadResolution,
2245                                QualType& ConvertedType,
2246                                bool &IncompatibleObjC) {
2247   IncompatibleObjC = false;
2248   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2249                               IncompatibleObjC))
2250     return true;
2251 
2252   // Conversion from a null pointer constant to any Objective-C pointer type.
2253   if (ToType->isObjCObjectPointerType() &&
2254       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2255     ConvertedType = ToType;
2256     return true;
2257   }
2258 
2259   // Blocks: Block pointers can be converted to void*.
2260   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2261       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2262     ConvertedType = ToType;
2263     return true;
2264   }
2265   // Blocks: A null pointer constant can be converted to a block
2266   // pointer type.
2267   if (ToType->isBlockPointerType() &&
2268       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2269     ConvertedType = ToType;
2270     return true;
2271   }
2272 
2273   // If the left-hand-side is nullptr_t, the right side can be a null
2274   // pointer constant.
2275   if (ToType->isNullPtrType() &&
2276       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2277     ConvertedType = ToType;
2278     return true;
2279   }
2280 
2281   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2282   if (!ToTypePtr)
2283     return false;
2284 
2285   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2286   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2287     ConvertedType = ToType;
2288     return true;
2289   }
2290 
2291   // Beyond this point, both types need to be pointers
2292   // , including objective-c pointers.
2293   QualType ToPointeeType = ToTypePtr->getPointeeType();
2294   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2295       !getLangOpts().ObjCAutoRefCount) {
2296     ConvertedType = BuildSimilarlyQualifiedPointerType(
2297                                       FromType->getAs<ObjCObjectPointerType>(),
2298                                                        ToPointeeType,
2299                                                        ToType, Context);
2300     return true;
2301   }
2302   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2303   if (!FromTypePtr)
2304     return false;
2305 
2306   QualType FromPointeeType = FromTypePtr->getPointeeType();
2307 
2308   // If the unqualified pointee types are the same, this can't be a
2309   // pointer conversion, so don't do all of the work below.
2310   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2311     return false;
2312 
2313   // An rvalue of type "pointer to cv T," where T is an object type,
2314   // can be converted to an rvalue of type "pointer to cv void" (C++
2315   // 4.10p2).
2316   if (FromPointeeType->isIncompleteOrObjectType() &&
2317       ToPointeeType->isVoidType()) {
2318     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2319                                                        ToPointeeType,
2320                                                        ToType, Context,
2321                                                    /*StripObjCLifetime=*/true);
2322     return true;
2323   }
2324 
2325   // MSVC allows implicit function to void* type conversion.
2326   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2327       ToPointeeType->isVoidType()) {
2328     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2329                                                        ToPointeeType,
2330                                                        ToType, Context);
2331     return true;
2332   }
2333 
2334   // When we're overloading in C, we allow a special kind of pointer
2335   // conversion for compatible-but-not-identical pointee types.
2336   if (!getLangOpts().CPlusPlus &&
2337       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2338     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2339                                                        ToPointeeType,
2340                                                        ToType, Context);
2341     return true;
2342   }
2343 
2344   // C++ [conv.ptr]p3:
2345   //
2346   //   An rvalue of type "pointer to cv D," where D is a class type,
2347   //   can be converted to an rvalue of type "pointer to cv B," where
2348   //   B is a base class (clause 10) of D. If B is an inaccessible
2349   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2350   //   necessitates this conversion is ill-formed. The result of the
2351   //   conversion is a pointer to the base class sub-object of the
2352   //   derived class object. The null pointer value is converted to
2353   //   the null pointer value of the destination type.
2354   //
2355   // Note that we do not check for ambiguity or inaccessibility
2356   // here. That is handled by CheckPointerConversion.
2357   if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2358       ToPointeeType->isRecordType() &&
2359       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2360       IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2361     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2362                                                        ToPointeeType,
2363                                                        ToType, Context);
2364     return true;
2365   }
2366 
2367   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2368       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2369     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2370                                                        ToPointeeType,
2371                                                        ToType, Context);
2372     return true;
2373   }
2374 
2375   return false;
2376 }
2377 
2378 /// Adopt the given qualifiers for the given type.
2379 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2380   Qualifiers TQs = T.getQualifiers();
2381 
2382   // Check whether qualifiers already match.
2383   if (TQs == Qs)
2384     return T;
2385 
2386   if (Qs.compatiblyIncludes(TQs))
2387     return Context.getQualifiedType(T, Qs);
2388 
2389   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2390 }
2391 
2392 /// isObjCPointerConversion - Determines whether this is an
2393 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2394 /// with the same arguments and return values.
2395 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2396                                    QualType& ConvertedType,
2397                                    bool &IncompatibleObjC) {
2398   if (!getLangOpts().ObjC)
2399     return false;
2400 
2401   // The set of qualifiers on the type we're converting from.
2402   Qualifiers FromQualifiers = FromType.getQualifiers();
2403 
2404   // First, we handle all conversions on ObjC object pointer types.
2405   const ObjCObjectPointerType* ToObjCPtr =
2406     ToType->getAs<ObjCObjectPointerType>();
2407   const ObjCObjectPointerType *FromObjCPtr =
2408     FromType->getAs<ObjCObjectPointerType>();
2409 
2410   if (ToObjCPtr && FromObjCPtr) {
2411     // If the pointee types are the same (ignoring qualifications),
2412     // then this is not a pointer conversion.
2413     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2414                                        FromObjCPtr->getPointeeType()))
2415       return false;
2416 
2417     // Conversion between Objective-C pointers.
2418     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2419       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2420       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2421       if (getLangOpts().CPlusPlus && LHS && RHS &&
2422           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2423                                                 FromObjCPtr->getPointeeType()))
2424         return false;
2425       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2426                                                    ToObjCPtr->getPointeeType(),
2427                                                          ToType, Context);
2428       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2429       return true;
2430     }
2431 
2432     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2433       // Okay: this is some kind of implicit downcast of Objective-C
2434       // interfaces, which is permitted. However, we're going to
2435       // complain about it.
2436       IncompatibleObjC = true;
2437       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2438                                                    ToObjCPtr->getPointeeType(),
2439                                                          ToType, Context);
2440       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2441       return true;
2442     }
2443   }
2444   // Beyond this point, both types need to be C pointers or block pointers.
2445   QualType ToPointeeType;
2446   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2447     ToPointeeType = ToCPtr->getPointeeType();
2448   else if (const BlockPointerType *ToBlockPtr =
2449             ToType->getAs<BlockPointerType>()) {
2450     // Objective C++: We're able to convert from a pointer to any object
2451     // to a block pointer type.
2452     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2453       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2454       return true;
2455     }
2456     ToPointeeType = ToBlockPtr->getPointeeType();
2457   }
2458   else if (FromType->getAs<BlockPointerType>() &&
2459            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2460     // Objective C++: We're able to convert from a block pointer type to a
2461     // pointer to any object.
2462     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2463     return true;
2464   }
2465   else
2466     return false;
2467 
2468   QualType FromPointeeType;
2469   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2470     FromPointeeType = FromCPtr->getPointeeType();
2471   else if (const BlockPointerType *FromBlockPtr =
2472            FromType->getAs<BlockPointerType>())
2473     FromPointeeType = FromBlockPtr->getPointeeType();
2474   else
2475     return false;
2476 
2477   // If we have pointers to pointers, recursively check whether this
2478   // is an Objective-C conversion.
2479   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2480       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2481                               IncompatibleObjC)) {
2482     // We always complain about this conversion.
2483     IncompatibleObjC = true;
2484     ConvertedType = Context.getPointerType(ConvertedType);
2485     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2486     return true;
2487   }
2488   // Allow conversion of pointee being objective-c pointer to another one;
2489   // as in I* to id.
2490   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2491       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2492       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2493                               IncompatibleObjC)) {
2494 
2495     ConvertedType = Context.getPointerType(ConvertedType);
2496     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2497     return true;
2498   }
2499 
2500   // If we have pointers to functions or blocks, check whether the only
2501   // differences in the argument and result types are in Objective-C
2502   // pointer conversions. If so, we permit the conversion (but
2503   // complain about it).
2504   const FunctionProtoType *FromFunctionType
2505     = FromPointeeType->getAs<FunctionProtoType>();
2506   const FunctionProtoType *ToFunctionType
2507     = ToPointeeType->getAs<FunctionProtoType>();
2508   if (FromFunctionType && ToFunctionType) {
2509     // If the function types are exactly the same, this isn't an
2510     // Objective-C pointer conversion.
2511     if (Context.getCanonicalType(FromPointeeType)
2512           == Context.getCanonicalType(ToPointeeType))
2513       return false;
2514 
2515     // Perform the quick checks that will tell us whether these
2516     // function types are obviously different.
2517     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2518         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2519         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2520       return false;
2521 
2522     bool HasObjCConversion = false;
2523     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2524         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2525       // Okay, the types match exactly. Nothing to do.
2526     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2527                                        ToFunctionType->getReturnType(),
2528                                        ConvertedType, IncompatibleObjC)) {
2529       // Okay, we have an Objective-C pointer conversion.
2530       HasObjCConversion = true;
2531     } else {
2532       // Function types are too different. Abort.
2533       return false;
2534     }
2535 
2536     // Check argument types.
2537     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2538          ArgIdx != NumArgs; ++ArgIdx) {
2539       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2540       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2541       if (Context.getCanonicalType(FromArgType)
2542             == Context.getCanonicalType(ToArgType)) {
2543         // Okay, the types match exactly. Nothing to do.
2544       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2545                                          ConvertedType, IncompatibleObjC)) {
2546         // Okay, we have an Objective-C pointer conversion.
2547         HasObjCConversion = true;
2548       } else {
2549         // Argument types are too different. Abort.
2550         return false;
2551       }
2552     }
2553 
2554     if (HasObjCConversion) {
2555       // We had an Objective-C conversion. Allow this pointer
2556       // conversion, but complain about it.
2557       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2558       IncompatibleObjC = true;
2559       return true;
2560     }
2561   }
2562 
2563   return false;
2564 }
2565 
2566 /// Determine whether this is an Objective-C writeback conversion,
2567 /// used for parameter passing when performing automatic reference counting.
2568 ///
2569 /// \param FromType The type we're converting form.
2570 ///
2571 /// \param ToType The type we're converting to.
2572 ///
2573 /// \param ConvertedType The type that will be produced after applying
2574 /// this conversion.
2575 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2576                                      QualType &ConvertedType) {
2577   if (!getLangOpts().ObjCAutoRefCount ||
2578       Context.hasSameUnqualifiedType(FromType, ToType))
2579     return false;
2580 
2581   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2582   QualType ToPointee;
2583   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2584     ToPointee = ToPointer->getPointeeType();
2585   else
2586     return false;
2587 
2588   Qualifiers ToQuals = ToPointee.getQualifiers();
2589   if (!ToPointee->isObjCLifetimeType() ||
2590       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2591       !ToQuals.withoutObjCLifetime().empty())
2592     return false;
2593 
2594   // Argument must be a pointer to __strong to __weak.
2595   QualType FromPointee;
2596   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2597     FromPointee = FromPointer->getPointeeType();
2598   else
2599     return false;
2600 
2601   Qualifiers FromQuals = FromPointee.getQualifiers();
2602   if (!FromPointee->isObjCLifetimeType() ||
2603       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2604        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2605     return false;
2606 
2607   // Make sure that we have compatible qualifiers.
2608   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2609   if (!ToQuals.compatiblyIncludes(FromQuals))
2610     return false;
2611 
2612   // Remove qualifiers from the pointee type we're converting from; they
2613   // aren't used in the compatibility check belong, and we'll be adding back
2614   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2615   FromPointee = FromPointee.getUnqualifiedType();
2616 
2617   // The unqualified form of the pointee types must be compatible.
2618   ToPointee = ToPointee.getUnqualifiedType();
2619   bool IncompatibleObjC;
2620   if (Context.typesAreCompatible(FromPointee, ToPointee))
2621     FromPointee = ToPointee;
2622   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2623                                     IncompatibleObjC))
2624     return false;
2625 
2626   /// Construct the type we're converting to, which is a pointer to
2627   /// __autoreleasing pointee.
2628   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2629   ConvertedType = Context.getPointerType(FromPointee);
2630   return true;
2631 }
2632 
2633 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2634                                     QualType& ConvertedType) {
2635   QualType ToPointeeType;
2636   if (const BlockPointerType *ToBlockPtr =
2637         ToType->getAs<BlockPointerType>())
2638     ToPointeeType = ToBlockPtr->getPointeeType();
2639   else
2640     return false;
2641 
2642   QualType FromPointeeType;
2643   if (const BlockPointerType *FromBlockPtr =
2644       FromType->getAs<BlockPointerType>())
2645     FromPointeeType = FromBlockPtr->getPointeeType();
2646   else
2647     return false;
2648   // We have pointer to blocks, check whether the only
2649   // differences in the argument and result types are in Objective-C
2650   // pointer conversions. If so, we permit the conversion.
2651 
2652   const FunctionProtoType *FromFunctionType
2653     = FromPointeeType->getAs<FunctionProtoType>();
2654   const FunctionProtoType *ToFunctionType
2655     = ToPointeeType->getAs<FunctionProtoType>();
2656 
2657   if (!FromFunctionType || !ToFunctionType)
2658     return false;
2659 
2660   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2661     return true;
2662 
2663   // Perform the quick checks that will tell us whether these
2664   // function types are obviously different.
2665   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2666       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2667     return false;
2668 
2669   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2670   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2671   if (FromEInfo != ToEInfo)
2672     return false;
2673 
2674   bool IncompatibleObjC = false;
2675   if (Context.hasSameType(FromFunctionType->getReturnType(),
2676                           ToFunctionType->getReturnType())) {
2677     // Okay, the types match exactly. Nothing to do.
2678   } else {
2679     QualType RHS = FromFunctionType->getReturnType();
2680     QualType LHS = ToFunctionType->getReturnType();
2681     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2682         !RHS.hasQualifiers() && LHS.hasQualifiers())
2683        LHS = LHS.getUnqualifiedType();
2684 
2685      if (Context.hasSameType(RHS,LHS)) {
2686        // OK exact match.
2687      } else if (isObjCPointerConversion(RHS, LHS,
2688                                         ConvertedType, IncompatibleObjC)) {
2689      if (IncompatibleObjC)
2690        return false;
2691      // Okay, we have an Objective-C pointer conversion.
2692      }
2693      else
2694        return false;
2695    }
2696 
2697    // Check argument types.
2698    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2699         ArgIdx != NumArgs; ++ArgIdx) {
2700      IncompatibleObjC = false;
2701      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2702      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2703      if (Context.hasSameType(FromArgType, ToArgType)) {
2704        // Okay, the types match exactly. Nothing to do.
2705      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2706                                         ConvertedType, IncompatibleObjC)) {
2707        if (IncompatibleObjC)
2708          return false;
2709        // Okay, we have an Objective-C pointer conversion.
2710      } else
2711        // Argument types are too different. Abort.
2712        return false;
2713    }
2714 
2715    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2716    bool CanUseToFPT, CanUseFromFPT;
2717    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2718                                       CanUseToFPT, CanUseFromFPT,
2719                                       NewParamInfos))
2720      return false;
2721 
2722    ConvertedType = ToType;
2723    return true;
2724 }
2725 
2726 enum {
2727   ft_default,
2728   ft_different_class,
2729   ft_parameter_arity,
2730   ft_parameter_mismatch,
2731   ft_return_type,
2732   ft_qualifer_mismatch,
2733   ft_noexcept
2734 };
2735 
2736 /// Attempts to get the FunctionProtoType from a Type. Handles
2737 /// MemberFunctionPointers properly.
2738 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2739   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2740     return FPT;
2741 
2742   if (auto *MPT = FromType->getAs<MemberPointerType>())
2743     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2744 
2745   return nullptr;
2746 }
2747 
2748 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2749 /// function types.  Catches different number of parameter, mismatch in
2750 /// parameter types, and different return types.
2751 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2752                                       QualType FromType, QualType ToType) {
2753   // If either type is not valid, include no extra info.
2754   if (FromType.isNull() || ToType.isNull()) {
2755     PDiag << ft_default;
2756     return;
2757   }
2758 
2759   // Get the function type from the pointers.
2760   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2761     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2762                             *ToMember = ToType->getAs<MemberPointerType>();
2763     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2764       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2765             << QualType(FromMember->getClass(), 0);
2766       return;
2767     }
2768     FromType = FromMember->getPointeeType();
2769     ToType = ToMember->getPointeeType();
2770   }
2771 
2772   if (FromType->isPointerType())
2773     FromType = FromType->getPointeeType();
2774   if (ToType->isPointerType())
2775     ToType = ToType->getPointeeType();
2776 
2777   // Remove references.
2778   FromType = FromType.getNonReferenceType();
2779   ToType = ToType.getNonReferenceType();
2780 
2781   // Don't print extra info for non-specialized template functions.
2782   if (FromType->isInstantiationDependentType() &&
2783       !FromType->getAs<TemplateSpecializationType>()) {
2784     PDiag << ft_default;
2785     return;
2786   }
2787 
2788   // No extra info for same types.
2789   if (Context.hasSameType(FromType, ToType)) {
2790     PDiag << ft_default;
2791     return;
2792   }
2793 
2794   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2795                           *ToFunction = tryGetFunctionProtoType(ToType);
2796 
2797   // Both types need to be function types.
2798   if (!FromFunction || !ToFunction) {
2799     PDiag << ft_default;
2800     return;
2801   }
2802 
2803   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2804     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2805           << FromFunction->getNumParams();
2806     return;
2807   }
2808 
2809   // Handle different parameter types.
2810   unsigned ArgPos;
2811   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2812     PDiag << ft_parameter_mismatch << ArgPos + 1
2813           << ToFunction->getParamType(ArgPos)
2814           << FromFunction->getParamType(ArgPos);
2815     return;
2816   }
2817 
2818   // Handle different return type.
2819   if (!Context.hasSameType(FromFunction->getReturnType(),
2820                            ToFunction->getReturnType())) {
2821     PDiag << ft_return_type << ToFunction->getReturnType()
2822           << FromFunction->getReturnType();
2823     return;
2824   }
2825 
2826   unsigned FromQuals = FromFunction->getTypeQuals(),
2827            ToQuals = ToFunction->getTypeQuals();
2828   if (FromQuals != ToQuals) {
2829     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2830     return;
2831   }
2832 
2833   // Handle exception specification differences on canonical type (in C++17
2834   // onwards).
2835   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2836           ->isNothrow() !=
2837       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2838           ->isNothrow()) {
2839     PDiag << ft_noexcept;
2840     return;
2841   }
2842 
2843   // Unable to find a difference, so add no extra info.
2844   PDiag << ft_default;
2845 }
2846 
2847 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2848 /// for equality of their argument types. Caller has already checked that
2849 /// they have same number of arguments.  If the parameters are different,
2850 /// ArgPos will have the parameter index of the first different parameter.
2851 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2852                                       const FunctionProtoType *NewType,
2853                                       unsigned *ArgPos) {
2854   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2855                                               N = NewType->param_type_begin(),
2856                                               E = OldType->param_type_end();
2857        O && (O != E); ++O, ++N) {
2858     if (!Context.hasSameType(O->getUnqualifiedType(),
2859                              N->getUnqualifiedType())) {
2860       if (ArgPos)
2861         *ArgPos = O - OldType->param_type_begin();
2862       return false;
2863     }
2864   }
2865   return true;
2866 }
2867 
2868 /// CheckPointerConversion - Check the pointer conversion from the
2869 /// expression From to the type ToType. This routine checks for
2870 /// ambiguous or inaccessible derived-to-base pointer
2871 /// conversions for which IsPointerConversion has already returned
2872 /// true. It returns true and produces a diagnostic if there was an
2873 /// error, or returns false otherwise.
2874 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2875                                   CastKind &Kind,
2876                                   CXXCastPath& BasePath,
2877                                   bool IgnoreBaseAccess,
2878                                   bool Diagnose) {
2879   QualType FromType = From->getType();
2880   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2881 
2882   Kind = CK_BitCast;
2883 
2884   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2885       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2886           Expr::NPCK_ZeroExpression) {
2887     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2888       DiagRuntimeBehavior(From->getExprLoc(), From,
2889                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2890                             << ToType << From->getSourceRange());
2891     else if (!isUnevaluatedContext())
2892       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2893         << ToType << From->getSourceRange();
2894   }
2895   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2896     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2897       QualType FromPointeeType = FromPtrType->getPointeeType(),
2898                ToPointeeType   = ToPtrType->getPointeeType();
2899 
2900       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2901           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2902         // We must have a derived-to-base conversion. Check an
2903         // ambiguous or inaccessible conversion.
2904         unsigned InaccessibleID = 0;
2905         unsigned AmbigiousID = 0;
2906         if (Diagnose) {
2907           InaccessibleID = diag::err_upcast_to_inaccessible_base;
2908           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2909         }
2910         if (CheckDerivedToBaseConversion(
2911                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2912                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2913                 &BasePath, IgnoreBaseAccess))
2914           return true;
2915 
2916         // The conversion was successful.
2917         Kind = CK_DerivedToBase;
2918       }
2919 
2920       if (Diagnose && !IsCStyleOrFunctionalCast &&
2921           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2922         assert(getLangOpts().MSVCCompat &&
2923                "this should only be possible with MSVCCompat!");
2924         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2925             << From->getSourceRange();
2926       }
2927     }
2928   } else if (const ObjCObjectPointerType *ToPtrType =
2929                ToType->getAs<ObjCObjectPointerType>()) {
2930     if (const ObjCObjectPointerType *FromPtrType =
2931           FromType->getAs<ObjCObjectPointerType>()) {
2932       // Objective-C++ conversions are always okay.
2933       // FIXME: We should have a different class of conversions for the
2934       // Objective-C++ implicit conversions.
2935       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2936         return false;
2937     } else if (FromType->isBlockPointerType()) {
2938       Kind = CK_BlockPointerToObjCPointerCast;
2939     } else {
2940       Kind = CK_CPointerToObjCPointerCast;
2941     }
2942   } else if (ToType->isBlockPointerType()) {
2943     if (!FromType->isBlockPointerType())
2944       Kind = CK_AnyPointerToBlockPointerCast;
2945   }
2946 
2947   // We shouldn't fall into this case unless it's valid for other
2948   // reasons.
2949   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2950     Kind = CK_NullToPointer;
2951 
2952   return false;
2953 }
2954 
2955 /// IsMemberPointerConversion - Determines whether the conversion of the
2956 /// expression From, which has the (possibly adjusted) type FromType, can be
2957 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2958 /// If so, returns true and places the converted type (that might differ from
2959 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2960 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2961                                      QualType ToType,
2962                                      bool InOverloadResolution,
2963                                      QualType &ConvertedType) {
2964   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2965   if (!ToTypePtr)
2966     return false;
2967 
2968   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2969   if (From->isNullPointerConstant(Context,
2970                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2971                                         : Expr::NPC_ValueDependentIsNull)) {
2972     ConvertedType = ToType;
2973     return true;
2974   }
2975 
2976   // Otherwise, both types have to be member pointers.
2977   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2978   if (!FromTypePtr)
2979     return false;
2980 
2981   // A pointer to member of B can be converted to a pointer to member of D,
2982   // where D is derived from B (C++ 4.11p2).
2983   QualType FromClass(FromTypePtr->getClass(), 0);
2984   QualType ToClass(ToTypePtr->getClass(), 0);
2985 
2986   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2987       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
2988     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2989                                                  ToClass.getTypePtr());
2990     return true;
2991   }
2992 
2993   return false;
2994 }
2995 
2996 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2997 /// expression From to the type ToType. This routine checks for ambiguous or
2998 /// virtual or inaccessible base-to-derived member pointer conversions
2999 /// for which IsMemberPointerConversion has already returned true. It returns
3000 /// true and produces a diagnostic if there was an error, or returns false
3001 /// otherwise.
3002 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3003                                         CastKind &Kind,
3004                                         CXXCastPath &BasePath,
3005                                         bool IgnoreBaseAccess) {
3006   QualType FromType = From->getType();
3007   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3008   if (!FromPtrType) {
3009     // This must be a null pointer to member pointer conversion
3010     assert(From->isNullPointerConstant(Context,
3011                                        Expr::NPC_ValueDependentIsNull) &&
3012            "Expr must be null pointer constant!");
3013     Kind = CK_NullToMemberPointer;
3014     return false;
3015   }
3016 
3017   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3018   assert(ToPtrType && "No member pointer cast has a target type "
3019                       "that is not a member pointer.");
3020 
3021   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3022   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3023 
3024   // FIXME: What about dependent types?
3025   assert(FromClass->isRecordType() && "Pointer into non-class.");
3026   assert(ToClass->isRecordType() && "Pointer into non-class.");
3027 
3028   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3029                      /*DetectVirtual=*/true);
3030   bool DerivationOkay =
3031       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3032   assert(DerivationOkay &&
3033          "Should not have been called if derivation isn't OK.");
3034   (void)DerivationOkay;
3035 
3036   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3037                                   getUnqualifiedType())) {
3038     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3039     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3040       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3041     return true;
3042   }
3043 
3044   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3045     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3046       << FromClass << ToClass << QualType(VBase, 0)
3047       << From->getSourceRange();
3048     return true;
3049   }
3050 
3051   if (!IgnoreBaseAccess)
3052     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3053                          Paths.front(),
3054                          diag::err_downcast_from_inaccessible_base);
3055 
3056   // Must be a base to derived member conversion.
3057   BuildBasePathArray(Paths, BasePath);
3058   Kind = CK_BaseToDerivedMemberPointer;
3059   return false;
3060 }
3061 
3062 /// Determine whether the lifetime conversion between the two given
3063 /// qualifiers sets is nontrivial.
3064 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3065                                                Qualifiers ToQuals) {
3066   // Converting anything to const __unsafe_unretained is trivial.
3067   if (ToQuals.hasConst() &&
3068       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3069     return false;
3070 
3071   return true;
3072 }
3073 
3074 /// IsQualificationConversion - Determines whether the conversion from
3075 /// an rvalue of type FromType to ToType is a qualification conversion
3076 /// (C++ 4.4).
3077 ///
3078 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3079 /// when the qualification conversion involves a change in the Objective-C
3080 /// object lifetime.
3081 bool
3082 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3083                                 bool CStyle, bool &ObjCLifetimeConversion) {
3084   FromType = Context.getCanonicalType(FromType);
3085   ToType = Context.getCanonicalType(ToType);
3086   ObjCLifetimeConversion = false;
3087 
3088   // If FromType and ToType are the same type, this is not a
3089   // qualification conversion.
3090   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3091     return false;
3092 
3093   // (C++ 4.4p4):
3094   //   A conversion can add cv-qualifiers at levels other than the first
3095   //   in multi-level pointers, subject to the following rules: [...]
3096   bool PreviousToQualsIncludeConst = true;
3097   bool UnwrappedAnyPointer = false;
3098   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3099     // Within each iteration of the loop, we check the qualifiers to
3100     // determine if this still looks like a qualification
3101     // conversion. Then, if all is well, we unwrap one more level of
3102     // pointers or pointers-to-members and do it all again
3103     // until there are no more pointers or pointers-to-members left to
3104     // unwrap.
3105     UnwrappedAnyPointer = true;
3106 
3107     Qualifiers FromQuals = FromType.getQualifiers();
3108     Qualifiers ToQuals = ToType.getQualifiers();
3109 
3110     // Ignore __unaligned qualifier if this type is void.
3111     if (ToType.getUnqualifiedType()->isVoidType())
3112       FromQuals.removeUnaligned();
3113 
3114     // Objective-C ARC:
3115     //   Check Objective-C lifetime conversions.
3116     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3117         UnwrappedAnyPointer) {
3118       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3119         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3120           ObjCLifetimeConversion = true;
3121         FromQuals.removeObjCLifetime();
3122         ToQuals.removeObjCLifetime();
3123       } else {
3124         // Qualification conversions cannot cast between different
3125         // Objective-C lifetime qualifiers.
3126         return false;
3127       }
3128     }
3129 
3130     // Allow addition/removal of GC attributes but not changing GC attributes.
3131     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3132         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3133       FromQuals.removeObjCGCAttr();
3134       ToQuals.removeObjCGCAttr();
3135     }
3136 
3137     //   -- for every j > 0, if const is in cv 1,j then const is in cv
3138     //      2,j, and similarly for volatile.
3139     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3140       return false;
3141 
3142     //   -- if the cv 1,j and cv 2,j are different, then const is in
3143     //      every cv for 0 < k < j.
3144     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3145         && !PreviousToQualsIncludeConst)
3146       return false;
3147 
3148     // Keep track of whether all prior cv-qualifiers in the "to" type
3149     // include const.
3150     PreviousToQualsIncludeConst
3151       = PreviousToQualsIncludeConst && ToQuals.hasConst();
3152   }
3153 
3154   // Allows address space promotion by language rules implemented in
3155   // Type::Qualifiers::isAddressSpaceSupersetOf.
3156   Qualifiers FromQuals = FromType.getQualifiers();
3157   Qualifiers ToQuals = ToType.getQualifiers();
3158   if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) &&
3159       !FromQuals.isAddressSpaceSupersetOf(ToQuals)) {
3160     return false;
3161   }
3162 
3163   // We are left with FromType and ToType being the pointee types
3164   // after unwrapping the original FromType and ToType the same number
3165   // of types. If we unwrapped any pointers, and if FromType and
3166   // ToType have the same unqualified type (since we checked
3167   // qualifiers above), then this is a qualification conversion.
3168   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3169 }
3170 
3171 /// - Determine whether this is a conversion from a scalar type to an
3172 /// atomic type.
3173 ///
3174 /// If successful, updates \c SCS's second and third steps in the conversion
3175 /// sequence to finish the conversion.
3176 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3177                                 bool InOverloadResolution,
3178                                 StandardConversionSequence &SCS,
3179                                 bool CStyle) {
3180   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3181   if (!ToAtomic)
3182     return false;
3183 
3184   StandardConversionSequence InnerSCS;
3185   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3186                             InOverloadResolution, InnerSCS,
3187                             CStyle, /*AllowObjCWritebackConversion=*/false))
3188     return false;
3189 
3190   SCS.Second = InnerSCS.Second;
3191   SCS.setToType(1, InnerSCS.getToType(1));
3192   SCS.Third = InnerSCS.Third;
3193   SCS.QualificationIncludesObjCLifetime
3194     = InnerSCS.QualificationIncludesObjCLifetime;
3195   SCS.setToType(2, InnerSCS.getToType(2));
3196   return true;
3197 }
3198 
3199 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3200                                               CXXConstructorDecl *Constructor,
3201                                               QualType Type) {
3202   const FunctionProtoType *CtorType =
3203       Constructor->getType()->getAs<FunctionProtoType>();
3204   if (CtorType->getNumParams() > 0) {
3205     QualType FirstArg = CtorType->getParamType(0);
3206     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3207       return true;
3208   }
3209   return false;
3210 }
3211 
3212 static OverloadingResult
3213 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3214                                        CXXRecordDecl *To,
3215                                        UserDefinedConversionSequence &User,
3216                                        OverloadCandidateSet &CandidateSet,
3217                                        bool AllowExplicit) {
3218   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3219   for (auto *D : S.LookupConstructors(To)) {
3220     auto Info = getConstructorInfo(D);
3221     if (!Info)
3222       continue;
3223 
3224     bool Usable = !Info.Constructor->isInvalidDecl() &&
3225                   S.isInitListConstructor(Info.Constructor) &&
3226                   (AllowExplicit || !Info.Constructor->isExplicit());
3227     if (Usable) {
3228       // If the first argument is (a reference to) the target type,
3229       // suppress conversions.
3230       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3231           S.Context, Info.Constructor, ToType);
3232       if (Info.ConstructorTmpl)
3233         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3234                                        /*ExplicitArgs*/ nullptr, From,
3235                                        CandidateSet, SuppressUserConversions);
3236       else
3237         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3238                                CandidateSet, SuppressUserConversions);
3239     }
3240   }
3241 
3242   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3243 
3244   OverloadCandidateSet::iterator Best;
3245   switch (auto Result =
3246               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3247   case OR_Deleted:
3248   case OR_Success: {
3249     // Record the standard conversion we used and the conversion function.
3250     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3251     QualType ThisType = Constructor->getThisType(S.Context);
3252     // Initializer lists don't have conversions as such.
3253     User.Before.setAsIdentityConversion();
3254     User.HadMultipleCandidates = HadMultipleCandidates;
3255     User.ConversionFunction = Constructor;
3256     User.FoundConversionFunction = Best->FoundDecl;
3257     User.After.setAsIdentityConversion();
3258     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3259     User.After.setAllToTypes(ToType);
3260     return Result;
3261   }
3262 
3263   case OR_No_Viable_Function:
3264     return OR_No_Viable_Function;
3265   case OR_Ambiguous:
3266     return OR_Ambiguous;
3267   }
3268 
3269   llvm_unreachable("Invalid OverloadResult!");
3270 }
3271 
3272 /// Determines whether there is a user-defined conversion sequence
3273 /// (C++ [over.ics.user]) that converts expression From to the type
3274 /// ToType. If such a conversion exists, User will contain the
3275 /// user-defined conversion sequence that performs such a conversion
3276 /// and this routine will return true. Otherwise, this routine returns
3277 /// false and User is unspecified.
3278 ///
3279 /// \param AllowExplicit  true if the conversion should consider C++0x
3280 /// "explicit" conversion functions as well as non-explicit conversion
3281 /// functions (C++0x [class.conv.fct]p2).
3282 ///
3283 /// \param AllowObjCConversionOnExplicit true if the conversion should
3284 /// allow an extra Objective-C pointer conversion on uses of explicit
3285 /// constructors. Requires \c AllowExplicit to also be set.
3286 static OverloadingResult
3287 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3288                         UserDefinedConversionSequence &User,
3289                         OverloadCandidateSet &CandidateSet,
3290                         bool AllowExplicit,
3291                         bool AllowObjCConversionOnExplicit) {
3292   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3293   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3294 
3295   // Whether we will only visit constructors.
3296   bool ConstructorsOnly = false;
3297 
3298   // If the type we are conversion to is a class type, enumerate its
3299   // constructors.
3300   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3301     // C++ [over.match.ctor]p1:
3302     //   When objects of class type are direct-initialized (8.5), or
3303     //   copy-initialized from an expression of the same or a
3304     //   derived class type (8.5), overload resolution selects the
3305     //   constructor. [...] For copy-initialization, the candidate
3306     //   functions are all the converting constructors (12.3.1) of
3307     //   that class. The argument list is the expression-list within
3308     //   the parentheses of the initializer.
3309     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3310         (From->getType()->getAs<RecordType>() &&
3311          S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3312       ConstructorsOnly = true;
3313 
3314     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3315       // We're not going to find any constructors.
3316     } else if (CXXRecordDecl *ToRecordDecl
3317                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3318 
3319       Expr **Args = &From;
3320       unsigned NumArgs = 1;
3321       bool ListInitializing = false;
3322       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3323         // But first, see if there is an init-list-constructor that will work.
3324         OverloadingResult Result = IsInitializerListConstructorConversion(
3325             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3326         if (Result != OR_No_Viable_Function)
3327           return Result;
3328         // Never mind.
3329         CandidateSet.clear(
3330             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3331 
3332         // If we're list-initializing, we pass the individual elements as
3333         // arguments, not the entire list.
3334         Args = InitList->getInits();
3335         NumArgs = InitList->getNumInits();
3336         ListInitializing = true;
3337       }
3338 
3339       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3340         auto Info = getConstructorInfo(D);
3341         if (!Info)
3342           continue;
3343 
3344         bool Usable = !Info.Constructor->isInvalidDecl();
3345         if (ListInitializing)
3346           Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3347         else
3348           Usable = Usable &&
3349                    Info.Constructor->isConvertingConstructor(AllowExplicit);
3350         if (Usable) {
3351           bool SuppressUserConversions = !ConstructorsOnly;
3352           if (SuppressUserConversions && ListInitializing) {
3353             SuppressUserConversions = false;
3354             if (NumArgs == 1) {
3355               // If the first argument is (a reference to) the target type,
3356               // suppress conversions.
3357               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3358                   S.Context, Info.Constructor, ToType);
3359             }
3360           }
3361           if (Info.ConstructorTmpl)
3362             S.AddTemplateOverloadCandidate(
3363                 Info.ConstructorTmpl, Info.FoundDecl,
3364                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3365                 CandidateSet, SuppressUserConversions);
3366           else
3367             // Allow one user-defined conversion when user specifies a
3368             // From->ToType conversion via an static cast (c-style, etc).
3369             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3370                                    llvm::makeArrayRef(Args, NumArgs),
3371                                    CandidateSet, SuppressUserConversions);
3372         }
3373       }
3374     }
3375   }
3376 
3377   // Enumerate conversion functions, if we're allowed to.
3378   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3379   } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3380     // No conversion functions from incomplete types.
3381   } else if (const RecordType *FromRecordType =
3382                  From->getType()->getAs<RecordType>()) {
3383     if (CXXRecordDecl *FromRecordDecl
3384          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3385       // Add all of the conversion functions as candidates.
3386       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3387       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3388         DeclAccessPair FoundDecl = I.getPair();
3389         NamedDecl *D = FoundDecl.getDecl();
3390         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3391         if (isa<UsingShadowDecl>(D))
3392           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3393 
3394         CXXConversionDecl *Conv;
3395         FunctionTemplateDecl *ConvTemplate;
3396         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3397           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3398         else
3399           Conv = cast<CXXConversionDecl>(D);
3400 
3401         if (AllowExplicit || !Conv->isExplicit()) {
3402           if (ConvTemplate)
3403             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3404                                              ActingContext, From, ToType,
3405                                              CandidateSet,
3406                                              AllowObjCConversionOnExplicit);
3407           else
3408             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3409                                      From, ToType, CandidateSet,
3410                                      AllowObjCConversionOnExplicit);
3411         }
3412       }
3413     }
3414   }
3415 
3416   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3417 
3418   OverloadCandidateSet::iterator Best;
3419   switch (auto Result =
3420               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3421   case OR_Success:
3422   case OR_Deleted:
3423     // Record the standard conversion we used and the conversion function.
3424     if (CXXConstructorDecl *Constructor
3425           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3426       // C++ [over.ics.user]p1:
3427       //   If the user-defined conversion is specified by a
3428       //   constructor (12.3.1), the initial standard conversion
3429       //   sequence converts the source type to the type required by
3430       //   the argument of the constructor.
3431       //
3432       QualType ThisType = Constructor->getThisType(S.Context);
3433       if (isa<InitListExpr>(From)) {
3434         // Initializer lists don't have conversions as such.
3435         User.Before.setAsIdentityConversion();
3436       } else {
3437         if (Best->Conversions[0].isEllipsis())
3438           User.EllipsisConversion = true;
3439         else {
3440           User.Before = Best->Conversions[0].Standard;
3441           User.EllipsisConversion = false;
3442         }
3443       }
3444       User.HadMultipleCandidates = HadMultipleCandidates;
3445       User.ConversionFunction = Constructor;
3446       User.FoundConversionFunction = Best->FoundDecl;
3447       User.After.setAsIdentityConversion();
3448       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3449       User.After.setAllToTypes(ToType);
3450       return Result;
3451     }
3452     if (CXXConversionDecl *Conversion
3453                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3454       // C++ [over.ics.user]p1:
3455       //
3456       //   [...] If the user-defined conversion is specified by a
3457       //   conversion function (12.3.2), the initial standard
3458       //   conversion sequence converts the source type to the
3459       //   implicit object parameter of the conversion function.
3460       User.Before = Best->Conversions[0].Standard;
3461       User.HadMultipleCandidates = HadMultipleCandidates;
3462       User.ConversionFunction = Conversion;
3463       User.FoundConversionFunction = Best->FoundDecl;
3464       User.EllipsisConversion = false;
3465 
3466       // C++ [over.ics.user]p2:
3467       //   The second standard conversion sequence converts the
3468       //   result of the user-defined conversion to the target type
3469       //   for the sequence. Since an implicit conversion sequence
3470       //   is an initialization, the special rules for
3471       //   initialization by user-defined conversion apply when
3472       //   selecting the best user-defined conversion for a
3473       //   user-defined conversion sequence (see 13.3.3 and
3474       //   13.3.3.1).
3475       User.After = Best->FinalConversion;
3476       return Result;
3477     }
3478     llvm_unreachable("Not a constructor or conversion function?");
3479 
3480   case OR_No_Viable_Function:
3481     return OR_No_Viable_Function;
3482 
3483   case OR_Ambiguous:
3484     return OR_Ambiguous;
3485   }
3486 
3487   llvm_unreachable("Invalid OverloadResult!");
3488 }
3489 
3490 bool
3491 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3492   ImplicitConversionSequence ICS;
3493   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3494                                     OverloadCandidateSet::CSK_Normal);
3495   OverloadingResult OvResult =
3496     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3497                             CandidateSet, false, false);
3498   if (OvResult == OR_Ambiguous)
3499     Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3500         << From->getType() << ToType << From->getSourceRange();
3501   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3502     if (!RequireCompleteType(From->getBeginLoc(), ToType,
3503                              diag::err_typecheck_nonviable_condition_incomplete,
3504                              From->getType(), From->getSourceRange()))
3505       Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3506           << false << From->getType() << From->getSourceRange() << ToType;
3507   } else
3508     return false;
3509   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3510   return true;
3511 }
3512 
3513 /// Compare the user-defined conversion functions or constructors
3514 /// of two user-defined conversion sequences to determine whether any ordering
3515 /// is possible.
3516 static ImplicitConversionSequence::CompareKind
3517 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3518                            FunctionDecl *Function2) {
3519   if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11)
3520     return ImplicitConversionSequence::Indistinguishable;
3521 
3522   // Objective-C++:
3523   //   If both conversion functions are implicitly-declared conversions from
3524   //   a lambda closure type to a function pointer and a block pointer,
3525   //   respectively, always prefer the conversion to a function pointer,
3526   //   because the function pointer is more lightweight and is more likely
3527   //   to keep code working.
3528   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3529   if (!Conv1)
3530     return ImplicitConversionSequence::Indistinguishable;
3531 
3532   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3533   if (!Conv2)
3534     return ImplicitConversionSequence::Indistinguishable;
3535 
3536   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3537     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3538     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3539     if (Block1 != Block2)
3540       return Block1 ? ImplicitConversionSequence::Worse
3541                     : ImplicitConversionSequence::Better;
3542   }
3543 
3544   return ImplicitConversionSequence::Indistinguishable;
3545 }
3546 
3547 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3548     const ImplicitConversionSequence &ICS) {
3549   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3550          (ICS.isUserDefined() &&
3551           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3552 }
3553 
3554 /// CompareImplicitConversionSequences - Compare two implicit
3555 /// conversion sequences to determine whether one is better than the
3556 /// other or if they are indistinguishable (C++ 13.3.3.2).
3557 static ImplicitConversionSequence::CompareKind
3558 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3559                                    const ImplicitConversionSequence& ICS1,
3560                                    const ImplicitConversionSequence& ICS2)
3561 {
3562   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3563   // conversion sequences (as defined in 13.3.3.1)
3564   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3565   //      conversion sequence than a user-defined conversion sequence or
3566   //      an ellipsis conversion sequence, and
3567   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3568   //      conversion sequence than an ellipsis conversion sequence
3569   //      (13.3.3.1.3).
3570   //
3571   // C++0x [over.best.ics]p10:
3572   //   For the purpose of ranking implicit conversion sequences as
3573   //   described in 13.3.3.2, the ambiguous conversion sequence is
3574   //   treated as a user-defined sequence that is indistinguishable
3575   //   from any other user-defined conversion sequence.
3576 
3577   // String literal to 'char *' conversion has been deprecated in C++03. It has
3578   // been removed from C++11. We still accept this conversion, if it happens at
3579   // the best viable function. Otherwise, this conversion is considered worse
3580   // than ellipsis conversion. Consider this as an extension; this is not in the
3581   // standard. For example:
3582   //
3583   // int &f(...);    // #1
3584   // void f(char*);  // #2
3585   // void g() { int &r = f("foo"); }
3586   //
3587   // In C++03, we pick #2 as the best viable function.
3588   // In C++11, we pick #1 as the best viable function, because ellipsis
3589   // conversion is better than string-literal to char* conversion (since there
3590   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3591   // convert arguments, #2 would be the best viable function in C++11.
3592   // If the best viable function has this conversion, a warning will be issued
3593   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3594 
3595   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3596       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3597       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3598     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3599                ? ImplicitConversionSequence::Worse
3600                : ImplicitConversionSequence::Better;
3601 
3602   if (ICS1.getKindRank() < ICS2.getKindRank())
3603     return ImplicitConversionSequence::Better;
3604   if (ICS2.getKindRank() < ICS1.getKindRank())
3605     return ImplicitConversionSequence::Worse;
3606 
3607   // The following checks require both conversion sequences to be of
3608   // the same kind.
3609   if (ICS1.getKind() != ICS2.getKind())
3610     return ImplicitConversionSequence::Indistinguishable;
3611 
3612   ImplicitConversionSequence::CompareKind Result =
3613       ImplicitConversionSequence::Indistinguishable;
3614 
3615   // Two implicit conversion sequences of the same form are
3616   // indistinguishable conversion sequences unless one of the
3617   // following rules apply: (C++ 13.3.3.2p3):
3618 
3619   // List-initialization sequence L1 is a better conversion sequence than
3620   // list-initialization sequence L2 if:
3621   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3622   //   if not that,
3623   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3624   //   and N1 is smaller than N2.,
3625   // even if one of the other rules in this paragraph would otherwise apply.
3626   if (!ICS1.isBad()) {
3627     if (ICS1.isStdInitializerListElement() &&
3628         !ICS2.isStdInitializerListElement())
3629       return ImplicitConversionSequence::Better;
3630     if (!ICS1.isStdInitializerListElement() &&
3631         ICS2.isStdInitializerListElement())
3632       return ImplicitConversionSequence::Worse;
3633   }
3634 
3635   if (ICS1.isStandard())
3636     // Standard conversion sequence S1 is a better conversion sequence than
3637     // standard conversion sequence S2 if [...]
3638     Result = CompareStandardConversionSequences(S, Loc,
3639                                                 ICS1.Standard, ICS2.Standard);
3640   else if (ICS1.isUserDefined()) {
3641     // User-defined conversion sequence U1 is a better conversion
3642     // sequence than another user-defined conversion sequence U2 if
3643     // they contain the same user-defined conversion function or
3644     // constructor and if the second standard conversion sequence of
3645     // U1 is better than the second standard conversion sequence of
3646     // U2 (C++ 13.3.3.2p3).
3647     if (ICS1.UserDefined.ConversionFunction ==
3648           ICS2.UserDefined.ConversionFunction)
3649       Result = CompareStandardConversionSequences(S, Loc,
3650                                                   ICS1.UserDefined.After,
3651                                                   ICS2.UserDefined.After);
3652     else
3653       Result = compareConversionFunctions(S,
3654                                           ICS1.UserDefined.ConversionFunction,
3655                                           ICS2.UserDefined.ConversionFunction);
3656   }
3657 
3658   return Result;
3659 }
3660 
3661 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3662 // determine if one is a proper subset of the other.
3663 static ImplicitConversionSequence::CompareKind
3664 compareStandardConversionSubsets(ASTContext &Context,
3665                                  const StandardConversionSequence& SCS1,
3666                                  const StandardConversionSequence& SCS2) {
3667   ImplicitConversionSequence::CompareKind Result
3668     = ImplicitConversionSequence::Indistinguishable;
3669 
3670   // the identity conversion sequence is considered to be a subsequence of
3671   // any non-identity conversion sequence
3672   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3673     return ImplicitConversionSequence::Better;
3674   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3675     return ImplicitConversionSequence::Worse;
3676 
3677   if (SCS1.Second != SCS2.Second) {
3678     if (SCS1.Second == ICK_Identity)
3679       Result = ImplicitConversionSequence::Better;
3680     else if (SCS2.Second == ICK_Identity)
3681       Result = ImplicitConversionSequence::Worse;
3682     else
3683       return ImplicitConversionSequence::Indistinguishable;
3684   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3685     return ImplicitConversionSequence::Indistinguishable;
3686 
3687   if (SCS1.Third == SCS2.Third) {
3688     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3689                              : ImplicitConversionSequence::Indistinguishable;
3690   }
3691 
3692   if (SCS1.Third == ICK_Identity)
3693     return Result == ImplicitConversionSequence::Worse
3694              ? ImplicitConversionSequence::Indistinguishable
3695              : ImplicitConversionSequence::Better;
3696 
3697   if (SCS2.Third == ICK_Identity)
3698     return Result == ImplicitConversionSequence::Better
3699              ? ImplicitConversionSequence::Indistinguishable
3700              : ImplicitConversionSequence::Worse;
3701 
3702   return ImplicitConversionSequence::Indistinguishable;
3703 }
3704 
3705 /// Determine whether one of the given reference bindings is better
3706 /// than the other based on what kind of bindings they are.
3707 static bool
3708 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3709                              const StandardConversionSequence &SCS2) {
3710   // C++0x [over.ics.rank]p3b4:
3711   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3712   //      implicit object parameter of a non-static member function declared
3713   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3714   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3715   //      lvalue reference to a function lvalue and S2 binds an rvalue
3716   //      reference*.
3717   //
3718   // FIXME: Rvalue references. We're going rogue with the above edits,
3719   // because the semantics in the current C++0x working paper (N3225 at the
3720   // time of this writing) break the standard definition of std::forward
3721   // and std::reference_wrapper when dealing with references to functions.
3722   // Proposed wording changes submitted to CWG for consideration.
3723   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3724       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3725     return false;
3726 
3727   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3728           SCS2.IsLvalueReference) ||
3729          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3730           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3731 }
3732 
3733 /// CompareStandardConversionSequences - Compare two standard
3734 /// conversion sequences to determine whether one is better than the
3735 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3736 static ImplicitConversionSequence::CompareKind
3737 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3738                                    const StandardConversionSequence& SCS1,
3739                                    const StandardConversionSequence& SCS2)
3740 {
3741   // Standard conversion sequence S1 is a better conversion sequence
3742   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3743 
3744   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3745   //     sequences in the canonical form defined by 13.3.3.1.1,
3746   //     excluding any Lvalue Transformation; the identity conversion
3747   //     sequence is considered to be a subsequence of any
3748   //     non-identity conversion sequence) or, if not that,
3749   if (ImplicitConversionSequence::CompareKind CK
3750         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3751     return CK;
3752 
3753   //  -- the rank of S1 is better than the rank of S2 (by the rules
3754   //     defined below), or, if not that,
3755   ImplicitConversionRank Rank1 = SCS1.getRank();
3756   ImplicitConversionRank Rank2 = SCS2.getRank();
3757   if (Rank1 < Rank2)
3758     return ImplicitConversionSequence::Better;
3759   else if (Rank2 < Rank1)
3760     return ImplicitConversionSequence::Worse;
3761 
3762   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3763   // are indistinguishable unless one of the following rules
3764   // applies:
3765 
3766   //   A conversion that is not a conversion of a pointer, or
3767   //   pointer to member, to bool is better than another conversion
3768   //   that is such a conversion.
3769   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3770     return SCS2.isPointerConversionToBool()
3771              ? ImplicitConversionSequence::Better
3772              : ImplicitConversionSequence::Worse;
3773 
3774   // C++ [over.ics.rank]p4b2:
3775   //
3776   //   If class B is derived directly or indirectly from class A,
3777   //   conversion of B* to A* is better than conversion of B* to
3778   //   void*, and conversion of A* to void* is better than conversion
3779   //   of B* to void*.
3780   bool SCS1ConvertsToVoid
3781     = SCS1.isPointerConversionToVoidPointer(S.Context);
3782   bool SCS2ConvertsToVoid
3783     = SCS2.isPointerConversionToVoidPointer(S.Context);
3784   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3785     // Exactly one of the conversion sequences is a conversion to
3786     // a void pointer; it's the worse conversion.
3787     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3788                               : ImplicitConversionSequence::Worse;
3789   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3790     // Neither conversion sequence converts to a void pointer; compare
3791     // their derived-to-base conversions.
3792     if (ImplicitConversionSequence::CompareKind DerivedCK
3793           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3794       return DerivedCK;
3795   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3796              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3797     // Both conversion sequences are conversions to void
3798     // pointers. Compare the source types to determine if there's an
3799     // inheritance relationship in their sources.
3800     QualType FromType1 = SCS1.getFromType();
3801     QualType FromType2 = SCS2.getFromType();
3802 
3803     // Adjust the types we're converting from via the array-to-pointer
3804     // conversion, if we need to.
3805     if (SCS1.First == ICK_Array_To_Pointer)
3806       FromType1 = S.Context.getArrayDecayedType(FromType1);
3807     if (SCS2.First == ICK_Array_To_Pointer)
3808       FromType2 = S.Context.getArrayDecayedType(FromType2);
3809 
3810     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3811     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3812 
3813     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3814       return ImplicitConversionSequence::Better;
3815     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3816       return ImplicitConversionSequence::Worse;
3817 
3818     // Objective-C++: If one interface is more specific than the
3819     // other, it is the better one.
3820     const ObjCObjectPointerType* FromObjCPtr1
3821       = FromType1->getAs<ObjCObjectPointerType>();
3822     const ObjCObjectPointerType* FromObjCPtr2
3823       = FromType2->getAs<ObjCObjectPointerType>();
3824     if (FromObjCPtr1 && FromObjCPtr2) {
3825       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3826                                                           FromObjCPtr2);
3827       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3828                                                            FromObjCPtr1);
3829       if (AssignLeft != AssignRight) {
3830         return AssignLeft? ImplicitConversionSequence::Better
3831                          : ImplicitConversionSequence::Worse;
3832       }
3833     }
3834   }
3835 
3836   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3837   // bullet 3).
3838   if (ImplicitConversionSequence::CompareKind QualCK
3839         = CompareQualificationConversions(S, SCS1, SCS2))
3840     return QualCK;
3841 
3842   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3843     // Check for a better reference binding based on the kind of bindings.
3844     if (isBetterReferenceBindingKind(SCS1, SCS2))
3845       return ImplicitConversionSequence::Better;
3846     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3847       return ImplicitConversionSequence::Worse;
3848 
3849     // C++ [over.ics.rank]p3b4:
3850     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3851     //      which the references refer are the same type except for
3852     //      top-level cv-qualifiers, and the type to which the reference
3853     //      initialized by S2 refers is more cv-qualified than the type
3854     //      to which the reference initialized by S1 refers.
3855     QualType T1 = SCS1.getToType(2);
3856     QualType T2 = SCS2.getToType(2);
3857     T1 = S.Context.getCanonicalType(T1);
3858     T2 = S.Context.getCanonicalType(T2);
3859     Qualifiers T1Quals, T2Quals;
3860     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3861     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3862     if (UnqualT1 == UnqualT2) {
3863       // Objective-C++ ARC: If the references refer to objects with different
3864       // lifetimes, prefer bindings that don't change lifetime.
3865       if (SCS1.ObjCLifetimeConversionBinding !=
3866                                           SCS2.ObjCLifetimeConversionBinding) {
3867         return SCS1.ObjCLifetimeConversionBinding
3868                                            ? ImplicitConversionSequence::Worse
3869                                            : ImplicitConversionSequence::Better;
3870       }
3871 
3872       // If the type is an array type, promote the element qualifiers to the
3873       // type for comparison.
3874       if (isa<ArrayType>(T1) && T1Quals)
3875         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3876       if (isa<ArrayType>(T2) && T2Quals)
3877         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3878       if (T2.isMoreQualifiedThan(T1))
3879         return ImplicitConversionSequence::Better;
3880       else if (T1.isMoreQualifiedThan(T2))
3881         return ImplicitConversionSequence::Worse;
3882     }
3883   }
3884 
3885   // In Microsoft mode, prefer an integral conversion to a
3886   // floating-to-integral conversion if the integral conversion
3887   // is between types of the same size.
3888   // For example:
3889   // void f(float);
3890   // void f(int);
3891   // int main {
3892   //    long a;
3893   //    f(a);
3894   // }
3895   // Here, MSVC will call f(int) instead of generating a compile error
3896   // as clang will do in standard mode.
3897   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3898       SCS2.Second == ICK_Floating_Integral &&
3899       S.Context.getTypeSize(SCS1.getFromType()) ==
3900           S.Context.getTypeSize(SCS1.getToType(2)))
3901     return ImplicitConversionSequence::Better;
3902 
3903   // Prefer a compatible vector conversion over a lax vector conversion
3904   // For example:
3905   //
3906   // typedef float __v4sf __attribute__((__vector_size__(16)));
3907   // void f(vector float);
3908   // void f(vector signed int);
3909   // int main() {
3910   //   __v4sf a;
3911   //   f(a);
3912   // }
3913   // Here, we'd like to choose f(vector float) and not
3914   // report an ambiguous call error
3915   if (SCS1.Second == ICK_Vector_Conversion &&
3916       SCS2.Second == ICK_Vector_Conversion) {
3917     bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
3918         SCS1.getFromType(), SCS1.getToType(2));
3919     bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
3920         SCS2.getFromType(), SCS2.getToType(2));
3921 
3922     if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
3923       return SCS1IsCompatibleVectorConversion
3924                  ? ImplicitConversionSequence::Better
3925                  : ImplicitConversionSequence::Worse;
3926   }
3927 
3928   return ImplicitConversionSequence::Indistinguishable;
3929 }
3930 
3931 /// CompareQualificationConversions - Compares two standard conversion
3932 /// sequences to determine whether they can be ranked based on their
3933 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3934 static ImplicitConversionSequence::CompareKind
3935 CompareQualificationConversions(Sema &S,
3936                                 const StandardConversionSequence& SCS1,
3937                                 const StandardConversionSequence& SCS2) {
3938   // C++ 13.3.3.2p3:
3939   //  -- S1 and S2 differ only in their qualification conversion and
3940   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3941   //     cv-qualification signature of type T1 is a proper subset of
3942   //     the cv-qualification signature of type T2, and S1 is not the
3943   //     deprecated string literal array-to-pointer conversion (4.2).
3944   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3945       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3946     return ImplicitConversionSequence::Indistinguishable;
3947 
3948   // FIXME: the example in the standard doesn't use a qualification
3949   // conversion (!)
3950   QualType T1 = SCS1.getToType(2);
3951   QualType T2 = SCS2.getToType(2);
3952   T1 = S.Context.getCanonicalType(T1);
3953   T2 = S.Context.getCanonicalType(T2);
3954   Qualifiers T1Quals, T2Quals;
3955   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3956   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3957 
3958   // If the types are the same, we won't learn anything by unwrapped
3959   // them.
3960   if (UnqualT1 == UnqualT2)
3961     return ImplicitConversionSequence::Indistinguishable;
3962 
3963   // If the type is an array type, promote the element qualifiers to the type
3964   // for comparison.
3965   if (isa<ArrayType>(T1) && T1Quals)
3966     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3967   if (isa<ArrayType>(T2) && T2Quals)
3968     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3969 
3970   ImplicitConversionSequence::CompareKind Result
3971     = ImplicitConversionSequence::Indistinguishable;
3972 
3973   // Objective-C++ ARC:
3974   //   Prefer qualification conversions not involving a change in lifetime
3975   //   to qualification conversions that do not change lifetime.
3976   if (SCS1.QualificationIncludesObjCLifetime !=
3977                                       SCS2.QualificationIncludesObjCLifetime) {
3978     Result = SCS1.QualificationIncludesObjCLifetime
3979                ? ImplicitConversionSequence::Worse
3980                : ImplicitConversionSequence::Better;
3981   }
3982 
3983   while (S.Context.UnwrapSimilarTypes(T1, T2)) {
3984     // Within each iteration of the loop, we check the qualifiers to
3985     // determine if this still looks like a qualification
3986     // conversion. Then, if all is well, we unwrap one more level of
3987     // pointers or pointers-to-members and do it all again
3988     // until there are no more pointers or pointers-to-members left
3989     // to unwrap. This essentially mimics what
3990     // IsQualificationConversion does, but here we're checking for a
3991     // strict subset of qualifiers.
3992     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3993       // The qualifiers are the same, so this doesn't tell us anything
3994       // about how the sequences rank.
3995       ;
3996     else if (T2.isMoreQualifiedThan(T1)) {
3997       // T1 has fewer qualifiers, so it could be the better sequence.
3998       if (Result == ImplicitConversionSequence::Worse)
3999         // Neither has qualifiers that are a subset of the other's
4000         // qualifiers.
4001         return ImplicitConversionSequence::Indistinguishable;
4002 
4003       Result = ImplicitConversionSequence::Better;
4004     } else if (T1.isMoreQualifiedThan(T2)) {
4005       // T2 has fewer qualifiers, so it could be the better sequence.
4006       if (Result == ImplicitConversionSequence::Better)
4007         // Neither has qualifiers that are a subset of the other's
4008         // qualifiers.
4009         return ImplicitConversionSequence::Indistinguishable;
4010 
4011       Result = ImplicitConversionSequence::Worse;
4012     } else {
4013       // Qualifiers are disjoint.
4014       return ImplicitConversionSequence::Indistinguishable;
4015     }
4016 
4017     // If the types after this point are equivalent, we're done.
4018     if (S.Context.hasSameUnqualifiedType(T1, T2))
4019       break;
4020   }
4021 
4022   // Check that the winning standard conversion sequence isn't using
4023   // the deprecated string literal array to pointer conversion.
4024   switch (Result) {
4025   case ImplicitConversionSequence::Better:
4026     if (SCS1.DeprecatedStringLiteralToCharPtr)
4027       Result = ImplicitConversionSequence::Indistinguishable;
4028     break;
4029 
4030   case ImplicitConversionSequence::Indistinguishable:
4031     break;
4032 
4033   case ImplicitConversionSequence::Worse:
4034     if (SCS2.DeprecatedStringLiteralToCharPtr)
4035       Result = ImplicitConversionSequence::Indistinguishable;
4036     break;
4037   }
4038 
4039   return Result;
4040 }
4041 
4042 /// CompareDerivedToBaseConversions - Compares two standard conversion
4043 /// sequences to determine whether they can be ranked based on their
4044 /// various kinds of derived-to-base conversions (C++
4045 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4046 /// conversions between Objective-C interface types.
4047 static ImplicitConversionSequence::CompareKind
4048 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4049                                 const StandardConversionSequence& SCS1,
4050                                 const StandardConversionSequence& SCS2) {
4051   QualType FromType1 = SCS1.getFromType();
4052   QualType ToType1 = SCS1.getToType(1);
4053   QualType FromType2 = SCS2.getFromType();
4054   QualType ToType2 = SCS2.getToType(1);
4055 
4056   // Adjust the types we're converting from via the array-to-pointer
4057   // conversion, if we need to.
4058   if (SCS1.First == ICK_Array_To_Pointer)
4059     FromType1 = S.Context.getArrayDecayedType(FromType1);
4060   if (SCS2.First == ICK_Array_To_Pointer)
4061     FromType2 = S.Context.getArrayDecayedType(FromType2);
4062 
4063   // Canonicalize all of the types.
4064   FromType1 = S.Context.getCanonicalType(FromType1);
4065   ToType1 = S.Context.getCanonicalType(ToType1);
4066   FromType2 = S.Context.getCanonicalType(FromType2);
4067   ToType2 = S.Context.getCanonicalType(ToType2);
4068 
4069   // C++ [over.ics.rank]p4b3:
4070   //
4071   //   If class B is derived directly or indirectly from class A and
4072   //   class C is derived directly or indirectly from B,
4073   //
4074   // Compare based on pointer conversions.
4075   if (SCS1.Second == ICK_Pointer_Conversion &&
4076       SCS2.Second == ICK_Pointer_Conversion &&
4077       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4078       FromType1->isPointerType() && FromType2->isPointerType() &&
4079       ToType1->isPointerType() && ToType2->isPointerType()) {
4080     QualType FromPointee1
4081       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4082     QualType ToPointee1
4083       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4084     QualType FromPointee2
4085       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4086     QualType ToPointee2
4087       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4088 
4089     //   -- conversion of C* to B* is better than conversion of C* to A*,
4090     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4091       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4092         return ImplicitConversionSequence::Better;
4093       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4094         return ImplicitConversionSequence::Worse;
4095     }
4096 
4097     //   -- conversion of B* to A* is better than conversion of C* to A*,
4098     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4099       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4100         return ImplicitConversionSequence::Better;
4101       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4102         return ImplicitConversionSequence::Worse;
4103     }
4104   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4105              SCS2.Second == ICK_Pointer_Conversion) {
4106     const ObjCObjectPointerType *FromPtr1
4107       = FromType1->getAs<ObjCObjectPointerType>();
4108     const ObjCObjectPointerType *FromPtr2
4109       = FromType2->getAs<ObjCObjectPointerType>();
4110     const ObjCObjectPointerType *ToPtr1
4111       = ToType1->getAs<ObjCObjectPointerType>();
4112     const ObjCObjectPointerType *ToPtr2
4113       = ToType2->getAs<ObjCObjectPointerType>();
4114 
4115     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4116       // Apply the same conversion ranking rules for Objective-C pointer types
4117       // that we do for C++ pointers to class types. However, we employ the
4118       // Objective-C pseudo-subtyping relationship used for assignment of
4119       // Objective-C pointer types.
4120       bool FromAssignLeft
4121         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4122       bool FromAssignRight
4123         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4124       bool ToAssignLeft
4125         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4126       bool ToAssignRight
4127         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4128 
4129       // A conversion to an a non-id object pointer type or qualified 'id'
4130       // type is better than a conversion to 'id'.
4131       if (ToPtr1->isObjCIdType() &&
4132           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4133         return ImplicitConversionSequence::Worse;
4134       if (ToPtr2->isObjCIdType() &&
4135           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4136         return ImplicitConversionSequence::Better;
4137 
4138       // A conversion to a non-id object pointer type is better than a
4139       // conversion to a qualified 'id' type
4140       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4141         return ImplicitConversionSequence::Worse;
4142       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4143         return ImplicitConversionSequence::Better;
4144 
4145       // A conversion to an a non-Class object pointer type or qualified 'Class'
4146       // type is better than a conversion to 'Class'.
4147       if (ToPtr1->isObjCClassType() &&
4148           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4149         return ImplicitConversionSequence::Worse;
4150       if (ToPtr2->isObjCClassType() &&
4151           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4152         return ImplicitConversionSequence::Better;
4153 
4154       // A conversion to a non-Class object pointer type is better than a
4155       // conversion to a qualified 'Class' type.
4156       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4157         return ImplicitConversionSequence::Worse;
4158       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4159         return ImplicitConversionSequence::Better;
4160 
4161       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4162       if (S.Context.hasSameType(FromType1, FromType2) &&
4163           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4164           (ToAssignLeft != ToAssignRight)) {
4165         if (FromPtr1->isSpecialized()) {
4166           // "conversion of B<A> * to B * is better than conversion of B * to
4167           // C *.
4168           bool IsFirstSame =
4169               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4170           bool IsSecondSame =
4171               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4172           if (IsFirstSame) {
4173             if (!IsSecondSame)
4174               return ImplicitConversionSequence::Better;
4175           } else if (IsSecondSame)
4176             return ImplicitConversionSequence::Worse;
4177         }
4178         return ToAssignLeft? ImplicitConversionSequence::Worse
4179                            : ImplicitConversionSequence::Better;
4180       }
4181 
4182       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4183       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4184           (FromAssignLeft != FromAssignRight))
4185         return FromAssignLeft? ImplicitConversionSequence::Better
4186         : ImplicitConversionSequence::Worse;
4187     }
4188   }
4189 
4190   // Ranking of member-pointer types.
4191   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4192       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4193       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4194     const MemberPointerType * FromMemPointer1 =
4195                                         FromType1->getAs<MemberPointerType>();
4196     const MemberPointerType * ToMemPointer1 =
4197                                           ToType1->getAs<MemberPointerType>();
4198     const MemberPointerType * FromMemPointer2 =
4199                                           FromType2->getAs<MemberPointerType>();
4200     const MemberPointerType * ToMemPointer2 =
4201                                           ToType2->getAs<MemberPointerType>();
4202     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4203     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4204     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4205     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4206     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4207     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4208     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4209     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4210     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4211     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4212       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4213         return ImplicitConversionSequence::Worse;
4214       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4215         return ImplicitConversionSequence::Better;
4216     }
4217     // conversion of B::* to C::* is better than conversion of A::* to C::*
4218     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4219       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4220         return ImplicitConversionSequence::Better;
4221       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4222         return ImplicitConversionSequence::Worse;
4223     }
4224   }
4225 
4226   if (SCS1.Second == ICK_Derived_To_Base) {
4227     //   -- conversion of C to B is better than conversion of C to A,
4228     //   -- binding of an expression of type C to a reference of type
4229     //      B& is better than binding an expression of type C to a
4230     //      reference of type A&,
4231     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4232         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4233       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4234         return ImplicitConversionSequence::Better;
4235       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4236         return ImplicitConversionSequence::Worse;
4237     }
4238 
4239     //   -- conversion of B to A is better than conversion of C to A.
4240     //   -- binding of an expression of type B to a reference of type
4241     //      A& is better than binding an expression of type C to a
4242     //      reference of type A&,
4243     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4244         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4245       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4246         return ImplicitConversionSequence::Better;
4247       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4248         return ImplicitConversionSequence::Worse;
4249     }
4250   }
4251 
4252   return ImplicitConversionSequence::Indistinguishable;
4253 }
4254 
4255 /// Determine whether the given type is valid, e.g., it is not an invalid
4256 /// C++ class.
4257 static bool isTypeValid(QualType T) {
4258   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4259     return !Record->isInvalidDecl();
4260 
4261   return true;
4262 }
4263 
4264 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4265 /// determine whether they are reference-related,
4266 /// reference-compatible, reference-compatible with added
4267 /// qualification, or incompatible, for use in C++ initialization by
4268 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4269 /// type, and the first type (T1) is the pointee type of the reference
4270 /// type being initialized.
4271 Sema::ReferenceCompareResult
4272 Sema::CompareReferenceRelationship(SourceLocation Loc,
4273                                    QualType OrigT1, QualType OrigT2,
4274                                    bool &DerivedToBase,
4275                                    bool &ObjCConversion,
4276                                    bool &ObjCLifetimeConversion) {
4277   assert(!OrigT1->isReferenceType() &&
4278     "T1 must be the pointee type of the reference type");
4279   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4280 
4281   QualType T1 = Context.getCanonicalType(OrigT1);
4282   QualType T2 = Context.getCanonicalType(OrigT2);
4283   Qualifiers T1Quals, T2Quals;
4284   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4285   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4286 
4287   // C++ [dcl.init.ref]p4:
4288   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4289   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4290   //   T1 is a base class of T2.
4291   DerivedToBase = false;
4292   ObjCConversion = false;
4293   ObjCLifetimeConversion = false;
4294   QualType ConvertedT2;
4295   if (UnqualT1 == UnqualT2) {
4296     // Nothing to do.
4297   } else if (isCompleteType(Loc, OrigT2) &&
4298              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4299              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4300     DerivedToBase = true;
4301   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4302            UnqualT2->isObjCObjectOrInterfaceType() &&
4303            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4304     ObjCConversion = true;
4305   else if (UnqualT2->isFunctionType() &&
4306            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4307     // C++1z [dcl.init.ref]p4:
4308     //   cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4309     //   function" and T1 is "function"
4310     //
4311     // We extend this to also apply to 'noreturn', so allow any function
4312     // conversion between function types.
4313     return Ref_Compatible;
4314   else
4315     return Ref_Incompatible;
4316 
4317   // At this point, we know that T1 and T2 are reference-related (at
4318   // least).
4319 
4320   // If the type is an array type, promote the element qualifiers to the type
4321   // for comparison.
4322   if (isa<ArrayType>(T1) && T1Quals)
4323     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4324   if (isa<ArrayType>(T2) && T2Quals)
4325     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4326 
4327   // C++ [dcl.init.ref]p4:
4328   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4329   //   reference-related to T2 and cv1 is the same cv-qualification
4330   //   as, or greater cv-qualification than, cv2. For purposes of
4331   //   overload resolution, cases for which cv1 is greater
4332   //   cv-qualification than cv2 are identified as
4333   //   reference-compatible with added qualification (see 13.3.3.2).
4334   //
4335   // Note that we also require equivalence of Objective-C GC and address-space
4336   // qualifiers when performing these computations, so that e.g., an int in
4337   // address space 1 is not reference-compatible with an int in address
4338   // space 2.
4339   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4340       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4341     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4342       ObjCLifetimeConversion = true;
4343 
4344     T1Quals.removeObjCLifetime();
4345     T2Quals.removeObjCLifetime();
4346   }
4347 
4348   // MS compiler ignores __unaligned qualifier for references; do the same.
4349   T1Quals.removeUnaligned();
4350   T2Quals.removeUnaligned();
4351 
4352   if (T1Quals.compatiblyIncludes(T2Quals))
4353     return Ref_Compatible;
4354   else
4355     return Ref_Related;
4356 }
4357 
4358 /// Look for a user-defined conversion to a value reference-compatible
4359 ///        with DeclType. Return true if something definite is found.
4360 static bool
4361 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4362                          QualType DeclType, SourceLocation DeclLoc,
4363                          Expr *Init, QualType T2, bool AllowRvalues,
4364                          bool AllowExplicit) {
4365   assert(T2->isRecordType() && "Can only find conversions of record types.");
4366   CXXRecordDecl *T2RecordDecl
4367     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4368 
4369   OverloadCandidateSet CandidateSet(
4370       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4371   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4372   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4373     NamedDecl *D = *I;
4374     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4375     if (isa<UsingShadowDecl>(D))
4376       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4377 
4378     FunctionTemplateDecl *ConvTemplate
4379       = dyn_cast<FunctionTemplateDecl>(D);
4380     CXXConversionDecl *Conv;
4381     if (ConvTemplate)
4382       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4383     else
4384       Conv = cast<CXXConversionDecl>(D);
4385 
4386     // If this is an explicit conversion, and we're not allowed to consider
4387     // explicit conversions, skip it.
4388     if (!AllowExplicit && Conv->isExplicit())
4389       continue;
4390 
4391     if (AllowRvalues) {
4392       bool DerivedToBase = false;
4393       bool ObjCConversion = false;
4394       bool ObjCLifetimeConversion = false;
4395 
4396       // If we are initializing an rvalue reference, don't permit conversion
4397       // functions that return lvalues.
4398       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4399         const ReferenceType *RefType
4400           = Conv->getConversionType()->getAs<LValueReferenceType>();
4401         if (RefType && !RefType->getPointeeType()->isFunctionType())
4402           continue;
4403       }
4404 
4405       if (!ConvTemplate &&
4406           S.CompareReferenceRelationship(
4407             DeclLoc,
4408             Conv->getConversionType().getNonReferenceType()
4409               .getUnqualifiedType(),
4410             DeclType.getNonReferenceType().getUnqualifiedType(),
4411             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4412           Sema::Ref_Incompatible)
4413         continue;
4414     } else {
4415       // If the conversion function doesn't return a reference type,
4416       // it can't be considered for this conversion. An rvalue reference
4417       // is only acceptable if its referencee is a function type.
4418 
4419       const ReferenceType *RefType =
4420         Conv->getConversionType()->getAs<ReferenceType>();
4421       if (!RefType ||
4422           (!RefType->isLValueReferenceType() &&
4423            !RefType->getPointeeType()->isFunctionType()))
4424         continue;
4425     }
4426 
4427     if (ConvTemplate)
4428       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4429                                        Init, DeclType, CandidateSet,
4430                                        /*AllowObjCConversionOnExplicit=*/false);
4431     else
4432       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4433                                DeclType, CandidateSet,
4434                                /*AllowObjCConversionOnExplicit=*/false);
4435   }
4436 
4437   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4438 
4439   OverloadCandidateSet::iterator Best;
4440   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4441   case OR_Success:
4442     // C++ [over.ics.ref]p1:
4443     //
4444     //   [...] If the parameter binds directly to the result of
4445     //   applying a conversion function to the argument
4446     //   expression, the implicit conversion sequence is a
4447     //   user-defined conversion sequence (13.3.3.1.2), with the
4448     //   second standard conversion sequence either an identity
4449     //   conversion or, if the conversion function returns an
4450     //   entity of a type that is a derived class of the parameter
4451     //   type, a derived-to-base Conversion.
4452     if (!Best->FinalConversion.DirectBinding)
4453       return false;
4454 
4455     ICS.setUserDefined();
4456     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4457     ICS.UserDefined.After = Best->FinalConversion;
4458     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4459     ICS.UserDefined.ConversionFunction = Best->Function;
4460     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4461     ICS.UserDefined.EllipsisConversion = false;
4462     assert(ICS.UserDefined.After.ReferenceBinding &&
4463            ICS.UserDefined.After.DirectBinding &&
4464            "Expected a direct reference binding!");
4465     return true;
4466 
4467   case OR_Ambiguous:
4468     ICS.setAmbiguous();
4469     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4470          Cand != CandidateSet.end(); ++Cand)
4471       if (Cand->Viable)
4472         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4473     return true;
4474 
4475   case OR_No_Viable_Function:
4476   case OR_Deleted:
4477     // There was no suitable conversion, or we found a deleted
4478     // conversion; continue with other checks.
4479     return false;
4480   }
4481 
4482   llvm_unreachable("Invalid OverloadResult!");
4483 }
4484 
4485 /// Compute an implicit conversion sequence for reference
4486 /// initialization.
4487 static ImplicitConversionSequence
4488 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4489                  SourceLocation DeclLoc,
4490                  bool SuppressUserConversions,
4491                  bool AllowExplicit) {
4492   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4493 
4494   // Most paths end in a failed conversion.
4495   ImplicitConversionSequence ICS;
4496   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4497 
4498   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4499   QualType T2 = Init->getType();
4500 
4501   // If the initializer is the address of an overloaded function, try
4502   // to resolve the overloaded function. If all goes well, T2 is the
4503   // type of the resulting function.
4504   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4505     DeclAccessPair Found;
4506     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4507                                                                 false, Found))
4508       T2 = Fn->getType();
4509   }
4510 
4511   // Compute some basic properties of the types and the initializer.
4512   bool isRValRef = DeclType->isRValueReferenceType();
4513   bool DerivedToBase = false;
4514   bool ObjCConversion = false;
4515   bool ObjCLifetimeConversion = false;
4516   Expr::Classification InitCategory = Init->Classify(S.Context);
4517   Sema::ReferenceCompareResult RefRelationship
4518     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4519                                      ObjCConversion, ObjCLifetimeConversion);
4520 
4521 
4522   // C++0x [dcl.init.ref]p5:
4523   //   A reference to type "cv1 T1" is initialized by an expression
4524   //   of type "cv2 T2" as follows:
4525 
4526   //     -- If reference is an lvalue reference and the initializer expression
4527   if (!isRValRef) {
4528     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4529     //        reference-compatible with "cv2 T2," or
4530     //
4531     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4532     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4533       // C++ [over.ics.ref]p1:
4534       //   When a parameter of reference type binds directly (8.5.3)
4535       //   to an argument expression, the implicit conversion sequence
4536       //   is the identity conversion, unless the argument expression
4537       //   has a type that is a derived class of the parameter type,
4538       //   in which case the implicit conversion sequence is a
4539       //   derived-to-base Conversion (13.3.3.1).
4540       ICS.setStandard();
4541       ICS.Standard.First = ICK_Identity;
4542       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4543                          : ObjCConversion? ICK_Compatible_Conversion
4544                          : ICK_Identity;
4545       ICS.Standard.Third = ICK_Identity;
4546       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4547       ICS.Standard.setToType(0, T2);
4548       ICS.Standard.setToType(1, T1);
4549       ICS.Standard.setToType(2, T1);
4550       ICS.Standard.ReferenceBinding = true;
4551       ICS.Standard.DirectBinding = true;
4552       ICS.Standard.IsLvalueReference = !isRValRef;
4553       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4554       ICS.Standard.BindsToRvalue = false;
4555       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4556       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4557       ICS.Standard.CopyConstructor = nullptr;
4558       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4559 
4560       // Nothing more to do: the inaccessibility/ambiguity check for
4561       // derived-to-base conversions is suppressed when we're
4562       // computing the implicit conversion sequence (C++
4563       // [over.best.ics]p2).
4564       return ICS;
4565     }
4566 
4567     //       -- has a class type (i.e., T2 is a class type), where T1 is
4568     //          not reference-related to T2, and can be implicitly
4569     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4570     //          is reference-compatible with "cv3 T3" 92) (this
4571     //          conversion is selected by enumerating the applicable
4572     //          conversion functions (13.3.1.6) and choosing the best
4573     //          one through overload resolution (13.3)),
4574     if (!SuppressUserConversions && T2->isRecordType() &&
4575         S.isCompleteType(DeclLoc, T2) &&
4576         RefRelationship == Sema::Ref_Incompatible) {
4577       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4578                                    Init, T2, /*AllowRvalues=*/false,
4579                                    AllowExplicit))
4580         return ICS;
4581     }
4582   }
4583 
4584   //     -- Otherwise, the reference shall be an lvalue reference to a
4585   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4586   //        shall be an rvalue reference.
4587   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4588     return ICS;
4589 
4590   //       -- If the initializer expression
4591   //
4592   //            -- is an xvalue, class prvalue, array prvalue or function
4593   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4594   if (RefRelationship == Sema::Ref_Compatible &&
4595       (InitCategory.isXValue() ||
4596        (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4597        (InitCategory.isLValue() && T2->isFunctionType()))) {
4598     ICS.setStandard();
4599     ICS.Standard.First = ICK_Identity;
4600     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4601                       : ObjCConversion? ICK_Compatible_Conversion
4602                       : ICK_Identity;
4603     ICS.Standard.Third = ICK_Identity;
4604     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4605     ICS.Standard.setToType(0, T2);
4606     ICS.Standard.setToType(1, T1);
4607     ICS.Standard.setToType(2, T1);
4608     ICS.Standard.ReferenceBinding = true;
4609     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4610     // binding unless we're binding to a class prvalue.
4611     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4612     // allow the use of rvalue references in C++98/03 for the benefit of
4613     // standard library implementors; therefore, we need the xvalue check here.
4614     ICS.Standard.DirectBinding =
4615       S.getLangOpts().CPlusPlus11 ||
4616       !(InitCategory.isPRValue() || T2->isRecordType());
4617     ICS.Standard.IsLvalueReference = !isRValRef;
4618     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4619     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4620     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4621     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4622     ICS.Standard.CopyConstructor = nullptr;
4623     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4624     return ICS;
4625   }
4626 
4627   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4628   //               reference-related to T2, and can be implicitly converted to
4629   //               an xvalue, class prvalue, or function lvalue of type
4630   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4631   //               "cv3 T3",
4632   //
4633   //          then the reference is bound to the value of the initializer
4634   //          expression in the first case and to the result of the conversion
4635   //          in the second case (or, in either case, to an appropriate base
4636   //          class subobject).
4637   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4638       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4639       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4640                                Init, T2, /*AllowRvalues=*/true,
4641                                AllowExplicit)) {
4642     // In the second case, if the reference is an rvalue reference
4643     // and the second standard conversion sequence of the
4644     // user-defined conversion sequence includes an lvalue-to-rvalue
4645     // conversion, the program is ill-formed.
4646     if (ICS.isUserDefined() && isRValRef &&
4647         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4648       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4649 
4650     return ICS;
4651   }
4652 
4653   // A temporary of function type cannot be created; don't even try.
4654   if (T1->isFunctionType())
4655     return ICS;
4656 
4657   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4658   //          initialized from the initializer expression using the
4659   //          rules for a non-reference copy initialization (8.5). The
4660   //          reference is then bound to the temporary. If T1 is
4661   //          reference-related to T2, cv1 must be the same
4662   //          cv-qualification as, or greater cv-qualification than,
4663   //          cv2; otherwise, the program is ill-formed.
4664   if (RefRelationship == Sema::Ref_Related) {
4665     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4666     // we would be reference-compatible or reference-compatible with
4667     // added qualification. But that wasn't the case, so the reference
4668     // initialization fails.
4669     //
4670     // Note that we only want to check address spaces and cvr-qualifiers here.
4671     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4672     Qualifiers T1Quals = T1.getQualifiers();
4673     Qualifiers T2Quals = T2.getQualifiers();
4674     T1Quals.removeObjCGCAttr();
4675     T1Quals.removeObjCLifetime();
4676     T2Quals.removeObjCGCAttr();
4677     T2Quals.removeObjCLifetime();
4678     // MS compiler ignores __unaligned qualifier for references; do the same.
4679     T1Quals.removeUnaligned();
4680     T2Quals.removeUnaligned();
4681     if (!T1Quals.compatiblyIncludes(T2Quals))
4682       return ICS;
4683   }
4684 
4685   // If at least one of the types is a class type, the types are not
4686   // related, and we aren't allowed any user conversions, the
4687   // reference binding fails. This case is important for breaking
4688   // recursion, since TryImplicitConversion below will attempt to
4689   // create a temporary through the use of a copy constructor.
4690   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4691       (T1->isRecordType() || T2->isRecordType()))
4692     return ICS;
4693 
4694   // If T1 is reference-related to T2 and the reference is an rvalue
4695   // reference, the initializer expression shall not be an lvalue.
4696   if (RefRelationship >= Sema::Ref_Related &&
4697       isRValRef && Init->Classify(S.Context).isLValue())
4698     return ICS;
4699 
4700   // C++ [over.ics.ref]p2:
4701   //   When a parameter of reference type is not bound directly to
4702   //   an argument expression, the conversion sequence is the one
4703   //   required to convert the argument expression to the
4704   //   underlying type of the reference according to
4705   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4706   //   to copy-initializing a temporary of the underlying type with
4707   //   the argument expression. Any difference in top-level
4708   //   cv-qualification is subsumed by the initialization itself
4709   //   and does not constitute a conversion.
4710   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4711                               /*AllowExplicit=*/false,
4712                               /*InOverloadResolution=*/false,
4713                               /*CStyle=*/false,
4714                               /*AllowObjCWritebackConversion=*/false,
4715                               /*AllowObjCConversionOnExplicit=*/false);
4716 
4717   // Of course, that's still a reference binding.
4718   if (ICS.isStandard()) {
4719     ICS.Standard.ReferenceBinding = true;
4720     ICS.Standard.IsLvalueReference = !isRValRef;
4721     ICS.Standard.BindsToFunctionLvalue = false;
4722     ICS.Standard.BindsToRvalue = true;
4723     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4724     ICS.Standard.ObjCLifetimeConversionBinding = false;
4725   } else if (ICS.isUserDefined()) {
4726     const ReferenceType *LValRefType =
4727         ICS.UserDefined.ConversionFunction->getReturnType()
4728             ->getAs<LValueReferenceType>();
4729 
4730     // C++ [over.ics.ref]p3:
4731     //   Except for an implicit object parameter, for which see 13.3.1, a
4732     //   standard conversion sequence cannot be formed if it requires [...]
4733     //   binding an rvalue reference to an lvalue other than a function
4734     //   lvalue.
4735     // Note that the function case is not possible here.
4736     if (DeclType->isRValueReferenceType() && LValRefType) {
4737       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4738       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4739       // reference to an rvalue!
4740       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4741       return ICS;
4742     }
4743 
4744     ICS.UserDefined.After.ReferenceBinding = true;
4745     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4746     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4747     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4748     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4749     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4750   }
4751 
4752   return ICS;
4753 }
4754 
4755 static ImplicitConversionSequence
4756 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4757                       bool SuppressUserConversions,
4758                       bool InOverloadResolution,
4759                       bool AllowObjCWritebackConversion,
4760                       bool AllowExplicit = false);
4761 
4762 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4763 /// initializer list From.
4764 static ImplicitConversionSequence
4765 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4766                   bool SuppressUserConversions,
4767                   bool InOverloadResolution,
4768                   bool AllowObjCWritebackConversion) {
4769   // C++11 [over.ics.list]p1:
4770   //   When an argument is an initializer list, it is not an expression and
4771   //   special rules apply for converting it to a parameter type.
4772 
4773   ImplicitConversionSequence Result;
4774   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4775 
4776   // We need a complete type for what follows. Incomplete types can never be
4777   // initialized from init lists.
4778   if (!S.isCompleteType(From->getBeginLoc(), ToType))
4779     return Result;
4780 
4781   // Per DR1467:
4782   //   If the parameter type is a class X and the initializer list has a single
4783   //   element of type cv U, where U is X or a class derived from X, the
4784   //   implicit conversion sequence is the one required to convert the element
4785   //   to the parameter type.
4786   //
4787   //   Otherwise, if the parameter type is a character array [... ]
4788   //   and the initializer list has a single element that is an
4789   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4790   //   implicit conversion sequence is the identity conversion.
4791   if (From->getNumInits() == 1) {
4792     if (ToType->isRecordType()) {
4793       QualType InitType = From->getInit(0)->getType();
4794       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4795           S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
4796         return TryCopyInitialization(S, From->getInit(0), ToType,
4797                                      SuppressUserConversions,
4798                                      InOverloadResolution,
4799                                      AllowObjCWritebackConversion);
4800     }
4801     // FIXME: Check the other conditions here: array of character type,
4802     // initializer is a string literal.
4803     if (ToType->isArrayType()) {
4804       InitializedEntity Entity =
4805         InitializedEntity::InitializeParameter(S.Context, ToType,
4806                                                /*Consumed=*/false);
4807       if (S.CanPerformCopyInitialization(Entity, From)) {
4808         Result.setStandard();
4809         Result.Standard.setAsIdentityConversion();
4810         Result.Standard.setFromType(ToType);
4811         Result.Standard.setAllToTypes(ToType);
4812         return Result;
4813       }
4814     }
4815   }
4816 
4817   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4818   // C++11 [over.ics.list]p2:
4819   //   If the parameter type is std::initializer_list<X> or "array of X" and
4820   //   all the elements can be implicitly converted to X, the implicit
4821   //   conversion sequence is the worst conversion necessary to convert an
4822   //   element of the list to X.
4823   //
4824   // C++14 [over.ics.list]p3:
4825   //   Otherwise, if the parameter type is "array of N X", if the initializer
4826   //   list has exactly N elements or if it has fewer than N elements and X is
4827   //   default-constructible, and if all the elements of the initializer list
4828   //   can be implicitly converted to X, the implicit conversion sequence is
4829   //   the worst conversion necessary to convert an element of the list to X.
4830   //
4831   // FIXME: We're missing a lot of these checks.
4832   bool toStdInitializerList = false;
4833   QualType X;
4834   if (ToType->isArrayType())
4835     X = S.Context.getAsArrayType(ToType)->getElementType();
4836   else
4837     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4838   if (!X.isNull()) {
4839     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4840       Expr *Init = From->getInit(i);
4841       ImplicitConversionSequence ICS =
4842           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4843                                 InOverloadResolution,
4844                                 AllowObjCWritebackConversion);
4845       // If a single element isn't convertible, fail.
4846       if (ICS.isBad()) {
4847         Result = ICS;
4848         break;
4849       }
4850       // Otherwise, look for the worst conversion.
4851       if (Result.isBad() || CompareImplicitConversionSequences(
4852                                 S, From->getBeginLoc(), ICS, Result) ==
4853                                 ImplicitConversionSequence::Worse)
4854         Result = ICS;
4855     }
4856 
4857     // For an empty list, we won't have computed any conversion sequence.
4858     // Introduce the identity conversion sequence.
4859     if (From->getNumInits() == 0) {
4860       Result.setStandard();
4861       Result.Standard.setAsIdentityConversion();
4862       Result.Standard.setFromType(ToType);
4863       Result.Standard.setAllToTypes(ToType);
4864     }
4865 
4866     Result.setStdInitializerListElement(toStdInitializerList);
4867     return Result;
4868   }
4869 
4870   // C++14 [over.ics.list]p4:
4871   // C++11 [over.ics.list]p3:
4872   //   Otherwise, if the parameter is a non-aggregate class X and overload
4873   //   resolution chooses a single best constructor [...] the implicit
4874   //   conversion sequence is a user-defined conversion sequence. If multiple
4875   //   constructors are viable but none is better than the others, the
4876   //   implicit conversion sequence is a user-defined conversion sequence.
4877   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4878     // This function can deal with initializer lists.
4879     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4880                                     /*AllowExplicit=*/false,
4881                                     InOverloadResolution, /*CStyle=*/false,
4882                                     AllowObjCWritebackConversion,
4883                                     /*AllowObjCConversionOnExplicit=*/false);
4884   }
4885 
4886   // C++14 [over.ics.list]p5:
4887   // C++11 [over.ics.list]p4:
4888   //   Otherwise, if the parameter has an aggregate type which can be
4889   //   initialized from the initializer list [...] the implicit conversion
4890   //   sequence is a user-defined conversion sequence.
4891   if (ToType->isAggregateType()) {
4892     // Type is an aggregate, argument is an init list. At this point it comes
4893     // down to checking whether the initialization works.
4894     // FIXME: Find out whether this parameter is consumed or not.
4895     // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4896     // need to call into the initialization code here; overload resolution
4897     // should not be doing that.
4898     InitializedEntity Entity =
4899         InitializedEntity::InitializeParameter(S.Context, ToType,
4900                                                /*Consumed=*/false);
4901     if (S.CanPerformCopyInitialization(Entity, From)) {
4902       Result.setUserDefined();
4903       Result.UserDefined.Before.setAsIdentityConversion();
4904       // Initializer lists don't have a type.
4905       Result.UserDefined.Before.setFromType(QualType());
4906       Result.UserDefined.Before.setAllToTypes(QualType());
4907 
4908       Result.UserDefined.After.setAsIdentityConversion();
4909       Result.UserDefined.After.setFromType(ToType);
4910       Result.UserDefined.After.setAllToTypes(ToType);
4911       Result.UserDefined.ConversionFunction = nullptr;
4912     }
4913     return Result;
4914   }
4915 
4916   // C++14 [over.ics.list]p6:
4917   // C++11 [over.ics.list]p5:
4918   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4919   if (ToType->isReferenceType()) {
4920     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4921     // mention initializer lists in any way. So we go by what list-
4922     // initialization would do and try to extrapolate from that.
4923 
4924     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4925 
4926     // If the initializer list has a single element that is reference-related
4927     // to the parameter type, we initialize the reference from that.
4928     if (From->getNumInits() == 1) {
4929       Expr *Init = From->getInit(0);
4930 
4931       QualType T2 = Init->getType();
4932 
4933       // If the initializer is the address of an overloaded function, try
4934       // to resolve the overloaded function. If all goes well, T2 is the
4935       // type of the resulting function.
4936       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4937         DeclAccessPair Found;
4938         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4939                                    Init, ToType, false, Found))
4940           T2 = Fn->getType();
4941       }
4942 
4943       // Compute some basic properties of the types and the initializer.
4944       bool dummy1 = false;
4945       bool dummy2 = false;
4946       bool dummy3 = false;
4947       Sema::ReferenceCompareResult RefRelationship =
4948           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2, dummy1,
4949                                          dummy2, dummy3);
4950 
4951       if (RefRelationship >= Sema::Ref_Related) {
4952         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
4953                                 SuppressUserConversions,
4954                                 /*AllowExplicit=*/false);
4955       }
4956     }
4957 
4958     // Otherwise, we bind the reference to a temporary created from the
4959     // initializer list.
4960     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4961                                InOverloadResolution,
4962                                AllowObjCWritebackConversion);
4963     if (Result.isFailure())
4964       return Result;
4965     assert(!Result.isEllipsis() &&
4966            "Sub-initialization cannot result in ellipsis conversion.");
4967 
4968     // Can we even bind to a temporary?
4969     if (ToType->isRValueReferenceType() ||
4970         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4971       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4972                                             Result.UserDefined.After;
4973       SCS.ReferenceBinding = true;
4974       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4975       SCS.BindsToRvalue = true;
4976       SCS.BindsToFunctionLvalue = false;
4977       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4978       SCS.ObjCLifetimeConversionBinding = false;
4979     } else
4980       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4981                     From, ToType);
4982     return Result;
4983   }
4984 
4985   // C++14 [over.ics.list]p7:
4986   // C++11 [over.ics.list]p6:
4987   //   Otherwise, if the parameter type is not a class:
4988   if (!ToType->isRecordType()) {
4989     //    - if the initializer list has one element that is not itself an
4990     //      initializer list, the implicit conversion sequence is the one
4991     //      required to convert the element to the parameter type.
4992     unsigned NumInits = From->getNumInits();
4993     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4994       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4995                                      SuppressUserConversions,
4996                                      InOverloadResolution,
4997                                      AllowObjCWritebackConversion);
4998     //    - if the initializer list has no elements, the implicit conversion
4999     //      sequence is the identity conversion.
5000     else if (NumInits == 0) {
5001       Result.setStandard();
5002       Result.Standard.setAsIdentityConversion();
5003       Result.Standard.setFromType(ToType);
5004       Result.Standard.setAllToTypes(ToType);
5005     }
5006     return Result;
5007   }
5008 
5009   // C++14 [over.ics.list]p8:
5010   // C++11 [over.ics.list]p7:
5011   //   In all cases other than those enumerated above, no conversion is possible
5012   return Result;
5013 }
5014 
5015 /// TryCopyInitialization - Try to copy-initialize a value of type
5016 /// ToType from the expression From. Return the implicit conversion
5017 /// sequence required to pass this argument, which may be a bad
5018 /// conversion sequence (meaning that the argument cannot be passed to
5019 /// a parameter of this type). If @p SuppressUserConversions, then we
5020 /// do not permit any user-defined conversion sequences.
5021 static ImplicitConversionSequence
5022 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5023                       bool SuppressUserConversions,
5024                       bool InOverloadResolution,
5025                       bool AllowObjCWritebackConversion,
5026                       bool AllowExplicit) {
5027   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5028     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5029                              InOverloadResolution,AllowObjCWritebackConversion);
5030 
5031   if (ToType->isReferenceType())
5032     return TryReferenceInit(S, From, ToType,
5033                             /*FIXME:*/ From->getBeginLoc(),
5034                             SuppressUserConversions, AllowExplicit);
5035 
5036   return TryImplicitConversion(S, From, ToType,
5037                                SuppressUserConversions,
5038                                /*AllowExplicit=*/false,
5039                                InOverloadResolution,
5040                                /*CStyle=*/false,
5041                                AllowObjCWritebackConversion,
5042                                /*AllowObjCConversionOnExplicit=*/false);
5043 }
5044 
5045 static bool TryCopyInitialization(const CanQualType FromQTy,
5046                                   const CanQualType ToQTy,
5047                                   Sema &S,
5048                                   SourceLocation Loc,
5049                                   ExprValueKind FromVK) {
5050   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5051   ImplicitConversionSequence ICS =
5052     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5053 
5054   return !ICS.isBad();
5055 }
5056 
5057 /// TryObjectArgumentInitialization - Try to initialize the object
5058 /// parameter of the given member function (@c Method) from the
5059 /// expression @p From.
5060 static ImplicitConversionSequence
5061 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5062                                 Expr::Classification FromClassification,
5063                                 CXXMethodDecl *Method,
5064                                 CXXRecordDecl *ActingContext) {
5065   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5066   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5067   //                 const volatile object.
5068   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
5069     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
5070   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
5071 
5072   // Set up the conversion sequence as a "bad" conversion, to allow us
5073   // to exit early.
5074   ImplicitConversionSequence ICS;
5075 
5076   // We need to have an object of class type.
5077   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5078     FromType = PT->getPointeeType();
5079 
5080     // When we had a pointer, it's implicitly dereferenced, so we
5081     // better have an lvalue.
5082     assert(FromClassification.isLValue());
5083   }
5084 
5085   assert(FromType->isRecordType());
5086 
5087   // C++0x [over.match.funcs]p4:
5088   //   For non-static member functions, the type of the implicit object
5089   //   parameter is
5090   //
5091   //     - "lvalue reference to cv X" for functions declared without a
5092   //        ref-qualifier or with the & ref-qualifier
5093   //     - "rvalue reference to cv X" for functions declared with the &&
5094   //        ref-qualifier
5095   //
5096   // where X is the class of which the function is a member and cv is the
5097   // cv-qualification on the member function declaration.
5098   //
5099   // However, when finding an implicit conversion sequence for the argument, we
5100   // are not allowed to perform user-defined conversions
5101   // (C++ [over.match.funcs]p5). We perform a simplified version of
5102   // reference binding here, that allows class rvalues to bind to
5103   // non-constant references.
5104 
5105   // First check the qualifiers.
5106   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5107   if (ImplicitParamType.getCVRQualifiers()
5108                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5109       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5110     ICS.setBad(BadConversionSequence::bad_qualifiers,
5111                FromType, ImplicitParamType);
5112     return ICS;
5113   }
5114 
5115   // Check that we have either the same type or a derived type. It
5116   // affects the conversion rank.
5117   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5118   ImplicitConversionKind SecondKind;
5119   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5120     SecondKind = ICK_Identity;
5121   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5122     SecondKind = ICK_Derived_To_Base;
5123   else {
5124     ICS.setBad(BadConversionSequence::unrelated_class,
5125                FromType, ImplicitParamType);
5126     return ICS;
5127   }
5128 
5129   // Check the ref-qualifier.
5130   switch (Method->getRefQualifier()) {
5131   case RQ_None:
5132     // Do nothing; we don't care about lvalueness or rvalueness.
5133     break;
5134 
5135   case RQ_LValue:
5136     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5137       // non-const lvalue reference cannot bind to an rvalue
5138       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5139                  ImplicitParamType);
5140       return ICS;
5141     }
5142     break;
5143 
5144   case RQ_RValue:
5145     if (!FromClassification.isRValue()) {
5146       // rvalue reference cannot bind to an lvalue
5147       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5148                  ImplicitParamType);
5149       return ICS;
5150     }
5151     break;
5152   }
5153 
5154   // Success. Mark this as a reference binding.
5155   ICS.setStandard();
5156   ICS.Standard.setAsIdentityConversion();
5157   ICS.Standard.Second = SecondKind;
5158   ICS.Standard.setFromType(FromType);
5159   ICS.Standard.setAllToTypes(ImplicitParamType);
5160   ICS.Standard.ReferenceBinding = true;
5161   ICS.Standard.DirectBinding = true;
5162   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5163   ICS.Standard.BindsToFunctionLvalue = false;
5164   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5165   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5166     = (Method->getRefQualifier() == RQ_None);
5167   return ICS;
5168 }
5169 
5170 /// PerformObjectArgumentInitialization - Perform initialization of
5171 /// the implicit object parameter for the given Method with the given
5172 /// expression.
5173 ExprResult
5174 Sema::PerformObjectArgumentInitialization(Expr *From,
5175                                           NestedNameSpecifier *Qualifier,
5176                                           NamedDecl *FoundDecl,
5177                                           CXXMethodDecl *Method) {
5178   QualType FromRecordType, DestType;
5179   QualType ImplicitParamRecordType  =
5180     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
5181 
5182   Expr::Classification FromClassification;
5183   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5184     FromRecordType = PT->getPointeeType();
5185     DestType = Method->getThisType(Context);
5186     FromClassification = Expr::Classification::makeSimpleLValue();
5187   } else {
5188     FromRecordType = From->getType();
5189     DestType = ImplicitParamRecordType;
5190     FromClassification = From->Classify(Context);
5191 
5192     // When performing member access on an rvalue, materialize a temporary.
5193     if (From->isRValue()) {
5194       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5195                                             Method->getRefQualifier() !=
5196                                                 RefQualifierKind::RQ_RValue);
5197     }
5198   }
5199 
5200   // Note that we always use the true parent context when performing
5201   // the actual argument initialization.
5202   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5203       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5204       Method->getParent());
5205   if (ICS.isBad()) {
5206     switch (ICS.Bad.Kind) {
5207     case BadConversionSequence::bad_qualifiers: {
5208       Qualifiers FromQs = FromRecordType.getQualifiers();
5209       Qualifiers ToQs = DestType.getQualifiers();
5210       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5211       if (CVR) {
5212         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5213             << Method->getDeclName() << FromRecordType << (CVR - 1)
5214             << From->getSourceRange();
5215         Diag(Method->getLocation(), diag::note_previous_decl)
5216           << Method->getDeclName();
5217         return ExprError();
5218       }
5219       break;
5220     }
5221 
5222     case BadConversionSequence::lvalue_ref_to_rvalue:
5223     case BadConversionSequence::rvalue_ref_to_lvalue: {
5224       bool IsRValueQualified =
5225         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5226       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5227           << Method->getDeclName() << FromClassification.isRValue()
5228           << IsRValueQualified;
5229       Diag(Method->getLocation(), diag::note_previous_decl)
5230         << Method->getDeclName();
5231       return ExprError();
5232     }
5233 
5234     case BadConversionSequence::no_conversion:
5235     case BadConversionSequence::unrelated_class:
5236       break;
5237     }
5238 
5239     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5240            << ImplicitParamRecordType << FromRecordType
5241            << From->getSourceRange();
5242   }
5243 
5244   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5245     ExprResult FromRes =
5246       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5247     if (FromRes.isInvalid())
5248       return ExprError();
5249     From = FromRes.get();
5250   }
5251 
5252   if (!Context.hasSameType(From->getType(), DestType))
5253     From = ImpCastExprToType(From, DestType, CK_NoOp,
5254                              From->getValueKind()).get();
5255   return From;
5256 }
5257 
5258 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5259 /// expression From to bool (C++0x [conv]p3).
5260 static ImplicitConversionSequence
5261 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5262   return TryImplicitConversion(S, From, S.Context.BoolTy,
5263                                /*SuppressUserConversions=*/false,
5264                                /*AllowExplicit=*/true,
5265                                /*InOverloadResolution=*/false,
5266                                /*CStyle=*/false,
5267                                /*AllowObjCWritebackConversion=*/false,
5268                                /*AllowObjCConversionOnExplicit=*/false);
5269 }
5270 
5271 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5272 /// of the expression From to bool (C++0x [conv]p3).
5273 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5274   if (checkPlaceholderForOverload(*this, From))
5275     return ExprError();
5276 
5277   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5278   if (!ICS.isBad())
5279     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5280 
5281   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5282     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5283            << From->getType() << From->getSourceRange();
5284   return ExprError();
5285 }
5286 
5287 /// Check that the specified conversion is permitted in a converted constant
5288 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5289 /// is acceptable.
5290 static bool CheckConvertedConstantConversions(Sema &S,
5291                                               StandardConversionSequence &SCS) {
5292   // Since we know that the target type is an integral or unscoped enumeration
5293   // type, most conversion kinds are impossible. All possible First and Third
5294   // conversions are fine.
5295   switch (SCS.Second) {
5296   case ICK_Identity:
5297   case ICK_Function_Conversion:
5298   case ICK_Integral_Promotion:
5299   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5300   case ICK_Zero_Queue_Conversion:
5301     return true;
5302 
5303   case ICK_Boolean_Conversion:
5304     // Conversion from an integral or unscoped enumeration type to bool is
5305     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5306     // conversion, so we allow it in a converted constant expression.
5307     //
5308     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5309     // a lot of popular code. We should at least add a warning for this
5310     // (non-conforming) extension.
5311     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5312            SCS.getToType(2)->isBooleanType();
5313 
5314   case ICK_Pointer_Conversion:
5315   case ICK_Pointer_Member:
5316     // C++1z: null pointer conversions and null member pointer conversions are
5317     // only permitted if the source type is std::nullptr_t.
5318     return SCS.getFromType()->isNullPtrType();
5319 
5320   case ICK_Floating_Promotion:
5321   case ICK_Complex_Promotion:
5322   case ICK_Floating_Conversion:
5323   case ICK_Complex_Conversion:
5324   case ICK_Floating_Integral:
5325   case ICK_Compatible_Conversion:
5326   case ICK_Derived_To_Base:
5327   case ICK_Vector_Conversion:
5328   case ICK_Vector_Splat:
5329   case ICK_Complex_Real:
5330   case ICK_Block_Pointer_Conversion:
5331   case ICK_TransparentUnionConversion:
5332   case ICK_Writeback_Conversion:
5333   case ICK_Zero_Event_Conversion:
5334   case ICK_C_Only_Conversion:
5335   case ICK_Incompatible_Pointer_Conversion:
5336     return false;
5337 
5338   case ICK_Lvalue_To_Rvalue:
5339   case ICK_Array_To_Pointer:
5340   case ICK_Function_To_Pointer:
5341     llvm_unreachable("found a first conversion kind in Second");
5342 
5343   case ICK_Qualification:
5344     llvm_unreachable("found a third conversion kind in Second");
5345 
5346   case ICK_Num_Conversion_Kinds:
5347     break;
5348   }
5349 
5350   llvm_unreachable("unknown conversion kind");
5351 }
5352 
5353 /// CheckConvertedConstantExpression - Check that the expression From is a
5354 /// converted constant expression of type T, perform the conversion and produce
5355 /// the converted expression, per C++11 [expr.const]p3.
5356 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5357                                                    QualType T, APValue &Value,
5358                                                    Sema::CCEKind CCE,
5359                                                    bool RequireInt) {
5360   assert(S.getLangOpts().CPlusPlus11 &&
5361          "converted constant expression outside C++11");
5362 
5363   if (checkPlaceholderForOverload(S, From))
5364     return ExprError();
5365 
5366   // C++1z [expr.const]p3:
5367   //  A converted constant expression of type T is an expression,
5368   //  implicitly converted to type T, where the converted
5369   //  expression is a constant expression and the implicit conversion
5370   //  sequence contains only [... list of conversions ...].
5371   // C++1z [stmt.if]p2:
5372   //  If the if statement is of the form if constexpr, the value of the
5373   //  condition shall be a contextually converted constant expression of type
5374   //  bool.
5375   ImplicitConversionSequence ICS =
5376       CCE == Sema::CCEK_ConstexprIf
5377           ? TryContextuallyConvertToBool(S, From)
5378           : TryCopyInitialization(S, From, T,
5379                                   /*SuppressUserConversions=*/false,
5380                                   /*InOverloadResolution=*/false,
5381                                   /*AllowObjcWritebackConversion=*/false,
5382                                   /*AllowExplicit=*/false);
5383   StandardConversionSequence *SCS = nullptr;
5384   switch (ICS.getKind()) {
5385   case ImplicitConversionSequence::StandardConversion:
5386     SCS = &ICS.Standard;
5387     break;
5388   case ImplicitConversionSequence::UserDefinedConversion:
5389     // We are converting to a non-class type, so the Before sequence
5390     // must be trivial.
5391     SCS = &ICS.UserDefined.After;
5392     break;
5393   case ImplicitConversionSequence::AmbiguousConversion:
5394   case ImplicitConversionSequence::BadConversion:
5395     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5396       return S.Diag(From->getBeginLoc(),
5397                     diag::err_typecheck_converted_constant_expression)
5398              << From->getType() << From->getSourceRange() << T;
5399     return ExprError();
5400 
5401   case ImplicitConversionSequence::EllipsisConversion:
5402     llvm_unreachable("ellipsis conversion in converted constant expression");
5403   }
5404 
5405   // Check that we would only use permitted conversions.
5406   if (!CheckConvertedConstantConversions(S, *SCS)) {
5407     return S.Diag(From->getBeginLoc(),
5408                   diag::err_typecheck_converted_constant_expression_disallowed)
5409            << From->getType() << From->getSourceRange() << T;
5410   }
5411   // [...] and where the reference binding (if any) binds directly.
5412   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5413     return S.Diag(From->getBeginLoc(),
5414                   diag::err_typecheck_converted_constant_expression_indirect)
5415            << From->getType() << From->getSourceRange() << T;
5416   }
5417 
5418   ExprResult Result =
5419       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5420   if (Result.isInvalid())
5421     return Result;
5422 
5423   // Check for a narrowing implicit conversion.
5424   APValue PreNarrowingValue;
5425   QualType PreNarrowingType;
5426   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5427                                 PreNarrowingType)) {
5428   case NK_Dependent_Narrowing:
5429     // Implicit conversion to a narrower type, but the expression is
5430     // value-dependent so we can't tell whether it's actually narrowing.
5431   case NK_Variable_Narrowing:
5432     // Implicit conversion to a narrower type, and the value is not a constant
5433     // expression. We'll diagnose this in a moment.
5434   case NK_Not_Narrowing:
5435     break;
5436 
5437   case NK_Constant_Narrowing:
5438     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5439         << CCE << /*Constant*/ 1
5440         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5441     break;
5442 
5443   case NK_Type_Narrowing:
5444     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5445         << CCE << /*Constant*/ 0 << From->getType() << T;
5446     break;
5447   }
5448 
5449   if (Result.get()->isValueDependent()) {
5450     Value = APValue();
5451     return Result;
5452   }
5453 
5454   // Check the expression is a constant expression.
5455   SmallVector<PartialDiagnosticAt, 8> Notes;
5456   Expr::EvalResult Eval;
5457   Eval.Diag = &Notes;
5458   Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5459                                    ? Expr::EvaluateForMangling
5460                                    : Expr::EvaluateForCodeGen;
5461 
5462   if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5463       (RequireInt && !Eval.Val.isInt())) {
5464     // The expression can't be folded, so we can't keep it at this position in
5465     // the AST.
5466     Result = ExprError();
5467   } else {
5468     Value = Eval.Val;
5469 
5470     if (Notes.empty()) {
5471       // It's a constant expression.
5472       return ConstantExpr::Create(S.Context, Result.get());
5473     }
5474   }
5475 
5476   // It's not a constant expression. Produce an appropriate diagnostic.
5477   if (Notes.size() == 1 &&
5478       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5479     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5480   else {
5481     S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5482         << CCE << From->getSourceRange();
5483     for (unsigned I = 0; I < Notes.size(); ++I)
5484       S.Diag(Notes[I].first, Notes[I].second);
5485   }
5486   return ExprError();
5487 }
5488 
5489 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5490                                                   APValue &Value, CCEKind CCE) {
5491   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5492 }
5493 
5494 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5495                                                   llvm::APSInt &Value,
5496                                                   CCEKind CCE) {
5497   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5498 
5499   APValue V;
5500   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5501   if (!R.isInvalid() && !R.get()->isValueDependent())
5502     Value = V.getInt();
5503   return R;
5504 }
5505 
5506 
5507 /// dropPointerConversions - If the given standard conversion sequence
5508 /// involves any pointer conversions, remove them.  This may change
5509 /// the result type of the conversion sequence.
5510 static void dropPointerConversion(StandardConversionSequence &SCS) {
5511   if (SCS.Second == ICK_Pointer_Conversion) {
5512     SCS.Second = ICK_Identity;
5513     SCS.Third = ICK_Identity;
5514     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5515   }
5516 }
5517 
5518 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5519 /// convert the expression From to an Objective-C pointer type.
5520 static ImplicitConversionSequence
5521 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5522   // Do an implicit conversion to 'id'.
5523   QualType Ty = S.Context.getObjCIdType();
5524   ImplicitConversionSequence ICS
5525     = TryImplicitConversion(S, From, Ty,
5526                             // FIXME: Are these flags correct?
5527                             /*SuppressUserConversions=*/false,
5528                             /*AllowExplicit=*/true,
5529                             /*InOverloadResolution=*/false,
5530                             /*CStyle=*/false,
5531                             /*AllowObjCWritebackConversion=*/false,
5532                             /*AllowObjCConversionOnExplicit=*/true);
5533 
5534   // Strip off any final conversions to 'id'.
5535   switch (ICS.getKind()) {
5536   case ImplicitConversionSequence::BadConversion:
5537   case ImplicitConversionSequence::AmbiguousConversion:
5538   case ImplicitConversionSequence::EllipsisConversion:
5539     break;
5540 
5541   case ImplicitConversionSequence::UserDefinedConversion:
5542     dropPointerConversion(ICS.UserDefined.After);
5543     break;
5544 
5545   case ImplicitConversionSequence::StandardConversion:
5546     dropPointerConversion(ICS.Standard);
5547     break;
5548   }
5549 
5550   return ICS;
5551 }
5552 
5553 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5554 /// conversion of the expression From to an Objective-C pointer type.
5555 /// Returns a valid but null ExprResult if no conversion sequence exists.
5556 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5557   if (checkPlaceholderForOverload(*this, From))
5558     return ExprError();
5559 
5560   QualType Ty = Context.getObjCIdType();
5561   ImplicitConversionSequence ICS =
5562     TryContextuallyConvertToObjCPointer(*this, From);
5563   if (!ICS.isBad())
5564     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5565   return ExprResult();
5566 }
5567 
5568 /// Determine whether the provided type is an integral type, or an enumeration
5569 /// type of a permitted flavor.
5570 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5571   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5572                                  : T->isIntegralOrUnscopedEnumerationType();
5573 }
5574 
5575 static ExprResult
5576 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5577                             Sema::ContextualImplicitConverter &Converter,
5578                             QualType T, UnresolvedSetImpl &ViableConversions) {
5579 
5580   if (Converter.Suppress)
5581     return ExprError();
5582 
5583   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5584   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5585     CXXConversionDecl *Conv =
5586         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5587     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5588     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5589   }
5590   return From;
5591 }
5592 
5593 static bool
5594 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5595                            Sema::ContextualImplicitConverter &Converter,
5596                            QualType T, bool HadMultipleCandidates,
5597                            UnresolvedSetImpl &ExplicitConversions) {
5598   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5599     DeclAccessPair Found = ExplicitConversions[0];
5600     CXXConversionDecl *Conversion =
5601         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5602 
5603     // The user probably meant to invoke the given explicit
5604     // conversion; use it.
5605     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5606     std::string TypeStr;
5607     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5608 
5609     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5610         << FixItHint::CreateInsertion(From->getBeginLoc(),
5611                                       "static_cast<" + TypeStr + ">(")
5612         << FixItHint::CreateInsertion(
5613                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5614     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5615 
5616     // If we aren't in a SFINAE context, build a call to the
5617     // explicit conversion function.
5618     if (SemaRef.isSFINAEContext())
5619       return true;
5620 
5621     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5622     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5623                                                        HadMultipleCandidates);
5624     if (Result.isInvalid())
5625       return true;
5626     // Record usage of conversion in an implicit cast.
5627     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5628                                     CK_UserDefinedConversion, Result.get(),
5629                                     nullptr, Result.get()->getValueKind());
5630   }
5631   return false;
5632 }
5633 
5634 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5635                              Sema::ContextualImplicitConverter &Converter,
5636                              QualType T, bool HadMultipleCandidates,
5637                              DeclAccessPair &Found) {
5638   CXXConversionDecl *Conversion =
5639       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5640   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5641 
5642   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5643   if (!Converter.SuppressConversion) {
5644     if (SemaRef.isSFINAEContext())
5645       return true;
5646 
5647     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5648         << From->getSourceRange();
5649   }
5650 
5651   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5652                                                      HadMultipleCandidates);
5653   if (Result.isInvalid())
5654     return true;
5655   // Record usage of conversion in an implicit cast.
5656   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5657                                   CK_UserDefinedConversion, Result.get(),
5658                                   nullptr, Result.get()->getValueKind());
5659   return false;
5660 }
5661 
5662 static ExprResult finishContextualImplicitConversion(
5663     Sema &SemaRef, SourceLocation Loc, Expr *From,
5664     Sema::ContextualImplicitConverter &Converter) {
5665   if (!Converter.match(From->getType()) && !Converter.Suppress)
5666     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5667         << From->getSourceRange();
5668 
5669   return SemaRef.DefaultLvalueConversion(From);
5670 }
5671 
5672 static void
5673 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5674                                   UnresolvedSetImpl &ViableConversions,
5675                                   OverloadCandidateSet &CandidateSet) {
5676   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5677     DeclAccessPair FoundDecl = ViableConversions[I];
5678     NamedDecl *D = FoundDecl.getDecl();
5679     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5680     if (isa<UsingShadowDecl>(D))
5681       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5682 
5683     CXXConversionDecl *Conv;
5684     FunctionTemplateDecl *ConvTemplate;
5685     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5686       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5687     else
5688       Conv = cast<CXXConversionDecl>(D);
5689 
5690     if (ConvTemplate)
5691       SemaRef.AddTemplateConversionCandidate(
5692         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5693         /*AllowObjCConversionOnExplicit=*/false);
5694     else
5695       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5696                                      ToType, CandidateSet,
5697                                      /*AllowObjCConversionOnExplicit=*/false);
5698   }
5699 }
5700 
5701 /// Attempt to convert the given expression to a type which is accepted
5702 /// by the given converter.
5703 ///
5704 /// This routine will attempt to convert an expression of class type to a
5705 /// type accepted by the specified converter. In C++11 and before, the class
5706 /// must have a single non-explicit conversion function converting to a matching
5707 /// type. In C++1y, there can be multiple such conversion functions, but only
5708 /// one target type.
5709 ///
5710 /// \param Loc The source location of the construct that requires the
5711 /// conversion.
5712 ///
5713 /// \param From The expression we're converting from.
5714 ///
5715 /// \param Converter Used to control and diagnose the conversion process.
5716 ///
5717 /// \returns The expression, converted to an integral or enumeration type if
5718 /// successful.
5719 ExprResult Sema::PerformContextualImplicitConversion(
5720     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5721   // We can't perform any more checking for type-dependent expressions.
5722   if (From->isTypeDependent())
5723     return From;
5724 
5725   // Process placeholders immediately.
5726   if (From->hasPlaceholderType()) {
5727     ExprResult result = CheckPlaceholderExpr(From);
5728     if (result.isInvalid())
5729       return result;
5730     From = result.get();
5731   }
5732 
5733   // If the expression already has a matching type, we're golden.
5734   QualType T = From->getType();
5735   if (Converter.match(T))
5736     return DefaultLvalueConversion(From);
5737 
5738   // FIXME: Check for missing '()' if T is a function type?
5739 
5740   // We can only perform contextual implicit conversions on objects of class
5741   // type.
5742   const RecordType *RecordTy = T->getAs<RecordType>();
5743   if (!RecordTy || !getLangOpts().CPlusPlus) {
5744     if (!Converter.Suppress)
5745       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5746     return From;
5747   }
5748 
5749   // We must have a complete class type.
5750   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5751     ContextualImplicitConverter &Converter;
5752     Expr *From;
5753 
5754     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5755         : Converter(Converter), From(From) {}
5756 
5757     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5758       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5759     }
5760   } IncompleteDiagnoser(Converter, From);
5761 
5762   if (Converter.Suppress ? !isCompleteType(Loc, T)
5763                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5764     return From;
5765 
5766   // Look for a conversion to an integral or enumeration type.
5767   UnresolvedSet<4>
5768       ViableConversions; // These are *potentially* viable in C++1y.
5769   UnresolvedSet<4> ExplicitConversions;
5770   const auto &Conversions =
5771       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5772 
5773   bool HadMultipleCandidates =
5774       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5775 
5776   // To check that there is only one target type, in C++1y:
5777   QualType ToType;
5778   bool HasUniqueTargetType = true;
5779 
5780   // Collect explicit or viable (potentially in C++1y) conversions.
5781   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5782     NamedDecl *D = (*I)->getUnderlyingDecl();
5783     CXXConversionDecl *Conversion;
5784     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5785     if (ConvTemplate) {
5786       if (getLangOpts().CPlusPlus14)
5787         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5788       else
5789         continue; // C++11 does not consider conversion operator templates(?).
5790     } else
5791       Conversion = cast<CXXConversionDecl>(D);
5792 
5793     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5794            "Conversion operator templates are considered potentially "
5795            "viable in C++1y");
5796 
5797     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5798     if (Converter.match(CurToType) || ConvTemplate) {
5799 
5800       if (Conversion->isExplicit()) {
5801         // FIXME: For C++1y, do we need this restriction?
5802         // cf. diagnoseNoViableConversion()
5803         if (!ConvTemplate)
5804           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5805       } else {
5806         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5807           if (ToType.isNull())
5808             ToType = CurToType.getUnqualifiedType();
5809           else if (HasUniqueTargetType &&
5810                    (CurToType.getUnqualifiedType() != ToType))
5811             HasUniqueTargetType = false;
5812         }
5813         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5814       }
5815     }
5816   }
5817 
5818   if (getLangOpts().CPlusPlus14) {
5819     // C++1y [conv]p6:
5820     // ... An expression e of class type E appearing in such a context
5821     // is said to be contextually implicitly converted to a specified
5822     // type T and is well-formed if and only if e can be implicitly
5823     // converted to a type T that is determined as follows: E is searched
5824     // for conversion functions whose return type is cv T or reference to
5825     // cv T such that T is allowed by the context. There shall be
5826     // exactly one such T.
5827 
5828     // If no unique T is found:
5829     if (ToType.isNull()) {
5830       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5831                                      HadMultipleCandidates,
5832                                      ExplicitConversions))
5833         return ExprError();
5834       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5835     }
5836 
5837     // If more than one unique Ts are found:
5838     if (!HasUniqueTargetType)
5839       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5840                                          ViableConversions);
5841 
5842     // If one unique T is found:
5843     // First, build a candidate set from the previously recorded
5844     // potentially viable conversions.
5845     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5846     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5847                                       CandidateSet);
5848 
5849     // Then, perform overload resolution over the candidate set.
5850     OverloadCandidateSet::iterator Best;
5851     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5852     case OR_Success: {
5853       // Apply this conversion.
5854       DeclAccessPair Found =
5855           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5856       if (recordConversion(*this, Loc, From, Converter, T,
5857                            HadMultipleCandidates, Found))
5858         return ExprError();
5859       break;
5860     }
5861     case OR_Ambiguous:
5862       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5863                                          ViableConversions);
5864     case OR_No_Viable_Function:
5865       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5866                                      HadMultipleCandidates,
5867                                      ExplicitConversions))
5868         return ExprError();
5869       LLVM_FALLTHROUGH;
5870     case OR_Deleted:
5871       // We'll complain below about a non-integral condition type.
5872       break;
5873     }
5874   } else {
5875     switch (ViableConversions.size()) {
5876     case 0: {
5877       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5878                                      HadMultipleCandidates,
5879                                      ExplicitConversions))
5880         return ExprError();
5881 
5882       // We'll complain below about a non-integral condition type.
5883       break;
5884     }
5885     case 1: {
5886       // Apply this conversion.
5887       DeclAccessPair Found = ViableConversions[0];
5888       if (recordConversion(*this, Loc, From, Converter, T,
5889                            HadMultipleCandidates, Found))
5890         return ExprError();
5891       break;
5892     }
5893     default:
5894       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5895                                          ViableConversions);
5896     }
5897   }
5898 
5899   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5900 }
5901 
5902 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5903 /// an acceptable non-member overloaded operator for a call whose
5904 /// arguments have types T1 (and, if non-empty, T2). This routine
5905 /// implements the check in C++ [over.match.oper]p3b2 concerning
5906 /// enumeration types.
5907 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5908                                                    FunctionDecl *Fn,
5909                                                    ArrayRef<Expr *> Args) {
5910   QualType T1 = Args[0]->getType();
5911   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5912 
5913   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5914     return true;
5915 
5916   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5917     return true;
5918 
5919   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5920   if (Proto->getNumParams() < 1)
5921     return false;
5922 
5923   if (T1->isEnumeralType()) {
5924     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5925     if (Context.hasSameUnqualifiedType(T1, ArgType))
5926       return true;
5927   }
5928 
5929   if (Proto->getNumParams() < 2)
5930     return false;
5931 
5932   if (!T2.isNull() && T2->isEnumeralType()) {
5933     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5934     if (Context.hasSameUnqualifiedType(T2, ArgType))
5935       return true;
5936   }
5937 
5938   return false;
5939 }
5940 
5941 /// AddOverloadCandidate - Adds the given function to the set of
5942 /// candidate functions, using the given function call arguments.  If
5943 /// @p SuppressUserConversions, then don't allow user-defined
5944 /// conversions via constructors or conversion operators.
5945 ///
5946 /// \param PartialOverloading true if we are performing "partial" overloading
5947 /// based on an incomplete set of function arguments. This feature is used by
5948 /// code completion.
5949 void Sema::AddOverloadCandidate(FunctionDecl *Function,
5950                                 DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
5951                                 OverloadCandidateSet &CandidateSet,
5952                                 bool SuppressUserConversions,
5953                                 bool PartialOverloading, bool AllowExplicit,
5954                                 ADLCallKind IsADLCandidate,
5955                                 ConversionSequenceList EarlyConversions) {
5956   const FunctionProtoType *Proto
5957     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5958   assert(Proto && "Functions without a prototype cannot be overloaded");
5959   assert(!Function->getDescribedFunctionTemplate() &&
5960          "Use AddTemplateOverloadCandidate for function templates");
5961 
5962   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5963     if (!isa<CXXConstructorDecl>(Method)) {
5964       // If we get here, it's because we're calling a member function
5965       // that is named without a member access expression (e.g.,
5966       // "this->f") that was either written explicitly or created
5967       // implicitly. This can happen with a qualified call to a member
5968       // function, e.g., X::f(). We use an empty type for the implied
5969       // object argument (C++ [over.call.func]p3), and the acting context
5970       // is irrelevant.
5971       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
5972                          Expr::Classification::makeSimpleLValue(), Args,
5973                          CandidateSet, SuppressUserConversions,
5974                          PartialOverloading, EarlyConversions);
5975       return;
5976     }
5977     // We treat a constructor like a non-member function, since its object
5978     // argument doesn't participate in overload resolution.
5979   }
5980 
5981   if (!CandidateSet.isNewCandidate(Function))
5982     return;
5983 
5984   // C++ [over.match.oper]p3:
5985   //   if no operand has a class type, only those non-member functions in the
5986   //   lookup set that have a first parameter of type T1 or "reference to
5987   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5988   //   is a right operand) a second parameter of type T2 or "reference to
5989   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5990   //   candidate functions.
5991   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5992       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5993     return;
5994 
5995   // C++11 [class.copy]p11: [DR1402]
5996   //   A defaulted move constructor that is defined as deleted is ignored by
5997   //   overload resolution.
5998   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5999   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6000       Constructor->isMoveConstructor())
6001     return;
6002 
6003   // Overload resolution is always an unevaluated context.
6004   EnterExpressionEvaluationContext Unevaluated(
6005       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6006 
6007   // Add this candidate
6008   OverloadCandidate &Candidate =
6009       CandidateSet.addCandidate(Args.size(), EarlyConversions);
6010   Candidate.FoundDecl = FoundDecl;
6011   Candidate.Function = Function;
6012   Candidate.Viable = true;
6013   Candidate.IsSurrogate = false;
6014   Candidate.IsADLCandidate = IsADLCandidate;
6015   Candidate.IgnoreObjectArgument = false;
6016   Candidate.ExplicitCallArguments = Args.size();
6017 
6018   if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6019       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6020     Candidate.Viable = false;
6021     Candidate.FailureKind = ovl_non_default_multiversion_function;
6022     return;
6023   }
6024 
6025   if (Constructor) {
6026     // C++ [class.copy]p3:
6027     //   A member function template is never instantiated to perform the copy
6028     //   of a class object to an object of its class type.
6029     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6030     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6031         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6032          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6033                        ClassType))) {
6034       Candidate.Viable = false;
6035       Candidate.FailureKind = ovl_fail_illegal_constructor;
6036       return;
6037     }
6038 
6039     // C++ [over.match.funcs]p8: (proposed DR resolution)
6040     //   A constructor inherited from class type C that has a first parameter
6041     //   of type "reference to P" (including such a constructor instantiated
6042     //   from a template) is excluded from the set of candidate functions when
6043     //   constructing an object of type cv D if the argument list has exactly
6044     //   one argument and D is reference-related to P and P is reference-related
6045     //   to C.
6046     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6047     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6048         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6049       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6050       QualType C = Context.getRecordType(Constructor->getParent());
6051       QualType D = Context.getRecordType(Shadow->getParent());
6052       SourceLocation Loc = Args.front()->getExprLoc();
6053       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6054           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6055         Candidate.Viable = false;
6056         Candidate.FailureKind = ovl_fail_inhctor_slice;
6057         return;
6058       }
6059     }
6060   }
6061 
6062   unsigned NumParams = Proto->getNumParams();
6063 
6064   // (C++ 13.3.2p2): A candidate function having fewer than m
6065   // parameters is viable only if it has an ellipsis in its parameter
6066   // list (8.3.5).
6067   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6068       !Proto->isVariadic()) {
6069     Candidate.Viable = false;
6070     Candidate.FailureKind = ovl_fail_too_many_arguments;
6071     return;
6072   }
6073 
6074   // (C++ 13.3.2p2): A candidate function having more than m parameters
6075   // is viable only if the (m+1)st parameter has a default argument
6076   // (8.3.6). For the purposes of overload resolution, the
6077   // parameter list is truncated on the right, so that there are
6078   // exactly m parameters.
6079   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6080   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6081     // Not enough arguments.
6082     Candidate.Viable = false;
6083     Candidate.FailureKind = ovl_fail_too_few_arguments;
6084     return;
6085   }
6086 
6087   // (CUDA B.1): Check for invalid calls between targets.
6088   if (getLangOpts().CUDA)
6089     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6090       // Skip the check for callers that are implicit members, because in this
6091       // case we may not yet know what the member's target is; the target is
6092       // inferred for the member automatically, based on the bases and fields of
6093       // the class.
6094       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6095         Candidate.Viable = false;
6096         Candidate.FailureKind = ovl_fail_bad_target;
6097         return;
6098       }
6099 
6100   // Determine the implicit conversion sequences for each of the
6101   // arguments.
6102   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6103     if (Candidate.Conversions[ArgIdx].isInitialized()) {
6104       // We already formed a conversion sequence for this parameter during
6105       // template argument deduction.
6106     } else if (ArgIdx < NumParams) {
6107       // (C++ 13.3.2p3): for F to be a viable function, there shall
6108       // exist for each argument an implicit conversion sequence
6109       // (13.3.3.1) that converts that argument to the corresponding
6110       // parameter of F.
6111       QualType ParamType = Proto->getParamType(ArgIdx);
6112       Candidate.Conversions[ArgIdx]
6113         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6114                                 SuppressUserConversions,
6115                                 /*InOverloadResolution=*/true,
6116                                 /*AllowObjCWritebackConversion=*/
6117                                   getLangOpts().ObjCAutoRefCount,
6118                                 AllowExplicit);
6119       if (Candidate.Conversions[ArgIdx].isBad()) {
6120         Candidate.Viable = false;
6121         Candidate.FailureKind = ovl_fail_bad_conversion;
6122         return;
6123       }
6124     } else {
6125       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6126       // argument for which there is no corresponding parameter is
6127       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6128       Candidate.Conversions[ArgIdx].setEllipsis();
6129     }
6130   }
6131 
6132   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6133     Candidate.Viable = false;
6134     Candidate.FailureKind = ovl_fail_enable_if;
6135     Candidate.DeductionFailure.Data = FailedAttr;
6136     return;
6137   }
6138 
6139   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6140     Candidate.Viable = false;
6141     Candidate.FailureKind = ovl_fail_ext_disabled;
6142     return;
6143   }
6144 }
6145 
6146 ObjCMethodDecl *
6147 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6148                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6149   if (Methods.size() <= 1)
6150     return nullptr;
6151 
6152   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6153     bool Match = true;
6154     ObjCMethodDecl *Method = Methods[b];
6155     unsigned NumNamedArgs = Sel.getNumArgs();
6156     // Method might have more arguments than selector indicates. This is due
6157     // to addition of c-style arguments in method.
6158     if (Method->param_size() > NumNamedArgs)
6159       NumNamedArgs = Method->param_size();
6160     if (Args.size() < NumNamedArgs)
6161       continue;
6162 
6163     for (unsigned i = 0; i < NumNamedArgs; i++) {
6164       // We can't do any type-checking on a type-dependent argument.
6165       if (Args[i]->isTypeDependent()) {
6166         Match = false;
6167         break;
6168       }
6169 
6170       ParmVarDecl *param = Method->parameters()[i];
6171       Expr *argExpr = Args[i];
6172       assert(argExpr && "SelectBestMethod(): missing expression");
6173 
6174       // Strip the unbridged-cast placeholder expression off unless it's
6175       // a consumed argument.
6176       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6177           !param->hasAttr<CFConsumedAttr>())
6178         argExpr = stripARCUnbridgedCast(argExpr);
6179 
6180       // If the parameter is __unknown_anytype, move on to the next method.
6181       if (param->getType() == Context.UnknownAnyTy) {
6182         Match = false;
6183         break;
6184       }
6185 
6186       ImplicitConversionSequence ConversionState
6187         = TryCopyInitialization(*this, argExpr, param->getType(),
6188                                 /*SuppressUserConversions*/false,
6189                                 /*InOverloadResolution=*/true,
6190                                 /*AllowObjCWritebackConversion=*/
6191                                 getLangOpts().ObjCAutoRefCount,
6192                                 /*AllowExplicit*/false);
6193       // This function looks for a reasonably-exact match, so we consider
6194       // incompatible pointer conversions to be a failure here.
6195       if (ConversionState.isBad() ||
6196           (ConversionState.isStandard() &&
6197            ConversionState.Standard.Second ==
6198                ICK_Incompatible_Pointer_Conversion)) {
6199         Match = false;
6200         break;
6201       }
6202     }
6203     // Promote additional arguments to variadic methods.
6204     if (Match && Method->isVariadic()) {
6205       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6206         if (Args[i]->isTypeDependent()) {
6207           Match = false;
6208           break;
6209         }
6210         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6211                                                           nullptr);
6212         if (Arg.isInvalid()) {
6213           Match = false;
6214           break;
6215         }
6216       }
6217     } else {
6218       // Check for extra arguments to non-variadic methods.
6219       if (Args.size() != NumNamedArgs)
6220         Match = false;
6221       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6222         // Special case when selectors have no argument. In this case, select
6223         // one with the most general result type of 'id'.
6224         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6225           QualType ReturnT = Methods[b]->getReturnType();
6226           if (ReturnT->isObjCIdType())
6227             return Methods[b];
6228         }
6229       }
6230     }
6231 
6232     if (Match)
6233       return Method;
6234   }
6235   return nullptr;
6236 }
6237 
6238 static bool
6239 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6240                                  ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6241                                  bool MissingImplicitThis, Expr *&ConvertedThis,
6242                                  SmallVectorImpl<Expr *> &ConvertedArgs) {
6243   if (ThisArg) {
6244     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6245     assert(!isa<CXXConstructorDecl>(Method) &&
6246            "Shouldn't have `this` for ctors!");
6247     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6248     ExprResult R = S.PerformObjectArgumentInitialization(
6249         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6250     if (R.isInvalid())
6251       return false;
6252     ConvertedThis = R.get();
6253   } else {
6254     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6255       (void)MD;
6256       assert((MissingImplicitThis || MD->isStatic() ||
6257               isa<CXXConstructorDecl>(MD)) &&
6258              "Expected `this` for non-ctor instance methods");
6259     }
6260     ConvertedThis = nullptr;
6261   }
6262 
6263   // Ignore any variadic arguments. Converting them is pointless, since the
6264   // user can't refer to them in the function condition.
6265   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6266 
6267   // Convert the arguments.
6268   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6269     ExprResult R;
6270     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6271                                         S.Context, Function->getParamDecl(I)),
6272                                     SourceLocation(), Args[I]);
6273 
6274     if (R.isInvalid())
6275       return false;
6276 
6277     ConvertedArgs.push_back(R.get());
6278   }
6279 
6280   if (Trap.hasErrorOccurred())
6281     return false;
6282 
6283   // Push default arguments if needed.
6284   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6285     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6286       ParmVarDecl *P = Function->getParamDecl(i);
6287       Expr *DefArg = P->hasUninstantiatedDefaultArg()
6288                          ? P->getUninstantiatedDefaultArg()
6289                          : P->getDefaultArg();
6290       // This can only happen in code completion, i.e. when PartialOverloading
6291       // is true.
6292       if (!DefArg)
6293         return false;
6294       ExprResult R =
6295           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6296                                           S.Context, Function->getParamDecl(i)),
6297                                       SourceLocation(), DefArg);
6298       if (R.isInvalid())
6299         return false;
6300       ConvertedArgs.push_back(R.get());
6301     }
6302 
6303     if (Trap.hasErrorOccurred())
6304       return false;
6305   }
6306   return true;
6307 }
6308 
6309 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6310                                   bool MissingImplicitThis) {
6311   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6312   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6313     return nullptr;
6314 
6315   SFINAETrap Trap(*this);
6316   SmallVector<Expr *, 16> ConvertedArgs;
6317   // FIXME: We should look into making enable_if late-parsed.
6318   Expr *DiscardedThis;
6319   if (!convertArgsForAvailabilityChecks(
6320           *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6321           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6322     return *EnableIfAttrs.begin();
6323 
6324   for (auto *EIA : EnableIfAttrs) {
6325     APValue Result;
6326     // FIXME: This doesn't consider value-dependent cases, because doing so is
6327     // very difficult. Ideally, we should handle them more gracefully.
6328     if (!EIA->getCond()->EvaluateWithSubstitution(
6329             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6330       return EIA;
6331 
6332     if (!Result.isInt() || !Result.getInt().getBoolValue())
6333       return EIA;
6334   }
6335   return nullptr;
6336 }
6337 
6338 template <typename CheckFn>
6339 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6340                                         bool ArgDependent, SourceLocation Loc,
6341                                         CheckFn &&IsSuccessful) {
6342   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6343   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6344     if (ArgDependent == DIA->getArgDependent())
6345       Attrs.push_back(DIA);
6346   }
6347 
6348   // Common case: No diagnose_if attributes, so we can quit early.
6349   if (Attrs.empty())
6350     return false;
6351 
6352   auto WarningBegin = std::stable_partition(
6353       Attrs.begin(), Attrs.end(),
6354       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6355 
6356   // Note that diagnose_if attributes are late-parsed, so they appear in the
6357   // correct order (unlike enable_if attributes).
6358   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6359                                IsSuccessful);
6360   if (ErrAttr != WarningBegin) {
6361     const DiagnoseIfAttr *DIA = *ErrAttr;
6362     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6363     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6364         << DIA->getParent() << DIA->getCond()->getSourceRange();
6365     return true;
6366   }
6367 
6368   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6369     if (IsSuccessful(DIA)) {
6370       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6371       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6372           << DIA->getParent() << DIA->getCond()->getSourceRange();
6373     }
6374 
6375   return false;
6376 }
6377 
6378 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6379                                                const Expr *ThisArg,
6380                                                ArrayRef<const Expr *> Args,
6381                                                SourceLocation Loc) {
6382   return diagnoseDiagnoseIfAttrsWith(
6383       *this, Function, /*ArgDependent=*/true, Loc,
6384       [&](const DiagnoseIfAttr *DIA) {
6385         APValue Result;
6386         // It's sane to use the same Args for any redecl of this function, since
6387         // EvaluateWithSubstitution only cares about the position of each
6388         // argument in the arg list, not the ParmVarDecl* it maps to.
6389         if (!DIA->getCond()->EvaluateWithSubstitution(
6390                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6391           return false;
6392         return Result.isInt() && Result.getInt().getBoolValue();
6393       });
6394 }
6395 
6396 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6397                                                  SourceLocation Loc) {
6398   return diagnoseDiagnoseIfAttrsWith(
6399       *this, ND, /*ArgDependent=*/false, Loc,
6400       [&](const DiagnoseIfAttr *DIA) {
6401         bool Result;
6402         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6403                Result;
6404       });
6405 }
6406 
6407 /// Add all of the function declarations in the given function set to
6408 /// the overload candidate set.
6409 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6410                                  ArrayRef<Expr *> Args,
6411                                  OverloadCandidateSet &CandidateSet,
6412                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6413                                  bool SuppressUserConversions,
6414                                  bool PartialOverloading,
6415                                  bool FirstArgumentIsBase) {
6416   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6417     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6418     ArrayRef<Expr *> FunctionArgs = Args;
6419 
6420     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6421     FunctionDecl *FD =
6422         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6423 
6424     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6425       QualType ObjectType;
6426       Expr::Classification ObjectClassification;
6427       if (Args.size() > 0) {
6428         if (Expr *E = Args[0]) {
6429           // Use the explicit base to restrict the lookup:
6430           ObjectType = E->getType();
6431           // Pointers in the object arguments are implicitly dereferenced, so we
6432           // always classify them as l-values.
6433           if (!ObjectType.isNull() && ObjectType->isPointerType())
6434             ObjectClassification = Expr::Classification::makeSimpleLValue();
6435           else
6436             ObjectClassification = E->Classify(Context);
6437         } // .. else there is an implicit base.
6438         FunctionArgs = Args.slice(1);
6439       }
6440       if (FunTmpl) {
6441         AddMethodTemplateCandidate(
6442             FunTmpl, F.getPair(),
6443             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6444             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6445             FunctionArgs, CandidateSet, SuppressUserConversions,
6446             PartialOverloading);
6447       } else {
6448         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6449                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6450                            ObjectClassification, FunctionArgs, CandidateSet,
6451                            SuppressUserConversions, PartialOverloading);
6452       }
6453     } else {
6454       // This branch handles both standalone functions and static methods.
6455 
6456       // Slice the first argument (which is the base) when we access
6457       // static method as non-static.
6458       if (Args.size() > 0 &&
6459           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6460                         !isa<CXXConstructorDecl>(FD)))) {
6461         assert(cast<CXXMethodDecl>(FD)->isStatic());
6462         FunctionArgs = Args.slice(1);
6463       }
6464       if (FunTmpl) {
6465         AddTemplateOverloadCandidate(
6466             FunTmpl, F.getPair(), ExplicitTemplateArgs, FunctionArgs,
6467             CandidateSet, SuppressUserConversions, PartialOverloading);
6468       } else {
6469         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6470                              SuppressUserConversions, PartialOverloading);
6471       }
6472     }
6473   }
6474 }
6475 
6476 /// AddMethodCandidate - Adds a named decl (which is some kind of
6477 /// method) as a method candidate to the given overload set.
6478 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6479                               QualType ObjectType,
6480                               Expr::Classification ObjectClassification,
6481                               ArrayRef<Expr *> Args,
6482                               OverloadCandidateSet& CandidateSet,
6483                               bool SuppressUserConversions) {
6484   NamedDecl *Decl = FoundDecl.getDecl();
6485   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6486 
6487   if (isa<UsingShadowDecl>(Decl))
6488     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6489 
6490   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6491     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6492            "Expected a member function template");
6493     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6494                                /*ExplicitArgs*/ nullptr, ObjectType,
6495                                ObjectClassification, Args, CandidateSet,
6496                                SuppressUserConversions);
6497   } else {
6498     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6499                        ObjectType, ObjectClassification, Args, CandidateSet,
6500                        SuppressUserConversions);
6501   }
6502 }
6503 
6504 /// AddMethodCandidate - Adds the given C++ member function to the set
6505 /// of candidate functions, using the given function call arguments
6506 /// and the object argument (@c Object). For example, in a call
6507 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6508 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6509 /// allow user-defined conversions via constructors or conversion
6510 /// operators.
6511 void
6512 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6513                          CXXRecordDecl *ActingContext, QualType ObjectType,
6514                          Expr::Classification ObjectClassification,
6515                          ArrayRef<Expr *> Args,
6516                          OverloadCandidateSet &CandidateSet,
6517                          bool SuppressUserConversions,
6518                          bool PartialOverloading,
6519                          ConversionSequenceList EarlyConversions) {
6520   const FunctionProtoType *Proto
6521     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6522   assert(Proto && "Methods without a prototype cannot be overloaded");
6523   assert(!isa<CXXConstructorDecl>(Method) &&
6524          "Use AddOverloadCandidate for constructors");
6525 
6526   if (!CandidateSet.isNewCandidate(Method))
6527     return;
6528 
6529   // C++11 [class.copy]p23: [DR1402]
6530   //   A defaulted move assignment operator that is defined as deleted is
6531   //   ignored by overload resolution.
6532   if (Method->isDefaulted() && Method->isDeleted() &&
6533       Method->isMoveAssignmentOperator())
6534     return;
6535 
6536   // Overload resolution is always an unevaluated context.
6537   EnterExpressionEvaluationContext Unevaluated(
6538       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6539 
6540   // Add this candidate
6541   OverloadCandidate &Candidate =
6542       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6543   Candidate.FoundDecl = FoundDecl;
6544   Candidate.Function = Method;
6545   Candidate.IsSurrogate = false;
6546   Candidate.IgnoreObjectArgument = false;
6547   Candidate.ExplicitCallArguments = Args.size();
6548 
6549   unsigned NumParams = Proto->getNumParams();
6550 
6551   // (C++ 13.3.2p2): A candidate function having fewer than m
6552   // parameters is viable only if it has an ellipsis in its parameter
6553   // list (8.3.5).
6554   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6555       !Proto->isVariadic()) {
6556     Candidate.Viable = false;
6557     Candidate.FailureKind = ovl_fail_too_many_arguments;
6558     return;
6559   }
6560 
6561   // (C++ 13.3.2p2): A candidate function having more than m parameters
6562   // is viable only if the (m+1)st parameter has a default argument
6563   // (8.3.6). For the purposes of overload resolution, the
6564   // parameter list is truncated on the right, so that there are
6565   // exactly m parameters.
6566   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6567   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6568     // Not enough arguments.
6569     Candidate.Viable = false;
6570     Candidate.FailureKind = ovl_fail_too_few_arguments;
6571     return;
6572   }
6573 
6574   Candidate.Viable = true;
6575 
6576   if (Method->isStatic() || ObjectType.isNull())
6577     // The implicit object argument is ignored.
6578     Candidate.IgnoreObjectArgument = true;
6579   else {
6580     // Determine the implicit conversion sequence for the object
6581     // parameter.
6582     Candidate.Conversions[0] = TryObjectArgumentInitialization(
6583         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6584         Method, ActingContext);
6585     if (Candidate.Conversions[0].isBad()) {
6586       Candidate.Viable = false;
6587       Candidate.FailureKind = ovl_fail_bad_conversion;
6588       return;
6589     }
6590   }
6591 
6592   // (CUDA B.1): Check for invalid calls between targets.
6593   if (getLangOpts().CUDA)
6594     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6595       if (!IsAllowedCUDACall(Caller, Method)) {
6596         Candidate.Viable = false;
6597         Candidate.FailureKind = ovl_fail_bad_target;
6598         return;
6599       }
6600 
6601   // Determine the implicit conversion sequences for each of the
6602   // arguments.
6603   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6604     if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6605       // We already formed a conversion sequence for this parameter during
6606       // template argument deduction.
6607     } else if (ArgIdx < NumParams) {
6608       // (C++ 13.3.2p3): for F to be a viable function, there shall
6609       // exist for each argument an implicit conversion sequence
6610       // (13.3.3.1) that converts that argument to the corresponding
6611       // parameter of F.
6612       QualType ParamType = Proto->getParamType(ArgIdx);
6613       Candidate.Conversions[ArgIdx + 1]
6614         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6615                                 SuppressUserConversions,
6616                                 /*InOverloadResolution=*/true,
6617                                 /*AllowObjCWritebackConversion=*/
6618                                   getLangOpts().ObjCAutoRefCount);
6619       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6620         Candidate.Viable = false;
6621         Candidate.FailureKind = ovl_fail_bad_conversion;
6622         return;
6623       }
6624     } else {
6625       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6626       // argument for which there is no corresponding parameter is
6627       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6628       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6629     }
6630   }
6631 
6632   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6633     Candidate.Viable = false;
6634     Candidate.FailureKind = ovl_fail_enable_if;
6635     Candidate.DeductionFailure.Data = FailedAttr;
6636     return;
6637   }
6638 
6639   if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6640       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6641     Candidate.Viable = false;
6642     Candidate.FailureKind = ovl_non_default_multiversion_function;
6643   }
6644 }
6645 
6646 /// Add a C++ member function template as a candidate to the candidate
6647 /// set, using template argument deduction to produce an appropriate member
6648 /// function template specialization.
6649 void
6650 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6651                                  DeclAccessPair FoundDecl,
6652                                  CXXRecordDecl *ActingContext,
6653                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6654                                  QualType ObjectType,
6655                                  Expr::Classification ObjectClassification,
6656                                  ArrayRef<Expr *> Args,
6657                                  OverloadCandidateSet& CandidateSet,
6658                                  bool SuppressUserConversions,
6659                                  bool PartialOverloading) {
6660   if (!CandidateSet.isNewCandidate(MethodTmpl))
6661     return;
6662 
6663   // C++ [over.match.funcs]p7:
6664   //   In each case where a candidate is a function template, candidate
6665   //   function template specializations are generated using template argument
6666   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6667   //   candidate functions in the usual way.113) A given name can refer to one
6668   //   or more function templates and also to a set of overloaded non-template
6669   //   functions. In such a case, the candidate functions generated from each
6670   //   function template are combined with the set of non-template candidate
6671   //   functions.
6672   TemplateDeductionInfo Info(CandidateSet.getLocation());
6673   FunctionDecl *Specialization = nullptr;
6674   ConversionSequenceList Conversions;
6675   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6676           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6677           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6678             return CheckNonDependentConversions(
6679                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6680                 SuppressUserConversions, ActingContext, ObjectType,
6681                 ObjectClassification);
6682           })) {
6683     OverloadCandidate &Candidate =
6684         CandidateSet.addCandidate(Conversions.size(), Conversions);
6685     Candidate.FoundDecl = FoundDecl;
6686     Candidate.Function = MethodTmpl->getTemplatedDecl();
6687     Candidate.Viable = false;
6688     Candidate.IsSurrogate = false;
6689     Candidate.IgnoreObjectArgument =
6690         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6691         ObjectType.isNull();
6692     Candidate.ExplicitCallArguments = Args.size();
6693     if (Result == TDK_NonDependentConversionFailure)
6694       Candidate.FailureKind = ovl_fail_bad_conversion;
6695     else {
6696       Candidate.FailureKind = ovl_fail_bad_deduction;
6697       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6698                                                             Info);
6699     }
6700     return;
6701   }
6702 
6703   // Add the function template specialization produced by template argument
6704   // deduction as a candidate.
6705   assert(Specialization && "Missing member function template specialization?");
6706   assert(isa<CXXMethodDecl>(Specialization) &&
6707          "Specialization is not a member function?");
6708   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6709                      ActingContext, ObjectType, ObjectClassification, Args,
6710                      CandidateSet, SuppressUserConversions, PartialOverloading,
6711                      Conversions);
6712 }
6713 
6714 /// Add a C++ function template specialization as a candidate
6715 /// in the candidate set, using template argument deduction to produce
6716 /// an appropriate function template specialization.
6717 void Sema::AddTemplateOverloadCandidate(
6718     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
6719     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6720     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6721     bool PartialOverloading, ADLCallKind IsADLCandidate) {
6722   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6723     return;
6724 
6725   // C++ [over.match.funcs]p7:
6726   //   In each case where a candidate is a function template, candidate
6727   //   function template specializations are generated using template argument
6728   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6729   //   candidate functions in the usual way.113) A given name can refer to one
6730   //   or more function templates and also to a set of overloaded non-template
6731   //   functions. In such a case, the candidate functions generated from each
6732   //   function template are combined with the set of non-template candidate
6733   //   functions.
6734   TemplateDeductionInfo Info(CandidateSet.getLocation());
6735   FunctionDecl *Specialization = nullptr;
6736   ConversionSequenceList Conversions;
6737   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6738           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6739           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6740             return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6741                                                 Args, CandidateSet, Conversions,
6742                                                 SuppressUserConversions);
6743           })) {
6744     OverloadCandidate &Candidate =
6745         CandidateSet.addCandidate(Conversions.size(), Conversions);
6746     Candidate.FoundDecl = FoundDecl;
6747     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6748     Candidate.Viable = false;
6749     Candidate.IsSurrogate = false;
6750     Candidate.IsADLCandidate = IsADLCandidate;
6751     // Ignore the object argument if there is one, since we don't have an object
6752     // type.
6753     Candidate.IgnoreObjectArgument =
6754         isa<CXXMethodDecl>(Candidate.Function) &&
6755         !isa<CXXConstructorDecl>(Candidate.Function);
6756     Candidate.ExplicitCallArguments = Args.size();
6757     if (Result == TDK_NonDependentConversionFailure)
6758       Candidate.FailureKind = ovl_fail_bad_conversion;
6759     else {
6760       Candidate.FailureKind = ovl_fail_bad_deduction;
6761       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6762                                                             Info);
6763     }
6764     return;
6765   }
6766 
6767   // Add the function template specialization produced by template argument
6768   // deduction as a candidate.
6769   assert(Specialization && "Missing function template specialization?");
6770   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6771                        SuppressUserConversions, PartialOverloading,
6772                        /*AllowExplicit*/ false, IsADLCandidate, Conversions);
6773 }
6774 
6775 /// Check that implicit conversion sequences can be formed for each argument
6776 /// whose corresponding parameter has a non-dependent type, per DR1391's
6777 /// [temp.deduct.call]p10.
6778 bool Sema::CheckNonDependentConversions(
6779     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6780     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6781     ConversionSequenceList &Conversions, bool SuppressUserConversions,
6782     CXXRecordDecl *ActingContext, QualType ObjectType,
6783     Expr::Classification ObjectClassification) {
6784   // FIXME: The cases in which we allow explicit conversions for constructor
6785   // arguments never consider calling a constructor template. It's not clear
6786   // that is correct.
6787   const bool AllowExplicit = false;
6788 
6789   auto *FD = FunctionTemplate->getTemplatedDecl();
6790   auto *Method = dyn_cast<CXXMethodDecl>(FD);
6791   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6792   unsigned ThisConversions = HasThisConversion ? 1 : 0;
6793 
6794   Conversions =
6795       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6796 
6797   // Overload resolution is always an unevaluated context.
6798   EnterExpressionEvaluationContext Unevaluated(
6799       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6800 
6801   // For a method call, check the 'this' conversion here too. DR1391 doesn't
6802   // require that, but this check should never result in a hard error, and
6803   // overload resolution is permitted to sidestep instantiations.
6804   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6805       !ObjectType.isNull()) {
6806     Conversions[0] = TryObjectArgumentInitialization(
6807         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6808         Method, ActingContext);
6809     if (Conversions[0].isBad())
6810       return true;
6811   }
6812 
6813   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6814        ++I) {
6815     QualType ParamType = ParamTypes[I];
6816     if (!ParamType->isDependentType()) {
6817       Conversions[ThisConversions + I]
6818         = TryCopyInitialization(*this, Args[I], ParamType,
6819                                 SuppressUserConversions,
6820                                 /*InOverloadResolution=*/true,
6821                                 /*AllowObjCWritebackConversion=*/
6822                                   getLangOpts().ObjCAutoRefCount,
6823                                 AllowExplicit);
6824       if (Conversions[ThisConversions + I].isBad())
6825         return true;
6826     }
6827   }
6828 
6829   return false;
6830 }
6831 
6832 /// Determine whether this is an allowable conversion from the result
6833 /// of an explicit conversion operator to the expected type, per C++
6834 /// [over.match.conv]p1 and [over.match.ref]p1.
6835 ///
6836 /// \param ConvType The return type of the conversion function.
6837 ///
6838 /// \param ToType The type we are converting to.
6839 ///
6840 /// \param AllowObjCPointerConversion Allow a conversion from one
6841 /// Objective-C pointer to another.
6842 ///
6843 /// \returns true if the conversion is allowable, false otherwise.
6844 static bool isAllowableExplicitConversion(Sema &S,
6845                                           QualType ConvType, QualType ToType,
6846                                           bool AllowObjCPointerConversion) {
6847   QualType ToNonRefType = ToType.getNonReferenceType();
6848 
6849   // Easy case: the types are the same.
6850   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6851     return true;
6852 
6853   // Allow qualification conversions.
6854   bool ObjCLifetimeConversion;
6855   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6856                                   ObjCLifetimeConversion))
6857     return true;
6858 
6859   // If we're not allowed to consider Objective-C pointer conversions,
6860   // we're done.
6861   if (!AllowObjCPointerConversion)
6862     return false;
6863 
6864   // Is this an Objective-C pointer conversion?
6865   bool IncompatibleObjC = false;
6866   QualType ConvertedType;
6867   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6868                                    IncompatibleObjC);
6869 }
6870 
6871 /// AddConversionCandidate - Add a C++ conversion function as a
6872 /// candidate in the candidate set (C++ [over.match.conv],
6873 /// C++ [over.match.copy]). From is the expression we're converting from,
6874 /// and ToType is the type that we're eventually trying to convert to
6875 /// (which may or may not be the same type as the type that the
6876 /// conversion function produces).
6877 void
6878 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6879                              DeclAccessPair FoundDecl,
6880                              CXXRecordDecl *ActingContext,
6881                              Expr *From, QualType ToType,
6882                              OverloadCandidateSet& CandidateSet,
6883                              bool AllowObjCConversionOnExplicit,
6884                              bool AllowResultConversion) {
6885   assert(!Conversion->getDescribedFunctionTemplate() &&
6886          "Conversion function templates use AddTemplateConversionCandidate");
6887   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6888   if (!CandidateSet.isNewCandidate(Conversion))
6889     return;
6890 
6891   // If the conversion function has an undeduced return type, trigger its
6892   // deduction now.
6893   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6894     if (DeduceReturnType(Conversion, From->getExprLoc()))
6895       return;
6896     ConvType = Conversion->getConversionType().getNonReferenceType();
6897   }
6898 
6899   // If we don't allow any conversion of the result type, ignore conversion
6900   // functions that don't convert to exactly (possibly cv-qualified) T.
6901   if (!AllowResultConversion &&
6902       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
6903     return;
6904 
6905   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6906   // operator is only a candidate if its return type is the target type or
6907   // can be converted to the target type with a qualification conversion.
6908   if (Conversion->isExplicit() &&
6909       !isAllowableExplicitConversion(*this, ConvType, ToType,
6910                                      AllowObjCConversionOnExplicit))
6911     return;
6912 
6913   // Overload resolution is always an unevaluated context.
6914   EnterExpressionEvaluationContext Unevaluated(
6915       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6916 
6917   // Add this candidate
6918   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6919   Candidate.FoundDecl = FoundDecl;
6920   Candidate.Function = Conversion;
6921   Candidate.IsSurrogate = false;
6922   Candidate.IgnoreObjectArgument = false;
6923   Candidate.FinalConversion.setAsIdentityConversion();
6924   Candidate.FinalConversion.setFromType(ConvType);
6925   Candidate.FinalConversion.setAllToTypes(ToType);
6926   Candidate.Viable = true;
6927   Candidate.ExplicitCallArguments = 1;
6928 
6929   // C++ [over.match.funcs]p4:
6930   //   For conversion functions, the function is considered to be a member of
6931   //   the class of the implicit implied object argument for the purpose of
6932   //   defining the type of the implicit object parameter.
6933   //
6934   // Determine the implicit conversion sequence for the implicit
6935   // object parameter.
6936   QualType ImplicitParamType = From->getType();
6937   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6938     ImplicitParamType = FromPtrType->getPointeeType();
6939   CXXRecordDecl *ConversionContext
6940     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6941 
6942   Candidate.Conversions[0] = TryObjectArgumentInitialization(
6943       *this, CandidateSet.getLocation(), From->getType(),
6944       From->Classify(Context), Conversion, ConversionContext);
6945 
6946   if (Candidate.Conversions[0].isBad()) {
6947     Candidate.Viable = false;
6948     Candidate.FailureKind = ovl_fail_bad_conversion;
6949     return;
6950   }
6951 
6952   // We won't go through a user-defined type conversion function to convert a
6953   // derived to base as such conversions are given Conversion Rank. They only
6954   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6955   QualType FromCanon
6956     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6957   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6958   if (FromCanon == ToCanon ||
6959       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6960     Candidate.Viable = false;
6961     Candidate.FailureKind = ovl_fail_trivial_conversion;
6962     return;
6963   }
6964 
6965   // To determine what the conversion from the result of calling the
6966   // conversion function to the type we're eventually trying to
6967   // convert to (ToType), we need to synthesize a call to the
6968   // conversion function and attempt copy initialization from it. This
6969   // makes sure that we get the right semantics with respect to
6970   // lvalues/rvalues and the type. Fortunately, we can allocate this
6971   // call on the stack and we don't need its arguments to be
6972   // well-formed.
6973   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), VK_LValue,
6974                             From->getBeginLoc());
6975   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6976                                 Context.getPointerType(Conversion->getType()),
6977                                 CK_FunctionToPointerDecay,
6978                                 &ConversionRef, VK_RValue);
6979 
6980   QualType ConversionType = Conversion->getConversionType();
6981   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
6982     Candidate.Viable = false;
6983     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6984     return;
6985   }
6986 
6987   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6988 
6989   // Note that it is safe to allocate CallExpr on the stack here because
6990   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6991   // allocator).
6992   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6993   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6994                 From->getBeginLoc());
6995   ImplicitConversionSequence ICS =
6996     TryCopyInitialization(*this, &Call, ToType,
6997                           /*SuppressUserConversions=*/true,
6998                           /*InOverloadResolution=*/false,
6999                           /*AllowObjCWritebackConversion=*/false);
7000 
7001   switch (ICS.getKind()) {
7002   case ImplicitConversionSequence::StandardConversion:
7003     Candidate.FinalConversion = ICS.Standard;
7004 
7005     // C++ [over.ics.user]p3:
7006     //   If the user-defined conversion is specified by a specialization of a
7007     //   conversion function template, the second standard conversion sequence
7008     //   shall have exact match rank.
7009     if (Conversion->getPrimaryTemplate() &&
7010         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7011       Candidate.Viable = false;
7012       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7013       return;
7014     }
7015 
7016     // C++0x [dcl.init.ref]p5:
7017     //    In the second case, if the reference is an rvalue reference and
7018     //    the second standard conversion sequence of the user-defined
7019     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7020     //    program is ill-formed.
7021     if (ToType->isRValueReferenceType() &&
7022         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7023       Candidate.Viable = false;
7024       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7025       return;
7026     }
7027     break;
7028 
7029   case ImplicitConversionSequence::BadConversion:
7030     Candidate.Viable = false;
7031     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7032     return;
7033 
7034   default:
7035     llvm_unreachable(
7036            "Can only end up with a standard conversion sequence or failure");
7037   }
7038 
7039   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7040     Candidate.Viable = false;
7041     Candidate.FailureKind = ovl_fail_enable_if;
7042     Candidate.DeductionFailure.Data = FailedAttr;
7043     return;
7044   }
7045 
7046   if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7047       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7048     Candidate.Viable = false;
7049     Candidate.FailureKind = ovl_non_default_multiversion_function;
7050   }
7051 }
7052 
7053 /// Adds a conversion function template specialization
7054 /// candidate to the overload set, using template argument deduction
7055 /// to deduce the template arguments of the conversion function
7056 /// template from the type that we are converting to (C++
7057 /// [temp.deduct.conv]).
7058 void
7059 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
7060                                      DeclAccessPair FoundDecl,
7061                                      CXXRecordDecl *ActingDC,
7062                                      Expr *From, QualType ToType,
7063                                      OverloadCandidateSet &CandidateSet,
7064                                      bool AllowObjCConversionOnExplicit,
7065                                      bool AllowResultConversion) {
7066   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7067          "Only conversion function templates permitted here");
7068 
7069   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7070     return;
7071 
7072   TemplateDeductionInfo Info(CandidateSet.getLocation());
7073   CXXConversionDecl *Specialization = nullptr;
7074   if (TemplateDeductionResult Result
7075         = DeduceTemplateArguments(FunctionTemplate, ToType,
7076                                   Specialization, Info)) {
7077     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7078     Candidate.FoundDecl = FoundDecl;
7079     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7080     Candidate.Viable = false;
7081     Candidate.FailureKind = ovl_fail_bad_deduction;
7082     Candidate.IsSurrogate = false;
7083     Candidate.IgnoreObjectArgument = false;
7084     Candidate.ExplicitCallArguments = 1;
7085     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7086                                                           Info);
7087     return;
7088   }
7089 
7090   // Add the conversion function template specialization produced by
7091   // template argument deduction as a candidate.
7092   assert(Specialization && "Missing function template specialization?");
7093   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7094                          CandidateSet, AllowObjCConversionOnExplicit,
7095                          AllowResultConversion);
7096 }
7097 
7098 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7099 /// converts the given @c Object to a function pointer via the
7100 /// conversion function @c Conversion, and then attempts to call it
7101 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7102 /// the type of function that we'll eventually be calling.
7103 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7104                                  DeclAccessPair FoundDecl,
7105                                  CXXRecordDecl *ActingContext,
7106                                  const FunctionProtoType *Proto,
7107                                  Expr *Object,
7108                                  ArrayRef<Expr *> Args,
7109                                  OverloadCandidateSet& CandidateSet) {
7110   if (!CandidateSet.isNewCandidate(Conversion))
7111     return;
7112 
7113   // Overload resolution is always an unevaluated context.
7114   EnterExpressionEvaluationContext Unevaluated(
7115       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7116 
7117   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7118   Candidate.FoundDecl = FoundDecl;
7119   Candidate.Function = nullptr;
7120   Candidate.Surrogate = Conversion;
7121   Candidate.Viable = true;
7122   Candidate.IsSurrogate = true;
7123   Candidate.IgnoreObjectArgument = false;
7124   Candidate.ExplicitCallArguments = Args.size();
7125 
7126   // Determine the implicit conversion sequence for the implicit
7127   // object parameter.
7128   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7129       *this, CandidateSet.getLocation(), Object->getType(),
7130       Object->Classify(Context), Conversion, ActingContext);
7131   if (ObjectInit.isBad()) {
7132     Candidate.Viable = false;
7133     Candidate.FailureKind = ovl_fail_bad_conversion;
7134     Candidate.Conversions[0] = ObjectInit;
7135     return;
7136   }
7137 
7138   // The first conversion is actually a user-defined conversion whose
7139   // first conversion is ObjectInit's standard conversion (which is
7140   // effectively a reference binding). Record it as such.
7141   Candidate.Conversions[0].setUserDefined();
7142   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7143   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7144   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7145   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7146   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7147   Candidate.Conversions[0].UserDefined.After
7148     = Candidate.Conversions[0].UserDefined.Before;
7149   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7150 
7151   // Find the
7152   unsigned NumParams = Proto->getNumParams();
7153 
7154   // (C++ 13.3.2p2): A candidate function having fewer than m
7155   // parameters is viable only if it has an ellipsis in its parameter
7156   // list (8.3.5).
7157   if (Args.size() > NumParams && !Proto->isVariadic()) {
7158     Candidate.Viable = false;
7159     Candidate.FailureKind = ovl_fail_too_many_arguments;
7160     return;
7161   }
7162 
7163   // Function types don't have any default arguments, so just check if
7164   // we have enough arguments.
7165   if (Args.size() < NumParams) {
7166     // Not enough arguments.
7167     Candidate.Viable = false;
7168     Candidate.FailureKind = ovl_fail_too_few_arguments;
7169     return;
7170   }
7171 
7172   // Determine the implicit conversion sequences for each of the
7173   // arguments.
7174   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7175     if (ArgIdx < NumParams) {
7176       // (C++ 13.3.2p3): for F to be a viable function, there shall
7177       // exist for each argument an implicit conversion sequence
7178       // (13.3.3.1) that converts that argument to the corresponding
7179       // parameter of F.
7180       QualType ParamType = Proto->getParamType(ArgIdx);
7181       Candidate.Conversions[ArgIdx + 1]
7182         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7183                                 /*SuppressUserConversions=*/false,
7184                                 /*InOverloadResolution=*/false,
7185                                 /*AllowObjCWritebackConversion=*/
7186                                   getLangOpts().ObjCAutoRefCount);
7187       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7188         Candidate.Viable = false;
7189         Candidate.FailureKind = ovl_fail_bad_conversion;
7190         return;
7191       }
7192     } else {
7193       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7194       // argument for which there is no corresponding parameter is
7195       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7196       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7197     }
7198   }
7199 
7200   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7201     Candidate.Viable = false;
7202     Candidate.FailureKind = ovl_fail_enable_if;
7203     Candidate.DeductionFailure.Data = FailedAttr;
7204     return;
7205   }
7206 }
7207 
7208 /// Add overload candidates for overloaded operators that are
7209 /// member functions.
7210 ///
7211 /// Add the overloaded operator candidates that are member functions
7212 /// for the operator Op that was used in an operator expression such
7213 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7214 /// CandidateSet will store the added overload candidates. (C++
7215 /// [over.match.oper]).
7216 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7217                                        SourceLocation OpLoc,
7218                                        ArrayRef<Expr *> Args,
7219                                        OverloadCandidateSet& CandidateSet,
7220                                        SourceRange OpRange) {
7221   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7222 
7223   // C++ [over.match.oper]p3:
7224   //   For a unary operator @ with an operand of a type whose
7225   //   cv-unqualified version is T1, and for a binary operator @ with
7226   //   a left operand of a type whose cv-unqualified version is T1 and
7227   //   a right operand of a type whose cv-unqualified version is T2,
7228   //   three sets of candidate functions, designated member
7229   //   candidates, non-member candidates and built-in candidates, are
7230   //   constructed as follows:
7231   QualType T1 = Args[0]->getType();
7232 
7233   //     -- If T1 is a complete class type or a class currently being
7234   //        defined, the set of member candidates is the result of the
7235   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7236   //        the set of member candidates is empty.
7237   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7238     // Complete the type if it can be completed.
7239     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7240       return;
7241     // If the type is neither complete nor being defined, bail out now.
7242     if (!T1Rec->getDecl()->getDefinition())
7243       return;
7244 
7245     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7246     LookupQualifiedName(Operators, T1Rec->getDecl());
7247     Operators.suppressDiagnostics();
7248 
7249     for (LookupResult::iterator Oper = Operators.begin(),
7250                              OperEnd = Operators.end();
7251          Oper != OperEnd;
7252          ++Oper)
7253       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7254                          Args[0]->Classify(Context), Args.slice(1),
7255                          CandidateSet, /*SuppressUserConversions=*/false);
7256   }
7257 }
7258 
7259 /// AddBuiltinCandidate - Add a candidate for a built-in
7260 /// operator. ResultTy and ParamTys are the result and parameter types
7261 /// of the built-in candidate, respectively. Args and NumArgs are the
7262 /// arguments being passed to the candidate. IsAssignmentOperator
7263 /// should be true when this built-in candidate is an assignment
7264 /// operator. NumContextualBoolArguments is the number of arguments
7265 /// (at the beginning of the argument list) that will be contextually
7266 /// converted to bool.
7267 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7268                                OverloadCandidateSet& CandidateSet,
7269                                bool IsAssignmentOperator,
7270                                unsigned NumContextualBoolArguments) {
7271   // Overload resolution is always an unevaluated context.
7272   EnterExpressionEvaluationContext Unevaluated(
7273       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7274 
7275   // Add this candidate
7276   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7277   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7278   Candidate.Function = nullptr;
7279   Candidate.IsSurrogate = false;
7280   Candidate.IgnoreObjectArgument = false;
7281   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7282 
7283   // Determine the implicit conversion sequences for each of the
7284   // arguments.
7285   Candidate.Viable = true;
7286   Candidate.ExplicitCallArguments = Args.size();
7287   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7288     // C++ [over.match.oper]p4:
7289     //   For the built-in assignment operators, conversions of the
7290     //   left operand are restricted as follows:
7291     //     -- no temporaries are introduced to hold the left operand, and
7292     //     -- no user-defined conversions are applied to the left
7293     //        operand to achieve a type match with the left-most
7294     //        parameter of a built-in candidate.
7295     //
7296     // We block these conversions by turning off user-defined
7297     // conversions, since that is the only way that initialization of
7298     // a reference to a non-class type can occur from something that
7299     // is not of the same type.
7300     if (ArgIdx < NumContextualBoolArguments) {
7301       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7302              "Contextual conversion to bool requires bool type");
7303       Candidate.Conversions[ArgIdx]
7304         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7305     } else {
7306       Candidate.Conversions[ArgIdx]
7307         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7308                                 ArgIdx == 0 && IsAssignmentOperator,
7309                                 /*InOverloadResolution=*/false,
7310                                 /*AllowObjCWritebackConversion=*/
7311                                   getLangOpts().ObjCAutoRefCount);
7312     }
7313     if (Candidate.Conversions[ArgIdx].isBad()) {
7314       Candidate.Viable = false;
7315       Candidate.FailureKind = ovl_fail_bad_conversion;
7316       break;
7317     }
7318   }
7319 }
7320 
7321 namespace {
7322 
7323 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7324 /// candidate operator functions for built-in operators (C++
7325 /// [over.built]). The types are separated into pointer types and
7326 /// enumeration types.
7327 class BuiltinCandidateTypeSet  {
7328   /// TypeSet - A set of types.
7329   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7330                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7331 
7332   /// PointerTypes - The set of pointer types that will be used in the
7333   /// built-in candidates.
7334   TypeSet PointerTypes;
7335 
7336   /// MemberPointerTypes - The set of member pointer types that will be
7337   /// used in the built-in candidates.
7338   TypeSet MemberPointerTypes;
7339 
7340   /// EnumerationTypes - The set of enumeration types that will be
7341   /// used in the built-in candidates.
7342   TypeSet EnumerationTypes;
7343 
7344   /// The set of vector types that will be used in the built-in
7345   /// candidates.
7346   TypeSet VectorTypes;
7347 
7348   /// A flag indicating non-record types are viable candidates
7349   bool HasNonRecordTypes;
7350 
7351   /// A flag indicating whether either arithmetic or enumeration types
7352   /// were present in the candidate set.
7353   bool HasArithmeticOrEnumeralTypes;
7354 
7355   /// A flag indicating whether the nullptr type was present in the
7356   /// candidate set.
7357   bool HasNullPtrType;
7358 
7359   /// Sema - The semantic analysis instance where we are building the
7360   /// candidate type set.
7361   Sema &SemaRef;
7362 
7363   /// Context - The AST context in which we will build the type sets.
7364   ASTContext &Context;
7365 
7366   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7367                                                const Qualifiers &VisibleQuals);
7368   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7369 
7370 public:
7371   /// iterator - Iterates through the types that are part of the set.
7372   typedef TypeSet::iterator iterator;
7373 
7374   BuiltinCandidateTypeSet(Sema &SemaRef)
7375     : HasNonRecordTypes(false),
7376       HasArithmeticOrEnumeralTypes(false),
7377       HasNullPtrType(false),
7378       SemaRef(SemaRef),
7379       Context(SemaRef.Context) { }
7380 
7381   void AddTypesConvertedFrom(QualType Ty,
7382                              SourceLocation Loc,
7383                              bool AllowUserConversions,
7384                              bool AllowExplicitConversions,
7385                              const Qualifiers &VisibleTypeConversionsQuals);
7386 
7387   /// pointer_begin - First pointer type found;
7388   iterator pointer_begin() { return PointerTypes.begin(); }
7389 
7390   /// pointer_end - Past the last pointer type found;
7391   iterator pointer_end() { return PointerTypes.end(); }
7392 
7393   /// member_pointer_begin - First member pointer type found;
7394   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7395 
7396   /// member_pointer_end - Past the last member pointer type found;
7397   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7398 
7399   /// enumeration_begin - First enumeration type found;
7400   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7401 
7402   /// enumeration_end - Past the last enumeration type found;
7403   iterator enumeration_end() { return EnumerationTypes.end(); }
7404 
7405   iterator vector_begin() { return VectorTypes.begin(); }
7406   iterator vector_end() { return VectorTypes.end(); }
7407 
7408   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7409   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7410   bool hasNullPtrType() const { return HasNullPtrType; }
7411 };
7412 
7413 } // end anonymous namespace
7414 
7415 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7416 /// the set of pointer types along with any more-qualified variants of
7417 /// that type. For example, if @p Ty is "int const *", this routine
7418 /// will add "int const *", "int const volatile *", "int const
7419 /// restrict *", and "int const volatile restrict *" to the set of
7420 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7421 /// false otherwise.
7422 ///
7423 /// FIXME: what to do about extended qualifiers?
7424 bool
7425 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7426                                              const Qualifiers &VisibleQuals) {
7427 
7428   // Insert this type.
7429   if (!PointerTypes.insert(Ty))
7430     return false;
7431 
7432   QualType PointeeTy;
7433   const PointerType *PointerTy = Ty->getAs<PointerType>();
7434   bool buildObjCPtr = false;
7435   if (!PointerTy) {
7436     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7437     PointeeTy = PTy->getPointeeType();
7438     buildObjCPtr = true;
7439   } else {
7440     PointeeTy = PointerTy->getPointeeType();
7441   }
7442 
7443   // Don't add qualified variants of arrays. For one, they're not allowed
7444   // (the qualifier would sink to the element type), and for another, the
7445   // only overload situation where it matters is subscript or pointer +- int,
7446   // and those shouldn't have qualifier variants anyway.
7447   if (PointeeTy->isArrayType())
7448     return true;
7449 
7450   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7451   bool hasVolatile = VisibleQuals.hasVolatile();
7452   bool hasRestrict = VisibleQuals.hasRestrict();
7453 
7454   // Iterate through all strict supersets of BaseCVR.
7455   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7456     if ((CVR | BaseCVR) != CVR) continue;
7457     // Skip over volatile if no volatile found anywhere in the types.
7458     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7459 
7460     // Skip over restrict if no restrict found anywhere in the types, or if
7461     // the type cannot be restrict-qualified.
7462     if ((CVR & Qualifiers::Restrict) &&
7463         (!hasRestrict ||
7464          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7465       continue;
7466 
7467     // Build qualified pointee type.
7468     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7469 
7470     // Build qualified pointer type.
7471     QualType QPointerTy;
7472     if (!buildObjCPtr)
7473       QPointerTy = Context.getPointerType(QPointeeTy);
7474     else
7475       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7476 
7477     // Insert qualified pointer type.
7478     PointerTypes.insert(QPointerTy);
7479   }
7480 
7481   return true;
7482 }
7483 
7484 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7485 /// to the set of pointer types along with any more-qualified variants of
7486 /// that type. For example, if @p Ty is "int const *", this routine
7487 /// will add "int const *", "int const volatile *", "int const
7488 /// restrict *", and "int const volatile restrict *" to the set of
7489 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7490 /// false otherwise.
7491 ///
7492 /// FIXME: what to do about extended qualifiers?
7493 bool
7494 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7495     QualType Ty) {
7496   // Insert this type.
7497   if (!MemberPointerTypes.insert(Ty))
7498     return false;
7499 
7500   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7501   assert(PointerTy && "type was not a member pointer type!");
7502 
7503   QualType PointeeTy = PointerTy->getPointeeType();
7504   // Don't add qualified variants of arrays. For one, they're not allowed
7505   // (the qualifier would sink to the element type), and for another, the
7506   // only overload situation where it matters is subscript or pointer +- int,
7507   // and those shouldn't have qualifier variants anyway.
7508   if (PointeeTy->isArrayType())
7509     return true;
7510   const Type *ClassTy = PointerTy->getClass();
7511 
7512   // Iterate through all strict supersets of the pointee type's CVR
7513   // qualifiers.
7514   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7515   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7516     if ((CVR | BaseCVR) != CVR) continue;
7517 
7518     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7519     MemberPointerTypes.insert(
7520       Context.getMemberPointerType(QPointeeTy, ClassTy));
7521   }
7522 
7523   return true;
7524 }
7525 
7526 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7527 /// Ty can be implicit converted to the given set of @p Types. We're
7528 /// primarily interested in pointer types and enumeration types. We also
7529 /// take member pointer types, for the conditional operator.
7530 /// AllowUserConversions is true if we should look at the conversion
7531 /// functions of a class type, and AllowExplicitConversions if we
7532 /// should also include the explicit conversion functions of a class
7533 /// type.
7534 void
7535 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7536                                                SourceLocation Loc,
7537                                                bool AllowUserConversions,
7538                                                bool AllowExplicitConversions,
7539                                                const Qualifiers &VisibleQuals) {
7540   // Only deal with canonical types.
7541   Ty = Context.getCanonicalType(Ty);
7542 
7543   // Look through reference types; they aren't part of the type of an
7544   // expression for the purposes of conversions.
7545   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7546     Ty = RefTy->getPointeeType();
7547 
7548   // If we're dealing with an array type, decay to the pointer.
7549   if (Ty->isArrayType())
7550     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7551 
7552   // Otherwise, we don't care about qualifiers on the type.
7553   Ty = Ty.getLocalUnqualifiedType();
7554 
7555   // Flag if we ever add a non-record type.
7556   const RecordType *TyRec = Ty->getAs<RecordType>();
7557   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7558 
7559   // Flag if we encounter an arithmetic type.
7560   HasArithmeticOrEnumeralTypes =
7561     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7562 
7563   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7564     PointerTypes.insert(Ty);
7565   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7566     // Insert our type, and its more-qualified variants, into the set
7567     // of types.
7568     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7569       return;
7570   } else if (Ty->isMemberPointerType()) {
7571     // Member pointers are far easier, since the pointee can't be converted.
7572     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7573       return;
7574   } else if (Ty->isEnumeralType()) {
7575     HasArithmeticOrEnumeralTypes = true;
7576     EnumerationTypes.insert(Ty);
7577   } else if (Ty->isVectorType()) {
7578     // We treat vector types as arithmetic types in many contexts as an
7579     // extension.
7580     HasArithmeticOrEnumeralTypes = true;
7581     VectorTypes.insert(Ty);
7582   } else if (Ty->isNullPtrType()) {
7583     HasNullPtrType = true;
7584   } else if (AllowUserConversions && TyRec) {
7585     // No conversion functions in incomplete types.
7586     if (!SemaRef.isCompleteType(Loc, Ty))
7587       return;
7588 
7589     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7590     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7591       if (isa<UsingShadowDecl>(D))
7592         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7593 
7594       // Skip conversion function templates; they don't tell us anything
7595       // about which builtin types we can convert to.
7596       if (isa<FunctionTemplateDecl>(D))
7597         continue;
7598 
7599       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7600       if (AllowExplicitConversions || !Conv->isExplicit()) {
7601         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7602                               VisibleQuals);
7603       }
7604     }
7605   }
7606 }
7607 
7608 /// Helper function for AddBuiltinOperatorCandidates() that adds
7609 /// the volatile- and non-volatile-qualified assignment operators for the
7610 /// given type to the candidate set.
7611 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7612                                                    QualType T,
7613                                                    ArrayRef<Expr *> Args,
7614                                     OverloadCandidateSet &CandidateSet) {
7615   QualType ParamTypes[2];
7616 
7617   // T& operator=(T&, T)
7618   ParamTypes[0] = S.Context.getLValueReferenceType(T);
7619   ParamTypes[1] = T;
7620   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7621                         /*IsAssignmentOperator=*/true);
7622 
7623   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7624     // volatile T& operator=(volatile T&, T)
7625     ParamTypes[0]
7626       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7627     ParamTypes[1] = T;
7628     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7629                           /*IsAssignmentOperator=*/true);
7630   }
7631 }
7632 
7633 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7634 /// if any, found in visible type conversion functions found in ArgExpr's type.
7635 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7636     Qualifiers VRQuals;
7637     const RecordType *TyRec;
7638     if (const MemberPointerType *RHSMPType =
7639         ArgExpr->getType()->getAs<MemberPointerType>())
7640       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7641     else
7642       TyRec = ArgExpr->getType()->getAs<RecordType>();
7643     if (!TyRec) {
7644       // Just to be safe, assume the worst case.
7645       VRQuals.addVolatile();
7646       VRQuals.addRestrict();
7647       return VRQuals;
7648     }
7649 
7650     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7651     if (!ClassDecl->hasDefinition())
7652       return VRQuals;
7653 
7654     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7655       if (isa<UsingShadowDecl>(D))
7656         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7657       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7658         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7659         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7660           CanTy = ResTypeRef->getPointeeType();
7661         // Need to go down the pointer/mempointer chain and add qualifiers
7662         // as see them.
7663         bool done = false;
7664         while (!done) {
7665           if (CanTy.isRestrictQualified())
7666             VRQuals.addRestrict();
7667           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7668             CanTy = ResTypePtr->getPointeeType();
7669           else if (const MemberPointerType *ResTypeMPtr =
7670                 CanTy->getAs<MemberPointerType>())
7671             CanTy = ResTypeMPtr->getPointeeType();
7672           else
7673             done = true;
7674           if (CanTy.isVolatileQualified())
7675             VRQuals.addVolatile();
7676           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7677             return VRQuals;
7678         }
7679       }
7680     }
7681     return VRQuals;
7682 }
7683 
7684 namespace {
7685 
7686 /// Helper class to manage the addition of builtin operator overload
7687 /// candidates. It provides shared state and utility methods used throughout
7688 /// the process, as well as a helper method to add each group of builtin
7689 /// operator overloads from the standard to a candidate set.
7690 class BuiltinOperatorOverloadBuilder {
7691   // Common instance state available to all overload candidate addition methods.
7692   Sema &S;
7693   ArrayRef<Expr *> Args;
7694   Qualifiers VisibleTypeConversionsQuals;
7695   bool HasArithmeticOrEnumeralCandidateType;
7696   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7697   OverloadCandidateSet &CandidateSet;
7698 
7699   static constexpr int ArithmeticTypesCap = 24;
7700   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
7701 
7702   // Define some indices used to iterate over the arithemetic types in
7703   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
7704   // types are that preserved by promotion (C++ [over.built]p2).
7705   unsigned FirstIntegralType,
7706            LastIntegralType;
7707   unsigned FirstPromotedIntegralType,
7708            LastPromotedIntegralType;
7709   unsigned FirstPromotedArithmeticType,
7710            LastPromotedArithmeticType;
7711   unsigned NumArithmeticTypes;
7712 
7713   void InitArithmeticTypes() {
7714     // Start of promoted types.
7715     FirstPromotedArithmeticType = 0;
7716     ArithmeticTypes.push_back(S.Context.FloatTy);
7717     ArithmeticTypes.push_back(S.Context.DoubleTy);
7718     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7719     if (S.Context.getTargetInfo().hasFloat128Type())
7720       ArithmeticTypes.push_back(S.Context.Float128Ty);
7721 
7722     // Start of integral types.
7723     FirstIntegralType = ArithmeticTypes.size();
7724     FirstPromotedIntegralType = ArithmeticTypes.size();
7725     ArithmeticTypes.push_back(S.Context.IntTy);
7726     ArithmeticTypes.push_back(S.Context.LongTy);
7727     ArithmeticTypes.push_back(S.Context.LongLongTy);
7728     if (S.Context.getTargetInfo().hasInt128Type())
7729       ArithmeticTypes.push_back(S.Context.Int128Ty);
7730     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7731     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7732     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7733     if (S.Context.getTargetInfo().hasInt128Type())
7734       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7735     LastPromotedIntegralType = ArithmeticTypes.size();
7736     LastPromotedArithmeticType = ArithmeticTypes.size();
7737     // End of promoted types.
7738 
7739     ArithmeticTypes.push_back(S.Context.BoolTy);
7740     ArithmeticTypes.push_back(S.Context.CharTy);
7741     ArithmeticTypes.push_back(S.Context.WCharTy);
7742     if (S.Context.getLangOpts().Char8)
7743       ArithmeticTypes.push_back(S.Context.Char8Ty);
7744     ArithmeticTypes.push_back(S.Context.Char16Ty);
7745     ArithmeticTypes.push_back(S.Context.Char32Ty);
7746     ArithmeticTypes.push_back(S.Context.SignedCharTy);
7747     ArithmeticTypes.push_back(S.Context.ShortTy);
7748     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7749     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7750     LastIntegralType = ArithmeticTypes.size();
7751     NumArithmeticTypes = ArithmeticTypes.size();
7752     // End of integral types.
7753     // FIXME: What about complex? What about half?
7754 
7755     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
7756            "Enough inline storage for all arithmetic types.");
7757   }
7758 
7759   /// Helper method to factor out the common pattern of adding overloads
7760   /// for '++' and '--' builtin operators.
7761   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7762                                            bool HasVolatile,
7763                                            bool HasRestrict) {
7764     QualType ParamTypes[2] = {
7765       S.Context.getLValueReferenceType(CandidateTy),
7766       S.Context.IntTy
7767     };
7768 
7769     // Non-volatile version.
7770     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7771 
7772     // Use a heuristic to reduce number of builtin candidates in the set:
7773     // add volatile version only if there are conversions to a volatile type.
7774     if (HasVolatile) {
7775       ParamTypes[0] =
7776         S.Context.getLValueReferenceType(
7777           S.Context.getVolatileType(CandidateTy));
7778       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7779     }
7780 
7781     // Add restrict version only if there are conversions to a restrict type
7782     // and our candidate type is a non-restrict-qualified pointer.
7783     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7784         !CandidateTy.isRestrictQualified()) {
7785       ParamTypes[0]
7786         = S.Context.getLValueReferenceType(
7787             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7788       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7789 
7790       if (HasVolatile) {
7791         ParamTypes[0]
7792           = S.Context.getLValueReferenceType(
7793               S.Context.getCVRQualifiedType(CandidateTy,
7794                                             (Qualifiers::Volatile |
7795                                              Qualifiers::Restrict)));
7796         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7797       }
7798     }
7799 
7800   }
7801 
7802 public:
7803   BuiltinOperatorOverloadBuilder(
7804     Sema &S, ArrayRef<Expr *> Args,
7805     Qualifiers VisibleTypeConversionsQuals,
7806     bool HasArithmeticOrEnumeralCandidateType,
7807     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7808     OverloadCandidateSet &CandidateSet)
7809     : S(S), Args(Args),
7810       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7811       HasArithmeticOrEnumeralCandidateType(
7812         HasArithmeticOrEnumeralCandidateType),
7813       CandidateTypes(CandidateTypes),
7814       CandidateSet(CandidateSet) {
7815 
7816     InitArithmeticTypes();
7817   }
7818 
7819   // Increment is deprecated for bool since C++17.
7820   //
7821   // C++ [over.built]p3:
7822   //
7823   //   For every pair (T, VQ), where T is an arithmetic type other
7824   //   than bool, and VQ is either volatile or empty, there exist
7825   //   candidate operator functions of the form
7826   //
7827   //       VQ T&      operator++(VQ T&);
7828   //       T          operator++(VQ T&, int);
7829   //
7830   // C++ [over.built]p4:
7831   //
7832   //   For every pair (T, VQ), where T is an arithmetic type other
7833   //   than bool, and VQ is either volatile or empty, there exist
7834   //   candidate operator functions of the form
7835   //
7836   //       VQ T&      operator--(VQ T&);
7837   //       T          operator--(VQ T&, int);
7838   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7839     if (!HasArithmeticOrEnumeralCandidateType)
7840       return;
7841 
7842     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
7843       const auto TypeOfT = ArithmeticTypes[Arith];
7844       if (TypeOfT == S.Context.BoolTy) {
7845         if (Op == OO_MinusMinus)
7846           continue;
7847         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
7848           continue;
7849       }
7850       addPlusPlusMinusMinusStyleOverloads(
7851         TypeOfT,
7852         VisibleTypeConversionsQuals.hasVolatile(),
7853         VisibleTypeConversionsQuals.hasRestrict());
7854     }
7855   }
7856 
7857   // C++ [over.built]p5:
7858   //
7859   //   For every pair (T, VQ), where T is a cv-qualified or
7860   //   cv-unqualified object type, and VQ is either volatile or
7861   //   empty, there exist candidate operator functions of the form
7862   //
7863   //       T*VQ&      operator++(T*VQ&);
7864   //       T*VQ&      operator--(T*VQ&);
7865   //       T*         operator++(T*VQ&, int);
7866   //       T*         operator--(T*VQ&, int);
7867   void addPlusPlusMinusMinusPointerOverloads() {
7868     for (BuiltinCandidateTypeSet::iterator
7869               Ptr = CandidateTypes[0].pointer_begin(),
7870            PtrEnd = CandidateTypes[0].pointer_end();
7871          Ptr != PtrEnd; ++Ptr) {
7872       // Skip pointer types that aren't pointers to object types.
7873       if (!(*Ptr)->getPointeeType()->isObjectType())
7874         continue;
7875 
7876       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7877         (!(*Ptr).isVolatileQualified() &&
7878          VisibleTypeConversionsQuals.hasVolatile()),
7879         (!(*Ptr).isRestrictQualified() &&
7880          VisibleTypeConversionsQuals.hasRestrict()));
7881     }
7882   }
7883 
7884   // C++ [over.built]p6:
7885   //   For every cv-qualified or cv-unqualified object type T, there
7886   //   exist candidate operator functions of the form
7887   //
7888   //       T&         operator*(T*);
7889   //
7890   // C++ [over.built]p7:
7891   //   For every function type T that does not have cv-qualifiers or a
7892   //   ref-qualifier, there exist candidate operator functions of the form
7893   //       T&         operator*(T*);
7894   void addUnaryStarPointerOverloads() {
7895     for (BuiltinCandidateTypeSet::iterator
7896               Ptr = CandidateTypes[0].pointer_begin(),
7897            PtrEnd = CandidateTypes[0].pointer_end();
7898          Ptr != PtrEnd; ++Ptr) {
7899       QualType ParamTy = *Ptr;
7900       QualType PointeeTy = ParamTy->getPointeeType();
7901       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7902         continue;
7903 
7904       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7905         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7906           continue;
7907 
7908       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7909     }
7910   }
7911 
7912   // C++ [over.built]p9:
7913   //  For every promoted arithmetic type T, there exist candidate
7914   //  operator functions of the form
7915   //
7916   //       T         operator+(T);
7917   //       T         operator-(T);
7918   void addUnaryPlusOrMinusArithmeticOverloads() {
7919     if (!HasArithmeticOrEnumeralCandidateType)
7920       return;
7921 
7922     for (unsigned Arith = FirstPromotedArithmeticType;
7923          Arith < LastPromotedArithmeticType; ++Arith) {
7924       QualType ArithTy = ArithmeticTypes[Arith];
7925       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
7926     }
7927 
7928     // Extension: We also add these operators for vector types.
7929     for (BuiltinCandidateTypeSet::iterator
7930               Vec = CandidateTypes[0].vector_begin(),
7931            VecEnd = CandidateTypes[0].vector_end();
7932          Vec != VecEnd; ++Vec) {
7933       QualType VecTy = *Vec;
7934       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7935     }
7936   }
7937 
7938   // C++ [over.built]p8:
7939   //   For every type T, there exist candidate operator functions of
7940   //   the form
7941   //
7942   //       T*         operator+(T*);
7943   void addUnaryPlusPointerOverloads() {
7944     for (BuiltinCandidateTypeSet::iterator
7945               Ptr = CandidateTypes[0].pointer_begin(),
7946            PtrEnd = CandidateTypes[0].pointer_end();
7947          Ptr != PtrEnd; ++Ptr) {
7948       QualType ParamTy = *Ptr;
7949       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7950     }
7951   }
7952 
7953   // C++ [over.built]p10:
7954   //   For every promoted integral type T, there exist candidate
7955   //   operator functions of the form
7956   //
7957   //        T         operator~(T);
7958   void addUnaryTildePromotedIntegralOverloads() {
7959     if (!HasArithmeticOrEnumeralCandidateType)
7960       return;
7961 
7962     for (unsigned Int = FirstPromotedIntegralType;
7963          Int < LastPromotedIntegralType; ++Int) {
7964       QualType IntTy = ArithmeticTypes[Int];
7965       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
7966     }
7967 
7968     // Extension: We also add this operator for vector types.
7969     for (BuiltinCandidateTypeSet::iterator
7970               Vec = CandidateTypes[0].vector_begin(),
7971            VecEnd = CandidateTypes[0].vector_end();
7972          Vec != VecEnd; ++Vec) {
7973       QualType VecTy = *Vec;
7974       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7975     }
7976   }
7977 
7978   // C++ [over.match.oper]p16:
7979   //   For every pointer to member type T or type std::nullptr_t, there
7980   //   exist candidate operator functions of the form
7981   //
7982   //        bool operator==(T,T);
7983   //        bool operator!=(T,T);
7984   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
7985     /// Set of (canonical) types that we've already handled.
7986     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7987 
7988     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7989       for (BuiltinCandidateTypeSet::iterator
7990                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7991              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7992            MemPtr != MemPtrEnd;
7993            ++MemPtr) {
7994         // Don't add the same builtin candidate twice.
7995         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7996           continue;
7997 
7998         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7999         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8000       }
8001 
8002       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8003         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8004         if (AddedTypes.insert(NullPtrTy).second) {
8005           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8006           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8007         }
8008       }
8009     }
8010   }
8011 
8012   // C++ [over.built]p15:
8013   //
8014   //   For every T, where T is an enumeration type or a pointer type,
8015   //   there exist candidate operator functions of the form
8016   //
8017   //        bool       operator<(T, T);
8018   //        bool       operator>(T, T);
8019   //        bool       operator<=(T, T);
8020   //        bool       operator>=(T, T);
8021   //        bool       operator==(T, T);
8022   //        bool       operator!=(T, T);
8023   //           R       operator<=>(T, T)
8024   void addGenericBinaryPointerOrEnumeralOverloads() {
8025     // C++ [over.match.oper]p3:
8026     //   [...]the built-in candidates include all of the candidate operator
8027     //   functions defined in 13.6 that, compared to the given operator, [...]
8028     //   do not have the same parameter-type-list as any non-template non-member
8029     //   candidate.
8030     //
8031     // Note that in practice, this only affects enumeration types because there
8032     // aren't any built-in candidates of record type, and a user-defined operator
8033     // must have an operand of record or enumeration type. Also, the only other
8034     // overloaded operator with enumeration arguments, operator=,
8035     // cannot be overloaded for enumeration types, so this is the only place
8036     // where we must suppress candidates like this.
8037     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8038       UserDefinedBinaryOperators;
8039 
8040     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8041       if (CandidateTypes[ArgIdx].enumeration_begin() !=
8042           CandidateTypes[ArgIdx].enumeration_end()) {
8043         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8044                                          CEnd = CandidateSet.end();
8045              C != CEnd; ++C) {
8046           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8047             continue;
8048 
8049           if (C->Function->isFunctionTemplateSpecialization())
8050             continue;
8051 
8052           QualType FirstParamType =
8053             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
8054           QualType SecondParamType =
8055             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
8056 
8057           // Skip if either parameter isn't of enumeral type.
8058           if (!FirstParamType->isEnumeralType() ||
8059               !SecondParamType->isEnumeralType())
8060             continue;
8061 
8062           // Add this operator to the set of known user-defined operators.
8063           UserDefinedBinaryOperators.insert(
8064             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8065                            S.Context.getCanonicalType(SecondParamType)));
8066         }
8067       }
8068     }
8069 
8070     /// Set of (canonical) types that we've already handled.
8071     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8072 
8073     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8074       for (BuiltinCandidateTypeSet::iterator
8075                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8076              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8077            Ptr != PtrEnd; ++Ptr) {
8078         // Don't add the same builtin candidate twice.
8079         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8080           continue;
8081 
8082         QualType ParamTypes[2] = { *Ptr, *Ptr };
8083         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8084       }
8085       for (BuiltinCandidateTypeSet::iterator
8086                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8087              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8088            Enum != EnumEnd; ++Enum) {
8089         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8090 
8091         // Don't add the same builtin candidate twice, or if a user defined
8092         // candidate exists.
8093         if (!AddedTypes.insert(CanonType).second ||
8094             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8095                                                             CanonType)))
8096           continue;
8097         QualType ParamTypes[2] = { *Enum, *Enum };
8098         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8099       }
8100     }
8101   }
8102 
8103   // C++ [over.built]p13:
8104   //
8105   //   For every cv-qualified or cv-unqualified object type T
8106   //   there exist candidate operator functions of the form
8107   //
8108   //      T*         operator+(T*, ptrdiff_t);
8109   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8110   //      T*         operator-(T*, ptrdiff_t);
8111   //      T*         operator+(ptrdiff_t, T*);
8112   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8113   //
8114   // C++ [over.built]p14:
8115   //
8116   //   For every T, where T is a pointer to object type, there
8117   //   exist candidate operator functions of the form
8118   //
8119   //      ptrdiff_t  operator-(T, T);
8120   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8121     /// Set of (canonical) types that we've already handled.
8122     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8123 
8124     for (int Arg = 0; Arg < 2; ++Arg) {
8125       QualType AsymmetricParamTypes[2] = {
8126         S.Context.getPointerDiffType(),
8127         S.Context.getPointerDiffType(),
8128       };
8129       for (BuiltinCandidateTypeSet::iterator
8130                 Ptr = CandidateTypes[Arg].pointer_begin(),
8131              PtrEnd = CandidateTypes[Arg].pointer_end();
8132            Ptr != PtrEnd; ++Ptr) {
8133         QualType PointeeTy = (*Ptr)->getPointeeType();
8134         if (!PointeeTy->isObjectType())
8135           continue;
8136 
8137         AsymmetricParamTypes[Arg] = *Ptr;
8138         if (Arg == 0 || Op == OO_Plus) {
8139           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8140           // T* operator+(ptrdiff_t, T*);
8141           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8142         }
8143         if (Op == OO_Minus) {
8144           // ptrdiff_t operator-(T, T);
8145           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8146             continue;
8147 
8148           QualType ParamTypes[2] = { *Ptr, *Ptr };
8149           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8150         }
8151       }
8152     }
8153   }
8154 
8155   // C++ [over.built]p12:
8156   //
8157   //   For every pair of promoted arithmetic types L and R, there
8158   //   exist candidate operator functions of the form
8159   //
8160   //        LR         operator*(L, R);
8161   //        LR         operator/(L, R);
8162   //        LR         operator+(L, R);
8163   //        LR         operator-(L, R);
8164   //        bool       operator<(L, R);
8165   //        bool       operator>(L, R);
8166   //        bool       operator<=(L, R);
8167   //        bool       operator>=(L, R);
8168   //        bool       operator==(L, R);
8169   //        bool       operator!=(L, R);
8170   //
8171   //   where LR is the result of the usual arithmetic conversions
8172   //   between types L and R.
8173   //
8174   // C++ [over.built]p24:
8175   //
8176   //   For every pair of promoted arithmetic types L and R, there exist
8177   //   candidate operator functions of the form
8178   //
8179   //        LR       operator?(bool, L, R);
8180   //
8181   //   where LR is the result of the usual arithmetic conversions
8182   //   between types L and R.
8183   // Our candidates ignore the first parameter.
8184   void addGenericBinaryArithmeticOverloads() {
8185     if (!HasArithmeticOrEnumeralCandidateType)
8186       return;
8187 
8188     for (unsigned Left = FirstPromotedArithmeticType;
8189          Left < LastPromotedArithmeticType; ++Left) {
8190       for (unsigned Right = FirstPromotedArithmeticType;
8191            Right < LastPromotedArithmeticType; ++Right) {
8192         QualType LandR[2] = { ArithmeticTypes[Left],
8193                               ArithmeticTypes[Right] };
8194         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8195       }
8196     }
8197 
8198     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8199     // conditional operator for vector types.
8200     for (BuiltinCandidateTypeSet::iterator
8201               Vec1 = CandidateTypes[0].vector_begin(),
8202            Vec1End = CandidateTypes[0].vector_end();
8203          Vec1 != Vec1End; ++Vec1) {
8204       for (BuiltinCandidateTypeSet::iterator
8205                 Vec2 = CandidateTypes[1].vector_begin(),
8206              Vec2End = CandidateTypes[1].vector_end();
8207            Vec2 != Vec2End; ++Vec2) {
8208         QualType LandR[2] = { *Vec1, *Vec2 };
8209         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8210       }
8211     }
8212   }
8213 
8214   // C++2a [over.built]p14:
8215   //
8216   //   For every integral type T there exists a candidate operator function
8217   //   of the form
8218   //
8219   //        std::strong_ordering operator<=>(T, T)
8220   //
8221   // C++2a [over.built]p15:
8222   //
8223   //   For every pair of floating-point types L and R, there exists a candidate
8224   //   operator function of the form
8225   //
8226   //       std::partial_ordering operator<=>(L, R);
8227   //
8228   // FIXME: The current specification for integral types doesn't play nice with
8229   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8230   // comparisons. Under the current spec this can lead to ambiguity during
8231   // overload resolution. For example:
8232   //
8233   //   enum A : int {a};
8234   //   auto x = (a <=> (long)42);
8235   //
8236   //   error: call is ambiguous for arguments 'A' and 'long'.
8237   //   note: candidate operator<=>(int, int)
8238   //   note: candidate operator<=>(long, long)
8239   //
8240   // To avoid this error, this function deviates from the specification and adds
8241   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8242   // arithmetic types (the same as the generic relational overloads).
8243   //
8244   // For now this function acts as a placeholder.
8245   void addThreeWayArithmeticOverloads() {
8246     addGenericBinaryArithmeticOverloads();
8247   }
8248 
8249   // C++ [over.built]p17:
8250   //
8251   //   For every pair of promoted integral types L and R, there
8252   //   exist candidate operator functions of the form
8253   //
8254   //      LR         operator%(L, R);
8255   //      LR         operator&(L, R);
8256   //      LR         operator^(L, R);
8257   //      LR         operator|(L, R);
8258   //      L          operator<<(L, R);
8259   //      L          operator>>(L, R);
8260   //
8261   //   where LR is the result of the usual arithmetic conversions
8262   //   between types L and R.
8263   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8264     if (!HasArithmeticOrEnumeralCandidateType)
8265       return;
8266 
8267     for (unsigned Left = FirstPromotedIntegralType;
8268          Left < LastPromotedIntegralType; ++Left) {
8269       for (unsigned Right = FirstPromotedIntegralType;
8270            Right < LastPromotedIntegralType; ++Right) {
8271         QualType LandR[2] = { ArithmeticTypes[Left],
8272                               ArithmeticTypes[Right] };
8273         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8274       }
8275     }
8276   }
8277 
8278   // C++ [over.built]p20:
8279   //
8280   //   For every pair (T, VQ), where T is an enumeration or
8281   //   pointer to member type and VQ is either volatile or
8282   //   empty, there exist candidate operator functions of the form
8283   //
8284   //        VQ T&      operator=(VQ T&, T);
8285   void addAssignmentMemberPointerOrEnumeralOverloads() {
8286     /// Set of (canonical) types that we've already handled.
8287     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8288 
8289     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8290       for (BuiltinCandidateTypeSet::iterator
8291                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8292              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8293            Enum != EnumEnd; ++Enum) {
8294         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8295           continue;
8296 
8297         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8298       }
8299 
8300       for (BuiltinCandidateTypeSet::iterator
8301                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8302              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8303            MemPtr != MemPtrEnd; ++MemPtr) {
8304         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8305           continue;
8306 
8307         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8308       }
8309     }
8310   }
8311 
8312   // C++ [over.built]p19:
8313   //
8314   //   For every pair (T, VQ), where T is any type and VQ is either
8315   //   volatile or empty, there exist candidate operator functions
8316   //   of the form
8317   //
8318   //        T*VQ&      operator=(T*VQ&, T*);
8319   //
8320   // C++ [over.built]p21:
8321   //
8322   //   For every pair (T, VQ), where T is a cv-qualified or
8323   //   cv-unqualified object type and VQ is either volatile or
8324   //   empty, there exist candidate operator functions of the form
8325   //
8326   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8327   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8328   void addAssignmentPointerOverloads(bool isEqualOp) {
8329     /// Set of (canonical) types that we've already handled.
8330     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8331 
8332     for (BuiltinCandidateTypeSet::iterator
8333               Ptr = CandidateTypes[0].pointer_begin(),
8334            PtrEnd = CandidateTypes[0].pointer_end();
8335          Ptr != PtrEnd; ++Ptr) {
8336       // If this is operator=, keep track of the builtin candidates we added.
8337       if (isEqualOp)
8338         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8339       else if (!(*Ptr)->getPointeeType()->isObjectType())
8340         continue;
8341 
8342       // non-volatile version
8343       QualType ParamTypes[2] = {
8344         S.Context.getLValueReferenceType(*Ptr),
8345         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8346       };
8347       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8348                             /*IsAssigmentOperator=*/ isEqualOp);
8349 
8350       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8351                           VisibleTypeConversionsQuals.hasVolatile();
8352       if (NeedVolatile) {
8353         // volatile version
8354         ParamTypes[0] =
8355           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8356         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8357                               /*IsAssigmentOperator=*/isEqualOp);
8358       }
8359 
8360       if (!(*Ptr).isRestrictQualified() &&
8361           VisibleTypeConversionsQuals.hasRestrict()) {
8362         // restrict version
8363         ParamTypes[0]
8364           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8365         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8366                               /*IsAssigmentOperator=*/isEqualOp);
8367 
8368         if (NeedVolatile) {
8369           // volatile restrict version
8370           ParamTypes[0]
8371             = S.Context.getLValueReferenceType(
8372                 S.Context.getCVRQualifiedType(*Ptr,
8373                                               (Qualifiers::Volatile |
8374                                                Qualifiers::Restrict)));
8375           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8376                                 /*IsAssigmentOperator=*/isEqualOp);
8377         }
8378       }
8379     }
8380 
8381     if (isEqualOp) {
8382       for (BuiltinCandidateTypeSet::iterator
8383                 Ptr = CandidateTypes[1].pointer_begin(),
8384              PtrEnd = CandidateTypes[1].pointer_end();
8385            Ptr != PtrEnd; ++Ptr) {
8386         // Make sure we don't add the same candidate twice.
8387         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8388           continue;
8389 
8390         QualType ParamTypes[2] = {
8391           S.Context.getLValueReferenceType(*Ptr),
8392           *Ptr,
8393         };
8394 
8395         // non-volatile version
8396         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8397                               /*IsAssigmentOperator=*/true);
8398 
8399         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8400                            VisibleTypeConversionsQuals.hasVolatile();
8401         if (NeedVolatile) {
8402           // volatile version
8403           ParamTypes[0] =
8404             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8405           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8406                                 /*IsAssigmentOperator=*/true);
8407         }
8408 
8409         if (!(*Ptr).isRestrictQualified() &&
8410             VisibleTypeConversionsQuals.hasRestrict()) {
8411           // restrict version
8412           ParamTypes[0]
8413             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8414           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8415                                 /*IsAssigmentOperator=*/true);
8416 
8417           if (NeedVolatile) {
8418             // volatile restrict version
8419             ParamTypes[0]
8420               = S.Context.getLValueReferenceType(
8421                   S.Context.getCVRQualifiedType(*Ptr,
8422                                                 (Qualifiers::Volatile |
8423                                                  Qualifiers::Restrict)));
8424             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8425                                   /*IsAssigmentOperator=*/true);
8426           }
8427         }
8428       }
8429     }
8430   }
8431 
8432   // C++ [over.built]p18:
8433   //
8434   //   For every triple (L, VQ, R), where L is an arithmetic type,
8435   //   VQ is either volatile or empty, and R is a promoted
8436   //   arithmetic type, there exist candidate operator functions of
8437   //   the form
8438   //
8439   //        VQ L&      operator=(VQ L&, R);
8440   //        VQ L&      operator*=(VQ L&, R);
8441   //        VQ L&      operator/=(VQ L&, R);
8442   //        VQ L&      operator+=(VQ L&, R);
8443   //        VQ L&      operator-=(VQ L&, R);
8444   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8445     if (!HasArithmeticOrEnumeralCandidateType)
8446       return;
8447 
8448     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8449       for (unsigned Right = FirstPromotedArithmeticType;
8450            Right < LastPromotedArithmeticType; ++Right) {
8451         QualType ParamTypes[2];
8452         ParamTypes[1] = ArithmeticTypes[Right];
8453 
8454         // Add this built-in operator as a candidate (VQ is empty).
8455         ParamTypes[0] =
8456           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8457         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8458                               /*IsAssigmentOperator=*/isEqualOp);
8459 
8460         // Add this built-in operator as a candidate (VQ is 'volatile').
8461         if (VisibleTypeConversionsQuals.hasVolatile()) {
8462           ParamTypes[0] =
8463             S.Context.getVolatileType(ArithmeticTypes[Left]);
8464           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8465           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8466                                 /*IsAssigmentOperator=*/isEqualOp);
8467         }
8468       }
8469     }
8470 
8471     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8472     for (BuiltinCandidateTypeSet::iterator
8473               Vec1 = CandidateTypes[0].vector_begin(),
8474            Vec1End = CandidateTypes[0].vector_end();
8475          Vec1 != Vec1End; ++Vec1) {
8476       for (BuiltinCandidateTypeSet::iterator
8477                 Vec2 = CandidateTypes[1].vector_begin(),
8478              Vec2End = CandidateTypes[1].vector_end();
8479            Vec2 != Vec2End; ++Vec2) {
8480         QualType ParamTypes[2];
8481         ParamTypes[1] = *Vec2;
8482         // Add this built-in operator as a candidate (VQ is empty).
8483         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8484         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8485                               /*IsAssigmentOperator=*/isEqualOp);
8486 
8487         // Add this built-in operator as a candidate (VQ is 'volatile').
8488         if (VisibleTypeConversionsQuals.hasVolatile()) {
8489           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8490           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8491           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8492                                 /*IsAssigmentOperator=*/isEqualOp);
8493         }
8494       }
8495     }
8496   }
8497 
8498   // C++ [over.built]p22:
8499   //
8500   //   For every triple (L, VQ, R), where L is an integral type, VQ
8501   //   is either volatile or empty, and R is a promoted integral
8502   //   type, there exist candidate operator functions of the form
8503   //
8504   //        VQ L&       operator%=(VQ L&, R);
8505   //        VQ L&       operator<<=(VQ L&, R);
8506   //        VQ L&       operator>>=(VQ L&, R);
8507   //        VQ L&       operator&=(VQ L&, R);
8508   //        VQ L&       operator^=(VQ L&, R);
8509   //        VQ L&       operator|=(VQ L&, R);
8510   void addAssignmentIntegralOverloads() {
8511     if (!HasArithmeticOrEnumeralCandidateType)
8512       return;
8513 
8514     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8515       for (unsigned Right = FirstPromotedIntegralType;
8516            Right < LastPromotedIntegralType; ++Right) {
8517         QualType ParamTypes[2];
8518         ParamTypes[1] = ArithmeticTypes[Right];
8519 
8520         // Add this built-in operator as a candidate (VQ is empty).
8521         ParamTypes[0] =
8522           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8523         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8524         if (VisibleTypeConversionsQuals.hasVolatile()) {
8525           // Add this built-in operator as a candidate (VQ is 'volatile').
8526           ParamTypes[0] = ArithmeticTypes[Left];
8527           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8528           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8529           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8530         }
8531       }
8532     }
8533   }
8534 
8535   // C++ [over.operator]p23:
8536   //
8537   //   There also exist candidate operator functions of the form
8538   //
8539   //        bool        operator!(bool);
8540   //        bool        operator&&(bool, bool);
8541   //        bool        operator||(bool, bool);
8542   void addExclaimOverload() {
8543     QualType ParamTy = S.Context.BoolTy;
8544     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8545                           /*IsAssignmentOperator=*/false,
8546                           /*NumContextualBoolArguments=*/1);
8547   }
8548   void addAmpAmpOrPipePipeOverload() {
8549     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8550     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8551                           /*IsAssignmentOperator=*/false,
8552                           /*NumContextualBoolArguments=*/2);
8553   }
8554 
8555   // C++ [over.built]p13:
8556   //
8557   //   For every cv-qualified or cv-unqualified object type T there
8558   //   exist candidate operator functions of the form
8559   //
8560   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8561   //        T&         operator[](T*, ptrdiff_t);
8562   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8563   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8564   //        T&         operator[](ptrdiff_t, T*);
8565   void addSubscriptOverloads() {
8566     for (BuiltinCandidateTypeSet::iterator
8567               Ptr = CandidateTypes[0].pointer_begin(),
8568            PtrEnd = CandidateTypes[0].pointer_end();
8569          Ptr != PtrEnd; ++Ptr) {
8570       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8571       QualType PointeeType = (*Ptr)->getPointeeType();
8572       if (!PointeeType->isObjectType())
8573         continue;
8574 
8575       // T& operator[](T*, ptrdiff_t)
8576       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8577     }
8578 
8579     for (BuiltinCandidateTypeSet::iterator
8580               Ptr = CandidateTypes[1].pointer_begin(),
8581            PtrEnd = CandidateTypes[1].pointer_end();
8582          Ptr != PtrEnd; ++Ptr) {
8583       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8584       QualType PointeeType = (*Ptr)->getPointeeType();
8585       if (!PointeeType->isObjectType())
8586         continue;
8587 
8588       // T& operator[](ptrdiff_t, T*)
8589       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8590     }
8591   }
8592 
8593   // C++ [over.built]p11:
8594   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8595   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8596   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8597   //    there exist candidate operator functions of the form
8598   //
8599   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8600   //
8601   //    where CV12 is the union of CV1 and CV2.
8602   void addArrowStarOverloads() {
8603     for (BuiltinCandidateTypeSet::iterator
8604              Ptr = CandidateTypes[0].pointer_begin(),
8605            PtrEnd = CandidateTypes[0].pointer_end();
8606          Ptr != PtrEnd; ++Ptr) {
8607       QualType C1Ty = (*Ptr);
8608       QualType C1;
8609       QualifierCollector Q1;
8610       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8611       if (!isa<RecordType>(C1))
8612         continue;
8613       // heuristic to reduce number of builtin candidates in the set.
8614       // Add volatile/restrict version only if there are conversions to a
8615       // volatile/restrict type.
8616       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8617         continue;
8618       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8619         continue;
8620       for (BuiltinCandidateTypeSet::iterator
8621                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8622              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8623            MemPtr != MemPtrEnd; ++MemPtr) {
8624         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8625         QualType C2 = QualType(mptr->getClass(), 0);
8626         C2 = C2.getUnqualifiedType();
8627         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8628           break;
8629         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8630         // build CV12 T&
8631         QualType T = mptr->getPointeeType();
8632         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8633             T.isVolatileQualified())
8634           continue;
8635         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8636             T.isRestrictQualified())
8637           continue;
8638         T = Q1.apply(S.Context, T);
8639         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8640       }
8641     }
8642   }
8643 
8644   // Note that we don't consider the first argument, since it has been
8645   // contextually converted to bool long ago. The candidates below are
8646   // therefore added as binary.
8647   //
8648   // C++ [over.built]p25:
8649   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8650   //   enumeration type, there exist candidate operator functions of the form
8651   //
8652   //        T        operator?(bool, T, T);
8653   //
8654   void addConditionalOperatorOverloads() {
8655     /// Set of (canonical) types that we've already handled.
8656     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8657 
8658     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8659       for (BuiltinCandidateTypeSet::iterator
8660                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8661              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8662            Ptr != PtrEnd; ++Ptr) {
8663         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8664           continue;
8665 
8666         QualType ParamTypes[2] = { *Ptr, *Ptr };
8667         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8668       }
8669 
8670       for (BuiltinCandidateTypeSet::iterator
8671                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8672              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8673            MemPtr != MemPtrEnd; ++MemPtr) {
8674         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8675           continue;
8676 
8677         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8678         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8679       }
8680 
8681       if (S.getLangOpts().CPlusPlus11) {
8682         for (BuiltinCandidateTypeSet::iterator
8683                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8684                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8685              Enum != EnumEnd; ++Enum) {
8686           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8687             continue;
8688 
8689           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8690             continue;
8691 
8692           QualType ParamTypes[2] = { *Enum, *Enum };
8693           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8694         }
8695       }
8696     }
8697   }
8698 };
8699 
8700 } // end anonymous namespace
8701 
8702 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8703 /// operator overloads to the candidate set (C++ [over.built]), based
8704 /// on the operator @p Op and the arguments given. For example, if the
8705 /// operator is a binary '+', this routine might add "int
8706 /// operator+(int, int)" to cover integer addition.
8707 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8708                                         SourceLocation OpLoc,
8709                                         ArrayRef<Expr *> Args,
8710                                         OverloadCandidateSet &CandidateSet) {
8711   // Find all of the types that the arguments can convert to, but only
8712   // if the operator we're looking at has built-in operator candidates
8713   // that make use of these types. Also record whether we encounter non-record
8714   // candidate types or either arithmetic or enumeral candidate types.
8715   Qualifiers VisibleTypeConversionsQuals;
8716   VisibleTypeConversionsQuals.addConst();
8717   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8718     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8719 
8720   bool HasNonRecordCandidateType = false;
8721   bool HasArithmeticOrEnumeralCandidateType = false;
8722   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8723   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8724     CandidateTypes.emplace_back(*this);
8725     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8726                                                  OpLoc,
8727                                                  true,
8728                                                  (Op == OO_Exclaim ||
8729                                                   Op == OO_AmpAmp ||
8730                                                   Op == OO_PipePipe),
8731                                                  VisibleTypeConversionsQuals);
8732     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8733         CandidateTypes[ArgIdx].hasNonRecordTypes();
8734     HasArithmeticOrEnumeralCandidateType =
8735         HasArithmeticOrEnumeralCandidateType ||
8736         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8737   }
8738 
8739   // Exit early when no non-record types have been added to the candidate set
8740   // for any of the arguments to the operator.
8741   //
8742   // We can't exit early for !, ||, or &&, since there we have always have
8743   // 'bool' overloads.
8744   if (!HasNonRecordCandidateType &&
8745       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8746     return;
8747 
8748   // Setup an object to manage the common state for building overloads.
8749   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8750                                            VisibleTypeConversionsQuals,
8751                                            HasArithmeticOrEnumeralCandidateType,
8752                                            CandidateTypes, CandidateSet);
8753 
8754   // Dispatch over the operation to add in only those overloads which apply.
8755   switch (Op) {
8756   case OO_None:
8757   case NUM_OVERLOADED_OPERATORS:
8758     llvm_unreachable("Expected an overloaded operator");
8759 
8760   case OO_New:
8761   case OO_Delete:
8762   case OO_Array_New:
8763   case OO_Array_Delete:
8764   case OO_Call:
8765     llvm_unreachable(
8766                     "Special operators don't use AddBuiltinOperatorCandidates");
8767 
8768   case OO_Comma:
8769   case OO_Arrow:
8770   case OO_Coawait:
8771     // C++ [over.match.oper]p3:
8772     //   -- For the operator ',', the unary operator '&', the
8773     //      operator '->', or the operator 'co_await', the
8774     //      built-in candidates set is empty.
8775     break;
8776 
8777   case OO_Plus: // '+' is either unary or binary
8778     if (Args.size() == 1)
8779       OpBuilder.addUnaryPlusPointerOverloads();
8780     LLVM_FALLTHROUGH;
8781 
8782   case OO_Minus: // '-' is either unary or binary
8783     if (Args.size() == 1) {
8784       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8785     } else {
8786       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8787       OpBuilder.addGenericBinaryArithmeticOverloads();
8788     }
8789     break;
8790 
8791   case OO_Star: // '*' is either unary or binary
8792     if (Args.size() == 1)
8793       OpBuilder.addUnaryStarPointerOverloads();
8794     else
8795       OpBuilder.addGenericBinaryArithmeticOverloads();
8796     break;
8797 
8798   case OO_Slash:
8799     OpBuilder.addGenericBinaryArithmeticOverloads();
8800     break;
8801 
8802   case OO_PlusPlus:
8803   case OO_MinusMinus:
8804     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8805     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8806     break;
8807 
8808   case OO_EqualEqual:
8809   case OO_ExclaimEqual:
8810     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8811     LLVM_FALLTHROUGH;
8812 
8813   case OO_Less:
8814   case OO_Greater:
8815   case OO_LessEqual:
8816   case OO_GreaterEqual:
8817     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8818     OpBuilder.addGenericBinaryArithmeticOverloads();
8819     break;
8820 
8821   case OO_Spaceship:
8822     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8823     OpBuilder.addThreeWayArithmeticOverloads();
8824     break;
8825 
8826   case OO_Percent:
8827   case OO_Caret:
8828   case OO_Pipe:
8829   case OO_LessLess:
8830   case OO_GreaterGreater:
8831     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8832     break;
8833 
8834   case OO_Amp: // '&' is either unary or binary
8835     if (Args.size() == 1)
8836       // C++ [over.match.oper]p3:
8837       //   -- For the operator ',', the unary operator '&', or the
8838       //      operator '->', the built-in candidates set is empty.
8839       break;
8840 
8841     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8842     break;
8843 
8844   case OO_Tilde:
8845     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8846     break;
8847 
8848   case OO_Equal:
8849     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8850     LLVM_FALLTHROUGH;
8851 
8852   case OO_PlusEqual:
8853   case OO_MinusEqual:
8854     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8855     LLVM_FALLTHROUGH;
8856 
8857   case OO_StarEqual:
8858   case OO_SlashEqual:
8859     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8860     break;
8861 
8862   case OO_PercentEqual:
8863   case OO_LessLessEqual:
8864   case OO_GreaterGreaterEqual:
8865   case OO_AmpEqual:
8866   case OO_CaretEqual:
8867   case OO_PipeEqual:
8868     OpBuilder.addAssignmentIntegralOverloads();
8869     break;
8870 
8871   case OO_Exclaim:
8872     OpBuilder.addExclaimOverload();
8873     break;
8874 
8875   case OO_AmpAmp:
8876   case OO_PipePipe:
8877     OpBuilder.addAmpAmpOrPipePipeOverload();
8878     break;
8879 
8880   case OO_Subscript:
8881     OpBuilder.addSubscriptOverloads();
8882     break;
8883 
8884   case OO_ArrowStar:
8885     OpBuilder.addArrowStarOverloads();
8886     break;
8887 
8888   case OO_Conditional:
8889     OpBuilder.addConditionalOperatorOverloads();
8890     OpBuilder.addGenericBinaryArithmeticOverloads();
8891     break;
8892   }
8893 }
8894 
8895 /// Add function candidates found via argument-dependent lookup
8896 /// to the set of overloading candidates.
8897 ///
8898 /// This routine performs argument-dependent name lookup based on the
8899 /// given function name (which may also be an operator name) and adds
8900 /// all of the overload candidates found by ADL to the overload
8901 /// candidate set (C++ [basic.lookup.argdep]).
8902 void
8903 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8904                                            SourceLocation Loc,
8905                                            ArrayRef<Expr *> Args,
8906                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8907                                            OverloadCandidateSet& CandidateSet,
8908                                            bool PartialOverloading) {
8909   ADLResult Fns;
8910 
8911   // FIXME: This approach for uniquing ADL results (and removing
8912   // redundant candidates from the set) relies on pointer-equality,
8913   // which means we need to key off the canonical decl.  However,
8914   // always going back to the canonical decl might not get us the
8915   // right set of default arguments.  What default arguments are
8916   // we supposed to consider on ADL candidates, anyway?
8917 
8918   // FIXME: Pass in the explicit template arguments?
8919   ArgumentDependentLookup(Name, Loc, Args, Fns);
8920 
8921   // Erase all of the candidates we already knew about.
8922   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8923                                    CandEnd = CandidateSet.end();
8924        Cand != CandEnd; ++Cand)
8925     if (Cand->Function) {
8926       Fns.erase(Cand->Function);
8927       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8928         Fns.erase(FunTmpl);
8929     }
8930 
8931   // For each of the ADL candidates we found, add it to the overload
8932   // set.
8933   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8934     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8935 
8936     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8937       if (ExplicitTemplateArgs)
8938         continue;
8939 
8940       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet,
8941                            /*SupressUserConversions=*/false, PartialOverloading,
8942                            /*AllowExplicit=*/false, ADLCallKind::UsesADL);
8943     } else {
8944       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), FoundDecl,
8945                                    ExplicitTemplateArgs, Args, CandidateSet,
8946                                    /*SupressUserConversions=*/false,
8947                                    PartialOverloading, ADLCallKind::UsesADL);
8948     }
8949   }
8950 }
8951 
8952 namespace {
8953 enum class Comparison { Equal, Better, Worse };
8954 }
8955 
8956 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8957 /// overload resolution.
8958 ///
8959 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8960 /// Cand1's first N enable_if attributes have precisely the same conditions as
8961 /// Cand2's first N enable_if attributes (where N = the number of enable_if
8962 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8963 ///
8964 /// Note that you can have a pair of candidates such that Cand1's enable_if
8965 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8966 /// worse than Cand1's.
8967 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8968                                        const FunctionDecl *Cand2) {
8969   // Common case: One (or both) decls don't have enable_if attrs.
8970   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8971   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8972   if (!Cand1Attr || !Cand2Attr) {
8973     if (Cand1Attr == Cand2Attr)
8974       return Comparison::Equal;
8975     return Cand1Attr ? Comparison::Better : Comparison::Worse;
8976   }
8977 
8978   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
8979   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
8980 
8981   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8982   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
8983     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
8984     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
8985 
8986     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8987     // has fewer enable_if attributes than Cand2, and vice versa.
8988     if (!Cand1A)
8989       return Comparison::Worse;
8990     if (!Cand2A)
8991       return Comparison::Better;
8992 
8993     Cand1ID.clear();
8994     Cand2ID.clear();
8995 
8996     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8997     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8998     if (Cand1ID != Cand2ID)
8999       return Comparison::Worse;
9000   }
9001 
9002   return Comparison::Equal;
9003 }
9004 
9005 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9006                                           const OverloadCandidate &Cand2) {
9007   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9008       !Cand2.Function->isMultiVersion())
9009     return false;
9010 
9011   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9012   // cpu_dispatch, else arbitrarily based on the identifiers.
9013   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9014   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9015   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9016   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9017 
9018   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9019     return false;
9020 
9021   if (Cand1CPUDisp && !Cand2CPUDisp)
9022     return true;
9023   if (Cand2CPUDisp && !Cand1CPUDisp)
9024     return false;
9025 
9026   if (Cand1CPUSpec && Cand2CPUSpec) {
9027     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9028       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size();
9029 
9030     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9031         FirstDiff = std::mismatch(
9032             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9033             Cand2CPUSpec->cpus_begin(),
9034             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9035               return LHS->getName() == RHS->getName();
9036             });
9037 
9038     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9039            "Two different cpu-specific versions should not have the same "
9040            "identifier list, otherwise they'd be the same decl!");
9041     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName();
9042   }
9043   llvm_unreachable("No way to get here unless both had cpu_dispatch");
9044 }
9045 
9046 /// isBetterOverloadCandidate - Determines whether the first overload
9047 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9048 bool clang::isBetterOverloadCandidate(
9049     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9050     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9051   // Define viable functions to be better candidates than non-viable
9052   // functions.
9053   if (!Cand2.Viable)
9054     return Cand1.Viable;
9055   else if (!Cand1.Viable)
9056     return false;
9057 
9058   // C++ [over.match.best]p1:
9059   //
9060   //   -- if F is a static member function, ICS1(F) is defined such
9061   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9062   //      any function G, and, symmetrically, ICS1(G) is neither
9063   //      better nor worse than ICS1(F).
9064   unsigned StartArg = 0;
9065   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9066     StartArg = 1;
9067 
9068   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9069     // We don't allow incompatible pointer conversions in C++.
9070     if (!S.getLangOpts().CPlusPlus)
9071       return ICS.isStandard() &&
9072              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9073 
9074     // The only ill-formed conversion we allow in C++ is the string literal to
9075     // char* conversion, which is only considered ill-formed after C++11.
9076     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9077            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9078   };
9079 
9080   // Define functions that don't require ill-formed conversions for a given
9081   // argument to be better candidates than functions that do.
9082   unsigned NumArgs = Cand1.Conversions.size();
9083   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9084   bool HasBetterConversion = false;
9085   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9086     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9087     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9088     if (Cand1Bad != Cand2Bad) {
9089       if (Cand1Bad)
9090         return false;
9091       HasBetterConversion = true;
9092     }
9093   }
9094 
9095   if (HasBetterConversion)
9096     return true;
9097 
9098   // C++ [over.match.best]p1:
9099   //   A viable function F1 is defined to be a better function than another
9100   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9101   //   conversion sequence than ICSi(F2), and then...
9102   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9103     switch (CompareImplicitConversionSequences(S, Loc,
9104                                                Cand1.Conversions[ArgIdx],
9105                                                Cand2.Conversions[ArgIdx])) {
9106     case ImplicitConversionSequence::Better:
9107       // Cand1 has a better conversion sequence.
9108       HasBetterConversion = true;
9109       break;
9110 
9111     case ImplicitConversionSequence::Worse:
9112       // Cand1 can't be better than Cand2.
9113       return false;
9114 
9115     case ImplicitConversionSequence::Indistinguishable:
9116       // Do nothing.
9117       break;
9118     }
9119   }
9120 
9121   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9122   //       ICSj(F2), or, if not that,
9123   if (HasBetterConversion)
9124     return true;
9125 
9126   //   -- the context is an initialization by user-defined conversion
9127   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9128   //      from the return type of F1 to the destination type (i.e.,
9129   //      the type of the entity being initialized) is a better
9130   //      conversion sequence than the standard conversion sequence
9131   //      from the return type of F2 to the destination type.
9132   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9133       Cand1.Function && Cand2.Function &&
9134       isa<CXXConversionDecl>(Cand1.Function) &&
9135       isa<CXXConversionDecl>(Cand2.Function)) {
9136     // First check whether we prefer one of the conversion functions over the
9137     // other. This only distinguishes the results in non-standard, extension
9138     // cases such as the conversion from a lambda closure type to a function
9139     // pointer or block.
9140     ImplicitConversionSequence::CompareKind Result =
9141         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9142     if (Result == ImplicitConversionSequence::Indistinguishable)
9143       Result = CompareStandardConversionSequences(S, Loc,
9144                                                   Cand1.FinalConversion,
9145                                                   Cand2.FinalConversion);
9146 
9147     if (Result != ImplicitConversionSequence::Indistinguishable)
9148       return Result == ImplicitConversionSequence::Better;
9149 
9150     // FIXME: Compare kind of reference binding if conversion functions
9151     // convert to a reference type used in direct reference binding, per
9152     // C++14 [over.match.best]p1 section 2 bullet 3.
9153   }
9154 
9155   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9156   // as combined with the resolution to CWG issue 243.
9157   //
9158   // When the context is initialization by constructor ([over.match.ctor] or
9159   // either phase of [over.match.list]), a constructor is preferred over
9160   // a conversion function.
9161   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9162       Cand1.Function && Cand2.Function &&
9163       isa<CXXConstructorDecl>(Cand1.Function) !=
9164           isa<CXXConstructorDecl>(Cand2.Function))
9165     return isa<CXXConstructorDecl>(Cand1.Function);
9166 
9167   //    -- F1 is a non-template function and F2 is a function template
9168   //       specialization, or, if not that,
9169   bool Cand1IsSpecialization = Cand1.Function &&
9170                                Cand1.Function->getPrimaryTemplate();
9171   bool Cand2IsSpecialization = Cand2.Function &&
9172                                Cand2.Function->getPrimaryTemplate();
9173   if (Cand1IsSpecialization != Cand2IsSpecialization)
9174     return Cand2IsSpecialization;
9175 
9176   //   -- F1 and F2 are function template specializations, and the function
9177   //      template for F1 is more specialized than the template for F2
9178   //      according to the partial ordering rules described in 14.5.5.2, or,
9179   //      if not that,
9180   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9181     if (FunctionTemplateDecl *BetterTemplate
9182           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9183                                          Cand2.Function->getPrimaryTemplate(),
9184                                          Loc,
9185                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9186                                                              : TPOC_Call,
9187                                          Cand1.ExplicitCallArguments,
9188                                          Cand2.ExplicitCallArguments))
9189       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9190   }
9191 
9192   // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9193   // A derived-class constructor beats an (inherited) base class constructor.
9194   bool Cand1IsInherited =
9195       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9196   bool Cand2IsInherited =
9197       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9198   if (Cand1IsInherited != Cand2IsInherited)
9199     return Cand2IsInherited;
9200   else if (Cand1IsInherited) {
9201     assert(Cand2IsInherited);
9202     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9203     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9204     if (Cand1Class->isDerivedFrom(Cand2Class))
9205       return true;
9206     if (Cand2Class->isDerivedFrom(Cand1Class))
9207       return false;
9208     // Inherited from sibling base classes: still ambiguous.
9209   }
9210 
9211   // Check C++17 tie-breakers for deduction guides.
9212   {
9213     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9214     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9215     if (Guide1 && Guide2) {
9216       //  -- F1 is generated from a deduction-guide and F2 is not
9217       if (Guide1->isImplicit() != Guide2->isImplicit())
9218         return Guide2->isImplicit();
9219 
9220       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9221       if (Guide1->isCopyDeductionCandidate())
9222         return true;
9223     }
9224   }
9225 
9226   // Check for enable_if value-based overload resolution.
9227   if (Cand1.Function && Cand2.Function) {
9228     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9229     if (Cmp != Comparison::Equal)
9230       return Cmp == Comparison::Better;
9231   }
9232 
9233   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9234     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9235     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9236            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9237   }
9238 
9239   bool HasPS1 = Cand1.Function != nullptr &&
9240                 functionHasPassObjectSizeParams(Cand1.Function);
9241   bool HasPS2 = Cand2.Function != nullptr &&
9242                 functionHasPassObjectSizeParams(Cand2.Function);
9243   if (HasPS1 != HasPS2 && HasPS1)
9244     return true;
9245 
9246   return isBetterMultiversionCandidate(Cand1, Cand2);
9247 }
9248 
9249 /// Determine whether two declarations are "equivalent" for the purposes of
9250 /// name lookup and overload resolution. This applies when the same internal/no
9251 /// linkage entity is defined by two modules (probably by textually including
9252 /// the same header). In such a case, we don't consider the declarations to
9253 /// declare the same entity, but we also don't want lookups with both
9254 /// declarations visible to be ambiguous in some cases (this happens when using
9255 /// a modularized libstdc++).
9256 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9257                                                   const NamedDecl *B) {
9258   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9259   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9260   if (!VA || !VB)
9261     return false;
9262 
9263   // The declarations must be declaring the same name as an internal linkage
9264   // entity in different modules.
9265   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9266           VB->getDeclContext()->getRedeclContext()) ||
9267       getOwningModule(const_cast<ValueDecl *>(VA)) ==
9268           getOwningModule(const_cast<ValueDecl *>(VB)) ||
9269       VA->isExternallyVisible() || VB->isExternallyVisible())
9270     return false;
9271 
9272   // Check that the declarations appear to be equivalent.
9273   //
9274   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9275   // For constants and functions, we should check the initializer or body is
9276   // the same. For non-constant variables, we shouldn't allow it at all.
9277   if (Context.hasSameType(VA->getType(), VB->getType()))
9278     return true;
9279 
9280   // Enum constants within unnamed enumerations will have different types, but
9281   // may still be similar enough to be interchangeable for our purposes.
9282   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9283     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9284       // Only handle anonymous enums. If the enumerations were named and
9285       // equivalent, they would have been merged to the same type.
9286       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9287       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9288       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9289           !Context.hasSameType(EnumA->getIntegerType(),
9290                                EnumB->getIntegerType()))
9291         return false;
9292       // Allow this only if the value is the same for both enumerators.
9293       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9294     }
9295   }
9296 
9297   // Nothing else is sufficiently similar.
9298   return false;
9299 }
9300 
9301 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9302     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9303   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9304 
9305   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9306   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9307       << !M << (M ? M->getFullModuleName() : "");
9308 
9309   for (auto *E : Equiv) {
9310     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9311     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9312         << !M << (M ? M->getFullModuleName() : "");
9313   }
9314 }
9315 
9316 /// Computes the best viable function (C++ 13.3.3)
9317 /// within an overload candidate set.
9318 ///
9319 /// \param Loc The location of the function name (or operator symbol) for
9320 /// which overload resolution occurs.
9321 ///
9322 /// \param Best If overload resolution was successful or found a deleted
9323 /// function, \p Best points to the candidate function found.
9324 ///
9325 /// \returns The result of overload resolution.
9326 OverloadingResult
9327 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9328                                          iterator &Best) {
9329   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9330   std::transform(begin(), end(), std::back_inserter(Candidates),
9331                  [](OverloadCandidate &Cand) { return &Cand; });
9332 
9333   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9334   // are accepted by both clang and NVCC. However, during a particular
9335   // compilation mode only one call variant is viable. We need to
9336   // exclude non-viable overload candidates from consideration based
9337   // only on their host/device attributes. Specifically, if one
9338   // candidate call is WrongSide and the other is SameSide, we ignore
9339   // the WrongSide candidate.
9340   if (S.getLangOpts().CUDA) {
9341     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9342     bool ContainsSameSideCandidate =
9343         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9344           return Cand->Function &&
9345                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9346                      Sema::CFP_SameSide;
9347         });
9348     if (ContainsSameSideCandidate) {
9349       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9350         return Cand->Function &&
9351                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9352                    Sema::CFP_WrongSide;
9353       };
9354       llvm::erase_if(Candidates, IsWrongSideCandidate);
9355     }
9356   }
9357 
9358   // Find the best viable function.
9359   Best = end();
9360   for (auto *Cand : Candidates)
9361     if (Cand->Viable)
9362       if (Best == end() ||
9363           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9364         Best = Cand;
9365 
9366   // If we didn't find any viable functions, abort.
9367   if (Best == end())
9368     return OR_No_Viable_Function;
9369 
9370   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9371 
9372   // Make sure that this function is better than every other viable
9373   // function. If not, we have an ambiguity.
9374   for (auto *Cand : Candidates) {
9375     if (Cand->Viable && Cand != Best &&
9376         !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
9377       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9378                                                    Cand->Function)) {
9379         EquivalentCands.push_back(Cand->Function);
9380         continue;
9381       }
9382 
9383       Best = end();
9384       return OR_Ambiguous;
9385     }
9386   }
9387 
9388   // Best is the best viable function.
9389   if (Best->Function &&
9390       (Best->Function->isDeleted() ||
9391        S.isFunctionConsideredUnavailable(Best->Function)))
9392     return OR_Deleted;
9393 
9394   if (!EquivalentCands.empty())
9395     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9396                                                     EquivalentCands);
9397 
9398   return OR_Success;
9399 }
9400 
9401 namespace {
9402 
9403 enum OverloadCandidateKind {
9404   oc_function,
9405   oc_method,
9406   oc_constructor,
9407   oc_implicit_default_constructor,
9408   oc_implicit_copy_constructor,
9409   oc_implicit_move_constructor,
9410   oc_implicit_copy_assignment,
9411   oc_implicit_move_assignment,
9412   oc_inherited_constructor
9413 };
9414 
9415 enum OverloadCandidateSelect {
9416   ocs_non_template,
9417   ocs_template,
9418   ocs_described_template,
9419 };
9420 
9421 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
9422 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9423                           std::string &Description) {
9424 
9425   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9426   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9427     isTemplate = true;
9428     Description = S.getTemplateArgumentBindingsText(
9429         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9430   }
9431 
9432   OverloadCandidateSelect Select = [&]() {
9433     if (!Description.empty())
9434       return ocs_described_template;
9435     return isTemplate ? ocs_template : ocs_non_template;
9436   }();
9437 
9438   OverloadCandidateKind Kind = [&]() {
9439     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9440       if (!Ctor->isImplicit()) {
9441         if (isa<ConstructorUsingShadowDecl>(Found))
9442           return oc_inherited_constructor;
9443         else
9444           return oc_constructor;
9445       }
9446 
9447       if (Ctor->isDefaultConstructor())
9448         return oc_implicit_default_constructor;
9449 
9450       if (Ctor->isMoveConstructor())
9451         return oc_implicit_move_constructor;
9452 
9453       assert(Ctor->isCopyConstructor() &&
9454              "unexpected sort of implicit constructor");
9455       return oc_implicit_copy_constructor;
9456     }
9457 
9458     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9459       // This actually gets spelled 'candidate function' for now, but
9460       // it doesn't hurt to split it out.
9461       if (!Meth->isImplicit())
9462         return oc_method;
9463 
9464       if (Meth->isMoveAssignmentOperator())
9465         return oc_implicit_move_assignment;
9466 
9467       if (Meth->isCopyAssignmentOperator())
9468         return oc_implicit_copy_assignment;
9469 
9470       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9471       return oc_method;
9472     }
9473 
9474     return oc_function;
9475   }();
9476 
9477   return std::make_pair(Kind, Select);
9478 }
9479 
9480 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9481   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9482   // set.
9483   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9484     S.Diag(FoundDecl->getLocation(),
9485            diag::note_ovl_candidate_inherited_constructor)
9486       << Shadow->getNominatedBaseClass();
9487 }
9488 
9489 } // end anonymous namespace
9490 
9491 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9492                                     const FunctionDecl *FD) {
9493   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9494     bool AlwaysTrue;
9495     if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9496       return false;
9497     if (!AlwaysTrue)
9498       return false;
9499   }
9500   return true;
9501 }
9502 
9503 /// Returns true if we can take the address of the function.
9504 ///
9505 /// \param Complain - If true, we'll emit a diagnostic
9506 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9507 ///   we in overload resolution?
9508 /// \param Loc - The location of the statement we're complaining about. Ignored
9509 ///   if we're not complaining, or if we're in overload resolution.
9510 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9511                                               bool Complain,
9512                                               bool InOverloadResolution,
9513                                               SourceLocation Loc) {
9514   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9515     if (Complain) {
9516       if (InOverloadResolution)
9517         S.Diag(FD->getBeginLoc(),
9518                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9519       else
9520         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9521     }
9522     return false;
9523   }
9524 
9525   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9526     return P->hasAttr<PassObjectSizeAttr>();
9527   });
9528   if (I == FD->param_end())
9529     return true;
9530 
9531   if (Complain) {
9532     // Add one to ParamNo because it's user-facing
9533     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9534     if (InOverloadResolution)
9535       S.Diag(FD->getLocation(),
9536              diag::note_ovl_candidate_has_pass_object_size_params)
9537           << ParamNo;
9538     else
9539       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9540           << FD << ParamNo;
9541   }
9542   return false;
9543 }
9544 
9545 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9546                                                const FunctionDecl *FD) {
9547   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9548                                            /*InOverloadResolution=*/true,
9549                                            /*Loc=*/SourceLocation());
9550 }
9551 
9552 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9553                                              bool Complain,
9554                                              SourceLocation Loc) {
9555   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9556                                              /*InOverloadResolution=*/false,
9557                                              Loc);
9558 }
9559 
9560 // Notes the location of an overload candidate.
9561 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9562                                  QualType DestType, bool TakingAddress) {
9563   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9564     return;
9565   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
9566       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
9567     return;
9568 
9569   std::string FnDesc;
9570   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
9571       ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9572   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9573                          << (unsigned)KSPair.first << (unsigned)KSPair.second
9574                          << Fn << FnDesc;
9575 
9576   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9577   Diag(Fn->getLocation(), PD);
9578   MaybeEmitInheritedConstructorNote(*this, Found);
9579 }
9580 
9581 // Notes the location of all overload candidates designated through
9582 // OverloadedExpr
9583 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9584                                      bool TakingAddress) {
9585   assert(OverloadedExpr->getType() == Context.OverloadTy);
9586 
9587   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9588   OverloadExpr *OvlExpr = Ovl.Expression;
9589 
9590   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9591                             IEnd = OvlExpr->decls_end();
9592        I != IEnd; ++I) {
9593     if (FunctionTemplateDecl *FunTmpl =
9594                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9595       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9596                             TakingAddress);
9597     } else if (FunctionDecl *Fun
9598                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9599       NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9600     }
9601   }
9602 }
9603 
9604 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9605 /// "lead" diagnostic; it will be given two arguments, the source and
9606 /// target types of the conversion.
9607 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9608                                  Sema &S,
9609                                  SourceLocation CaretLoc,
9610                                  const PartialDiagnostic &PDiag) const {
9611   S.Diag(CaretLoc, PDiag)
9612     << Ambiguous.getFromType() << Ambiguous.getToType();
9613   // FIXME: The note limiting machinery is borrowed from
9614   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9615   // refactoring here.
9616   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9617   unsigned CandsShown = 0;
9618   AmbiguousConversionSequence::const_iterator I, E;
9619   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9620     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9621       break;
9622     ++CandsShown;
9623     S.NoteOverloadCandidate(I->first, I->second);
9624   }
9625   if (I != E)
9626     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9627 }
9628 
9629 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9630                                   unsigned I, bool TakingCandidateAddress) {
9631   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9632   assert(Conv.isBad());
9633   assert(Cand->Function && "for now, candidate must be a function");
9634   FunctionDecl *Fn = Cand->Function;
9635 
9636   // There's a conversion slot for the object argument if this is a
9637   // non-constructor method.  Note that 'I' corresponds the
9638   // conversion-slot index.
9639   bool isObjectArgument = false;
9640   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9641     if (I == 0)
9642       isObjectArgument = true;
9643     else
9644       I--;
9645   }
9646 
9647   std::string FnDesc;
9648   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
9649       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9650 
9651   Expr *FromExpr = Conv.Bad.FromExpr;
9652   QualType FromTy = Conv.Bad.getFromType();
9653   QualType ToTy = Conv.Bad.getToType();
9654 
9655   if (FromTy == S.Context.OverloadTy) {
9656     assert(FromExpr && "overload set argument came from implicit argument?");
9657     Expr *E = FromExpr->IgnoreParens();
9658     if (isa<UnaryOperator>(E))
9659       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9660     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9661 
9662     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9663         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9664         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
9665         << Name << I + 1;
9666     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9667     return;
9668   }
9669 
9670   // Do some hand-waving analysis to see if the non-viability is due
9671   // to a qualifier mismatch.
9672   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9673   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9674   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9675     CToTy = RT->getPointeeType();
9676   else {
9677     // TODO: detect and diagnose the full richness of const mismatches.
9678     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9679       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9680         CFromTy = FromPT->getPointeeType();
9681         CToTy = ToPT->getPointeeType();
9682       }
9683   }
9684 
9685   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9686       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9687     Qualifiers FromQs = CFromTy.getQualifiers();
9688     Qualifiers ToQs = CToTy.getQualifiers();
9689 
9690     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9691       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9692           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9693           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9694           << ToTy << (unsigned)isObjectArgument << I + 1;
9695       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9696       return;
9697     }
9698 
9699     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9700       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9701           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9702           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9703           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9704           << (unsigned)isObjectArgument << I + 1;
9705       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9706       return;
9707     }
9708 
9709     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9710       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9711           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9712           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9713           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9714           << (unsigned)isObjectArgument << I + 1;
9715       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9716       return;
9717     }
9718 
9719     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9720       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9721           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9722           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9723           << FromQs.hasUnaligned() << I + 1;
9724       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9725       return;
9726     }
9727 
9728     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9729     assert(CVR && "unexpected qualifiers mismatch");
9730 
9731     if (isObjectArgument) {
9732       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9733           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9734           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9735           << (CVR - 1);
9736     } else {
9737       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9738           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9739           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9740           << (CVR - 1) << I + 1;
9741     }
9742     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9743     return;
9744   }
9745 
9746   // Special diagnostic for failure to convert an initializer list, since
9747   // telling the user that it has type void is not useful.
9748   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9749     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9750         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9751         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9752         << ToTy << (unsigned)isObjectArgument << I + 1;
9753     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9754     return;
9755   }
9756 
9757   // Diagnose references or pointers to incomplete types differently,
9758   // since it's far from impossible that the incompleteness triggered
9759   // the failure.
9760   QualType TempFromTy = FromTy.getNonReferenceType();
9761   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9762     TempFromTy = PTy->getPointeeType();
9763   if (TempFromTy->isIncompleteType()) {
9764     // Emit the generic diagnostic and, optionally, add the hints to it.
9765     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9766         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9767         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9768         << ToTy << (unsigned)isObjectArgument << I + 1
9769         << (unsigned)(Cand->Fix.Kind);
9770 
9771     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9772     return;
9773   }
9774 
9775   // Diagnose base -> derived pointer conversions.
9776   unsigned BaseToDerivedConversion = 0;
9777   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9778     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9779       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9780                                                FromPtrTy->getPointeeType()) &&
9781           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9782           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9783           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9784                           FromPtrTy->getPointeeType()))
9785         BaseToDerivedConversion = 1;
9786     }
9787   } else if (const ObjCObjectPointerType *FromPtrTy
9788                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9789     if (const ObjCObjectPointerType *ToPtrTy
9790                                         = ToTy->getAs<ObjCObjectPointerType>())
9791       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9792         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9793           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9794                                                 FromPtrTy->getPointeeType()) &&
9795               FromIface->isSuperClassOf(ToIface))
9796             BaseToDerivedConversion = 2;
9797   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9798     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9799         !FromTy->isIncompleteType() &&
9800         !ToRefTy->getPointeeType()->isIncompleteType() &&
9801         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9802       BaseToDerivedConversion = 3;
9803     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9804                ToTy.getNonReferenceType().getCanonicalType() ==
9805                FromTy.getNonReferenceType().getCanonicalType()) {
9806       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9807           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9808           << (unsigned)isObjectArgument << I + 1
9809           << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
9810       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9811       return;
9812     }
9813   }
9814 
9815   if (BaseToDerivedConversion) {
9816     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
9817         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9818         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9819         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
9820     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9821     return;
9822   }
9823 
9824   if (isa<ObjCObjectPointerType>(CFromTy) &&
9825       isa<PointerType>(CToTy)) {
9826       Qualifiers FromQs = CFromTy.getQualifiers();
9827       Qualifiers ToQs = CToTy.getQualifiers();
9828       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9829         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9830             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9831             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9832             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
9833         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9834         return;
9835       }
9836   }
9837 
9838   if (TakingCandidateAddress &&
9839       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9840     return;
9841 
9842   // Emit the generic diagnostic and, optionally, add the hints to it.
9843   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9844   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9845         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9846         << ToTy << (unsigned)isObjectArgument << I + 1
9847         << (unsigned)(Cand->Fix.Kind);
9848 
9849   // If we can fix the conversion, suggest the FixIts.
9850   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9851        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9852     FDiag << *HI;
9853   S.Diag(Fn->getLocation(), FDiag);
9854 
9855   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9856 }
9857 
9858 /// Additional arity mismatch diagnosis specific to a function overload
9859 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9860 /// over a candidate in any candidate set.
9861 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9862                                unsigned NumArgs) {
9863   FunctionDecl *Fn = Cand->Function;
9864   unsigned MinParams = Fn->getMinRequiredArguments();
9865 
9866   // With invalid overloaded operators, it's possible that we think we
9867   // have an arity mismatch when in fact it looks like we have the
9868   // right number of arguments, because only overloaded operators have
9869   // the weird behavior of overloading member and non-member functions.
9870   // Just don't report anything.
9871   if (Fn->isInvalidDecl() &&
9872       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9873     return true;
9874 
9875   if (NumArgs < MinParams) {
9876     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9877            (Cand->FailureKind == ovl_fail_bad_deduction &&
9878             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9879   } else {
9880     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9881            (Cand->FailureKind == ovl_fail_bad_deduction &&
9882             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9883   }
9884 
9885   return false;
9886 }
9887 
9888 /// General arity mismatch diagnosis over a candidate in a candidate set.
9889 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9890                                   unsigned NumFormalArgs) {
9891   assert(isa<FunctionDecl>(D) &&
9892       "The templated declaration should at least be a function"
9893       " when diagnosing bad template argument deduction due to too many"
9894       " or too few arguments");
9895 
9896   FunctionDecl *Fn = cast<FunctionDecl>(D);
9897 
9898   // TODO: treat calls to a missing default constructor as a special case
9899   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9900   unsigned MinParams = Fn->getMinRequiredArguments();
9901 
9902   // at least / at most / exactly
9903   unsigned mode, modeCount;
9904   if (NumFormalArgs < MinParams) {
9905     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9906         FnTy->isTemplateVariadic())
9907       mode = 0; // "at least"
9908     else
9909       mode = 2; // "exactly"
9910     modeCount = MinParams;
9911   } else {
9912     if (MinParams != FnTy->getNumParams())
9913       mode = 1; // "at most"
9914     else
9915       mode = 2; // "exactly"
9916     modeCount = FnTy->getNumParams();
9917   }
9918 
9919   std::string Description;
9920   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
9921       ClassifyOverloadCandidate(S, Found, Fn, Description);
9922 
9923   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9924     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9925         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9926         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
9927   else
9928     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9929         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9930         << Description << mode << modeCount << NumFormalArgs;
9931 
9932   MaybeEmitInheritedConstructorNote(S, Found);
9933 }
9934 
9935 /// Arity mismatch diagnosis specific to a function overload candidate.
9936 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9937                                   unsigned NumFormalArgs) {
9938   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9939     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9940 }
9941 
9942 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9943   if (TemplateDecl *TD = Templated->getDescribedTemplate())
9944     return TD;
9945   llvm_unreachable("Unsupported: Getting the described template declaration"
9946                    " for bad deduction diagnosis");
9947 }
9948 
9949 /// Diagnose a failed template-argument deduction.
9950 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9951                                  DeductionFailureInfo &DeductionFailure,
9952                                  unsigned NumArgs,
9953                                  bool TakingCandidateAddress) {
9954   TemplateParameter Param = DeductionFailure.getTemplateParameter();
9955   NamedDecl *ParamD;
9956   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9957   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9958   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9959   switch (DeductionFailure.Result) {
9960   case Sema::TDK_Success:
9961     llvm_unreachable("TDK_success while diagnosing bad deduction");
9962 
9963   case Sema::TDK_Incomplete: {
9964     assert(ParamD && "no parameter found for incomplete deduction result");
9965     S.Diag(Templated->getLocation(),
9966            diag::note_ovl_candidate_incomplete_deduction)
9967         << ParamD->getDeclName();
9968     MaybeEmitInheritedConstructorNote(S, Found);
9969     return;
9970   }
9971 
9972   case Sema::TDK_IncompletePack: {
9973     assert(ParamD && "no parameter found for incomplete deduction result");
9974     S.Diag(Templated->getLocation(),
9975            diag::note_ovl_candidate_incomplete_deduction_pack)
9976         << ParamD->getDeclName()
9977         << (DeductionFailure.getFirstArg()->pack_size() + 1)
9978         << *DeductionFailure.getFirstArg();
9979     MaybeEmitInheritedConstructorNote(S, Found);
9980     return;
9981   }
9982 
9983   case Sema::TDK_Underqualified: {
9984     assert(ParamD && "no parameter found for bad qualifiers deduction result");
9985     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9986 
9987     QualType Param = DeductionFailure.getFirstArg()->getAsType();
9988 
9989     // Param will have been canonicalized, but it should just be a
9990     // qualified version of ParamD, so move the qualifiers to that.
9991     QualifierCollector Qs;
9992     Qs.strip(Param);
9993     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9994     assert(S.Context.hasSameType(Param, NonCanonParam));
9995 
9996     // Arg has also been canonicalized, but there's nothing we can do
9997     // about that.  It also doesn't matter as much, because it won't
9998     // have any template parameters in it (because deduction isn't
9999     // done on dependent types).
10000     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10001 
10002     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10003         << ParamD->getDeclName() << Arg << NonCanonParam;
10004     MaybeEmitInheritedConstructorNote(S, Found);
10005     return;
10006   }
10007 
10008   case Sema::TDK_Inconsistent: {
10009     assert(ParamD && "no parameter found for inconsistent deduction result");
10010     int which = 0;
10011     if (isa<TemplateTypeParmDecl>(ParamD))
10012       which = 0;
10013     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10014       // Deduction might have failed because we deduced arguments of two
10015       // different types for a non-type template parameter.
10016       // FIXME: Use a different TDK value for this.
10017       QualType T1 =
10018           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10019       QualType T2 =
10020           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10021       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10022         S.Diag(Templated->getLocation(),
10023                diag::note_ovl_candidate_inconsistent_deduction_types)
10024           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10025           << *DeductionFailure.getSecondArg() << T2;
10026         MaybeEmitInheritedConstructorNote(S, Found);
10027         return;
10028       }
10029 
10030       which = 1;
10031     } else {
10032       which = 2;
10033     }
10034 
10035     S.Diag(Templated->getLocation(),
10036            diag::note_ovl_candidate_inconsistent_deduction)
10037         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10038         << *DeductionFailure.getSecondArg();
10039     MaybeEmitInheritedConstructorNote(S, Found);
10040     return;
10041   }
10042 
10043   case Sema::TDK_InvalidExplicitArguments:
10044     assert(ParamD && "no parameter found for invalid explicit arguments");
10045     if (ParamD->getDeclName())
10046       S.Diag(Templated->getLocation(),
10047              diag::note_ovl_candidate_explicit_arg_mismatch_named)
10048           << ParamD->getDeclName();
10049     else {
10050       int index = 0;
10051       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10052         index = TTP->getIndex();
10053       else if (NonTypeTemplateParmDecl *NTTP
10054                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10055         index = NTTP->getIndex();
10056       else
10057         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10058       S.Diag(Templated->getLocation(),
10059              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10060           << (index + 1);
10061     }
10062     MaybeEmitInheritedConstructorNote(S, Found);
10063     return;
10064 
10065   case Sema::TDK_TooManyArguments:
10066   case Sema::TDK_TooFewArguments:
10067     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10068     return;
10069 
10070   case Sema::TDK_InstantiationDepth:
10071     S.Diag(Templated->getLocation(),
10072            diag::note_ovl_candidate_instantiation_depth);
10073     MaybeEmitInheritedConstructorNote(S, Found);
10074     return;
10075 
10076   case Sema::TDK_SubstitutionFailure: {
10077     // Format the template argument list into the argument string.
10078     SmallString<128> TemplateArgString;
10079     if (TemplateArgumentList *Args =
10080             DeductionFailure.getTemplateArgumentList()) {
10081       TemplateArgString = " ";
10082       TemplateArgString += S.getTemplateArgumentBindingsText(
10083           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10084     }
10085 
10086     // If this candidate was disabled by enable_if, say so.
10087     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10088     if (PDiag && PDiag->second.getDiagID() ==
10089           diag::err_typename_nested_not_found_enable_if) {
10090       // FIXME: Use the source range of the condition, and the fully-qualified
10091       //        name of the enable_if template. These are both present in PDiag.
10092       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10093         << "'enable_if'" << TemplateArgString;
10094       return;
10095     }
10096 
10097     // We found a specific requirement that disabled the enable_if.
10098     if (PDiag && PDiag->second.getDiagID() ==
10099         diag::err_typename_nested_not_found_requirement) {
10100       S.Diag(Templated->getLocation(),
10101              diag::note_ovl_candidate_disabled_by_requirement)
10102         << PDiag->second.getStringArg(0) << TemplateArgString;
10103       return;
10104     }
10105 
10106     // Format the SFINAE diagnostic into the argument string.
10107     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10108     //        formatted message in another diagnostic.
10109     SmallString<128> SFINAEArgString;
10110     SourceRange R;
10111     if (PDiag) {
10112       SFINAEArgString = ": ";
10113       R = SourceRange(PDiag->first, PDiag->first);
10114       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10115     }
10116 
10117     S.Diag(Templated->getLocation(),
10118            diag::note_ovl_candidate_substitution_failure)
10119         << TemplateArgString << SFINAEArgString << R;
10120     MaybeEmitInheritedConstructorNote(S, Found);
10121     return;
10122   }
10123 
10124   case Sema::TDK_DeducedMismatch:
10125   case Sema::TDK_DeducedMismatchNested: {
10126     // Format the template argument list into the argument string.
10127     SmallString<128> TemplateArgString;
10128     if (TemplateArgumentList *Args =
10129             DeductionFailure.getTemplateArgumentList()) {
10130       TemplateArgString = " ";
10131       TemplateArgString += S.getTemplateArgumentBindingsText(
10132           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10133     }
10134 
10135     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10136         << (*DeductionFailure.getCallArgIndex() + 1)
10137         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10138         << TemplateArgString
10139         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10140     break;
10141   }
10142 
10143   case Sema::TDK_NonDeducedMismatch: {
10144     // FIXME: Provide a source location to indicate what we couldn't match.
10145     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10146     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10147     if (FirstTA.getKind() == TemplateArgument::Template &&
10148         SecondTA.getKind() == TemplateArgument::Template) {
10149       TemplateName FirstTN = FirstTA.getAsTemplate();
10150       TemplateName SecondTN = SecondTA.getAsTemplate();
10151       if (FirstTN.getKind() == TemplateName::Template &&
10152           SecondTN.getKind() == TemplateName::Template) {
10153         if (FirstTN.getAsTemplateDecl()->getName() ==
10154             SecondTN.getAsTemplateDecl()->getName()) {
10155           // FIXME: This fixes a bad diagnostic where both templates are named
10156           // the same.  This particular case is a bit difficult since:
10157           // 1) It is passed as a string to the diagnostic printer.
10158           // 2) The diagnostic printer only attempts to find a better
10159           //    name for types, not decls.
10160           // Ideally, this should folded into the diagnostic printer.
10161           S.Diag(Templated->getLocation(),
10162                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10163               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10164           return;
10165         }
10166       }
10167     }
10168 
10169     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10170         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10171       return;
10172 
10173     // FIXME: For generic lambda parameters, check if the function is a lambda
10174     // call operator, and if so, emit a prettier and more informative
10175     // diagnostic that mentions 'auto' and lambda in addition to
10176     // (or instead of?) the canonical template type parameters.
10177     S.Diag(Templated->getLocation(),
10178            diag::note_ovl_candidate_non_deduced_mismatch)
10179         << FirstTA << SecondTA;
10180     return;
10181   }
10182   // TODO: diagnose these individually, then kill off
10183   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10184   case Sema::TDK_MiscellaneousDeductionFailure:
10185     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10186     MaybeEmitInheritedConstructorNote(S, Found);
10187     return;
10188   case Sema::TDK_CUDATargetMismatch:
10189     S.Diag(Templated->getLocation(),
10190            diag::note_cuda_ovl_candidate_target_mismatch);
10191     return;
10192   }
10193 }
10194 
10195 /// Diagnose a failed template-argument deduction, for function calls.
10196 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10197                                  unsigned NumArgs,
10198                                  bool TakingCandidateAddress) {
10199   unsigned TDK = Cand->DeductionFailure.Result;
10200   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10201     if (CheckArityMismatch(S, Cand, NumArgs))
10202       return;
10203   }
10204   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10205                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10206 }
10207 
10208 /// CUDA: diagnose an invalid call across targets.
10209 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10210   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10211   FunctionDecl *Callee = Cand->Function;
10212 
10213   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10214                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10215 
10216   std::string FnDesc;
10217   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10218       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
10219 
10220   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10221       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10222       << FnDesc /* Ignored */
10223       << CalleeTarget << CallerTarget;
10224 
10225   // This could be an implicit constructor for which we could not infer the
10226   // target due to a collsion. Diagnose that case.
10227   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10228   if (Meth != nullptr && Meth->isImplicit()) {
10229     CXXRecordDecl *ParentClass = Meth->getParent();
10230     Sema::CXXSpecialMember CSM;
10231 
10232     switch (FnKindPair.first) {
10233     default:
10234       return;
10235     case oc_implicit_default_constructor:
10236       CSM = Sema::CXXDefaultConstructor;
10237       break;
10238     case oc_implicit_copy_constructor:
10239       CSM = Sema::CXXCopyConstructor;
10240       break;
10241     case oc_implicit_move_constructor:
10242       CSM = Sema::CXXMoveConstructor;
10243       break;
10244     case oc_implicit_copy_assignment:
10245       CSM = Sema::CXXCopyAssignment;
10246       break;
10247     case oc_implicit_move_assignment:
10248       CSM = Sema::CXXMoveAssignment;
10249       break;
10250     };
10251 
10252     bool ConstRHS = false;
10253     if (Meth->getNumParams()) {
10254       if (const ReferenceType *RT =
10255               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10256         ConstRHS = RT->getPointeeType().isConstQualified();
10257       }
10258     }
10259 
10260     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10261                                               /* ConstRHS */ ConstRHS,
10262                                               /* Diagnose */ true);
10263   }
10264 }
10265 
10266 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10267   FunctionDecl *Callee = Cand->Function;
10268   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10269 
10270   S.Diag(Callee->getLocation(),
10271          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10272       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10273 }
10274 
10275 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10276   FunctionDecl *Callee = Cand->Function;
10277 
10278   S.Diag(Callee->getLocation(),
10279          diag::note_ovl_candidate_disabled_by_extension)
10280     << S.getOpenCLExtensionsFromDeclExtMap(Callee);
10281 }
10282 
10283 /// Generates a 'note' diagnostic for an overload candidate.  We've
10284 /// already generated a primary error at the call site.
10285 ///
10286 /// It really does need to be a single diagnostic with its caret
10287 /// pointed at the candidate declaration.  Yes, this creates some
10288 /// major challenges of technical writing.  Yes, this makes pointing
10289 /// out problems with specific arguments quite awkward.  It's still
10290 /// better than generating twenty screens of text for every failed
10291 /// overload.
10292 ///
10293 /// It would be great to be able to express per-candidate problems
10294 /// more richly for those diagnostic clients that cared, but we'd
10295 /// still have to be just as careful with the default diagnostics.
10296 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10297                                   unsigned NumArgs,
10298                                   bool TakingCandidateAddress) {
10299   FunctionDecl *Fn = Cand->Function;
10300 
10301   // Note deleted candidates, but only if they're viable.
10302   if (Cand->Viable) {
10303     if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10304       std::string FnDesc;
10305       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10306           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
10307 
10308       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10309           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10310           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10311       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10312       return;
10313     }
10314 
10315     // We don't really have anything else to say about viable candidates.
10316     S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10317     return;
10318   }
10319 
10320   switch (Cand->FailureKind) {
10321   case ovl_fail_too_many_arguments:
10322   case ovl_fail_too_few_arguments:
10323     return DiagnoseArityMismatch(S, Cand, NumArgs);
10324 
10325   case ovl_fail_bad_deduction:
10326     return DiagnoseBadDeduction(S, Cand, NumArgs,
10327                                 TakingCandidateAddress);
10328 
10329   case ovl_fail_illegal_constructor: {
10330     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10331       << (Fn->getPrimaryTemplate() ? 1 : 0);
10332     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10333     return;
10334   }
10335 
10336   case ovl_fail_trivial_conversion:
10337   case ovl_fail_bad_final_conversion:
10338   case ovl_fail_final_conversion_not_exact:
10339     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10340 
10341   case ovl_fail_bad_conversion: {
10342     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10343     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10344       if (Cand->Conversions[I].isBad())
10345         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10346 
10347     // FIXME: this currently happens when we're called from SemaInit
10348     // when user-conversion overload fails.  Figure out how to handle
10349     // those conditions and diagnose them well.
10350     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10351   }
10352 
10353   case ovl_fail_bad_target:
10354     return DiagnoseBadTarget(S, Cand);
10355 
10356   case ovl_fail_enable_if:
10357     return DiagnoseFailedEnableIfAttr(S, Cand);
10358 
10359   case ovl_fail_ext_disabled:
10360     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10361 
10362   case ovl_fail_inhctor_slice:
10363     // It's generally not interesting to note copy/move constructors here.
10364     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10365       return;
10366     S.Diag(Fn->getLocation(),
10367            diag::note_ovl_candidate_inherited_constructor_slice)
10368       << (Fn->getPrimaryTemplate() ? 1 : 0)
10369       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10370     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10371     return;
10372 
10373   case ovl_fail_addr_not_available: {
10374     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10375     (void)Available;
10376     assert(!Available);
10377     break;
10378   }
10379   case ovl_non_default_multiversion_function:
10380     // Do nothing, these should simply be ignored.
10381     break;
10382   }
10383 }
10384 
10385 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10386   // Desugar the type of the surrogate down to a function type,
10387   // retaining as many typedefs as possible while still showing
10388   // the function type (and, therefore, its parameter types).
10389   QualType FnType = Cand->Surrogate->getConversionType();
10390   bool isLValueReference = false;
10391   bool isRValueReference = false;
10392   bool isPointer = false;
10393   if (const LValueReferenceType *FnTypeRef =
10394         FnType->getAs<LValueReferenceType>()) {
10395     FnType = FnTypeRef->getPointeeType();
10396     isLValueReference = true;
10397   } else if (const RValueReferenceType *FnTypeRef =
10398                FnType->getAs<RValueReferenceType>()) {
10399     FnType = FnTypeRef->getPointeeType();
10400     isRValueReference = true;
10401   }
10402   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10403     FnType = FnTypePtr->getPointeeType();
10404     isPointer = true;
10405   }
10406   // Desugar down to a function type.
10407   FnType = QualType(FnType->getAs<FunctionType>(), 0);
10408   // Reconstruct the pointer/reference as appropriate.
10409   if (isPointer) FnType = S.Context.getPointerType(FnType);
10410   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10411   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10412 
10413   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10414     << FnType;
10415 }
10416 
10417 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10418                                          SourceLocation OpLoc,
10419                                          OverloadCandidate *Cand) {
10420   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10421   std::string TypeStr("operator");
10422   TypeStr += Opc;
10423   TypeStr += "(";
10424   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
10425   if (Cand->Conversions.size() == 1) {
10426     TypeStr += ")";
10427     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10428   } else {
10429     TypeStr += ", ";
10430     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
10431     TypeStr += ")";
10432     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10433   }
10434 }
10435 
10436 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10437                                          OverloadCandidate *Cand) {
10438   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10439     if (ICS.isBad()) break; // all meaningless after first invalid
10440     if (!ICS.isAmbiguous()) continue;
10441 
10442     ICS.DiagnoseAmbiguousConversion(
10443         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10444   }
10445 }
10446 
10447 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10448   if (Cand->Function)
10449     return Cand->Function->getLocation();
10450   if (Cand->IsSurrogate)
10451     return Cand->Surrogate->getLocation();
10452   return SourceLocation();
10453 }
10454 
10455 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10456   switch ((Sema::TemplateDeductionResult)DFI.Result) {
10457   case Sema::TDK_Success:
10458   case Sema::TDK_NonDependentConversionFailure:
10459     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10460 
10461   case Sema::TDK_Invalid:
10462   case Sema::TDK_Incomplete:
10463   case Sema::TDK_IncompletePack:
10464     return 1;
10465 
10466   case Sema::TDK_Underqualified:
10467   case Sema::TDK_Inconsistent:
10468     return 2;
10469 
10470   case Sema::TDK_SubstitutionFailure:
10471   case Sema::TDK_DeducedMismatch:
10472   case Sema::TDK_DeducedMismatchNested:
10473   case Sema::TDK_NonDeducedMismatch:
10474   case Sema::TDK_MiscellaneousDeductionFailure:
10475   case Sema::TDK_CUDATargetMismatch:
10476     return 3;
10477 
10478   case Sema::TDK_InstantiationDepth:
10479     return 4;
10480 
10481   case Sema::TDK_InvalidExplicitArguments:
10482     return 5;
10483 
10484   case Sema::TDK_TooManyArguments:
10485   case Sema::TDK_TooFewArguments:
10486     return 6;
10487   }
10488   llvm_unreachable("Unhandled deduction result");
10489 }
10490 
10491 namespace {
10492 struct CompareOverloadCandidatesForDisplay {
10493   Sema &S;
10494   SourceLocation Loc;
10495   size_t NumArgs;
10496   OverloadCandidateSet::CandidateSetKind CSK;
10497 
10498   CompareOverloadCandidatesForDisplay(
10499       Sema &S, SourceLocation Loc, size_t NArgs,
10500       OverloadCandidateSet::CandidateSetKind CSK)
10501       : S(S), NumArgs(NArgs), CSK(CSK) {}
10502 
10503   bool operator()(const OverloadCandidate *L,
10504                   const OverloadCandidate *R) {
10505     // Fast-path this check.
10506     if (L == R) return false;
10507 
10508     // Order first by viability.
10509     if (L->Viable) {
10510       if (!R->Viable) return true;
10511 
10512       // TODO: introduce a tri-valued comparison for overload
10513       // candidates.  Would be more worthwhile if we had a sort
10514       // that could exploit it.
10515       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10516         return true;
10517       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10518         return false;
10519     } else if (R->Viable)
10520       return false;
10521 
10522     assert(L->Viable == R->Viable);
10523 
10524     // Criteria by which we can sort non-viable candidates:
10525     if (!L->Viable) {
10526       // 1. Arity mismatches come after other candidates.
10527       if (L->FailureKind == ovl_fail_too_many_arguments ||
10528           L->FailureKind == ovl_fail_too_few_arguments) {
10529         if (R->FailureKind == ovl_fail_too_many_arguments ||
10530             R->FailureKind == ovl_fail_too_few_arguments) {
10531           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10532           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10533           if (LDist == RDist) {
10534             if (L->FailureKind == R->FailureKind)
10535               // Sort non-surrogates before surrogates.
10536               return !L->IsSurrogate && R->IsSurrogate;
10537             // Sort candidates requiring fewer parameters than there were
10538             // arguments given after candidates requiring more parameters
10539             // than there were arguments given.
10540             return L->FailureKind == ovl_fail_too_many_arguments;
10541           }
10542           return LDist < RDist;
10543         }
10544         return false;
10545       }
10546       if (R->FailureKind == ovl_fail_too_many_arguments ||
10547           R->FailureKind == ovl_fail_too_few_arguments)
10548         return true;
10549 
10550       // 2. Bad conversions come first and are ordered by the number
10551       // of bad conversions and quality of good conversions.
10552       if (L->FailureKind == ovl_fail_bad_conversion) {
10553         if (R->FailureKind != ovl_fail_bad_conversion)
10554           return true;
10555 
10556         // The conversion that can be fixed with a smaller number of changes,
10557         // comes first.
10558         unsigned numLFixes = L->Fix.NumConversionsFixed;
10559         unsigned numRFixes = R->Fix.NumConversionsFixed;
10560         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10561         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10562         if (numLFixes != numRFixes) {
10563           return numLFixes < numRFixes;
10564         }
10565 
10566         // If there's any ordering between the defined conversions...
10567         // FIXME: this might not be transitive.
10568         assert(L->Conversions.size() == R->Conversions.size());
10569 
10570         int leftBetter = 0;
10571         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10572         for (unsigned E = L->Conversions.size(); I != E; ++I) {
10573           switch (CompareImplicitConversionSequences(S, Loc,
10574                                                      L->Conversions[I],
10575                                                      R->Conversions[I])) {
10576           case ImplicitConversionSequence::Better:
10577             leftBetter++;
10578             break;
10579 
10580           case ImplicitConversionSequence::Worse:
10581             leftBetter--;
10582             break;
10583 
10584           case ImplicitConversionSequence::Indistinguishable:
10585             break;
10586           }
10587         }
10588         if (leftBetter > 0) return true;
10589         if (leftBetter < 0) return false;
10590 
10591       } else if (R->FailureKind == ovl_fail_bad_conversion)
10592         return false;
10593 
10594       if (L->FailureKind == ovl_fail_bad_deduction) {
10595         if (R->FailureKind != ovl_fail_bad_deduction)
10596           return true;
10597 
10598         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10599           return RankDeductionFailure(L->DeductionFailure)
10600                < RankDeductionFailure(R->DeductionFailure);
10601       } else if (R->FailureKind == ovl_fail_bad_deduction)
10602         return false;
10603 
10604       // TODO: others?
10605     }
10606 
10607     // Sort everything else by location.
10608     SourceLocation LLoc = GetLocationForCandidate(L);
10609     SourceLocation RLoc = GetLocationForCandidate(R);
10610 
10611     // Put candidates without locations (e.g. builtins) at the end.
10612     if (LLoc.isInvalid()) return false;
10613     if (RLoc.isInvalid()) return true;
10614 
10615     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10616   }
10617 };
10618 }
10619 
10620 /// CompleteNonViableCandidate - Normally, overload resolution only
10621 /// computes up to the first bad conversion. Produces the FixIt set if
10622 /// possible.
10623 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10624                                        ArrayRef<Expr *> Args) {
10625   assert(!Cand->Viable);
10626 
10627   // Don't do anything on failures other than bad conversion.
10628   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10629 
10630   // We only want the FixIts if all the arguments can be corrected.
10631   bool Unfixable = false;
10632   // Use a implicit copy initialization to check conversion fixes.
10633   Cand->Fix.setConversionChecker(TryCopyInitialization);
10634 
10635   // Attempt to fix the bad conversion.
10636   unsigned ConvCount = Cand->Conversions.size();
10637   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10638        ++ConvIdx) {
10639     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10640     if (Cand->Conversions[ConvIdx].isInitialized() &&
10641         Cand->Conversions[ConvIdx].isBad()) {
10642       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10643       break;
10644     }
10645   }
10646 
10647   // FIXME: this should probably be preserved from the overload
10648   // operation somehow.
10649   bool SuppressUserConversions = false;
10650 
10651   unsigned ConvIdx = 0;
10652   ArrayRef<QualType> ParamTypes;
10653 
10654   if (Cand->IsSurrogate) {
10655     QualType ConvType
10656       = Cand->Surrogate->getConversionType().getNonReferenceType();
10657     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10658       ConvType = ConvPtrType->getPointeeType();
10659     ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10660     // Conversion 0 is 'this', which doesn't have a corresponding argument.
10661     ConvIdx = 1;
10662   } else if (Cand->Function) {
10663     ParamTypes =
10664         Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
10665     if (isa<CXXMethodDecl>(Cand->Function) &&
10666         !isa<CXXConstructorDecl>(Cand->Function)) {
10667       // Conversion 0 is 'this', which doesn't have a corresponding argument.
10668       ConvIdx = 1;
10669     }
10670   } else {
10671     // Builtin operator.
10672     assert(ConvCount <= 3);
10673     ParamTypes = Cand->BuiltinParamTypes;
10674   }
10675 
10676   // Fill in the rest of the conversions.
10677   for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10678     if (Cand->Conversions[ConvIdx].isInitialized()) {
10679       // We've already checked this conversion.
10680     } else if (ArgIdx < ParamTypes.size()) {
10681       if (ParamTypes[ArgIdx]->isDependentType())
10682         Cand->Conversions[ConvIdx].setAsIdentityConversion(
10683             Args[ArgIdx]->getType());
10684       else {
10685         Cand->Conversions[ConvIdx] =
10686             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10687                                   SuppressUserConversions,
10688                                   /*InOverloadResolution=*/true,
10689                                   /*AllowObjCWritebackConversion=*/
10690                                   S.getLangOpts().ObjCAutoRefCount);
10691         // Store the FixIt in the candidate if it exists.
10692         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10693           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10694       }
10695     } else
10696       Cand->Conversions[ConvIdx].setEllipsis();
10697   }
10698 }
10699 
10700 /// When overload resolution fails, prints diagnostic messages containing the
10701 /// candidates in the candidate set.
10702 void OverloadCandidateSet::NoteCandidates(
10703     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10704     StringRef Opc, SourceLocation OpLoc,
10705     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10706   // Sort the candidates by viability and position.  Sorting directly would
10707   // be prohibitive, so we make a set of pointers and sort those.
10708   SmallVector<OverloadCandidate*, 32> Cands;
10709   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10710   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10711     if (!Filter(*Cand))
10712       continue;
10713     if (Cand->Viable)
10714       Cands.push_back(Cand);
10715     else if (OCD == OCD_AllCandidates) {
10716       CompleteNonViableCandidate(S, Cand, Args);
10717       if (Cand->Function || Cand->IsSurrogate)
10718         Cands.push_back(Cand);
10719       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10720       // want to list every possible builtin candidate.
10721     }
10722   }
10723 
10724   std::stable_sort(Cands.begin(), Cands.end(),
10725             CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
10726 
10727   bool ReportedAmbiguousConversions = false;
10728 
10729   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10730   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10731   unsigned CandsShown = 0;
10732   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10733     OverloadCandidate *Cand = *I;
10734 
10735     // Set an arbitrary limit on the number of candidate functions we'll spam
10736     // the user with.  FIXME: This limit should depend on details of the
10737     // candidate list.
10738     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10739       break;
10740     }
10741     ++CandsShown;
10742 
10743     if (Cand->Function)
10744       NoteFunctionCandidate(S, Cand, Args.size(),
10745                             /*TakingCandidateAddress=*/false);
10746     else if (Cand->IsSurrogate)
10747       NoteSurrogateCandidate(S, Cand);
10748     else {
10749       assert(Cand->Viable &&
10750              "Non-viable built-in candidates are not added to Cands.");
10751       // Generally we only see ambiguities including viable builtin
10752       // operators if overload resolution got screwed up by an
10753       // ambiguous user-defined conversion.
10754       //
10755       // FIXME: It's quite possible for different conversions to see
10756       // different ambiguities, though.
10757       if (!ReportedAmbiguousConversions) {
10758         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10759         ReportedAmbiguousConversions = true;
10760       }
10761 
10762       // If this is a viable builtin, print it.
10763       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10764     }
10765   }
10766 
10767   if (I != E)
10768     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10769 }
10770 
10771 static SourceLocation
10772 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10773   return Cand->Specialization ? Cand->Specialization->getLocation()
10774                               : SourceLocation();
10775 }
10776 
10777 namespace {
10778 struct CompareTemplateSpecCandidatesForDisplay {
10779   Sema &S;
10780   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10781 
10782   bool operator()(const TemplateSpecCandidate *L,
10783                   const TemplateSpecCandidate *R) {
10784     // Fast-path this check.
10785     if (L == R)
10786       return false;
10787 
10788     // Assuming that both candidates are not matches...
10789 
10790     // Sort by the ranking of deduction failures.
10791     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10792       return RankDeductionFailure(L->DeductionFailure) <
10793              RankDeductionFailure(R->DeductionFailure);
10794 
10795     // Sort everything else by location.
10796     SourceLocation LLoc = GetLocationForCandidate(L);
10797     SourceLocation RLoc = GetLocationForCandidate(R);
10798 
10799     // Put candidates without locations (e.g. builtins) at the end.
10800     if (LLoc.isInvalid())
10801       return false;
10802     if (RLoc.isInvalid())
10803       return true;
10804 
10805     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10806   }
10807 };
10808 }
10809 
10810 /// Diagnose a template argument deduction failure.
10811 /// We are treating these failures as overload failures due to bad
10812 /// deductions.
10813 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10814                                                  bool ForTakingAddress) {
10815   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10816                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10817 }
10818 
10819 void TemplateSpecCandidateSet::destroyCandidates() {
10820   for (iterator i = begin(), e = end(); i != e; ++i) {
10821     i->DeductionFailure.Destroy();
10822   }
10823 }
10824 
10825 void TemplateSpecCandidateSet::clear() {
10826   destroyCandidates();
10827   Candidates.clear();
10828 }
10829 
10830 /// NoteCandidates - When no template specialization match is found, prints
10831 /// diagnostic messages containing the non-matching specializations that form
10832 /// the candidate set.
10833 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10834 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10835 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10836   // Sort the candidates by position (assuming no candidate is a match).
10837   // Sorting directly would be prohibitive, so we make a set of pointers
10838   // and sort those.
10839   SmallVector<TemplateSpecCandidate *, 32> Cands;
10840   Cands.reserve(size());
10841   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10842     if (Cand->Specialization)
10843       Cands.push_back(Cand);
10844     // Otherwise, this is a non-matching builtin candidate.  We do not,
10845     // in general, want to list every possible builtin candidate.
10846   }
10847 
10848   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
10849 
10850   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10851   // for generalization purposes (?).
10852   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10853 
10854   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10855   unsigned CandsShown = 0;
10856   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10857     TemplateSpecCandidate *Cand = *I;
10858 
10859     // Set an arbitrary limit on the number of candidates we'll spam
10860     // the user with.  FIXME: This limit should depend on details of the
10861     // candidate list.
10862     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10863       break;
10864     ++CandsShown;
10865 
10866     assert(Cand->Specialization &&
10867            "Non-matching built-in candidates are not added to Cands.");
10868     Cand->NoteDeductionFailure(S, ForTakingAddress);
10869   }
10870 
10871   if (I != E)
10872     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10873 }
10874 
10875 // [PossiblyAFunctionType]  -->   [Return]
10876 // NonFunctionType --> NonFunctionType
10877 // R (A) --> R(A)
10878 // R (*)(A) --> R (A)
10879 // R (&)(A) --> R (A)
10880 // R (S::*)(A) --> R (A)
10881 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10882   QualType Ret = PossiblyAFunctionType;
10883   if (const PointerType *ToTypePtr =
10884     PossiblyAFunctionType->getAs<PointerType>())
10885     Ret = ToTypePtr->getPointeeType();
10886   else if (const ReferenceType *ToTypeRef =
10887     PossiblyAFunctionType->getAs<ReferenceType>())
10888     Ret = ToTypeRef->getPointeeType();
10889   else if (const MemberPointerType *MemTypePtr =
10890     PossiblyAFunctionType->getAs<MemberPointerType>())
10891     Ret = MemTypePtr->getPointeeType();
10892   Ret =
10893     Context.getCanonicalType(Ret).getUnqualifiedType();
10894   return Ret;
10895 }
10896 
10897 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10898                                  bool Complain = true) {
10899   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10900       S.DeduceReturnType(FD, Loc, Complain))
10901     return true;
10902 
10903   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10904   if (S.getLangOpts().CPlusPlus17 &&
10905       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10906       !S.ResolveExceptionSpec(Loc, FPT))
10907     return true;
10908 
10909   return false;
10910 }
10911 
10912 namespace {
10913 // A helper class to help with address of function resolution
10914 // - allows us to avoid passing around all those ugly parameters
10915 class AddressOfFunctionResolver {
10916   Sema& S;
10917   Expr* SourceExpr;
10918   const QualType& TargetType;
10919   QualType TargetFunctionType; // Extracted function type from target type
10920 
10921   bool Complain;
10922   //DeclAccessPair& ResultFunctionAccessPair;
10923   ASTContext& Context;
10924 
10925   bool TargetTypeIsNonStaticMemberFunction;
10926   bool FoundNonTemplateFunction;
10927   bool StaticMemberFunctionFromBoundPointer;
10928   bool HasComplained;
10929 
10930   OverloadExpr::FindResult OvlExprInfo;
10931   OverloadExpr *OvlExpr;
10932   TemplateArgumentListInfo OvlExplicitTemplateArgs;
10933   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10934   TemplateSpecCandidateSet FailedCandidates;
10935 
10936 public:
10937   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10938                             const QualType &TargetType, bool Complain)
10939       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10940         Complain(Complain), Context(S.getASTContext()),
10941         TargetTypeIsNonStaticMemberFunction(
10942             !!TargetType->getAs<MemberPointerType>()),
10943         FoundNonTemplateFunction(false),
10944         StaticMemberFunctionFromBoundPointer(false),
10945         HasComplained(false),
10946         OvlExprInfo(OverloadExpr::find(SourceExpr)),
10947         OvlExpr(OvlExprInfo.Expression),
10948         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10949     ExtractUnqualifiedFunctionTypeFromTargetType();
10950 
10951     if (TargetFunctionType->isFunctionType()) {
10952       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10953         if (!UME->isImplicitAccess() &&
10954             !S.ResolveSingleFunctionTemplateSpecialization(UME))
10955           StaticMemberFunctionFromBoundPointer = true;
10956     } else if (OvlExpr->hasExplicitTemplateArgs()) {
10957       DeclAccessPair dap;
10958       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10959               OvlExpr, false, &dap)) {
10960         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10961           if (!Method->isStatic()) {
10962             // If the target type is a non-function type and the function found
10963             // is a non-static member function, pretend as if that was the
10964             // target, it's the only possible type to end up with.
10965             TargetTypeIsNonStaticMemberFunction = true;
10966 
10967             // And skip adding the function if its not in the proper form.
10968             // We'll diagnose this due to an empty set of functions.
10969             if (!OvlExprInfo.HasFormOfMemberPointer)
10970               return;
10971           }
10972 
10973         Matches.push_back(std::make_pair(dap, Fn));
10974       }
10975       return;
10976     }
10977 
10978     if (OvlExpr->hasExplicitTemplateArgs())
10979       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10980 
10981     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10982       // C++ [over.over]p4:
10983       //   If more than one function is selected, [...]
10984       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10985         if (FoundNonTemplateFunction)
10986           EliminateAllTemplateMatches();
10987         else
10988           EliminateAllExceptMostSpecializedTemplate();
10989       }
10990     }
10991 
10992     if (S.getLangOpts().CUDA && Matches.size() > 1)
10993       EliminateSuboptimalCudaMatches();
10994   }
10995 
10996   bool hasComplained() const { return HasComplained; }
10997 
10998 private:
10999   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
11000     QualType Discard;
11001     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
11002            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
11003   }
11004 
11005   /// \return true if A is considered a better overload candidate for the
11006   /// desired type than B.
11007   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
11008     // If A doesn't have exactly the correct type, we don't want to classify it
11009     // as "better" than anything else. This way, the user is required to
11010     // disambiguate for us if there are multiple candidates and no exact match.
11011     return candidateHasExactlyCorrectType(A) &&
11012            (!candidateHasExactlyCorrectType(B) ||
11013             compareEnableIfAttrs(S, A, B) == Comparison::Better);
11014   }
11015 
11016   /// \return true if we were able to eliminate all but one overload candidate,
11017   /// false otherwise.
11018   bool eliminiateSuboptimalOverloadCandidates() {
11019     // Same algorithm as overload resolution -- one pass to pick the "best",
11020     // another pass to be sure that nothing is better than the best.
11021     auto Best = Matches.begin();
11022     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11023       if (isBetterCandidate(I->second, Best->second))
11024         Best = I;
11025 
11026     const FunctionDecl *BestFn = Best->second;
11027     auto IsBestOrInferiorToBest = [this, BestFn](
11028         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11029       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11030     };
11031 
11032     // Note: We explicitly leave Matches unmodified if there isn't a clear best
11033     // option, so we can potentially give the user a better error
11034     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
11035       return false;
11036     Matches[0] = *Best;
11037     Matches.resize(1);
11038     return true;
11039   }
11040 
11041   bool isTargetTypeAFunction() const {
11042     return TargetFunctionType->isFunctionType();
11043   }
11044 
11045   // [ToType]     [Return]
11046 
11047   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11048   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11049   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11050   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11051     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11052   }
11053 
11054   // return true if any matching specializations were found
11055   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
11056                                    const DeclAccessPair& CurAccessFunPair) {
11057     if (CXXMethodDecl *Method
11058               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11059       // Skip non-static function templates when converting to pointer, and
11060       // static when converting to member pointer.
11061       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11062         return false;
11063     }
11064     else if (TargetTypeIsNonStaticMemberFunction)
11065       return false;
11066 
11067     // C++ [over.over]p2:
11068     //   If the name is a function template, template argument deduction is
11069     //   done (14.8.2.2), and if the argument deduction succeeds, the
11070     //   resulting template argument list is used to generate a single
11071     //   function template specialization, which is added to the set of
11072     //   overloaded functions considered.
11073     FunctionDecl *Specialization = nullptr;
11074     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11075     if (Sema::TemplateDeductionResult Result
11076           = S.DeduceTemplateArguments(FunctionTemplate,
11077                                       &OvlExplicitTemplateArgs,
11078                                       TargetFunctionType, Specialization,
11079                                       Info, /*IsAddressOfFunction*/true)) {
11080       // Make a note of the failed deduction for diagnostics.
11081       FailedCandidates.addCandidate()
11082           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
11083                MakeDeductionFailureInfo(Context, Result, Info));
11084       return false;
11085     }
11086 
11087     // Template argument deduction ensures that we have an exact match or
11088     // compatible pointer-to-function arguments that would be adjusted by ICS.
11089     // This function template specicalization works.
11090     assert(S.isSameOrCompatibleFunctionType(
11091               Context.getCanonicalType(Specialization->getType()),
11092               Context.getCanonicalType(TargetFunctionType)));
11093 
11094     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11095       return false;
11096 
11097     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11098     return true;
11099   }
11100 
11101   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11102                                       const DeclAccessPair& CurAccessFunPair) {
11103     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11104       // Skip non-static functions when converting to pointer, and static
11105       // when converting to member pointer.
11106       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11107         return false;
11108     }
11109     else if (TargetTypeIsNonStaticMemberFunction)
11110       return false;
11111 
11112     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11113       if (S.getLangOpts().CUDA)
11114         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11115           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11116             return false;
11117       if (FunDecl->isMultiVersion()) {
11118         const auto *TA = FunDecl->getAttr<TargetAttr>();
11119         if (TA && !TA->isDefaultVersion())
11120           return false;
11121       }
11122 
11123       // If any candidate has a placeholder return type, trigger its deduction
11124       // now.
11125       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
11126                                Complain)) {
11127         HasComplained |= Complain;
11128         return false;
11129       }
11130 
11131       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11132         return false;
11133 
11134       // If we're in C, we need to support types that aren't exactly identical.
11135       if (!S.getLangOpts().CPlusPlus ||
11136           candidateHasExactlyCorrectType(FunDecl)) {
11137         Matches.push_back(std::make_pair(
11138             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11139         FoundNonTemplateFunction = true;
11140         return true;
11141       }
11142     }
11143 
11144     return false;
11145   }
11146 
11147   bool FindAllFunctionsThatMatchTargetTypeExactly() {
11148     bool Ret = false;
11149 
11150     // If the overload expression doesn't have the form of a pointer to
11151     // member, don't try to convert it to a pointer-to-member type.
11152     if (IsInvalidFormOfPointerToMemberFunction())
11153       return false;
11154 
11155     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11156                                E = OvlExpr->decls_end();
11157          I != E; ++I) {
11158       // Look through any using declarations to find the underlying function.
11159       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11160 
11161       // C++ [over.over]p3:
11162       //   Non-member functions and static member functions match
11163       //   targets of type "pointer-to-function" or "reference-to-function."
11164       //   Nonstatic member functions match targets of
11165       //   type "pointer-to-member-function."
11166       // Note that according to DR 247, the containing class does not matter.
11167       if (FunctionTemplateDecl *FunctionTemplate
11168                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11169         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11170           Ret = true;
11171       }
11172       // If we have explicit template arguments supplied, skip non-templates.
11173       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11174                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11175         Ret = true;
11176     }
11177     assert(Ret || Matches.empty());
11178     return Ret;
11179   }
11180 
11181   void EliminateAllExceptMostSpecializedTemplate() {
11182     //   [...] and any given function template specialization F1 is
11183     //   eliminated if the set contains a second function template
11184     //   specialization whose function template is more specialized
11185     //   than the function template of F1 according to the partial
11186     //   ordering rules of 14.5.5.2.
11187 
11188     // The algorithm specified above is quadratic. We instead use a
11189     // two-pass algorithm (similar to the one used to identify the
11190     // best viable function in an overload set) that identifies the
11191     // best function template (if it exists).
11192 
11193     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11194     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11195       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11196 
11197     // TODO: It looks like FailedCandidates does not serve much purpose
11198     // here, since the no_viable diagnostic has index 0.
11199     UnresolvedSetIterator Result = S.getMostSpecialized(
11200         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11201         SourceExpr->getBeginLoc(), S.PDiag(),
11202         S.PDiag(diag::err_addr_ovl_ambiguous)
11203             << Matches[0].second->getDeclName(),
11204         S.PDiag(diag::note_ovl_candidate)
11205             << (unsigned)oc_function << (unsigned)ocs_described_template,
11206         Complain, TargetFunctionType);
11207 
11208     if (Result != MatchesCopy.end()) {
11209       // Make it the first and only element
11210       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11211       Matches[0].second = cast<FunctionDecl>(*Result);
11212       Matches.resize(1);
11213     } else
11214       HasComplained |= Complain;
11215   }
11216 
11217   void EliminateAllTemplateMatches() {
11218     //   [...] any function template specializations in the set are
11219     //   eliminated if the set also contains a non-template function, [...]
11220     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11221       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11222         ++I;
11223       else {
11224         Matches[I] = Matches[--N];
11225         Matches.resize(N);
11226       }
11227     }
11228   }
11229 
11230   void EliminateSuboptimalCudaMatches() {
11231     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11232   }
11233 
11234 public:
11235   void ComplainNoMatchesFound() const {
11236     assert(Matches.empty());
11237     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
11238         << OvlExpr->getName() << TargetFunctionType
11239         << OvlExpr->getSourceRange();
11240     if (FailedCandidates.empty())
11241       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11242                                   /*TakingAddress=*/true);
11243     else {
11244       // We have some deduction failure messages. Use them to diagnose
11245       // the function templates, and diagnose the non-template candidates
11246       // normally.
11247       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11248                                  IEnd = OvlExpr->decls_end();
11249            I != IEnd; ++I)
11250         if (FunctionDecl *Fun =
11251                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11252           if (!functionHasPassObjectSizeParams(Fun))
11253             S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
11254                                     /*TakingAddress=*/true);
11255       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
11256     }
11257   }
11258 
11259   bool IsInvalidFormOfPointerToMemberFunction() const {
11260     return TargetTypeIsNonStaticMemberFunction &&
11261       !OvlExprInfo.HasFormOfMemberPointer;
11262   }
11263 
11264   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11265       // TODO: Should we condition this on whether any functions might
11266       // have matched, or is it more appropriate to do that in callers?
11267       // TODO: a fixit wouldn't hurt.
11268       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11269         << TargetType << OvlExpr->getSourceRange();
11270   }
11271 
11272   bool IsStaticMemberFunctionFromBoundPointer() const {
11273     return StaticMemberFunctionFromBoundPointer;
11274   }
11275 
11276   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11277     S.Diag(OvlExpr->getBeginLoc(),
11278            diag::err_invalid_form_pointer_member_function)
11279         << OvlExpr->getSourceRange();
11280   }
11281 
11282   void ComplainOfInvalidConversion() const {
11283     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
11284         << OvlExpr->getName() << TargetType;
11285   }
11286 
11287   void ComplainMultipleMatchesFound() const {
11288     assert(Matches.size() > 1);
11289     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
11290         << OvlExpr->getName() << OvlExpr->getSourceRange();
11291     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11292                                 /*TakingAddress=*/true);
11293   }
11294 
11295   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11296 
11297   int getNumMatches() const { return Matches.size(); }
11298 
11299   FunctionDecl* getMatchingFunctionDecl() const {
11300     if (Matches.size() != 1) return nullptr;
11301     return Matches[0].second;
11302   }
11303 
11304   const DeclAccessPair* getMatchingFunctionAccessPair() const {
11305     if (Matches.size() != 1) return nullptr;
11306     return &Matches[0].first;
11307   }
11308 };
11309 }
11310 
11311 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11312 /// an overloaded function (C++ [over.over]), where @p From is an
11313 /// expression with overloaded function type and @p ToType is the type
11314 /// we're trying to resolve to. For example:
11315 ///
11316 /// @code
11317 /// int f(double);
11318 /// int f(int);
11319 ///
11320 /// int (*pfd)(double) = f; // selects f(double)
11321 /// @endcode
11322 ///
11323 /// This routine returns the resulting FunctionDecl if it could be
11324 /// resolved, and NULL otherwise. When @p Complain is true, this
11325 /// routine will emit diagnostics if there is an error.
11326 FunctionDecl *
11327 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11328                                          QualType TargetType,
11329                                          bool Complain,
11330                                          DeclAccessPair &FoundResult,
11331                                          bool *pHadMultipleCandidates) {
11332   assert(AddressOfExpr->getType() == Context.OverloadTy);
11333 
11334   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11335                                      Complain);
11336   int NumMatches = Resolver.getNumMatches();
11337   FunctionDecl *Fn = nullptr;
11338   bool ShouldComplain = Complain && !Resolver.hasComplained();
11339   if (NumMatches == 0 && ShouldComplain) {
11340     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11341       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11342     else
11343       Resolver.ComplainNoMatchesFound();
11344   }
11345   else if (NumMatches > 1 && ShouldComplain)
11346     Resolver.ComplainMultipleMatchesFound();
11347   else if (NumMatches == 1) {
11348     Fn = Resolver.getMatchingFunctionDecl();
11349     assert(Fn);
11350     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11351       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11352     FoundResult = *Resolver.getMatchingFunctionAccessPair();
11353     if (Complain) {
11354       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11355         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11356       else
11357         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11358     }
11359   }
11360 
11361   if (pHadMultipleCandidates)
11362     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11363   return Fn;
11364 }
11365 
11366 /// Given an expression that refers to an overloaded function, try to
11367 /// resolve that function to a single function that can have its address taken.
11368 /// This will modify `Pair` iff it returns non-null.
11369 ///
11370 /// This routine can only realistically succeed if all but one candidates in the
11371 /// overload set for SrcExpr cannot have their addresses taken.
11372 FunctionDecl *
11373 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11374                                                   DeclAccessPair &Pair) {
11375   OverloadExpr::FindResult R = OverloadExpr::find(E);
11376   OverloadExpr *Ovl = R.Expression;
11377   FunctionDecl *Result = nullptr;
11378   DeclAccessPair DAP;
11379   // Don't use the AddressOfResolver because we're specifically looking for
11380   // cases where we have one overload candidate that lacks
11381   // enable_if/pass_object_size/...
11382   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11383     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11384     if (!FD)
11385       return nullptr;
11386 
11387     if (!checkAddressOfFunctionIsAvailable(FD))
11388       continue;
11389 
11390     // We have more than one result; quit.
11391     if (Result)
11392       return nullptr;
11393     DAP = I.getPair();
11394     Result = FD;
11395   }
11396 
11397   if (Result)
11398     Pair = DAP;
11399   return Result;
11400 }
11401 
11402 /// Given an overloaded function, tries to turn it into a non-overloaded
11403 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11404 /// will perform access checks, diagnose the use of the resultant decl, and, if
11405 /// requested, potentially perform a function-to-pointer decay.
11406 ///
11407 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11408 /// Otherwise, returns true. This may emit diagnostics and return true.
11409 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11410     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
11411   Expr *E = SrcExpr.get();
11412   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11413 
11414   DeclAccessPair DAP;
11415   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11416   if (!Found || Found->isCPUDispatchMultiVersion() ||
11417       Found->isCPUSpecificMultiVersion())
11418     return false;
11419 
11420   // Emitting multiple diagnostics for a function that is both inaccessible and
11421   // unavailable is consistent with our behavior elsewhere. So, always check
11422   // for both.
11423   DiagnoseUseOfDecl(Found, E->getExprLoc());
11424   CheckAddressOfMemberAccess(E, DAP);
11425   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11426   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
11427     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11428   else
11429     SrcExpr = Fixed;
11430   return true;
11431 }
11432 
11433 /// Given an expression that refers to an overloaded function, try to
11434 /// resolve that overloaded function expression down to a single function.
11435 ///
11436 /// This routine can only resolve template-ids that refer to a single function
11437 /// template, where that template-id refers to a single template whose template
11438 /// arguments are either provided by the template-id or have defaults,
11439 /// as described in C++0x [temp.arg.explicit]p3.
11440 ///
11441 /// If no template-ids are found, no diagnostics are emitted and NULL is
11442 /// returned.
11443 FunctionDecl *
11444 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11445                                                   bool Complain,
11446                                                   DeclAccessPair *FoundResult) {
11447   // C++ [over.over]p1:
11448   //   [...] [Note: any redundant set of parentheses surrounding the
11449   //   overloaded function name is ignored (5.1). ]
11450   // C++ [over.over]p1:
11451   //   [...] The overloaded function name can be preceded by the &
11452   //   operator.
11453 
11454   // If we didn't actually find any template-ids, we're done.
11455   if (!ovl->hasExplicitTemplateArgs())
11456     return nullptr;
11457 
11458   TemplateArgumentListInfo ExplicitTemplateArgs;
11459   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11460   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11461 
11462   // Look through all of the overloaded functions, searching for one
11463   // whose type matches exactly.
11464   FunctionDecl *Matched = nullptr;
11465   for (UnresolvedSetIterator I = ovl->decls_begin(),
11466          E = ovl->decls_end(); I != E; ++I) {
11467     // C++0x [temp.arg.explicit]p3:
11468     //   [...] In contexts where deduction is done and fails, or in contexts
11469     //   where deduction is not done, if a template argument list is
11470     //   specified and it, along with any default template arguments,
11471     //   identifies a single function template specialization, then the
11472     //   template-id is an lvalue for the function template specialization.
11473     FunctionTemplateDecl *FunctionTemplate
11474       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11475 
11476     // C++ [over.over]p2:
11477     //   If the name is a function template, template argument deduction is
11478     //   done (14.8.2.2), and if the argument deduction succeeds, the
11479     //   resulting template argument list is used to generate a single
11480     //   function template specialization, which is added to the set of
11481     //   overloaded functions considered.
11482     FunctionDecl *Specialization = nullptr;
11483     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11484     if (TemplateDeductionResult Result
11485           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11486                                     Specialization, Info,
11487                                     /*IsAddressOfFunction*/true)) {
11488       // Make a note of the failed deduction for diagnostics.
11489       // TODO: Actually use the failed-deduction info?
11490       FailedCandidates.addCandidate()
11491           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11492                MakeDeductionFailureInfo(Context, Result, Info));
11493       continue;
11494     }
11495 
11496     assert(Specialization && "no specialization and no error?");
11497 
11498     // Multiple matches; we can't resolve to a single declaration.
11499     if (Matched) {
11500       if (Complain) {
11501         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11502           << ovl->getName();
11503         NoteAllOverloadCandidates(ovl);
11504       }
11505       return nullptr;
11506     }
11507 
11508     Matched = Specialization;
11509     if (FoundResult) *FoundResult = I.getPair();
11510   }
11511 
11512   if (Matched &&
11513       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11514     return nullptr;
11515 
11516   return Matched;
11517 }
11518 
11519 // Resolve and fix an overloaded expression that can be resolved
11520 // because it identifies a single function template specialization.
11521 //
11522 // Last three arguments should only be supplied if Complain = true
11523 //
11524 // Return true if it was logically possible to so resolve the
11525 // expression, regardless of whether or not it succeeded.  Always
11526 // returns true if 'complain' is set.
11527 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11528                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
11529                       bool complain, SourceRange OpRangeForComplaining,
11530                                            QualType DestTypeForComplaining,
11531                                             unsigned DiagIDForComplaining) {
11532   assert(SrcExpr.get()->getType() == Context.OverloadTy);
11533 
11534   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11535 
11536   DeclAccessPair found;
11537   ExprResult SingleFunctionExpression;
11538   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11539                            ovl.Expression, /*complain*/ false, &found)) {
11540     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
11541       SrcExpr = ExprError();
11542       return true;
11543     }
11544 
11545     // It is only correct to resolve to an instance method if we're
11546     // resolving a form that's permitted to be a pointer to member.
11547     // Otherwise we'll end up making a bound member expression, which
11548     // is illegal in all the contexts we resolve like this.
11549     if (!ovl.HasFormOfMemberPointer &&
11550         isa<CXXMethodDecl>(fn) &&
11551         cast<CXXMethodDecl>(fn)->isInstance()) {
11552       if (!complain) return false;
11553 
11554       Diag(ovl.Expression->getExprLoc(),
11555            diag::err_bound_member_function)
11556         << 0 << ovl.Expression->getSourceRange();
11557 
11558       // TODO: I believe we only end up here if there's a mix of
11559       // static and non-static candidates (otherwise the expression
11560       // would have 'bound member' type, not 'overload' type).
11561       // Ideally we would note which candidate was chosen and why
11562       // the static candidates were rejected.
11563       SrcExpr = ExprError();
11564       return true;
11565     }
11566 
11567     // Fix the expression to refer to 'fn'.
11568     SingleFunctionExpression =
11569         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11570 
11571     // If desired, do function-to-pointer decay.
11572     if (doFunctionPointerConverion) {
11573       SingleFunctionExpression =
11574         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11575       if (SingleFunctionExpression.isInvalid()) {
11576         SrcExpr = ExprError();
11577         return true;
11578       }
11579     }
11580   }
11581 
11582   if (!SingleFunctionExpression.isUsable()) {
11583     if (complain) {
11584       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11585         << ovl.Expression->getName()
11586         << DestTypeForComplaining
11587         << OpRangeForComplaining
11588         << ovl.Expression->getQualifierLoc().getSourceRange();
11589       NoteAllOverloadCandidates(SrcExpr.get());
11590 
11591       SrcExpr = ExprError();
11592       return true;
11593     }
11594 
11595     return false;
11596   }
11597 
11598   SrcExpr = SingleFunctionExpression;
11599   return true;
11600 }
11601 
11602 /// Add a single candidate to the overload set.
11603 static void AddOverloadedCallCandidate(Sema &S,
11604                                        DeclAccessPair FoundDecl,
11605                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
11606                                        ArrayRef<Expr *> Args,
11607                                        OverloadCandidateSet &CandidateSet,
11608                                        bool PartialOverloading,
11609                                        bool KnownValid) {
11610   NamedDecl *Callee = FoundDecl.getDecl();
11611   if (isa<UsingShadowDecl>(Callee))
11612     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11613 
11614   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11615     if (ExplicitTemplateArgs) {
11616       assert(!KnownValid && "Explicit template arguments?");
11617       return;
11618     }
11619     // Prevent ill-formed function decls to be added as overload candidates.
11620     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11621       return;
11622 
11623     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11624                            /*SuppressUsedConversions=*/false,
11625                            PartialOverloading);
11626     return;
11627   }
11628 
11629   if (FunctionTemplateDecl *FuncTemplate
11630       = dyn_cast<FunctionTemplateDecl>(Callee)) {
11631     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11632                                    ExplicitTemplateArgs, Args, CandidateSet,
11633                                    /*SuppressUsedConversions=*/false,
11634                                    PartialOverloading);
11635     return;
11636   }
11637 
11638   assert(!KnownValid && "unhandled case in overloaded call candidate");
11639 }
11640 
11641 /// Add the overload candidates named by callee and/or found by argument
11642 /// dependent lookup to the given overload set.
11643 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11644                                        ArrayRef<Expr *> Args,
11645                                        OverloadCandidateSet &CandidateSet,
11646                                        bool PartialOverloading) {
11647 
11648 #ifndef NDEBUG
11649   // Verify that ArgumentDependentLookup is consistent with the rules
11650   // in C++0x [basic.lookup.argdep]p3:
11651   //
11652   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11653   //   and let Y be the lookup set produced by argument dependent
11654   //   lookup (defined as follows). If X contains
11655   //
11656   //     -- a declaration of a class member, or
11657   //
11658   //     -- a block-scope function declaration that is not a
11659   //        using-declaration, or
11660   //
11661   //     -- a declaration that is neither a function or a function
11662   //        template
11663   //
11664   //   then Y is empty.
11665 
11666   if (ULE->requiresADL()) {
11667     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11668            E = ULE->decls_end(); I != E; ++I) {
11669       assert(!(*I)->getDeclContext()->isRecord());
11670       assert(isa<UsingShadowDecl>(*I) ||
11671              !(*I)->getDeclContext()->isFunctionOrMethod());
11672       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11673     }
11674   }
11675 #endif
11676 
11677   // It would be nice to avoid this copy.
11678   TemplateArgumentListInfo TABuffer;
11679   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11680   if (ULE->hasExplicitTemplateArgs()) {
11681     ULE->copyTemplateArgumentsInto(TABuffer);
11682     ExplicitTemplateArgs = &TABuffer;
11683   }
11684 
11685   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11686          E = ULE->decls_end(); I != E; ++I)
11687     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11688                                CandidateSet, PartialOverloading,
11689                                /*KnownValid*/ true);
11690 
11691   if (ULE->requiresADL())
11692     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11693                                          Args, ExplicitTemplateArgs,
11694                                          CandidateSet, PartialOverloading);
11695 }
11696 
11697 /// Determine whether a declaration with the specified name could be moved into
11698 /// a different namespace.
11699 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11700   switch (Name.getCXXOverloadedOperator()) {
11701   case OO_New: case OO_Array_New:
11702   case OO_Delete: case OO_Array_Delete:
11703     return false;
11704 
11705   default:
11706     return true;
11707   }
11708 }
11709 
11710 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11711 /// template, where the non-dependent name was declared after the template
11712 /// was defined. This is common in code written for a compilers which do not
11713 /// correctly implement two-stage name lookup.
11714 ///
11715 /// Returns true if a viable candidate was found and a diagnostic was issued.
11716 static bool
11717 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11718                        const CXXScopeSpec &SS, LookupResult &R,
11719                        OverloadCandidateSet::CandidateSetKind CSK,
11720                        TemplateArgumentListInfo *ExplicitTemplateArgs,
11721                        ArrayRef<Expr *> Args,
11722                        bool *DoDiagnoseEmptyLookup = nullptr) {
11723   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
11724     return false;
11725 
11726   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11727     if (DC->isTransparentContext())
11728       continue;
11729 
11730     SemaRef.LookupQualifiedName(R, DC);
11731 
11732     if (!R.empty()) {
11733       R.suppressDiagnostics();
11734 
11735       if (isa<CXXRecordDecl>(DC)) {
11736         // Don't diagnose names we find in classes; we get much better
11737         // diagnostics for these from DiagnoseEmptyLookup.
11738         R.clear();
11739         if (DoDiagnoseEmptyLookup)
11740           *DoDiagnoseEmptyLookup = true;
11741         return false;
11742       }
11743 
11744       OverloadCandidateSet Candidates(FnLoc, CSK);
11745       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11746         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11747                                    ExplicitTemplateArgs, Args,
11748                                    Candidates, false, /*KnownValid*/ false);
11749 
11750       OverloadCandidateSet::iterator Best;
11751       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11752         // No viable functions. Don't bother the user with notes for functions
11753         // which don't work and shouldn't be found anyway.
11754         R.clear();
11755         return false;
11756       }
11757 
11758       // Find the namespaces where ADL would have looked, and suggest
11759       // declaring the function there instead.
11760       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11761       Sema::AssociatedClassSet AssociatedClasses;
11762       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11763                                                  AssociatedNamespaces,
11764                                                  AssociatedClasses);
11765       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11766       if (canBeDeclaredInNamespace(R.getLookupName())) {
11767         DeclContext *Std = SemaRef.getStdNamespace();
11768         for (Sema::AssociatedNamespaceSet::iterator
11769                it = AssociatedNamespaces.begin(),
11770                end = AssociatedNamespaces.end(); it != end; ++it) {
11771           // Never suggest declaring a function within namespace 'std'.
11772           if (Std && Std->Encloses(*it))
11773             continue;
11774 
11775           // Never suggest declaring a function within a namespace with a
11776           // reserved name, like __gnu_cxx.
11777           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11778           if (NS &&
11779               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11780             continue;
11781 
11782           SuggestedNamespaces.insert(*it);
11783         }
11784       }
11785 
11786       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11787         << R.getLookupName();
11788       if (SuggestedNamespaces.empty()) {
11789         SemaRef.Diag(Best->Function->getLocation(),
11790                      diag::note_not_found_by_two_phase_lookup)
11791           << R.getLookupName() << 0;
11792       } else if (SuggestedNamespaces.size() == 1) {
11793         SemaRef.Diag(Best->Function->getLocation(),
11794                      diag::note_not_found_by_two_phase_lookup)
11795           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11796       } else {
11797         // FIXME: It would be useful to list the associated namespaces here,
11798         // but the diagnostics infrastructure doesn't provide a way to produce
11799         // a localized representation of a list of items.
11800         SemaRef.Diag(Best->Function->getLocation(),
11801                      diag::note_not_found_by_two_phase_lookup)
11802           << R.getLookupName() << 2;
11803       }
11804 
11805       // Try to recover by calling this function.
11806       return true;
11807     }
11808 
11809     R.clear();
11810   }
11811 
11812   return false;
11813 }
11814 
11815 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11816 /// template, where the non-dependent operator was declared after the template
11817 /// was defined.
11818 ///
11819 /// Returns true if a viable candidate was found and a diagnostic was issued.
11820 static bool
11821 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11822                                SourceLocation OpLoc,
11823                                ArrayRef<Expr *> Args) {
11824   DeclarationName OpName =
11825     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11826   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11827   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11828                                 OverloadCandidateSet::CSK_Operator,
11829                                 /*ExplicitTemplateArgs=*/nullptr, Args);
11830 }
11831 
11832 namespace {
11833 class BuildRecoveryCallExprRAII {
11834   Sema &SemaRef;
11835 public:
11836   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11837     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11838     SemaRef.IsBuildingRecoveryCallExpr = true;
11839   }
11840 
11841   ~BuildRecoveryCallExprRAII() {
11842     SemaRef.IsBuildingRecoveryCallExpr = false;
11843   }
11844 };
11845 
11846 }
11847 
11848 static std::unique_ptr<CorrectionCandidateCallback>
11849 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11850               bool HasTemplateArgs, bool AllowTypoCorrection) {
11851   if (!AllowTypoCorrection)
11852     return llvm::make_unique<NoTypoCorrectionCCC>();
11853   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11854                                                   HasTemplateArgs, ME);
11855 }
11856 
11857 /// Attempts to recover from a call where no functions were found.
11858 ///
11859 /// Returns true if new candidates were found.
11860 static ExprResult
11861 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11862                       UnresolvedLookupExpr *ULE,
11863                       SourceLocation LParenLoc,
11864                       MutableArrayRef<Expr *> Args,
11865                       SourceLocation RParenLoc,
11866                       bool EmptyLookup, bool AllowTypoCorrection) {
11867   // Do not try to recover if it is already building a recovery call.
11868   // This stops infinite loops for template instantiations like
11869   //
11870   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11871   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11872   //
11873   if (SemaRef.IsBuildingRecoveryCallExpr)
11874     return ExprError();
11875   BuildRecoveryCallExprRAII RCE(SemaRef);
11876 
11877   CXXScopeSpec SS;
11878   SS.Adopt(ULE->getQualifierLoc());
11879   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11880 
11881   TemplateArgumentListInfo TABuffer;
11882   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11883   if (ULE->hasExplicitTemplateArgs()) {
11884     ULE->copyTemplateArgumentsInto(TABuffer);
11885     ExplicitTemplateArgs = &TABuffer;
11886   }
11887 
11888   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11889                  Sema::LookupOrdinaryName);
11890   bool DoDiagnoseEmptyLookup = EmptyLookup;
11891   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11892                               OverloadCandidateSet::CSK_Normal,
11893                               ExplicitTemplateArgs, Args,
11894                               &DoDiagnoseEmptyLookup) &&
11895     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11896         S, SS, R,
11897         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11898                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11899         ExplicitTemplateArgs, Args)))
11900     return ExprError();
11901 
11902   assert(!R.empty() && "lookup results empty despite recovery");
11903 
11904   // If recovery created an ambiguity, just bail out.
11905   if (R.isAmbiguous()) {
11906     R.suppressDiagnostics();
11907     return ExprError();
11908   }
11909 
11910   // Build an implicit member call if appropriate.  Just drop the
11911   // casts and such from the call, we don't really care.
11912   ExprResult NewFn = ExprError();
11913   if ((*R.begin())->isCXXClassMember())
11914     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11915                                                     ExplicitTemplateArgs, S);
11916   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11917     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11918                                         ExplicitTemplateArgs);
11919   else
11920     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11921 
11922   if (NewFn.isInvalid())
11923     return ExprError();
11924 
11925   // This shouldn't cause an infinite loop because we're giving it
11926   // an expression with viable lookup results, which should never
11927   // end up here.
11928   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11929                                MultiExprArg(Args.data(), Args.size()),
11930                                RParenLoc);
11931 }
11932 
11933 /// Constructs and populates an OverloadedCandidateSet from
11934 /// the given function.
11935 /// \returns true when an the ExprResult output parameter has been set.
11936 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11937                                   UnresolvedLookupExpr *ULE,
11938                                   MultiExprArg Args,
11939                                   SourceLocation RParenLoc,
11940                                   OverloadCandidateSet *CandidateSet,
11941                                   ExprResult *Result) {
11942 #ifndef NDEBUG
11943   if (ULE->requiresADL()) {
11944     // To do ADL, we must have found an unqualified name.
11945     assert(!ULE->getQualifier() && "qualified name with ADL");
11946 
11947     // We don't perform ADL for implicit declarations of builtins.
11948     // Verify that this was correctly set up.
11949     FunctionDecl *F;
11950     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11951         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11952         F->getBuiltinID() && F->isImplicit())
11953       llvm_unreachable("performing ADL for builtin");
11954 
11955     // We don't perform ADL in C.
11956     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11957   }
11958 #endif
11959 
11960   UnbridgedCastsSet UnbridgedCasts;
11961   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11962     *Result = ExprError();
11963     return true;
11964   }
11965 
11966   // Add the functions denoted by the callee to the set of candidate
11967   // functions, including those from argument-dependent lookup.
11968   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11969 
11970   if (getLangOpts().MSVCCompat &&
11971       CurContext->isDependentContext() && !isSFINAEContext() &&
11972       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11973 
11974     OverloadCandidateSet::iterator Best;
11975     if (CandidateSet->empty() ||
11976         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
11977             OR_No_Viable_Function) {
11978       // In Microsoft mode, if we are inside a template class member function then
11979       // create a type dependent CallExpr. The goal is to postpone name lookup
11980       // to instantiation time to be able to search into type dependent base
11981       // classes.
11982       CallExpr *CE = new (Context) CallExpr(
11983           Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11984       CE->setTypeDependent(true);
11985       CE->setValueDependent(true);
11986       CE->setInstantiationDependent(true);
11987       *Result = CE;
11988       return true;
11989     }
11990   }
11991 
11992   if (CandidateSet->empty())
11993     return false;
11994 
11995   UnbridgedCasts.restore();
11996   return false;
11997 }
11998 
11999 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
12000 /// the completed call expression. If overload resolution fails, emits
12001 /// diagnostics and returns ExprError()
12002 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12003                                            UnresolvedLookupExpr *ULE,
12004                                            SourceLocation LParenLoc,
12005                                            MultiExprArg Args,
12006                                            SourceLocation RParenLoc,
12007                                            Expr *ExecConfig,
12008                                            OverloadCandidateSet *CandidateSet,
12009                                            OverloadCandidateSet::iterator *Best,
12010                                            OverloadingResult OverloadResult,
12011                                            bool AllowTypoCorrection) {
12012   if (CandidateSet->empty())
12013     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
12014                                  RParenLoc, /*EmptyLookup=*/true,
12015                                  AllowTypoCorrection);
12016 
12017   switch (OverloadResult) {
12018   case OR_Success: {
12019     FunctionDecl *FDecl = (*Best)->Function;
12020     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
12021     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
12022       return ExprError();
12023     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12024     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12025                                          ExecConfig, /*IsExecConfig=*/false,
12026                                          (*Best)->IsADLCandidate);
12027   }
12028 
12029   case OR_No_Viable_Function: {
12030     // Try to recover by looking for viable functions which the user might
12031     // have meant to call.
12032     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
12033                                                 Args, RParenLoc,
12034                                                 /*EmptyLookup=*/false,
12035                                                 AllowTypoCorrection);
12036     if (!Recovery.isInvalid())
12037       return Recovery;
12038 
12039     // If the user passes in a function that we can't take the address of, we
12040     // generally end up emitting really bad error messages. Here, we attempt to
12041     // emit better ones.
12042     for (const Expr *Arg : Args) {
12043       if (!Arg->getType()->isFunctionType())
12044         continue;
12045       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12046         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12047         if (FD &&
12048             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12049                                                        Arg->getExprLoc()))
12050           return ExprError();
12051       }
12052     }
12053 
12054     SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_no_viable_function_in_call)
12055         << ULE->getName() << Fn->getSourceRange();
12056     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
12057     break;
12058   }
12059 
12060   case OR_Ambiguous:
12061     SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_ambiguous_call)
12062         << ULE->getName() << Fn->getSourceRange();
12063     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
12064     break;
12065 
12066   case OR_Deleted: {
12067     SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_deleted_call)
12068         << (*Best)->Function->isDeleted() << ULE->getName()
12069         << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
12070         << Fn->getSourceRange();
12071     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
12072 
12073     // We emitted an error for the unavailable/deleted function call but keep
12074     // the call in the AST.
12075     FunctionDecl *FDecl = (*Best)->Function;
12076     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12077     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12078                                          ExecConfig, /*IsExecConfig=*/false,
12079                                          (*Best)->IsADLCandidate);
12080   }
12081   }
12082 
12083   // Overload resolution failed.
12084   return ExprError();
12085 }
12086 
12087 static void markUnaddressableCandidatesUnviable(Sema &S,
12088                                                 OverloadCandidateSet &CS) {
12089   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12090     if (I->Viable &&
12091         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12092       I->Viable = false;
12093       I->FailureKind = ovl_fail_addr_not_available;
12094     }
12095   }
12096 }
12097 
12098 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
12099 /// (which eventually refers to the declaration Func) and the call
12100 /// arguments Args/NumArgs, attempt to resolve the function call down
12101 /// to a specific function. If overload resolution succeeds, returns
12102 /// the call expression produced by overload resolution.
12103 /// Otherwise, emits diagnostics and returns ExprError.
12104 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12105                                          UnresolvedLookupExpr *ULE,
12106                                          SourceLocation LParenLoc,
12107                                          MultiExprArg Args,
12108                                          SourceLocation RParenLoc,
12109                                          Expr *ExecConfig,
12110                                          bool AllowTypoCorrection,
12111                                          bool CalleesAddressIsTaken) {
12112   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12113                                     OverloadCandidateSet::CSK_Normal);
12114   ExprResult result;
12115 
12116   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12117                              &result))
12118     return result;
12119 
12120   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12121   // functions that aren't addressible are considered unviable.
12122   if (CalleesAddressIsTaken)
12123     markUnaddressableCandidatesUnviable(*this, CandidateSet);
12124 
12125   OverloadCandidateSet::iterator Best;
12126   OverloadingResult OverloadResult =
12127       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
12128 
12129   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
12130                                   RParenLoc, ExecConfig, &CandidateSet,
12131                                   &Best, OverloadResult,
12132                                   AllowTypoCorrection);
12133 }
12134 
12135 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
12136   return Functions.size() > 1 ||
12137     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12138 }
12139 
12140 /// Create a unary operation that may resolve to an overloaded
12141 /// operator.
12142 ///
12143 /// \param OpLoc The location of the operator itself (e.g., '*').
12144 ///
12145 /// \param Opc The UnaryOperatorKind that describes this operator.
12146 ///
12147 /// \param Fns The set of non-member functions that will be
12148 /// considered by overload resolution. The caller needs to build this
12149 /// set based on the context using, e.g.,
12150 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12151 /// set should not contain any member functions; those will be added
12152 /// by CreateOverloadedUnaryOp().
12153 ///
12154 /// \param Input The input argument.
12155 ExprResult
12156 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12157                               const UnresolvedSetImpl &Fns,
12158                               Expr *Input, bool PerformADL) {
12159   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12160   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12161   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12162   // TODO: provide better source location info.
12163   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12164 
12165   if (checkPlaceholderForOverload(*this, Input))
12166     return ExprError();
12167 
12168   Expr *Args[2] = { Input, nullptr };
12169   unsigned NumArgs = 1;
12170 
12171   // For post-increment and post-decrement, add the implicit '0' as
12172   // the second argument, so that we know this is a post-increment or
12173   // post-decrement.
12174   if (Opc == UO_PostInc || Opc == UO_PostDec) {
12175     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12176     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12177                                      SourceLocation());
12178     NumArgs = 2;
12179   }
12180 
12181   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12182 
12183   if (Input->isTypeDependent()) {
12184     if (Fns.empty())
12185       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12186                                          VK_RValue, OK_Ordinary, OpLoc, false);
12187 
12188     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12189     UnresolvedLookupExpr *Fn
12190       = UnresolvedLookupExpr::Create(Context, NamingClass,
12191                                      NestedNameSpecifierLoc(), OpNameInfo,
12192                                      /*ADL*/ true, IsOverloaded(Fns),
12193                                      Fns.begin(), Fns.end());
12194     return new (Context)
12195         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
12196                             VK_RValue, OpLoc, FPOptions());
12197   }
12198 
12199   // Build an empty overload set.
12200   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12201 
12202   // Add the candidates from the given function set.
12203   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
12204 
12205   // Add operator candidates that are member functions.
12206   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12207 
12208   // Add candidates from ADL.
12209   if (PerformADL) {
12210     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12211                                          /*ExplicitTemplateArgs*/nullptr,
12212                                          CandidateSet);
12213   }
12214 
12215   // Add builtin operator candidates.
12216   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12217 
12218   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12219 
12220   // Perform overload resolution.
12221   OverloadCandidateSet::iterator Best;
12222   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12223   case OR_Success: {
12224     // We found a built-in operator or an overloaded operator.
12225     FunctionDecl *FnDecl = Best->Function;
12226 
12227     if (FnDecl) {
12228       Expr *Base = nullptr;
12229       // We matched an overloaded operator. Build a call to that
12230       // operator.
12231 
12232       // Convert the arguments.
12233       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12234         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12235 
12236         ExprResult InputRes =
12237           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12238                                               Best->FoundDecl, Method);
12239         if (InputRes.isInvalid())
12240           return ExprError();
12241         Base = Input = InputRes.get();
12242       } else {
12243         // Convert the arguments.
12244         ExprResult InputInit
12245           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12246                                                       Context,
12247                                                       FnDecl->getParamDecl(0)),
12248                                       SourceLocation(),
12249                                       Input);
12250         if (InputInit.isInvalid())
12251           return ExprError();
12252         Input = InputInit.get();
12253       }
12254 
12255       // Build the actual expression node.
12256       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12257                                                 Base, HadMultipleCandidates,
12258                                                 OpLoc);
12259       if (FnExpr.isInvalid())
12260         return ExprError();
12261 
12262       // Determine the result type.
12263       QualType ResultTy = FnDecl->getReturnType();
12264       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12265       ResultTy = ResultTy.getNonLValueExprType(Context);
12266 
12267       Args[0] = Input;
12268       CallExpr *TheCall = new (Context)
12269           CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, ResultTy,
12270                               VK, OpLoc, FPOptions(), Best->IsADLCandidate);
12271 
12272       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12273         return ExprError();
12274 
12275       if (CheckFunctionCall(FnDecl, TheCall,
12276                             FnDecl->getType()->castAs<FunctionProtoType>()))
12277         return ExprError();
12278 
12279       return MaybeBindToTemporary(TheCall);
12280     } else {
12281       // We matched a built-in operator. Convert the arguments, then
12282       // break out so that we will build the appropriate built-in
12283       // operator node.
12284       ExprResult InputRes = PerformImplicitConversion(
12285           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
12286           CCK_ForBuiltinOverloadedOp);
12287       if (InputRes.isInvalid())
12288         return ExprError();
12289       Input = InputRes.get();
12290       break;
12291     }
12292   }
12293 
12294   case OR_No_Viable_Function:
12295     // This is an erroneous use of an operator which can be overloaded by
12296     // a non-member function. Check for non-member operators which were
12297     // defined too late to be candidates.
12298     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12299       // FIXME: Recover by calling the found function.
12300       return ExprError();
12301 
12302     // No viable function; fall through to handling this as a
12303     // built-in operator, which will produce an error message for us.
12304     break;
12305 
12306   case OR_Ambiguous:
12307     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12308         << UnaryOperator::getOpcodeStr(Opc)
12309         << Input->getType()
12310         << Input->getSourceRange();
12311     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
12312                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12313     return ExprError();
12314 
12315   case OR_Deleted:
12316     Diag(OpLoc, diag::err_ovl_deleted_oper)
12317       << Best->Function->isDeleted()
12318       << UnaryOperator::getOpcodeStr(Opc)
12319       << getDeletedOrUnavailableSuffix(Best->Function)
12320       << Input->getSourceRange();
12321     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
12322                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12323     return ExprError();
12324   }
12325 
12326   // Either we found no viable overloaded operator or we matched a
12327   // built-in operator. In either case, fall through to trying to
12328   // build a built-in operation.
12329   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12330 }
12331 
12332 /// Create a binary operation that may resolve to an overloaded
12333 /// operator.
12334 ///
12335 /// \param OpLoc The location of the operator itself (e.g., '+').
12336 ///
12337 /// \param Opc The BinaryOperatorKind that describes this operator.
12338 ///
12339 /// \param Fns The set of non-member functions that will be
12340 /// considered by overload resolution. The caller needs to build this
12341 /// set based on the context using, e.g.,
12342 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12343 /// set should not contain any member functions; those will be added
12344 /// by CreateOverloadedBinOp().
12345 ///
12346 /// \param LHS Left-hand argument.
12347 /// \param RHS Right-hand argument.
12348 ExprResult
12349 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12350                             BinaryOperatorKind Opc,
12351                             const UnresolvedSetImpl &Fns,
12352                             Expr *LHS, Expr *RHS, bool PerformADL) {
12353   Expr *Args[2] = { LHS, RHS };
12354   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12355 
12356   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12357   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12358 
12359   // If either side is type-dependent, create an appropriate dependent
12360   // expression.
12361   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12362     if (Fns.empty()) {
12363       // If there are no functions to store, just build a dependent
12364       // BinaryOperator or CompoundAssignment.
12365       if (Opc <= BO_Assign || Opc > BO_OrAssign)
12366         return new (Context) BinaryOperator(
12367             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12368             OpLoc, FPFeatures);
12369 
12370       return new (Context) CompoundAssignOperator(
12371           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12372           Context.DependentTy, Context.DependentTy, OpLoc,
12373           FPFeatures);
12374     }
12375 
12376     // FIXME: save results of ADL from here?
12377     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12378     // TODO: provide better source location info in DNLoc component.
12379     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12380     UnresolvedLookupExpr *Fn
12381       = UnresolvedLookupExpr::Create(Context, NamingClass,
12382                                      NestedNameSpecifierLoc(), OpNameInfo,
12383                                      /*ADL*/PerformADL, IsOverloaded(Fns),
12384                                      Fns.begin(), Fns.end());
12385     return new (Context)
12386         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
12387                             VK_RValue, OpLoc, FPFeatures);
12388   }
12389 
12390   // Always do placeholder-like conversions on the RHS.
12391   if (checkPlaceholderForOverload(*this, Args[1]))
12392     return ExprError();
12393 
12394   // Do placeholder-like conversion on the LHS; note that we should
12395   // not get here with a PseudoObject LHS.
12396   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12397   if (checkPlaceholderForOverload(*this, Args[0]))
12398     return ExprError();
12399 
12400   // If this is the assignment operator, we only perform overload resolution
12401   // if the left-hand side is a class or enumeration type. This is actually
12402   // a hack. The standard requires that we do overload resolution between the
12403   // various built-in candidates, but as DR507 points out, this can lead to
12404   // problems. So we do it this way, which pretty much follows what GCC does.
12405   // Note that we go the traditional code path for compound assignment forms.
12406   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12407     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12408 
12409   // If this is the .* operator, which is not overloadable, just
12410   // create a built-in binary operator.
12411   if (Opc == BO_PtrMemD)
12412     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12413 
12414   // Build an empty overload set.
12415   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12416 
12417   // Add the candidates from the given function set.
12418   AddFunctionCandidates(Fns, Args, CandidateSet);
12419 
12420   // Add operator candidates that are member functions.
12421   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12422 
12423   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12424   // performed for an assignment operator (nor for operator[] nor operator->,
12425   // which don't get here).
12426   if (Opc != BO_Assign && PerformADL)
12427     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12428                                          /*ExplicitTemplateArgs*/ nullptr,
12429                                          CandidateSet);
12430 
12431   // Add builtin operator candidates.
12432   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12433 
12434   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12435 
12436   // Perform overload resolution.
12437   OverloadCandidateSet::iterator Best;
12438   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12439     case OR_Success: {
12440       // We found a built-in operator or an overloaded operator.
12441       FunctionDecl *FnDecl = Best->Function;
12442 
12443       if (FnDecl) {
12444         Expr *Base = nullptr;
12445         // We matched an overloaded operator. Build a call to that
12446         // operator.
12447 
12448         // Convert the arguments.
12449         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12450           // Best->Access is only meaningful for class members.
12451           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12452 
12453           ExprResult Arg1 =
12454             PerformCopyInitialization(
12455               InitializedEntity::InitializeParameter(Context,
12456                                                      FnDecl->getParamDecl(0)),
12457               SourceLocation(), Args[1]);
12458           if (Arg1.isInvalid())
12459             return ExprError();
12460 
12461           ExprResult Arg0 =
12462             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12463                                                 Best->FoundDecl, Method);
12464           if (Arg0.isInvalid())
12465             return ExprError();
12466           Base = Args[0] = Arg0.getAs<Expr>();
12467           Args[1] = RHS = Arg1.getAs<Expr>();
12468         } else {
12469           // Convert the arguments.
12470           ExprResult Arg0 = PerformCopyInitialization(
12471             InitializedEntity::InitializeParameter(Context,
12472                                                    FnDecl->getParamDecl(0)),
12473             SourceLocation(), Args[0]);
12474           if (Arg0.isInvalid())
12475             return ExprError();
12476 
12477           ExprResult Arg1 =
12478             PerformCopyInitialization(
12479               InitializedEntity::InitializeParameter(Context,
12480                                                      FnDecl->getParamDecl(1)),
12481               SourceLocation(), Args[1]);
12482           if (Arg1.isInvalid())
12483             return ExprError();
12484           Args[0] = LHS = Arg0.getAs<Expr>();
12485           Args[1] = RHS = Arg1.getAs<Expr>();
12486         }
12487 
12488         // Build the actual expression node.
12489         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12490                                                   Best->FoundDecl, Base,
12491                                                   HadMultipleCandidates, OpLoc);
12492         if (FnExpr.isInvalid())
12493           return ExprError();
12494 
12495         // Determine the result type.
12496         QualType ResultTy = FnDecl->getReturnType();
12497         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12498         ResultTy = ResultTy.getNonLValueExprType(Context);
12499 
12500         CXXOperatorCallExpr *TheCall = new (Context)
12501             CXXOperatorCallExpr(Context, Op, FnExpr.get(), Args, ResultTy, VK,
12502                                 OpLoc, FPFeatures, Best->IsADLCandidate);
12503 
12504         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12505                                 FnDecl))
12506           return ExprError();
12507 
12508         ArrayRef<const Expr *> ArgsArray(Args, 2);
12509         const Expr *ImplicitThis = nullptr;
12510         // Cut off the implicit 'this'.
12511         if (isa<CXXMethodDecl>(FnDecl)) {
12512           ImplicitThis = ArgsArray[0];
12513           ArgsArray = ArgsArray.slice(1);
12514         }
12515 
12516         // Check for a self move.
12517         if (Op == OO_Equal)
12518           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12519 
12520         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12521                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12522                   VariadicDoesNotApply);
12523 
12524         return MaybeBindToTemporary(TheCall);
12525       } else {
12526         // We matched a built-in operator. Convert the arguments, then
12527         // break out so that we will build the appropriate built-in
12528         // operator node.
12529         ExprResult ArgsRes0 = PerformImplicitConversion(
12530             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12531             AA_Passing, CCK_ForBuiltinOverloadedOp);
12532         if (ArgsRes0.isInvalid())
12533           return ExprError();
12534         Args[0] = ArgsRes0.get();
12535 
12536         ExprResult ArgsRes1 = PerformImplicitConversion(
12537             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12538             AA_Passing, CCK_ForBuiltinOverloadedOp);
12539         if (ArgsRes1.isInvalid())
12540           return ExprError();
12541         Args[1] = ArgsRes1.get();
12542         break;
12543       }
12544     }
12545 
12546     case OR_No_Viable_Function: {
12547       // C++ [over.match.oper]p9:
12548       //   If the operator is the operator , [...] and there are no
12549       //   viable functions, then the operator is assumed to be the
12550       //   built-in operator and interpreted according to clause 5.
12551       if (Opc == BO_Comma)
12552         break;
12553 
12554       // For class as left operand for assignment or compound assignment
12555       // operator do not fall through to handling in built-in, but report that
12556       // no overloaded assignment operator found
12557       ExprResult Result = ExprError();
12558       if (Args[0]->getType()->isRecordType() &&
12559           Opc >= BO_Assign && Opc <= BO_OrAssign) {
12560         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
12561              << BinaryOperator::getOpcodeStr(Opc)
12562              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12563         if (Args[0]->getType()->isIncompleteType()) {
12564           Diag(OpLoc, diag::note_assign_lhs_incomplete)
12565             << Args[0]->getType()
12566             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12567         }
12568       } else {
12569         // This is an erroneous use of an operator which can be overloaded by
12570         // a non-member function. Check for non-member operators which were
12571         // defined too late to be candidates.
12572         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12573           // FIXME: Recover by calling the found function.
12574           return ExprError();
12575 
12576         // No viable function; try to create a built-in operation, which will
12577         // produce an error. Then, show the non-viable candidates.
12578         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12579       }
12580       assert(Result.isInvalid() &&
12581              "C++ binary operator overloading is missing candidates!");
12582       if (Result.isInvalid())
12583         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12584                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
12585       return Result;
12586     }
12587 
12588     case OR_Ambiguous:
12589       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
12590           << BinaryOperator::getOpcodeStr(Opc)
12591           << Args[0]->getType() << Args[1]->getType()
12592           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12593       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12594                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12595       return ExprError();
12596 
12597     case OR_Deleted:
12598       if (isImplicitlyDeleted(Best->Function)) {
12599         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12600         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12601           << Context.getRecordType(Method->getParent())
12602           << getSpecialMember(Method);
12603 
12604         // The user probably meant to call this special member. Just
12605         // explain why it's deleted.
12606         NoteDeletedFunction(Method);
12607         return ExprError();
12608       } else {
12609         Diag(OpLoc, diag::err_ovl_deleted_oper)
12610           << Best->Function->isDeleted()
12611           << BinaryOperator::getOpcodeStr(Opc)
12612           << getDeletedOrUnavailableSuffix(Best->Function)
12613           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12614       }
12615       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12616                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12617       return ExprError();
12618   }
12619 
12620   // We matched a built-in operator; build it.
12621   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12622 }
12623 
12624 ExprResult
12625 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12626                                          SourceLocation RLoc,
12627                                          Expr *Base, Expr *Idx) {
12628   Expr *Args[2] = { Base, Idx };
12629   DeclarationName OpName =
12630       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12631 
12632   // If either side is type-dependent, create an appropriate dependent
12633   // expression.
12634   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12635 
12636     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12637     // CHECKME: no 'operator' keyword?
12638     DeclarationNameInfo OpNameInfo(OpName, LLoc);
12639     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12640     UnresolvedLookupExpr *Fn
12641       = UnresolvedLookupExpr::Create(Context, NamingClass,
12642                                      NestedNameSpecifierLoc(), OpNameInfo,
12643                                      /*ADL*/ true, /*Overloaded*/ false,
12644                                      UnresolvedSetIterator(),
12645                                      UnresolvedSetIterator());
12646     // Can't add any actual overloads yet
12647 
12648     return new (Context)
12649         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12650                             Context.DependentTy, VK_RValue, RLoc, FPOptions());
12651   }
12652 
12653   // Handle placeholders on both operands.
12654   if (checkPlaceholderForOverload(*this, Args[0]))
12655     return ExprError();
12656   if (checkPlaceholderForOverload(*this, Args[1]))
12657     return ExprError();
12658 
12659   // Build an empty overload set.
12660   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12661 
12662   // Subscript can only be overloaded as a member function.
12663 
12664   // Add operator candidates that are member functions.
12665   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12666 
12667   // Add builtin operator candidates.
12668   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12669 
12670   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12671 
12672   // Perform overload resolution.
12673   OverloadCandidateSet::iterator Best;
12674   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12675     case OR_Success: {
12676       // We found a built-in operator or an overloaded operator.
12677       FunctionDecl *FnDecl = Best->Function;
12678 
12679       if (FnDecl) {
12680         // We matched an overloaded operator. Build a call to that
12681         // operator.
12682 
12683         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12684 
12685         // Convert the arguments.
12686         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12687         ExprResult Arg0 =
12688           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12689                                               Best->FoundDecl, Method);
12690         if (Arg0.isInvalid())
12691           return ExprError();
12692         Args[0] = Arg0.get();
12693 
12694         // Convert the arguments.
12695         ExprResult InputInit
12696           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12697                                                       Context,
12698                                                       FnDecl->getParamDecl(0)),
12699                                       SourceLocation(),
12700                                       Args[1]);
12701         if (InputInit.isInvalid())
12702           return ExprError();
12703 
12704         Args[1] = InputInit.getAs<Expr>();
12705 
12706         // Build the actual expression node.
12707         DeclarationNameInfo OpLocInfo(OpName, LLoc);
12708         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12709         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12710                                                   Best->FoundDecl,
12711                                                   Base,
12712                                                   HadMultipleCandidates,
12713                                                   OpLocInfo.getLoc(),
12714                                                   OpLocInfo.getInfo());
12715         if (FnExpr.isInvalid())
12716           return ExprError();
12717 
12718         // Determine the result type
12719         QualType ResultTy = FnDecl->getReturnType();
12720         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12721         ResultTy = ResultTy.getNonLValueExprType(Context);
12722 
12723         CXXOperatorCallExpr *TheCall =
12724           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12725                                             FnExpr.get(), Args,
12726                                             ResultTy, VK, RLoc,
12727                                             FPOptions());
12728 
12729         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12730           return ExprError();
12731 
12732         if (CheckFunctionCall(Method, TheCall,
12733                               Method->getType()->castAs<FunctionProtoType>()))
12734           return ExprError();
12735 
12736         return MaybeBindToTemporary(TheCall);
12737       } else {
12738         // We matched a built-in operator. Convert the arguments, then
12739         // break out so that we will build the appropriate built-in
12740         // operator node.
12741         ExprResult ArgsRes0 = PerformImplicitConversion(
12742             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12743             AA_Passing, CCK_ForBuiltinOverloadedOp);
12744         if (ArgsRes0.isInvalid())
12745           return ExprError();
12746         Args[0] = ArgsRes0.get();
12747 
12748         ExprResult ArgsRes1 = PerformImplicitConversion(
12749             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12750             AA_Passing, CCK_ForBuiltinOverloadedOp);
12751         if (ArgsRes1.isInvalid())
12752           return ExprError();
12753         Args[1] = ArgsRes1.get();
12754 
12755         break;
12756       }
12757     }
12758 
12759     case OR_No_Viable_Function: {
12760       if (CandidateSet.empty())
12761         Diag(LLoc, diag::err_ovl_no_oper)
12762           << Args[0]->getType() << /*subscript*/ 0
12763           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12764       else
12765         Diag(LLoc, diag::err_ovl_no_viable_subscript)
12766           << Args[0]->getType()
12767           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12768       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12769                                   "[]", LLoc);
12770       return ExprError();
12771     }
12772 
12773     case OR_Ambiguous:
12774       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
12775           << "[]"
12776           << Args[0]->getType() << Args[1]->getType()
12777           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12778       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12779                                   "[]", LLoc);
12780       return ExprError();
12781 
12782     case OR_Deleted:
12783       Diag(LLoc, diag::err_ovl_deleted_oper)
12784         << Best->Function->isDeleted() << "[]"
12785         << getDeletedOrUnavailableSuffix(Best->Function)
12786         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12787       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12788                                   "[]", LLoc);
12789       return ExprError();
12790     }
12791 
12792   // We matched a built-in operator; build it.
12793   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12794 }
12795 
12796 /// BuildCallToMemberFunction - Build a call to a member
12797 /// function. MemExpr is the expression that refers to the member
12798 /// function (and includes the object parameter), Args/NumArgs are the
12799 /// arguments to the function call (not including the object
12800 /// parameter). The caller needs to validate that the member
12801 /// expression refers to a non-static member function or an overloaded
12802 /// member function.
12803 ExprResult
12804 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12805                                 SourceLocation LParenLoc,
12806                                 MultiExprArg Args,
12807                                 SourceLocation RParenLoc) {
12808   assert(MemExprE->getType() == Context.BoundMemberTy ||
12809          MemExprE->getType() == Context.OverloadTy);
12810 
12811   // Dig out the member expression. This holds both the object
12812   // argument and the member function we're referring to.
12813   Expr *NakedMemExpr = MemExprE->IgnoreParens();
12814 
12815   // Determine whether this is a call to a pointer-to-member function.
12816   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12817     assert(op->getType() == Context.BoundMemberTy);
12818     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12819 
12820     QualType fnType =
12821       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12822 
12823     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12824     QualType resultType = proto->getCallResultType(Context);
12825     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12826 
12827     // Check that the object type isn't more qualified than the
12828     // member function we're calling.
12829     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12830 
12831     QualType objectType = op->getLHS()->getType();
12832     if (op->getOpcode() == BO_PtrMemI)
12833       objectType = objectType->castAs<PointerType>()->getPointeeType();
12834     Qualifiers objectQuals = objectType.getQualifiers();
12835 
12836     Qualifiers difference = objectQuals - funcQuals;
12837     difference.removeObjCGCAttr();
12838     difference.removeAddressSpace();
12839     if (difference) {
12840       std::string qualsString = difference.getAsString();
12841       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12842         << fnType.getUnqualifiedType()
12843         << qualsString
12844         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12845     }
12846 
12847     CXXMemberCallExpr *call
12848       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12849                                         resultType, valueKind, RParenLoc,
12850                                         proto->getNumParams());
12851 
12852     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
12853                             call, nullptr))
12854       return ExprError();
12855 
12856     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12857       return ExprError();
12858 
12859     if (CheckOtherCall(call, proto))
12860       return ExprError();
12861 
12862     return MaybeBindToTemporary(call);
12863   }
12864 
12865   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12866     return new (Context)
12867         CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12868 
12869   UnbridgedCastsSet UnbridgedCasts;
12870   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12871     return ExprError();
12872 
12873   MemberExpr *MemExpr;
12874   CXXMethodDecl *Method = nullptr;
12875   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12876   NestedNameSpecifier *Qualifier = nullptr;
12877   if (isa<MemberExpr>(NakedMemExpr)) {
12878     MemExpr = cast<MemberExpr>(NakedMemExpr);
12879     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12880     FoundDecl = MemExpr->getFoundDecl();
12881     Qualifier = MemExpr->getQualifier();
12882     UnbridgedCasts.restore();
12883   } else {
12884     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12885     Qualifier = UnresExpr->getQualifier();
12886 
12887     QualType ObjectType = UnresExpr->getBaseType();
12888     Expr::Classification ObjectClassification
12889       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12890                             : UnresExpr->getBase()->Classify(Context);
12891 
12892     // Add overload candidates
12893     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12894                                       OverloadCandidateSet::CSK_Normal);
12895 
12896     // FIXME: avoid copy.
12897     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12898     if (UnresExpr->hasExplicitTemplateArgs()) {
12899       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12900       TemplateArgs = &TemplateArgsBuffer;
12901     }
12902 
12903     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12904            E = UnresExpr->decls_end(); I != E; ++I) {
12905 
12906       NamedDecl *Func = *I;
12907       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12908       if (isa<UsingShadowDecl>(Func))
12909         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12910 
12911 
12912       // Microsoft supports direct constructor calls.
12913       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12914         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12915                              Args, CandidateSet);
12916       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12917         // If explicit template arguments were provided, we can't call a
12918         // non-template member function.
12919         if (TemplateArgs)
12920           continue;
12921 
12922         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12923                            ObjectClassification, Args, CandidateSet,
12924                            /*SuppressUserConversions=*/false);
12925       } else {
12926         AddMethodTemplateCandidate(
12927             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
12928             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
12929             /*SuppressUsedConversions=*/false);
12930       }
12931     }
12932 
12933     DeclarationName DeclName = UnresExpr->getMemberName();
12934 
12935     UnbridgedCasts.restore();
12936 
12937     OverloadCandidateSet::iterator Best;
12938     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
12939                                             Best)) {
12940     case OR_Success:
12941       Method = cast<CXXMethodDecl>(Best->Function);
12942       FoundDecl = Best->FoundDecl;
12943       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12944       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12945         return ExprError();
12946       // If FoundDecl is different from Method (such as if one is a template
12947       // and the other a specialization), make sure DiagnoseUseOfDecl is
12948       // called on both.
12949       // FIXME: This would be more comprehensively addressed by modifying
12950       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12951       // being used.
12952       if (Method != FoundDecl.getDecl() &&
12953                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12954         return ExprError();
12955       break;
12956 
12957     case OR_No_Viable_Function:
12958       Diag(UnresExpr->getMemberLoc(),
12959            diag::err_ovl_no_viable_member_function_in_call)
12960         << DeclName << MemExprE->getSourceRange();
12961       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12962       // FIXME: Leaking incoming expressions!
12963       return ExprError();
12964 
12965     case OR_Ambiguous:
12966       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12967         << DeclName << MemExprE->getSourceRange();
12968       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12969       // FIXME: Leaking incoming expressions!
12970       return ExprError();
12971 
12972     case OR_Deleted:
12973       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12974         << Best->Function->isDeleted()
12975         << DeclName
12976         << getDeletedOrUnavailableSuffix(Best->Function)
12977         << MemExprE->getSourceRange();
12978       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12979       // FIXME: Leaking incoming expressions!
12980       return ExprError();
12981     }
12982 
12983     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12984 
12985     // If overload resolution picked a static member, build a
12986     // non-member call based on that function.
12987     if (Method->isStatic()) {
12988       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12989                                    RParenLoc);
12990     }
12991 
12992     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12993   }
12994 
12995   QualType ResultType = Method->getReturnType();
12996   ExprValueKind VK = Expr::getValueKindForType(ResultType);
12997   ResultType = ResultType.getNonLValueExprType(Context);
12998 
12999   assert(Method && "Member call to something that isn't a method?");
13000   const auto *Proto = Method->getType()->getAs<FunctionProtoType>();
13001   CXXMemberCallExpr *TheCall =
13002     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
13003                                     ResultType, VK, RParenLoc,
13004                                     Proto->getNumParams());
13005 
13006   // Check for a valid return type.
13007   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
13008                           TheCall, Method))
13009     return ExprError();
13010 
13011   // Convert the object argument (for a non-static member function call).
13012   // We only need to do this if there was actually an overload; otherwise
13013   // it was done at lookup.
13014   if (!Method->isStatic()) {
13015     ExprResult ObjectArg =
13016       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
13017                                           FoundDecl, Method);
13018     if (ObjectArg.isInvalid())
13019       return ExprError();
13020     MemExpr->setBase(ObjectArg.get());
13021   }
13022 
13023   // Convert the rest of the arguments
13024   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
13025                               RParenLoc))
13026     return ExprError();
13027 
13028   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13029 
13030   if (CheckFunctionCall(Method, TheCall, Proto))
13031     return ExprError();
13032 
13033   // In the case the method to call was not selected by the overloading
13034   // resolution process, we still need to handle the enable_if attribute. Do
13035   // that here, so it will not hide previous -- and more relevant -- errors.
13036   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
13037     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
13038       Diag(MemE->getMemberLoc(),
13039            diag::err_ovl_no_viable_member_function_in_call)
13040           << Method << Method->getSourceRange();
13041       Diag(Method->getLocation(),
13042            diag::note_ovl_candidate_disabled_by_function_cond_attr)
13043           << Attr->getCond()->getSourceRange() << Attr->getMessage();
13044       return ExprError();
13045     }
13046   }
13047 
13048   if ((isa<CXXConstructorDecl>(CurContext) ||
13049        isa<CXXDestructorDecl>(CurContext)) &&
13050       TheCall->getMethodDecl()->isPure()) {
13051     const CXXMethodDecl *MD = TheCall->getMethodDecl();
13052 
13053     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
13054         MemExpr->performsVirtualDispatch(getLangOpts())) {
13055       Diag(MemExpr->getBeginLoc(),
13056            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
13057           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
13058           << MD->getParent()->getDeclName();
13059 
13060       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
13061       if (getLangOpts().AppleKext)
13062         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
13063             << MD->getParent()->getDeclName() << MD->getDeclName();
13064     }
13065   }
13066 
13067   if (CXXDestructorDecl *DD =
13068           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
13069     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
13070     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
13071     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
13072                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
13073                          MemExpr->getMemberLoc());
13074   }
13075 
13076   return MaybeBindToTemporary(TheCall);
13077 }
13078 
13079 /// BuildCallToObjectOfClassType - Build a call to an object of class
13080 /// type (C++ [over.call.object]), which can end up invoking an
13081 /// overloaded function call operator (@c operator()) or performing a
13082 /// user-defined conversion on the object argument.
13083 ExprResult
13084 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
13085                                    SourceLocation LParenLoc,
13086                                    MultiExprArg Args,
13087                                    SourceLocation RParenLoc) {
13088   if (checkPlaceholderForOverload(*this, Obj))
13089     return ExprError();
13090   ExprResult Object = Obj;
13091 
13092   UnbridgedCastsSet UnbridgedCasts;
13093   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13094     return ExprError();
13095 
13096   assert(Object.get()->getType()->isRecordType() &&
13097          "Requires object type argument");
13098   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
13099 
13100   // C++ [over.call.object]p1:
13101   //  If the primary-expression E in the function call syntax
13102   //  evaluates to a class object of type "cv T", then the set of
13103   //  candidate functions includes at least the function call
13104   //  operators of T. The function call operators of T are obtained by
13105   //  ordinary lookup of the name operator() in the context of
13106   //  (E).operator().
13107   OverloadCandidateSet CandidateSet(LParenLoc,
13108                                     OverloadCandidateSet::CSK_Operator);
13109   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
13110 
13111   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
13112                           diag::err_incomplete_object_call, Object.get()))
13113     return true;
13114 
13115   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
13116   LookupQualifiedName(R, Record->getDecl());
13117   R.suppressDiagnostics();
13118 
13119   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13120        Oper != OperEnd; ++Oper) {
13121     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
13122                        Object.get()->Classify(Context), Args, CandidateSet,
13123                        /*SuppressUserConversions=*/false);
13124   }
13125 
13126   // C++ [over.call.object]p2:
13127   //   In addition, for each (non-explicit in C++0x) conversion function
13128   //   declared in T of the form
13129   //
13130   //        operator conversion-type-id () cv-qualifier;
13131   //
13132   //   where cv-qualifier is the same cv-qualification as, or a
13133   //   greater cv-qualification than, cv, and where conversion-type-id
13134   //   denotes the type "pointer to function of (P1,...,Pn) returning
13135   //   R", or the type "reference to pointer to function of
13136   //   (P1,...,Pn) returning R", or the type "reference to function
13137   //   of (P1,...,Pn) returning R", a surrogate call function [...]
13138   //   is also considered as a candidate function. Similarly,
13139   //   surrogate call functions are added to the set of candidate
13140   //   functions for each conversion function declared in an
13141   //   accessible base class provided the function is not hidden
13142   //   within T by another intervening declaration.
13143   const auto &Conversions =
13144       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
13145   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
13146     NamedDecl *D = *I;
13147     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
13148     if (isa<UsingShadowDecl>(D))
13149       D = cast<UsingShadowDecl>(D)->getTargetDecl();
13150 
13151     // Skip over templated conversion functions; they aren't
13152     // surrogates.
13153     if (isa<FunctionTemplateDecl>(D))
13154       continue;
13155 
13156     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
13157     if (!Conv->isExplicit()) {
13158       // Strip the reference type (if any) and then the pointer type (if
13159       // any) to get down to what might be a function type.
13160       QualType ConvType = Conv->getConversionType().getNonReferenceType();
13161       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13162         ConvType = ConvPtrType->getPointeeType();
13163 
13164       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13165       {
13166         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
13167                               Object.get(), Args, CandidateSet);
13168       }
13169     }
13170   }
13171 
13172   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13173 
13174   // Perform overload resolution.
13175   OverloadCandidateSet::iterator Best;
13176   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
13177                                           Best)) {
13178   case OR_Success:
13179     // Overload resolution succeeded; we'll build the appropriate call
13180     // below.
13181     break;
13182 
13183   case OR_No_Viable_Function:
13184     if (CandidateSet.empty())
13185       Diag(Object.get()->getBeginLoc(), diag::err_ovl_no_oper)
13186           << Object.get()->getType() << /*call*/ 1
13187           << Object.get()->getSourceRange();
13188     else
13189       Diag(Object.get()->getBeginLoc(), diag::err_ovl_no_viable_object_call)
13190           << Object.get()->getType() << Object.get()->getSourceRange();
13191     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13192     break;
13193 
13194   case OR_Ambiguous:
13195     Diag(Object.get()->getBeginLoc(), diag::err_ovl_ambiguous_object_call)
13196         << Object.get()->getType() << Object.get()->getSourceRange();
13197     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13198     break;
13199 
13200   case OR_Deleted:
13201     Diag(Object.get()->getBeginLoc(), diag::err_ovl_deleted_object_call)
13202         << Best->Function->isDeleted() << Object.get()->getType()
13203         << getDeletedOrUnavailableSuffix(Best->Function)
13204         << Object.get()->getSourceRange();
13205     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13206     break;
13207   }
13208 
13209   if (Best == CandidateSet.end())
13210     return true;
13211 
13212   UnbridgedCasts.restore();
13213 
13214   if (Best->Function == nullptr) {
13215     // Since there is no function declaration, this is one of the
13216     // surrogate candidates. Dig out the conversion function.
13217     CXXConversionDecl *Conv
13218       = cast<CXXConversionDecl>(
13219                          Best->Conversions[0].UserDefined.ConversionFunction);
13220 
13221     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13222                               Best->FoundDecl);
13223     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13224       return ExprError();
13225     assert(Conv == Best->FoundDecl.getDecl() &&
13226              "Found Decl & conversion-to-functionptr should be same, right?!");
13227     // We selected one of the surrogate functions that converts the
13228     // object parameter to a function pointer. Perform the conversion
13229     // on the object argument, then let ActOnCallExpr finish the job.
13230 
13231     // Create an implicit member expr to refer to the conversion operator.
13232     // and then call it.
13233     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13234                                              Conv, HadMultipleCandidates);
13235     if (Call.isInvalid())
13236       return ExprError();
13237     // Record usage of conversion in an implicit cast.
13238     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13239                                     CK_UserDefinedConversion, Call.get(),
13240                                     nullptr, VK_RValue);
13241 
13242     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13243   }
13244 
13245   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13246 
13247   // We found an overloaded operator(). Build a CXXOperatorCallExpr
13248   // that calls this method, using Object for the implicit object
13249   // parameter and passing along the remaining arguments.
13250   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13251 
13252   // An error diagnostic has already been printed when parsing the declaration.
13253   if (Method->isInvalidDecl())
13254     return ExprError();
13255 
13256   const FunctionProtoType *Proto =
13257     Method->getType()->getAs<FunctionProtoType>();
13258 
13259   unsigned NumParams = Proto->getNumParams();
13260 
13261   DeclarationNameInfo OpLocInfo(
13262                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13263   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13264   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13265                                            Obj, HadMultipleCandidates,
13266                                            OpLocInfo.getLoc(),
13267                                            OpLocInfo.getInfo());
13268   if (NewFn.isInvalid())
13269     return true;
13270 
13271   // The number of argument slots to allocate in the call. If we have default
13272   // arguments we need to allocate space for them as well. We additionally
13273   // need one more slot for the object parameter.
13274   unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
13275 
13276   // Build the full argument list for the method call (the implicit object
13277   // parameter is placed at the beginning of the list).
13278   SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
13279 
13280   bool IsError = false;
13281 
13282   // Initialize the implicit object parameter.
13283   ExprResult ObjRes =
13284     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13285                                         Best->FoundDecl, Method);
13286   if (ObjRes.isInvalid())
13287     IsError = true;
13288   else
13289     Object = ObjRes;
13290   MethodArgs[0] = Object.get();
13291 
13292   // Check the argument types.
13293   for (unsigned i = 0; i != NumParams; i++) {
13294     Expr *Arg;
13295     if (i < Args.size()) {
13296       Arg = Args[i];
13297 
13298       // Pass the argument.
13299 
13300       ExprResult InputInit
13301         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13302                                                     Context,
13303                                                     Method->getParamDecl(i)),
13304                                     SourceLocation(), Arg);
13305 
13306       IsError |= InputInit.isInvalid();
13307       Arg = InputInit.getAs<Expr>();
13308     } else {
13309       ExprResult DefArg
13310         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13311       if (DefArg.isInvalid()) {
13312         IsError = true;
13313         break;
13314       }
13315 
13316       Arg = DefArg.getAs<Expr>();
13317     }
13318 
13319     MethodArgs[i + 1] = Arg;
13320   }
13321 
13322   // If this is a variadic call, handle args passed through "...".
13323   if (Proto->isVariadic()) {
13324     // Promote the arguments (C99 6.5.2.2p7).
13325     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
13326       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13327                                                         nullptr);
13328       IsError |= Arg.isInvalid();
13329       MethodArgs[i + 1] = Arg.get();
13330     }
13331   }
13332 
13333   if (IsError)
13334     return true;
13335 
13336   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13337 
13338   // Once we've built TheCall, all of the expressions are properly owned.
13339   QualType ResultTy = Method->getReturnType();
13340   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13341   ResultTy = ResultTy.getNonLValueExprType(Context);
13342 
13343   CXXOperatorCallExpr *TheCall = new (Context)
13344       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
13345                           VK, RParenLoc, FPOptions());
13346 
13347   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
13348     return true;
13349 
13350   if (CheckFunctionCall(Method, TheCall, Proto))
13351     return true;
13352 
13353   return MaybeBindToTemporary(TheCall);
13354 }
13355 
13356 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13357 ///  (if one exists), where @c Base is an expression of class type and
13358 /// @c Member is the name of the member we're trying to find.
13359 ExprResult
13360 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13361                                bool *NoArrowOperatorFound) {
13362   assert(Base->getType()->isRecordType() &&
13363          "left-hand side must have class type");
13364 
13365   if (checkPlaceholderForOverload(*this, Base))
13366     return ExprError();
13367 
13368   SourceLocation Loc = Base->getExprLoc();
13369 
13370   // C++ [over.ref]p1:
13371   //
13372   //   [...] An expression x->m is interpreted as (x.operator->())->m
13373   //   for a class object x of type T if T::operator->() exists and if
13374   //   the operator is selected as the best match function by the
13375   //   overload resolution mechanism (13.3).
13376   DeclarationName OpName =
13377     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13378   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
13379   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13380 
13381   if (RequireCompleteType(Loc, Base->getType(),
13382                           diag::err_typecheck_incomplete_tag, Base))
13383     return ExprError();
13384 
13385   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13386   LookupQualifiedName(R, BaseRecord->getDecl());
13387   R.suppressDiagnostics();
13388 
13389   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13390        Oper != OperEnd; ++Oper) {
13391     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13392                        None, CandidateSet, /*SuppressUserConversions=*/false);
13393   }
13394 
13395   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13396 
13397   // Perform overload resolution.
13398   OverloadCandidateSet::iterator Best;
13399   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13400   case OR_Success:
13401     // Overload resolution succeeded; we'll build the call below.
13402     break;
13403 
13404   case OR_No_Viable_Function:
13405     if (CandidateSet.empty()) {
13406       QualType BaseType = Base->getType();
13407       if (NoArrowOperatorFound) {
13408         // Report this specific error to the caller instead of emitting a
13409         // diagnostic, as requested.
13410         *NoArrowOperatorFound = true;
13411         return ExprError();
13412       }
13413       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13414         << BaseType << Base->getSourceRange();
13415       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13416         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13417           << FixItHint::CreateReplacement(OpLoc, ".");
13418       }
13419     } else
13420       Diag(OpLoc, diag::err_ovl_no_viable_oper)
13421         << "operator->" << Base->getSourceRange();
13422     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13423     return ExprError();
13424 
13425   case OR_Ambiguous:
13426     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
13427       << "->" << Base->getType() << Base->getSourceRange();
13428     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
13429     return ExprError();
13430 
13431   case OR_Deleted:
13432     Diag(OpLoc,  diag::err_ovl_deleted_oper)
13433       << Best->Function->isDeleted()
13434       << "->"
13435       << getDeletedOrUnavailableSuffix(Best->Function)
13436       << Base->getSourceRange();
13437     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13438     return ExprError();
13439   }
13440 
13441   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13442 
13443   // Convert the object parameter.
13444   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13445   ExprResult BaseResult =
13446     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13447                                         Best->FoundDecl, Method);
13448   if (BaseResult.isInvalid())
13449     return ExprError();
13450   Base = BaseResult.get();
13451 
13452   // Build the operator call.
13453   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13454                                             Base, HadMultipleCandidates, OpLoc);
13455   if (FnExpr.isInvalid())
13456     return ExprError();
13457 
13458   QualType ResultTy = Method->getReturnType();
13459   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13460   ResultTy = ResultTy.getNonLValueExprType(Context);
13461   CXXOperatorCallExpr *TheCall =
13462     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
13463                                       Base, ResultTy, VK, OpLoc, FPOptions());
13464 
13465   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13466     return ExprError();
13467 
13468   if (CheckFunctionCall(Method, TheCall,
13469                         Method->getType()->castAs<FunctionProtoType>()))
13470     return ExprError();
13471 
13472   return MaybeBindToTemporary(TheCall);
13473 }
13474 
13475 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13476 /// a literal operator described by the provided lookup results.
13477 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13478                                           DeclarationNameInfo &SuffixInfo,
13479                                           ArrayRef<Expr*> Args,
13480                                           SourceLocation LitEndLoc,
13481                                        TemplateArgumentListInfo *TemplateArgs) {
13482   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13483 
13484   OverloadCandidateSet CandidateSet(UDSuffixLoc,
13485                                     OverloadCandidateSet::CSK_Normal);
13486   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13487                         /*SuppressUserConversions=*/true);
13488 
13489   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13490 
13491   // Perform overload resolution. This will usually be trivial, but might need
13492   // to perform substitutions for a literal operator template.
13493   OverloadCandidateSet::iterator Best;
13494   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13495   case OR_Success:
13496   case OR_Deleted:
13497     break;
13498 
13499   case OR_No_Viable_Function:
13500     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13501       << R.getLookupName();
13502     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13503     return ExprError();
13504 
13505   case OR_Ambiguous:
13506     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13507     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13508     return ExprError();
13509   }
13510 
13511   FunctionDecl *FD = Best->Function;
13512   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13513                                         nullptr, HadMultipleCandidates,
13514                                         SuffixInfo.getLoc(),
13515                                         SuffixInfo.getInfo());
13516   if (Fn.isInvalid())
13517     return true;
13518 
13519   // Check the argument types. This should almost always be a no-op, except
13520   // that array-to-pointer decay is applied to string literals.
13521   Expr *ConvArgs[2];
13522   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13523     ExprResult InputInit = PerformCopyInitialization(
13524       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13525       SourceLocation(), Args[ArgIdx]);
13526     if (InputInit.isInvalid())
13527       return true;
13528     ConvArgs[ArgIdx] = InputInit.get();
13529   }
13530 
13531   QualType ResultTy = FD->getReturnType();
13532   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13533   ResultTy = ResultTy.getNonLValueExprType(Context);
13534 
13535   UserDefinedLiteral *UDL =
13536     new (Context) UserDefinedLiteral(Context, Fn.get(),
13537                                      llvm::makeArrayRef(ConvArgs, Args.size()),
13538                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
13539 
13540   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13541     return ExprError();
13542 
13543   if (CheckFunctionCall(FD, UDL, nullptr))
13544     return ExprError();
13545 
13546   return MaybeBindToTemporary(UDL);
13547 }
13548 
13549 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13550 /// given LookupResult is non-empty, it is assumed to describe a member which
13551 /// will be invoked. Otherwise, the function will be found via argument
13552 /// dependent lookup.
13553 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13554 /// otherwise CallExpr is set to ExprError() and some non-success value
13555 /// is returned.
13556 Sema::ForRangeStatus
13557 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13558                                 SourceLocation RangeLoc,
13559                                 const DeclarationNameInfo &NameInfo,
13560                                 LookupResult &MemberLookup,
13561                                 OverloadCandidateSet *CandidateSet,
13562                                 Expr *Range, ExprResult *CallExpr) {
13563   Scope *S = nullptr;
13564 
13565   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
13566   if (!MemberLookup.empty()) {
13567     ExprResult MemberRef =
13568         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13569                                  /*IsPtr=*/false, CXXScopeSpec(),
13570                                  /*TemplateKWLoc=*/SourceLocation(),
13571                                  /*FirstQualifierInScope=*/nullptr,
13572                                  MemberLookup,
13573                                  /*TemplateArgs=*/nullptr, S);
13574     if (MemberRef.isInvalid()) {
13575       *CallExpr = ExprError();
13576       return FRS_DiagnosticIssued;
13577     }
13578     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13579     if (CallExpr->isInvalid()) {
13580       *CallExpr = ExprError();
13581       return FRS_DiagnosticIssued;
13582     }
13583   } else {
13584     UnresolvedSet<0> FoundNames;
13585     UnresolvedLookupExpr *Fn =
13586       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13587                                    NestedNameSpecifierLoc(), NameInfo,
13588                                    /*NeedsADL=*/true, /*Overloaded=*/false,
13589                                    FoundNames.begin(), FoundNames.end());
13590 
13591     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13592                                                     CandidateSet, CallExpr);
13593     if (CandidateSet->empty() || CandidateSetError) {
13594       *CallExpr = ExprError();
13595       return FRS_NoViableFunction;
13596     }
13597     OverloadCandidateSet::iterator Best;
13598     OverloadingResult OverloadResult =
13599         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
13600 
13601     if (OverloadResult == OR_No_Viable_Function) {
13602       *CallExpr = ExprError();
13603       return FRS_NoViableFunction;
13604     }
13605     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13606                                          Loc, nullptr, CandidateSet, &Best,
13607                                          OverloadResult,
13608                                          /*AllowTypoCorrection=*/false);
13609     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13610       *CallExpr = ExprError();
13611       return FRS_DiagnosticIssued;
13612     }
13613   }
13614   return FRS_Success;
13615 }
13616 
13617 
13618 /// FixOverloadedFunctionReference - E is an expression that refers to
13619 /// a C++ overloaded function (possibly with some parentheses and
13620 /// perhaps a '&' around it). We have resolved the overloaded function
13621 /// to the function declaration Fn, so patch up the expression E to
13622 /// refer (possibly indirectly) to Fn. Returns the new expr.
13623 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13624                                            FunctionDecl *Fn) {
13625   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13626     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13627                                                    Found, Fn);
13628     if (SubExpr == PE->getSubExpr())
13629       return PE;
13630 
13631     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13632   }
13633 
13634   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13635     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13636                                                    Found, Fn);
13637     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13638                                SubExpr->getType()) &&
13639            "Implicit cast type cannot be determined from overload");
13640     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13641     if (SubExpr == ICE->getSubExpr())
13642       return ICE;
13643 
13644     return ImplicitCastExpr::Create(Context, ICE->getType(),
13645                                     ICE->getCastKind(),
13646                                     SubExpr, nullptr,
13647                                     ICE->getValueKind());
13648   }
13649 
13650   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13651     if (!GSE->isResultDependent()) {
13652       Expr *SubExpr =
13653           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13654       if (SubExpr == GSE->getResultExpr())
13655         return GSE;
13656 
13657       // Replace the resulting type information before rebuilding the generic
13658       // selection expression.
13659       ArrayRef<Expr *> A = GSE->getAssocExprs();
13660       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13661       unsigned ResultIdx = GSE->getResultIndex();
13662       AssocExprs[ResultIdx] = SubExpr;
13663 
13664       return new (Context) GenericSelectionExpr(
13665           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13666           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13667           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13668           ResultIdx);
13669     }
13670     // Rather than fall through to the unreachable, return the original generic
13671     // selection expression.
13672     return GSE;
13673   }
13674 
13675   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13676     assert(UnOp->getOpcode() == UO_AddrOf &&
13677            "Can only take the address of an overloaded function");
13678     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13679       if (Method->isStatic()) {
13680         // Do nothing: static member functions aren't any different
13681         // from non-member functions.
13682       } else {
13683         // Fix the subexpression, which really has to be an
13684         // UnresolvedLookupExpr holding an overloaded member function
13685         // or template.
13686         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13687                                                        Found, Fn);
13688         if (SubExpr == UnOp->getSubExpr())
13689           return UnOp;
13690 
13691         assert(isa<DeclRefExpr>(SubExpr)
13692                && "fixed to something other than a decl ref");
13693         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13694                && "fixed to a member ref with no nested name qualifier");
13695 
13696         // We have taken the address of a pointer to member
13697         // function. Perform the computation here so that we get the
13698         // appropriate pointer to member type.
13699         QualType ClassType
13700           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13701         QualType MemPtrType
13702           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13703         // Under the MS ABI, lock down the inheritance model now.
13704         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13705           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13706 
13707         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13708                                            VK_RValue, OK_Ordinary,
13709                                            UnOp->getOperatorLoc(), false);
13710       }
13711     }
13712     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13713                                                    Found, Fn);
13714     if (SubExpr == UnOp->getSubExpr())
13715       return UnOp;
13716 
13717     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13718                                      Context.getPointerType(SubExpr->getType()),
13719                                        VK_RValue, OK_Ordinary,
13720                                        UnOp->getOperatorLoc(), false);
13721   }
13722 
13723   // C++ [except.spec]p17:
13724   //   An exception-specification is considered to be needed when:
13725   //   - in an expression the function is the unique lookup result or the
13726   //     selected member of a set of overloaded functions
13727   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13728     ResolveExceptionSpec(E->getExprLoc(), FPT);
13729 
13730   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13731     // FIXME: avoid copy.
13732     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13733     if (ULE->hasExplicitTemplateArgs()) {
13734       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13735       TemplateArgs = &TemplateArgsBuffer;
13736     }
13737 
13738     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13739                                            ULE->getQualifierLoc(),
13740                                            ULE->getTemplateKeywordLoc(),
13741                                            Fn,
13742                                            /*enclosing*/ false, // FIXME?
13743                                            ULE->getNameLoc(),
13744                                            Fn->getType(),
13745                                            VK_LValue,
13746                                            Found.getDecl(),
13747                                            TemplateArgs);
13748     MarkDeclRefReferenced(DRE);
13749     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13750     return DRE;
13751   }
13752 
13753   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13754     // FIXME: avoid copy.
13755     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13756     if (MemExpr->hasExplicitTemplateArgs()) {
13757       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13758       TemplateArgs = &TemplateArgsBuffer;
13759     }
13760 
13761     Expr *Base;
13762 
13763     // If we're filling in a static method where we used to have an
13764     // implicit member access, rewrite to a simple decl ref.
13765     if (MemExpr->isImplicitAccess()) {
13766       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13767         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13768                                                MemExpr->getQualifierLoc(),
13769                                                MemExpr->getTemplateKeywordLoc(),
13770                                                Fn,
13771                                                /*enclosing*/ false,
13772                                                MemExpr->getMemberLoc(),
13773                                                Fn->getType(),
13774                                                VK_LValue,
13775                                                Found.getDecl(),
13776                                                TemplateArgs);
13777         MarkDeclRefReferenced(DRE);
13778         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13779         return DRE;
13780       } else {
13781         SourceLocation Loc = MemExpr->getMemberLoc();
13782         if (MemExpr->getQualifier())
13783           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13784         CheckCXXThisCapture(Loc);
13785         Base = new (Context) CXXThisExpr(Loc,
13786                                          MemExpr->getBaseType(),
13787                                          /*isImplicit=*/true);
13788       }
13789     } else
13790       Base = MemExpr->getBase();
13791 
13792     ExprValueKind valueKind;
13793     QualType type;
13794     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13795       valueKind = VK_LValue;
13796       type = Fn->getType();
13797     } else {
13798       valueKind = VK_RValue;
13799       type = Context.BoundMemberTy;
13800     }
13801 
13802     MemberExpr *ME = MemberExpr::Create(
13803         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13804         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13805         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13806         OK_Ordinary);
13807     ME->setHadMultipleCandidates(true);
13808     MarkMemberReferenced(ME);
13809     return ME;
13810   }
13811 
13812   llvm_unreachable("Invalid reference to overloaded function");
13813 }
13814 
13815 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13816                                                 DeclAccessPair Found,
13817                                                 FunctionDecl *Fn) {
13818   return FixOverloadedFunctionReference(E.get(), Found, Fn);
13819 }
13820