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     // FIXME: OpenCL: Need to consider address spaces
1146     unsigned OldQuals = OldMethod->getTypeQualifiers().getCVRUQualifiers();
1147     unsigned NewQuals = NewMethod->getTypeQualifiers().getCVRUQualifiers();
1148     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1149         !isa<CXXConstructorDecl>(NewMethod))
1150       NewQuals |= Qualifiers::Const;
1151 
1152     // We do not allow overloading based off of '__restrict'.
1153     OldQuals &= ~Qualifiers::Restrict;
1154     NewQuals &= ~Qualifiers::Restrict;
1155     if (OldQuals != NewQuals)
1156       return true;
1157   }
1158 
1159   // Though pass_object_size is placed on parameters and takes an argument, we
1160   // consider it to be a function-level modifier for the sake of function
1161   // identity. Either the function has one or more parameters with
1162   // pass_object_size or it doesn't.
1163   if (functionHasPassObjectSizeParams(New) !=
1164       functionHasPassObjectSizeParams(Old))
1165     return true;
1166 
1167   // enable_if attributes are an order-sensitive part of the signature.
1168   for (specific_attr_iterator<EnableIfAttr>
1169          NewI = New->specific_attr_begin<EnableIfAttr>(),
1170          NewE = New->specific_attr_end<EnableIfAttr>(),
1171          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1172          OldE = Old->specific_attr_end<EnableIfAttr>();
1173        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1174     if (NewI == NewE || OldI == OldE)
1175       return true;
1176     llvm::FoldingSetNodeID NewID, OldID;
1177     NewI->getCond()->Profile(NewID, Context, true);
1178     OldI->getCond()->Profile(OldID, Context, true);
1179     if (NewID != OldID)
1180       return true;
1181   }
1182 
1183   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1184     // Don't allow overloading of destructors.  (In theory we could, but it
1185     // would be a giant change to clang.)
1186     if (isa<CXXDestructorDecl>(New))
1187       return false;
1188 
1189     CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1190                        OldTarget = IdentifyCUDATarget(Old);
1191     if (NewTarget == CFT_InvalidTarget)
1192       return false;
1193 
1194     assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1195 
1196     // Allow overloading of functions with same signature and different CUDA
1197     // target attributes.
1198     return NewTarget != OldTarget;
1199   }
1200 
1201   // The signatures match; this is not an overload.
1202   return false;
1203 }
1204 
1205 /// Checks availability of the function depending on the current
1206 /// function context. Inside an unavailable function, unavailability is ignored.
1207 ///
1208 /// \returns true if \arg FD is unavailable and current context is inside
1209 /// an available function, false otherwise.
1210 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1211   if (!FD->isUnavailable())
1212     return false;
1213 
1214   // Walk up the context of the caller.
1215   Decl *C = cast<Decl>(CurContext);
1216   do {
1217     if (C->isUnavailable())
1218       return false;
1219   } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1220   return true;
1221 }
1222 
1223 /// Tries a user-defined conversion from From to ToType.
1224 ///
1225 /// Produces an implicit conversion sequence for when a standard conversion
1226 /// is not an option. See TryImplicitConversion for more information.
1227 static ImplicitConversionSequence
1228 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1229                          bool SuppressUserConversions,
1230                          bool AllowExplicit,
1231                          bool InOverloadResolution,
1232                          bool CStyle,
1233                          bool AllowObjCWritebackConversion,
1234                          bool AllowObjCConversionOnExplicit) {
1235   ImplicitConversionSequence ICS;
1236 
1237   if (SuppressUserConversions) {
1238     // We're not in the case above, so there is no conversion that
1239     // we can perform.
1240     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1241     return ICS;
1242   }
1243 
1244   // Attempt user-defined conversion.
1245   OverloadCandidateSet Conversions(From->getExprLoc(),
1246                                    OverloadCandidateSet::CSK_Normal);
1247   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1248                                   Conversions, AllowExplicit,
1249                                   AllowObjCConversionOnExplicit)) {
1250   case OR_Success:
1251   case OR_Deleted:
1252     ICS.setUserDefined();
1253     // C++ [over.ics.user]p4:
1254     //   A conversion of an expression of class type to the same class
1255     //   type is given Exact Match rank, and a conversion of an
1256     //   expression of class type to a base class of that type is
1257     //   given Conversion rank, in spite of the fact that a copy
1258     //   constructor (i.e., a user-defined conversion function) is
1259     //   called for those cases.
1260     if (CXXConstructorDecl *Constructor
1261           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1262       QualType FromCanon
1263         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1264       QualType ToCanon
1265         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1266       if (Constructor->isCopyConstructor() &&
1267           (FromCanon == ToCanon ||
1268            S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1269         // Turn this into a "standard" conversion sequence, so that it
1270         // gets ranked with standard conversion sequences.
1271         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1272         ICS.setStandard();
1273         ICS.Standard.setAsIdentityConversion();
1274         ICS.Standard.setFromType(From->getType());
1275         ICS.Standard.setAllToTypes(ToType);
1276         ICS.Standard.CopyConstructor = Constructor;
1277         ICS.Standard.FoundCopyConstructor = Found;
1278         if (ToCanon != FromCanon)
1279           ICS.Standard.Second = ICK_Derived_To_Base;
1280       }
1281     }
1282     break;
1283 
1284   case OR_Ambiguous:
1285     ICS.setAmbiguous();
1286     ICS.Ambiguous.setFromType(From->getType());
1287     ICS.Ambiguous.setToType(ToType);
1288     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1289          Cand != Conversions.end(); ++Cand)
1290       if (Cand->Viable)
1291         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1292     break;
1293 
1294     // Fall through.
1295   case OR_No_Viable_Function:
1296     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1297     break;
1298   }
1299 
1300   return ICS;
1301 }
1302 
1303 /// TryImplicitConversion - Attempt to perform an implicit conversion
1304 /// from the given expression (Expr) to the given type (ToType). This
1305 /// function returns an implicit conversion sequence that can be used
1306 /// to perform the initialization. Given
1307 ///
1308 ///   void f(float f);
1309 ///   void g(int i) { f(i); }
1310 ///
1311 /// this routine would produce an implicit conversion sequence to
1312 /// describe the initialization of f from i, which will be a standard
1313 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1314 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1315 //
1316 /// Note that this routine only determines how the conversion can be
1317 /// performed; it does not actually perform the conversion. As such,
1318 /// it will not produce any diagnostics if no conversion is available,
1319 /// but will instead return an implicit conversion sequence of kind
1320 /// "BadConversion".
1321 ///
1322 /// If @p SuppressUserConversions, then user-defined conversions are
1323 /// not permitted.
1324 /// If @p AllowExplicit, then explicit user-defined conversions are
1325 /// permitted.
1326 ///
1327 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1328 /// writeback conversion, which allows __autoreleasing id* parameters to
1329 /// be initialized with __strong id* or __weak id* arguments.
1330 static ImplicitConversionSequence
1331 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1332                       bool SuppressUserConversions,
1333                       bool AllowExplicit,
1334                       bool InOverloadResolution,
1335                       bool CStyle,
1336                       bool AllowObjCWritebackConversion,
1337                       bool AllowObjCConversionOnExplicit) {
1338   ImplicitConversionSequence ICS;
1339   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1340                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1341     ICS.setStandard();
1342     return ICS;
1343   }
1344 
1345   if (!S.getLangOpts().CPlusPlus) {
1346     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1347     return ICS;
1348   }
1349 
1350   // C++ [over.ics.user]p4:
1351   //   A conversion of an expression of class type to the same class
1352   //   type is given Exact Match rank, and a conversion of an
1353   //   expression of class type to a base class of that type is
1354   //   given Conversion rank, in spite of the fact that a copy/move
1355   //   constructor (i.e., a user-defined conversion function) is
1356   //   called for those cases.
1357   QualType FromType = From->getType();
1358   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1359       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1360        S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1361     ICS.setStandard();
1362     ICS.Standard.setAsIdentityConversion();
1363     ICS.Standard.setFromType(FromType);
1364     ICS.Standard.setAllToTypes(ToType);
1365 
1366     // We don't actually check at this point whether there is a valid
1367     // copy/move constructor, since overloading just assumes that it
1368     // exists. When we actually perform initialization, we'll find the
1369     // appropriate constructor to copy the returned object, if needed.
1370     ICS.Standard.CopyConstructor = nullptr;
1371 
1372     // Determine whether this is considered a derived-to-base conversion.
1373     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1374       ICS.Standard.Second = ICK_Derived_To_Base;
1375 
1376     return ICS;
1377   }
1378 
1379   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1380                                   AllowExplicit, InOverloadResolution, CStyle,
1381                                   AllowObjCWritebackConversion,
1382                                   AllowObjCConversionOnExplicit);
1383 }
1384 
1385 ImplicitConversionSequence
1386 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1387                             bool SuppressUserConversions,
1388                             bool AllowExplicit,
1389                             bool InOverloadResolution,
1390                             bool CStyle,
1391                             bool AllowObjCWritebackConversion) {
1392   return ::TryImplicitConversion(*this, From, ToType,
1393                                  SuppressUserConversions, AllowExplicit,
1394                                  InOverloadResolution, CStyle,
1395                                  AllowObjCWritebackConversion,
1396                                  /*AllowObjCConversionOnExplicit=*/false);
1397 }
1398 
1399 /// PerformImplicitConversion - Perform an implicit conversion of the
1400 /// expression From to the type ToType. Returns the
1401 /// converted expression. Flavor is the kind of conversion we're
1402 /// performing, used in the error message. If @p AllowExplicit,
1403 /// explicit user-defined conversions are permitted.
1404 ExprResult
1405 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1406                                 AssignmentAction Action, bool AllowExplicit) {
1407   ImplicitConversionSequence ICS;
1408   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1409 }
1410 
1411 ExprResult
1412 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1413                                 AssignmentAction Action, bool AllowExplicit,
1414                                 ImplicitConversionSequence& ICS) {
1415   if (checkPlaceholderForOverload(*this, From))
1416     return ExprError();
1417 
1418   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1419   bool AllowObjCWritebackConversion
1420     = getLangOpts().ObjCAutoRefCount &&
1421       (Action == AA_Passing || Action == AA_Sending);
1422   if (getLangOpts().ObjC)
1423     CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1424                                       From->getType(), From);
1425   ICS = ::TryImplicitConversion(*this, From, ToType,
1426                                 /*SuppressUserConversions=*/false,
1427                                 AllowExplicit,
1428                                 /*InOverloadResolution=*/false,
1429                                 /*CStyle=*/false,
1430                                 AllowObjCWritebackConversion,
1431                                 /*AllowObjCConversionOnExplicit=*/false);
1432   return PerformImplicitConversion(From, ToType, ICS, Action);
1433 }
1434 
1435 /// Determine whether the conversion from FromType to ToType is a valid
1436 /// conversion that strips "noexcept" or "noreturn" off the nested function
1437 /// type.
1438 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1439                                 QualType &ResultTy) {
1440   if (Context.hasSameUnqualifiedType(FromType, ToType))
1441     return false;
1442 
1443   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1444   //                    or F(t noexcept) -> F(t)
1445   // where F adds one of the following at most once:
1446   //   - a pointer
1447   //   - a member pointer
1448   //   - a block pointer
1449   // Changes here need matching changes in FindCompositePointerType.
1450   CanQualType CanTo = Context.getCanonicalType(ToType);
1451   CanQualType CanFrom = Context.getCanonicalType(FromType);
1452   Type::TypeClass TyClass = CanTo->getTypeClass();
1453   if (TyClass != CanFrom->getTypeClass()) return false;
1454   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1455     if (TyClass == Type::Pointer) {
1456       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1457       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1458     } else if (TyClass == Type::BlockPointer) {
1459       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1460       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1461     } else if (TyClass == Type::MemberPointer) {
1462       auto ToMPT = CanTo.getAs<MemberPointerType>();
1463       auto FromMPT = CanFrom.getAs<MemberPointerType>();
1464       // A function pointer conversion cannot change the class of the function.
1465       if (ToMPT->getClass() != FromMPT->getClass())
1466         return false;
1467       CanTo = ToMPT->getPointeeType();
1468       CanFrom = FromMPT->getPointeeType();
1469     } else {
1470       return false;
1471     }
1472 
1473     TyClass = CanTo->getTypeClass();
1474     if (TyClass != CanFrom->getTypeClass()) return false;
1475     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1476       return false;
1477   }
1478 
1479   const auto *FromFn = cast<FunctionType>(CanFrom);
1480   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1481 
1482   const auto *ToFn = cast<FunctionType>(CanTo);
1483   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1484 
1485   bool Changed = false;
1486 
1487   // Drop 'noreturn' if not present in target type.
1488   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1489     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1490     Changed = true;
1491   }
1492 
1493   // Drop 'noexcept' if not present in target type.
1494   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1495     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1496     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1497       FromFn = cast<FunctionType>(
1498           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1499                                                    EST_None)
1500                  .getTypePtr());
1501       Changed = true;
1502     }
1503 
1504     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1505     // only if the ExtParameterInfo lists of the two function prototypes can be
1506     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1507     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1508     bool CanUseToFPT, CanUseFromFPT;
1509     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1510                                       CanUseFromFPT, NewParamInfos) &&
1511         CanUseToFPT && !CanUseFromFPT) {
1512       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1513       ExtInfo.ExtParameterInfos =
1514           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1515       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1516                                             FromFPT->getParamTypes(), ExtInfo);
1517       FromFn = QT->getAs<FunctionType>();
1518       Changed = true;
1519     }
1520   }
1521 
1522   if (!Changed)
1523     return false;
1524 
1525   assert(QualType(FromFn, 0).isCanonical());
1526   if (QualType(FromFn, 0) != CanTo) return false;
1527 
1528   ResultTy = ToType;
1529   return true;
1530 }
1531 
1532 /// Determine whether the conversion from FromType to ToType is a valid
1533 /// vector conversion.
1534 ///
1535 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1536 /// conversion.
1537 static bool IsVectorConversion(Sema &S, QualType FromType,
1538                                QualType ToType, ImplicitConversionKind &ICK) {
1539   // We need at least one of these types to be a vector type to have a vector
1540   // conversion.
1541   if (!ToType->isVectorType() && !FromType->isVectorType())
1542     return false;
1543 
1544   // Identical types require no conversions.
1545   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1546     return false;
1547 
1548   // There are no conversions between extended vector types, only identity.
1549   if (ToType->isExtVectorType()) {
1550     // There are no conversions between extended vector types other than the
1551     // identity conversion.
1552     if (FromType->isExtVectorType())
1553       return false;
1554 
1555     // Vector splat from any arithmetic type to a vector.
1556     if (FromType->isArithmeticType()) {
1557       ICK = ICK_Vector_Splat;
1558       return true;
1559     }
1560   }
1561 
1562   // We can perform the conversion between vector types in the following cases:
1563   // 1)vector types are equivalent AltiVec and GCC vector types
1564   // 2)lax vector conversions are permitted and the vector types are of the
1565   //   same size
1566   if (ToType->isVectorType() && FromType->isVectorType()) {
1567     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1568         S.isLaxVectorConversion(FromType, ToType)) {
1569       ICK = ICK_Vector_Conversion;
1570       return true;
1571     }
1572   }
1573 
1574   return false;
1575 }
1576 
1577 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1578                                 bool InOverloadResolution,
1579                                 StandardConversionSequence &SCS,
1580                                 bool CStyle);
1581 
1582 /// IsStandardConversion - Determines whether there is a standard
1583 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1584 /// expression From to the type ToType. Standard conversion sequences
1585 /// only consider non-class types; for conversions that involve class
1586 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1587 /// contain the standard conversion sequence required to perform this
1588 /// conversion and this routine will return true. Otherwise, this
1589 /// routine will return false and the value of SCS is unspecified.
1590 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1591                                  bool InOverloadResolution,
1592                                  StandardConversionSequence &SCS,
1593                                  bool CStyle,
1594                                  bool AllowObjCWritebackConversion) {
1595   QualType FromType = From->getType();
1596 
1597   // Standard conversions (C++ [conv])
1598   SCS.setAsIdentityConversion();
1599   SCS.IncompatibleObjC = false;
1600   SCS.setFromType(FromType);
1601   SCS.CopyConstructor = nullptr;
1602 
1603   // There are no standard conversions for class types in C++, so
1604   // abort early. When overloading in C, however, we do permit them.
1605   if (S.getLangOpts().CPlusPlus &&
1606       (FromType->isRecordType() || ToType->isRecordType()))
1607     return false;
1608 
1609   // The first conversion can be an lvalue-to-rvalue conversion,
1610   // array-to-pointer conversion, or function-to-pointer conversion
1611   // (C++ 4p1).
1612 
1613   if (FromType == S.Context.OverloadTy) {
1614     DeclAccessPair AccessPair;
1615     if (FunctionDecl *Fn
1616           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1617                                                  AccessPair)) {
1618       // We were able to resolve the address of the overloaded function,
1619       // so we can convert to the type of that function.
1620       FromType = Fn->getType();
1621       SCS.setFromType(FromType);
1622 
1623       // we can sometimes resolve &foo<int> regardless of ToType, so check
1624       // if the type matches (identity) or we are converting to bool
1625       if (!S.Context.hasSameUnqualifiedType(
1626                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1627         QualType resultTy;
1628         // if the function type matches except for [[noreturn]], it's ok
1629         if (!S.IsFunctionConversion(FromType,
1630               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1631           // otherwise, only a boolean conversion is standard
1632           if (!ToType->isBooleanType())
1633             return false;
1634       }
1635 
1636       // Check if the "from" expression is taking the address of an overloaded
1637       // function and recompute the FromType accordingly. Take advantage of the
1638       // fact that non-static member functions *must* have such an address-of
1639       // expression.
1640       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1641       if (Method && !Method->isStatic()) {
1642         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1643                "Non-unary operator on non-static member address");
1644         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1645                == UO_AddrOf &&
1646                "Non-address-of operator on non-static member address");
1647         const Type *ClassType
1648           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1649         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1650       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1651         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1652                UO_AddrOf &&
1653                "Non-address-of operator for overloaded function expression");
1654         FromType = S.Context.getPointerType(FromType);
1655       }
1656 
1657       // Check that we've computed the proper type after overload resolution.
1658       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1659       // be calling it from within an NDEBUG block.
1660       assert(S.Context.hasSameType(
1661         FromType,
1662         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1663     } else {
1664       return false;
1665     }
1666   }
1667   // Lvalue-to-rvalue conversion (C++11 4.1):
1668   //   A glvalue (3.10) of a non-function, non-array type T can
1669   //   be converted to a prvalue.
1670   bool argIsLValue = From->isGLValue();
1671   if (argIsLValue &&
1672       !FromType->isFunctionType() && !FromType->isArrayType() &&
1673       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1674     SCS.First = ICK_Lvalue_To_Rvalue;
1675 
1676     // C11 6.3.2.1p2:
1677     //   ... if the lvalue has atomic type, the value has the non-atomic version
1678     //   of the type of the lvalue ...
1679     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1680       FromType = Atomic->getValueType();
1681 
1682     // If T is a non-class type, the type of the rvalue is the
1683     // cv-unqualified version of T. Otherwise, the type of the rvalue
1684     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1685     // just strip the qualifiers because they don't matter.
1686     FromType = FromType.getUnqualifiedType();
1687   } else if (FromType->isArrayType()) {
1688     // Array-to-pointer conversion (C++ 4.2)
1689     SCS.First = ICK_Array_To_Pointer;
1690 
1691     // An lvalue or rvalue of type "array of N T" or "array of unknown
1692     // bound of T" can be converted to an rvalue of type "pointer to
1693     // T" (C++ 4.2p1).
1694     FromType = S.Context.getArrayDecayedType(FromType);
1695 
1696     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1697       // This conversion is deprecated in C++03 (D.4)
1698       SCS.DeprecatedStringLiteralToCharPtr = true;
1699 
1700       // For the purpose of ranking in overload resolution
1701       // (13.3.3.1.1), this conversion is considered an
1702       // array-to-pointer conversion followed by a qualification
1703       // conversion (4.4). (C++ 4.2p2)
1704       SCS.Second = ICK_Identity;
1705       SCS.Third = ICK_Qualification;
1706       SCS.QualificationIncludesObjCLifetime = false;
1707       SCS.setAllToTypes(FromType);
1708       return true;
1709     }
1710   } else if (FromType->isFunctionType() && argIsLValue) {
1711     // Function-to-pointer conversion (C++ 4.3).
1712     SCS.First = ICK_Function_To_Pointer;
1713 
1714     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1715       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1716         if (!S.checkAddressOfFunctionIsAvailable(FD))
1717           return false;
1718 
1719     // An lvalue of function type T can be converted to an rvalue of
1720     // type "pointer to T." The result is a pointer to the
1721     // function. (C++ 4.3p1).
1722     FromType = S.Context.getPointerType(FromType);
1723   } else {
1724     // We don't require any conversions for the first step.
1725     SCS.First = ICK_Identity;
1726   }
1727   SCS.setToType(0, FromType);
1728 
1729   // The second conversion can be an integral promotion, floating
1730   // point promotion, integral conversion, floating point conversion,
1731   // floating-integral conversion, pointer conversion,
1732   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1733   // For overloading in C, this can also be a "compatible-type"
1734   // conversion.
1735   bool IncompatibleObjC = false;
1736   ImplicitConversionKind SecondICK = ICK_Identity;
1737   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1738     // The unqualified versions of the types are the same: there's no
1739     // conversion to do.
1740     SCS.Second = ICK_Identity;
1741   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1742     // Integral promotion (C++ 4.5).
1743     SCS.Second = ICK_Integral_Promotion;
1744     FromType = ToType.getUnqualifiedType();
1745   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1746     // Floating point promotion (C++ 4.6).
1747     SCS.Second = ICK_Floating_Promotion;
1748     FromType = ToType.getUnqualifiedType();
1749   } else if (S.IsComplexPromotion(FromType, ToType)) {
1750     // Complex promotion (Clang extension)
1751     SCS.Second = ICK_Complex_Promotion;
1752     FromType = ToType.getUnqualifiedType();
1753   } else if (ToType->isBooleanType() &&
1754              (FromType->isArithmeticType() ||
1755               FromType->isAnyPointerType() ||
1756               FromType->isBlockPointerType() ||
1757               FromType->isMemberPointerType() ||
1758               FromType->isNullPtrType())) {
1759     // Boolean conversions (C++ 4.12).
1760     SCS.Second = ICK_Boolean_Conversion;
1761     FromType = S.Context.BoolTy;
1762   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1763              ToType->isIntegralType(S.Context)) {
1764     // Integral conversions (C++ 4.7).
1765     SCS.Second = ICK_Integral_Conversion;
1766     FromType = ToType.getUnqualifiedType();
1767   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1768     // Complex conversions (C99 6.3.1.6)
1769     SCS.Second = ICK_Complex_Conversion;
1770     FromType = ToType.getUnqualifiedType();
1771   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1772              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1773     // Complex-real conversions (C99 6.3.1.7)
1774     SCS.Second = ICK_Complex_Real;
1775     FromType = ToType.getUnqualifiedType();
1776   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1777     // FIXME: disable conversions between long double and __float128 if
1778     // their representation is different until there is back end support
1779     // We of course allow this conversion if long double is really double.
1780     if (&S.Context.getFloatTypeSemantics(FromType) !=
1781         &S.Context.getFloatTypeSemantics(ToType)) {
1782       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1783                                     ToType == S.Context.LongDoubleTy) ||
1784                                    (FromType == S.Context.LongDoubleTy &&
1785                                     ToType == S.Context.Float128Ty));
1786       if (Float128AndLongDouble &&
1787           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1788            &llvm::APFloat::PPCDoubleDouble()))
1789         return false;
1790     }
1791     // Floating point conversions (C++ 4.8).
1792     SCS.Second = ICK_Floating_Conversion;
1793     FromType = ToType.getUnqualifiedType();
1794   } else if ((FromType->isRealFloatingType() &&
1795               ToType->isIntegralType(S.Context)) ||
1796              (FromType->isIntegralOrUnscopedEnumerationType() &&
1797               ToType->isRealFloatingType())) {
1798     // Floating-integral conversions (C++ 4.9).
1799     SCS.Second = ICK_Floating_Integral;
1800     FromType = ToType.getUnqualifiedType();
1801   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1802     SCS.Second = ICK_Block_Pointer_Conversion;
1803   } else if (AllowObjCWritebackConversion &&
1804              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1805     SCS.Second = ICK_Writeback_Conversion;
1806   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1807                                    FromType, IncompatibleObjC)) {
1808     // Pointer conversions (C++ 4.10).
1809     SCS.Second = ICK_Pointer_Conversion;
1810     SCS.IncompatibleObjC = IncompatibleObjC;
1811     FromType = FromType.getUnqualifiedType();
1812   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1813                                          InOverloadResolution, FromType)) {
1814     // Pointer to member conversions (4.11).
1815     SCS.Second = ICK_Pointer_Member;
1816   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1817     SCS.Second = SecondICK;
1818     FromType = ToType.getUnqualifiedType();
1819   } else if (!S.getLangOpts().CPlusPlus &&
1820              S.Context.typesAreCompatible(ToType, FromType)) {
1821     // Compatible conversions (Clang extension for C function overloading)
1822     SCS.Second = ICK_Compatible_Conversion;
1823     FromType = ToType.getUnqualifiedType();
1824   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1825                                              InOverloadResolution,
1826                                              SCS, CStyle)) {
1827     SCS.Second = ICK_TransparentUnionConversion;
1828     FromType = ToType;
1829   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1830                                  CStyle)) {
1831     // tryAtomicConversion has updated the standard conversion sequence
1832     // appropriately.
1833     return true;
1834   } else if (ToType->isEventT() &&
1835              From->isIntegerConstantExpr(S.getASTContext()) &&
1836              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1837     SCS.Second = ICK_Zero_Event_Conversion;
1838     FromType = ToType;
1839   } else if (ToType->isQueueT() &&
1840              From->isIntegerConstantExpr(S.getASTContext()) &&
1841              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1842     SCS.Second = ICK_Zero_Queue_Conversion;
1843     FromType = ToType;
1844   } else {
1845     // No second conversion required.
1846     SCS.Second = ICK_Identity;
1847   }
1848   SCS.setToType(1, FromType);
1849 
1850   // The third conversion can be a function pointer conversion or a
1851   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1852   bool ObjCLifetimeConversion;
1853   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1854     // Function pointer conversions (removing 'noexcept') including removal of
1855     // 'noreturn' (Clang extension).
1856     SCS.Third = ICK_Function_Conversion;
1857   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1858                                          ObjCLifetimeConversion)) {
1859     SCS.Third = ICK_Qualification;
1860     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1861     FromType = ToType;
1862   } else {
1863     // No conversion required
1864     SCS.Third = ICK_Identity;
1865   }
1866 
1867   // C++ [over.best.ics]p6:
1868   //   [...] Any difference in top-level cv-qualification is
1869   //   subsumed by the initialization itself and does not constitute
1870   //   a conversion. [...]
1871   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1872   QualType CanonTo = S.Context.getCanonicalType(ToType);
1873   if (CanonFrom.getLocalUnqualifiedType()
1874                                      == CanonTo.getLocalUnqualifiedType() &&
1875       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1876     FromType = ToType;
1877     CanonFrom = CanonTo;
1878   }
1879 
1880   SCS.setToType(2, FromType);
1881 
1882   if (CanonFrom == CanonTo)
1883     return true;
1884 
1885   // If we have not converted the argument type to the parameter type,
1886   // this is a bad conversion sequence, unless we're resolving an overload in C.
1887   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1888     return false;
1889 
1890   ExprResult ER = ExprResult{From};
1891   Sema::AssignConvertType Conv =
1892       S.CheckSingleAssignmentConstraints(ToType, ER,
1893                                          /*Diagnose=*/false,
1894                                          /*DiagnoseCFAudited=*/false,
1895                                          /*ConvertRHS=*/false);
1896   ImplicitConversionKind SecondConv;
1897   switch (Conv) {
1898   case Sema::Compatible:
1899     SecondConv = ICK_C_Only_Conversion;
1900     break;
1901   // For our purposes, discarding qualifiers is just as bad as using an
1902   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1903   // qualifiers, as well.
1904   case Sema::CompatiblePointerDiscardsQualifiers:
1905   case Sema::IncompatiblePointer:
1906   case Sema::IncompatiblePointerSign:
1907     SecondConv = ICK_Incompatible_Pointer_Conversion;
1908     break;
1909   default:
1910     return false;
1911   }
1912 
1913   // First can only be an lvalue conversion, so we pretend that this was the
1914   // second conversion. First should already be valid from earlier in the
1915   // function.
1916   SCS.Second = SecondConv;
1917   SCS.setToType(1, ToType);
1918 
1919   // Third is Identity, because Second should rank us worse than any other
1920   // conversion. This could also be ICK_Qualification, but it's simpler to just
1921   // lump everything in with the second conversion, and we don't gain anything
1922   // from making this ICK_Qualification.
1923   SCS.Third = ICK_Identity;
1924   SCS.setToType(2, ToType);
1925   return true;
1926 }
1927 
1928 static bool
1929 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1930                                      QualType &ToType,
1931                                      bool InOverloadResolution,
1932                                      StandardConversionSequence &SCS,
1933                                      bool CStyle) {
1934 
1935   const RecordType *UT = ToType->getAsUnionType();
1936   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1937     return false;
1938   // The field to initialize within the transparent union.
1939   RecordDecl *UD = UT->getDecl();
1940   // It's compatible if the expression matches any of the fields.
1941   for (const auto *it : UD->fields()) {
1942     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1943                              CStyle, /*ObjCWritebackConversion=*/false)) {
1944       ToType = it->getType();
1945       return true;
1946     }
1947   }
1948   return false;
1949 }
1950 
1951 /// IsIntegralPromotion - Determines whether the conversion from the
1952 /// expression From (whose potentially-adjusted type is FromType) to
1953 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1954 /// sets PromotedType to the promoted type.
1955 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1956   const BuiltinType *To = ToType->getAs<BuiltinType>();
1957   // All integers are built-in.
1958   if (!To) {
1959     return false;
1960   }
1961 
1962   // An rvalue of type char, signed char, unsigned char, short int, or
1963   // unsigned short int can be converted to an rvalue of type int if
1964   // int can represent all the values of the source type; otherwise,
1965   // the source rvalue can be converted to an rvalue of type unsigned
1966   // int (C++ 4.5p1).
1967   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1968       !FromType->isEnumeralType()) {
1969     if (// We can promote any signed, promotable integer type to an int
1970         (FromType->isSignedIntegerType() ||
1971          // We can promote any unsigned integer type whose size is
1972          // less than int to an int.
1973          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1974       return To->getKind() == BuiltinType::Int;
1975     }
1976 
1977     return To->getKind() == BuiltinType::UInt;
1978   }
1979 
1980   // C++11 [conv.prom]p3:
1981   //   A prvalue of an unscoped enumeration type whose underlying type is not
1982   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1983   //   following types that can represent all the values of the enumeration
1984   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1985   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1986   //   long long int. If none of the types in that list can represent all the
1987   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1988   //   type can be converted to an rvalue a prvalue of the extended integer type
1989   //   with lowest integer conversion rank (4.13) greater than the rank of long
1990   //   long in which all the values of the enumeration can be represented. If
1991   //   there are two such extended types, the signed one is chosen.
1992   // C++11 [conv.prom]p4:
1993   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1994   //   can be converted to a prvalue of its underlying type. Moreover, if
1995   //   integral promotion can be applied to its underlying type, a prvalue of an
1996   //   unscoped enumeration type whose underlying type is fixed can also be
1997   //   converted to a prvalue of the promoted underlying type.
1998   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1999     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2000     // provided for a scoped enumeration.
2001     if (FromEnumType->getDecl()->isScoped())
2002       return false;
2003 
2004     // We can perform an integral promotion to the underlying type of the enum,
2005     // even if that's not the promoted type. Note that the check for promoting
2006     // the underlying type is based on the type alone, and does not consider
2007     // the bitfield-ness of the actual source expression.
2008     if (FromEnumType->getDecl()->isFixed()) {
2009       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2010       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2011              IsIntegralPromotion(nullptr, Underlying, ToType);
2012     }
2013 
2014     // We have already pre-calculated the promotion type, so this is trivial.
2015     if (ToType->isIntegerType() &&
2016         isCompleteType(From->getBeginLoc(), FromType))
2017       return Context.hasSameUnqualifiedType(
2018           ToType, FromEnumType->getDecl()->getPromotionType());
2019 
2020     // C++ [conv.prom]p5:
2021     //   If the bit-field has an enumerated type, it is treated as any other
2022     //   value of that type for promotion purposes.
2023     //
2024     // ... so do not fall through into the bit-field checks below in C++.
2025     if (getLangOpts().CPlusPlus)
2026       return false;
2027   }
2028 
2029   // C++0x [conv.prom]p2:
2030   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2031   //   to an rvalue a prvalue of the first of the following types that can
2032   //   represent all the values of its underlying type: int, unsigned int,
2033   //   long int, unsigned long int, long long int, or unsigned long long int.
2034   //   If none of the types in that list can represent all the values of its
2035   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2036   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2037   //   type.
2038   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2039       ToType->isIntegerType()) {
2040     // Determine whether the type we're converting from is signed or
2041     // unsigned.
2042     bool FromIsSigned = FromType->isSignedIntegerType();
2043     uint64_t FromSize = Context.getTypeSize(FromType);
2044 
2045     // The types we'll try to promote to, in the appropriate
2046     // order. Try each of these types.
2047     QualType PromoteTypes[6] = {
2048       Context.IntTy, Context.UnsignedIntTy,
2049       Context.LongTy, Context.UnsignedLongTy ,
2050       Context.LongLongTy, Context.UnsignedLongLongTy
2051     };
2052     for (int Idx = 0; Idx < 6; ++Idx) {
2053       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2054       if (FromSize < ToSize ||
2055           (FromSize == ToSize &&
2056            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2057         // We found the type that we can promote to. If this is the
2058         // type we wanted, we have a promotion. Otherwise, no
2059         // promotion.
2060         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2061       }
2062     }
2063   }
2064 
2065   // An rvalue for an integral bit-field (9.6) can be converted to an
2066   // rvalue of type int if int can represent all the values of the
2067   // bit-field; otherwise, it can be converted to unsigned int if
2068   // unsigned int can represent all the values of the bit-field. If
2069   // the bit-field is larger yet, no integral promotion applies to
2070   // it. If the bit-field has an enumerated type, it is treated as any
2071   // other value of that type for promotion purposes (C++ 4.5p3).
2072   // FIXME: We should delay checking of bit-fields until we actually perform the
2073   // conversion.
2074   //
2075   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2076   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2077   // bit-fields and those whose underlying type is larger than int) for GCC
2078   // compatibility.
2079   if (From) {
2080     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2081       llvm::APSInt BitWidth;
2082       if (FromType->isIntegralType(Context) &&
2083           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2084         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2085         ToSize = Context.getTypeSize(ToType);
2086 
2087         // Are we promoting to an int from a bitfield that fits in an int?
2088         if (BitWidth < ToSize ||
2089             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2090           return To->getKind() == BuiltinType::Int;
2091         }
2092 
2093         // Are we promoting to an unsigned int from an unsigned bitfield
2094         // that fits into an unsigned int?
2095         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2096           return To->getKind() == BuiltinType::UInt;
2097         }
2098 
2099         return false;
2100       }
2101     }
2102   }
2103 
2104   // An rvalue of type bool can be converted to an rvalue of type int,
2105   // with false becoming zero and true becoming one (C++ 4.5p4).
2106   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2107     return true;
2108   }
2109 
2110   return false;
2111 }
2112 
2113 /// IsFloatingPointPromotion - Determines whether the conversion from
2114 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2115 /// returns true and sets PromotedType to the promoted type.
2116 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2117   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2118     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2119       /// An rvalue of type float can be converted to an rvalue of type
2120       /// double. (C++ 4.6p1).
2121       if (FromBuiltin->getKind() == BuiltinType::Float &&
2122           ToBuiltin->getKind() == BuiltinType::Double)
2123         return true;
2124 
2125       // C99 6.3.1.5p1:
2126       //   When a float is promoted to double or long double, or a
2127       //   double is promoted to long double [...].
2128       if (!getLangOpts().CPlusPlus &&
2129           (FromBuiltin->getKind() == BuiltinType::Float ||
2130            FromBuiltin->getKind() == BuiltinType::Double) &&
2131           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2132            ToBuiltin->getKind() == BuiltinType::Float128))
2133         return true;
2134 
2135       // Half can be promoted to float.
2136       if (!getLangOpts().NativeHalfType &&
2137            FromBuiltin->getKind() == BuiltinType::Half &&
2138           ToBuiltin->getKind() == BuiltinType::Float)
2139         return true;
2140     }
2141 
2142   return false;
2143 }
2144 
2145 /// Determine if a conversion is a complex promotion.
2146 ///
2147 /// A complex promotion is defined as a complex -> complex conversion
2148 /// where the conversion between the underlying real types is a
2149 /// floating-point or integral promotion.
2150 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2151   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2152   if (!FromComplex)
2153     return false;
2154 
2155   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2156   if (!ToComplex)
2157     return false;
2158 
2159   return IsFloatingPointPromotion(FromComplex->getElementType(),
2160                                   ToComplex->getElementType()) ||
2161     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2162                         ToComplex->getElementType());
2163 }
2164 
2165 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2166 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2167 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2168 /// if non-empty, will be a pointer to ToType that may or may not have
2169 /// the right set of qualifiers on its pointee.
2170 ///
2171 static QualType
2172 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2173                                    QualType ToPointee, QualType ToType,
2174                                    ASTContext &Context,
2175                                    bool StripObjCLifetime = false) {
2176   assert((FromPtr->getTypeClass() == Type::Pointer ||
2177           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2178          "Invalid similarly-qualified pointer type");
2179 
2180   /// Conversions to 'id' subsume cv-qualifier conversions.
2181   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2182     return ToType.getUnqualifiedType();
2183 
2184   QualType CanonFromPointee
2185     = Context.getCanonicalType(FromPtr->getPointeeType());
2186   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2187   Qualifiers Quals = CanonFromPointee.getQualifiers();
2188 
2189   if (StripObjCLifetime)
2190     Quals.removeObjCLifetime();
2191 
2192   // Exact qualifier match -> return the pointer type we're converting to.
2193   if (CanonToPointee.getLocalQualifiers() == Quals) {
2194     // ToType is exactly what we need. Return it.
2195     if (!ToType.isNull())
2196       return ToType.getUnqualifiedType();
2197 
2198     // Build a pointer to ToPointee. It has the right qualifiers
2199     // already.
2200     if (isa<ObjCObjectPointerType>(ToType))
2201       return Context.getObjCObjectPointerType(ToPointee);
2202     return Context.getPointerType(ToPointee);
2203   }
2204 
2205   // Just build a canonical type that has the right qualifiers.
2206   QualType QualifiedCanonToPointee
2207     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2208 
2209   if (isa<ObjCObjectPointerType>(ToType))
2210     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2211   return Context.getPointerType(QualifiedCanonToPointee);
2212 }
2213 
2214 static bool isNullPointerConstantForConversion(Expr *Expr,
2215                                                bool InOverloadResolution,
2216                                                ASTContext &Context) {
2217   // Handle value-dependent integral null pointer constants correctly.
2218   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2219   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2220       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2221     return !InOverloadResolution;
2222 
2223   return Expr->isNullPointerConstant(Context,
2224                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2225                                         : Expr::NPC_ValueDependentIsNull);
2226 }
2227 
2228 /// IsPointerConversion - Determines whether the conversion of the
2229 /// expression From, which has the (possibly adjusted) type FromType,
2230 /// can be converted to the type ToType via a pointer conversion (C++
2231 /// 4.10). If so, returns true and places the converted type (that
2232 /// might differ from ToType in its cv-qualifiers at some level) into
2233 /// ConvertedType.
2234 ///
2235 /// This routine also supports conversions to and from block pointers
2236 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2237 /// pointers to interfaces. FIXME: Once we've determined the
2238 /// appropriate overloading rules for Objective-C, we may want to
2239 /// split the Objective-C checks into a different routine; however,
2240 /// GCC seems to consider all of these conversions to be pointer
2241 /// conversions, so for now they live here. IncompatibleObjC will be
2242 /// set if the conversion is an allowed Objective-C conversion that
2243 /// should result in a warning.
2244 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2245                                bool InOverloadResolution,
2246                                QualType& ConvertedType,
2247                                bool &IncompatibleObjC) {
2248   IncompatibleObjC = false;
2249   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2250                               IncompatibleObjC))
2251     return true;
2252 
2253   // Conversion from a null pointer constant to any Objective-C pointer type.
2254   if (ToType->isObjCObjectPointerType() &&
2255       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2256     ConvertedType = ToType;
2257     return true;
2258   }
2259 
2260   // Blocks: Block pointers can be converted to void*.
2261   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2262       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2263     ConvertedType = ToType;
2264     return true;
2265   }
2266   // Blocks: A null pointer constant can be converted to a block
2267   // pointer type.
2268   if (ToType->isBlockPointerType() &&
2269       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2270     ConvertedType = ToType;
2271     return true;
2272   }
2273 
2274   // If the left-hand-side is nullptr_t, the right side can be a null
2275   // pointer constant.
2276   if (ToType->isNullPtrType() &&
2277       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2278     ConvertedType = ToType;
2279     return true;
2280   }
2281 
2282   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2283   if (!ToTypePtr)
2284     return false;
2285 
2286   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2287   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2288     ConvertedType = ToType;
2289     return true;
2290   }
2291 
2292   // Beyond this point, both types need to be pointers
2293   // , including objective-c pointers.
2294   QualType ToPointeeType = ToTypePtr->getPointeeType();
2295   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2296       !getLangOpts().ObjCAutoRefCount) {
2297     ConvertedType = BuildSimilarlyQualifiedPointerType(
2298                                       FromType->getAs<ObjCObjectPointerType>(),
2299                                                        ToPointeeType,
2300                                                        ToType, Context);
2301     return true;
2302   }
2303   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2304   if (!FromTypePtr)
2305     return false;
2306 
2307   QualType FromPointeeType = FromTypePtr->getPointeeType();
2308 
2309   // If the unqualified pointee types are the same, this can't be a
2310   // pointer conversion, so don't do all of the work below.
2311   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2312     return false;
2313 
2314   // An rvalue of type "pointer to cv T," where T is an object type,
2315   // can be converted to an rvalue of type "pointer to cv void" (C++
2316   // 4.10p2).
2317   if (FromPointeeType->isIncompleteOrObjectType() &&
2318       ToPointeeType->isVoidType()) {
2319     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2320                                                        ToPointeeType,
2321                                                        ToType, Context,
2322                                                    /*StripObjCLifetime=*/true);
2323     return true;
2324   }
2325 
2326   // MSVC allows implicit function to void* type conversion.
2327   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2328       ToPointeeType->isVoidType()) {
2329     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2330                                                        ToPointeeType,
2331                                                        ToType, Context);
2332     return true;
2333   }
2334 
2335   // When we're overloading in C, we allow a special kind of pointer
2336   // conversion for compatible-but-not-identical pointee types.
2337   if (!getLangOpts().CPlusPlus &&
2338       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2339     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2340                                                        ToPointeeType,
2341                                                        ToType, Context);
2342     return true;
2343   }
2344 
2345   // C++ [conv.ptr]p3:
2346   //
2347   //   An rvalue of type "pointer to cv D," where D is a class type,
2348   //   can be converted to an rvalue of type "pointer to cv B," where
2349   //   B is a base class (clause 10) of D. If B is an inaccessible
2350   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2351   //   necessitates this conversion is ill-formed. The result of the
2352   //   conversion is a pointer to the base class sub-object of the
2353   //   derived class object. The null pointer value is converted to
2354   //   the null pointer value of the destination type.
2355   //
2356   // Note that we do not check for ambiguity or inaccessibility
2357   // here. That is handled by CheckPointerConversion.
2358   if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2359       ToPointeeType->isRecordType() &&
2360       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2361       IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2362     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2363                                                        ToPointeeType,
2364                                                        ToType, Context);
2365     return true;
2366   }
2367 
2368   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2369       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2370     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2371                                                        ToPointeeType,
2372                                                        ToType, Context);
2373     return true;
2374   }
2375 
2376   return false;
2377 }
2378 
2379 /// Adopt the given qualifiers for the given type.
2380 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2381   Qualifiers TQs = T.getQualifiers();
2382 
2383   // Check whether qualifiers already match.
2384   if (TQs == Qs)
2385     return T;
2386 
2387   if (Qs.compatiblyIncludes(TQs))
2388     return Context.getQualifiedType(T, Qs);
2389 
2390   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2391 }
2392 
2393 /// isObjCPointerConversion - Determines whether this is an
2394 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2395 /// with the same arguments and return values.
2396 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2397                                    QualType& ConvertedType,
2398                                    bool &IncompatibleObjC) {
2399   if (!getLangOpts().ObjC)
2400     return false;
2401 
2402   // The set of qualifiers on the type we're converting from.
2403   Qualifiers FromQualifiers = FromType.getQualifiers();
2404 
2405   // First, we handle all conversions on ObjC object pointer types.
2406   const ObjCObjectPointerType* ToObjCPtr =
2407     ToType->getAs<ObjCObjectPointerType>();
2408   const ObjCObjectPointerType *FromObjCPtr =
2409     FromType->getAs<ObjCObjectPointerType>();
2410 
2411   if (ToObjCPtr && FromObjCPtr) {
2412     // If the pointee types are the same (ignoring qualifications),
2413     // then this is not a pointer conversion.
2414     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2415                                        FromObjCPtr->getPointeeType()))
2416       return false;
2417 
2418     // Conversion between Objective-C pointers.
2419     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2420       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2421       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2422       if (getLangOpts().CPlusPlus && LHS && RHS &&
2423           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2424                                                 FromObjCPtr->getPointeeType()))
2425         return false;
2426       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2427                                                    ToObjCPtr->getPointeeType(),
2428                                                          ToType, Context);
2429       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2430       return true;
2431     }
2432 
2433     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2434       // Okay: this is some kind of implicit downcast of Objective-C
2435       // interfaces, which is permitted. However, we're going to
2436       // complain about it.
2437       IncompatibleObjC = true;
2438       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2439                                                    ToObjCPtr->getPointeeType(),
2440                                                          ToType, Context);
2441       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2442       return true;
2443     }
2444   }
2445   // Beyond this point, both types need to be C pointers or block pointers.
2446   QualType ToPointeeType;
2447   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2448     ToPointeeType = ToCPtr->getPointeeType();
2449   else if (const BlockPointerType *ToBlockPtr =
2450             ToType->getAs<BlockPointerType>()) {
2451     // Objective C++: We're able to convert from a pointer to any object
2452     // to a block pointer type.
2453     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2454       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2455       return true;
2456     }
2457     ToPointeeType = ToBlockPtr->getPointeeType();
2458   }
2459   else if (FromType->getAs<BlockPointerType>() &&
2460            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2461     // Objective C++: We're able to convert from a block pointer type to a
2462     // pointer to any object.
2463     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2464     return true;
2465   }
2466   else
2467     return false;
2468 
2469   QualType FromPointeeType;
2470   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2471     FromPointeeType = FromCPtr->getPointeeType();
2472   else if (const BlockPointerType *FromBlockPtr =
2473            FromType->getAs<BlockPointerType>())
2474     FromPointeeType = FromBlockPtr->getPointeeType();
2475   else
2476     return false;
2477 
2478   // If we have pointers to pointers, recursively check whether this
2479   // is an Objective-C conversion.
2480   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2481       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2482                               IncompatibleObjC)) {
2483     // We always complain about this conversion.
2484     IncompatibleObjC = true;
2485     ConvertedType = Context.getPointerType(ConvertedType);
2486     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2487     return true;
2488   }
2489   // Allow conversion of pointee being objective-c pointer to another one;
2490   // as in I* to id.
2491   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2492       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2493       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2494                               IncompatibleObjC)) {
2495 
2496     ConvertedType = Context.getPointerType(ConvertedType);
2497     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2498     return true;
2499   }
2500 
2501   // If we have pointers to functions or blocks, check whether the only
2502   // differences in the argument and result types are in Objective-C
2503   // pointer conversions. If so, we permit the conversion (but
2504   // complain about it).
2505   const FunctionProtoType *FromFunctionType
2506     = FromPointeeType->getAs<FunctionProtoType>();
2507   const FunctionProtoType *ToFunctionType
2508     = ToPointeeType->getAs<FunctionProtoType>();
2509   if (FromFunctionType && ToFunctionType) {
2510     // If the function types are exactly the same, this isn't an
2511     // Objective-C pointer conversion.
2512     if (Context.getCanonicalType(FromPointeeType)
2513           == Context.getCanonicalType(ToPointeeType))
2514       return false;
2515 
2516     // Perform the quick checks that will tell us whether these
2517     // function types are obviously different.
2518     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2519         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2520         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2521       return false;
2522 
2523     bool HasObjCConversion = false;
2524     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2525         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2526       // Okay, the types match exactly. Nothing to do.
2527     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2528                                        ToFunctionType->getReturnType(),
2529                                        ConvertedType, IncompatibleObjC)) {
2530       // Okay, we have an Objective-C pointer conversion.
2531       HasObjCConversion = true;
2532     } else {
2533       // Function types are too different. Abort.
2534       return false;
2535     }
2536 
2537     // Check argument types.
2538     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2539          ArgIdx != NumArgs; ++ArgIdx) {
2540       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2541       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2542       if (Context.getCanonicalType(FromArgType)
2543             == Context.getCanonicalType(ToArgType)) {
2544         // Okay, the types match exactly. Nothing to do.
2545       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2546                                          ConvertedType, IncompatibleObjC)) {
2547         // Okay, we have an Objective-C pointer conversion.
2548         HasObjCConversion = true;
2549       } else {
2550         // Argument types are too different. Abort.
2551         return false;
2552       }
2553     }
2554 
2555     if (HasObjCConversion) {
2556       // We had an Objective-C conversion. Allow this pointer
2557       // conversion, but complain about it.
2558       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2559       IncompatibleObjC = true;
2560       return true;
2561     }
2562   }
2563 
2564   return false;
2565 }
2566 
2567 /// Determine whether this is an Objective-C writeback conversion,
2568 /// used for parameter passing when performing automatic reference counting.
2569 ///
2570 /// \param FromType The type we're converting form.
2571 ///
2572 /// \param ToType The type we're converting to.
2573 ///
2574 /// \param ConvertedType The type that will be produced after applying
2575 /// this conversion.
2576 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2577                                      QualType &ConvertedType) {
2578   if (!getLangOpts().ObjCAutoRefCount ||
2579       Context.hasSameUnqualifiedType(FromType, ToType))
2580     return false;
2581 
2582   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2583   QualType ToPointee;
2584   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2585     ToPointee = ToPointer->getPointeeType();
2586   else
2587     return false;
2588 
2589   Qualifiers ToQuals = ToPointee.getQualifiers();
2590   if (!ToPointee->isObjCLifetimeType() ||
2591       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2592       !ToQuals.withoutObjCLifetime().empty())
2593     return false;
2594 
2595   // Argument must be a pointer to __strong to __weak.
2596   QualType FromPointee;
2597   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2598     FromPointee = FromPointer->getPointeeType();
2599   else
2600     return false;
2601 
2602   Qualifiers FromQuals = FromPointee.getQualifiers();
2603   if (!FromPointee->isObjCLifetimeType() ||
2604       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2605        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2606     return false;
2607 
2608   // Make sure that we have compatible qualifiers.
2609   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2610   if (!ToQuals.compatiblyIncludes(FromQuals))
2611     return false;
2612 
2613   // Remove qualifiers from the pointee type we're converting from; they
2614   // aren't used in the compatibility check belong, and we'll be adding back
2615   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2616   FromPointee = FromPointee.getUnqualifiedType();
2617 
2618   // The unqualified form of the pointee types must be compatible.
2619   ToPointee = ToPointee.getUnqualifiedType();
2620   bool IncompatibleObjC;
2621   if (Context.typesAreCompatible(FromPointee, ToPointee))
2622     FromPointee = ToPointee;
2623   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2624                                     IncompatibleObjC))
2625     return false;
2626 
2627   /// Construct the type we're converting to, which is a pointer to
2628   /// __autoreleasing pointee.
2629   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2630   ConvertedType = Context.getPointerType(FromPointee);
2631   return true;
2632 }
2633 
2634 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2635                                     QualType& ConvertedType) {
2636   QualType ToPointeeType;
2637   if (const BlockPointerType *ToBlockPtr =
2638         ToType->getAs<BlockPointerType>())
2639     ToPointeeType = ToBlockPtr->getPointeeType();
2640   else
2641     return false;
2642 
2643   QualType FromPointeeType;
2644   if (const BlockPointerType *FromBlockPtr =
2645       FromType->getAs<BlockPointerType>())
2646     FromPointeeType = FromBlockPtr->getPointeeType();
2647   else
2648     return false;
2649   // We have pointer to blocks, check whether the only
2650   // differences in the argument and result types are in Objective-C
2651   // pointer conversions. If so, we permit the conversion.
2652 
2653   const FunctionProtoType *FromFunctionType
2654     = FromPointeeType->getAs<FunctionProtoType>();
2655   const FunctionProtoType *ToFunctionType
2656     = ToPointeeType->getAs<FunctionProtoType>();
2657 
2658   if (!FromFunctionType || !ToFunctionType)
2659     return false;
2660 
2661   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2662     return true;
2663 
2664   // Perform the quick checks that will tell us whether these
2665   // function types are obviously different.
2666   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2667       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2668     return false;
2669 
2670   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2671   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2672   if (FromEInfo != ToEInfo)
2673     return false;
2674 
2675   bool IncompatibleObjC = false;
2676   if (Context.hasSameType(FromFunctionType->getReturnType(),
2677                           ToFunctionType->getReturnType())) {
2678     // Okay, the types match exactly. Nothing to do.
2679   } else {
2680     QualType RHS = FromFunctionType->getReturnType();
2681     QualType LHS = ToFunctionType->getReturnType();
2682     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2683         !RHS.hasQualifiers() && LHS.hasQualifiers())
2684        LHS = LHS.getUnqualifiedType();
2685 
2686      if (Context.hasSameType(RHS,LHS)) {
2687        // OK exact match.
2688      } else if (isObjCPointerConversion(RHS, LHS,
2689                                         ConvertedType, IncompatibleObjC)) {
2690      if (IncompatibleObjC)
2691        return false;
2692      // Okay, we have an Objective-C pointer conversion.
2693      }
2694      else
2695        return false;
2696    }
2697 
2698    // Check argument types.
2699    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2700         ArgIdx != NumArgs; ++ArgIdx) {
2701      IncompatibleObjC = false;
2702      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2703      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2704      if (Context.hasSameType(FromArgType, ToArgType)) {
2705        // Okay, the types match exactly. Nothing to do.
2706      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2707                                         ConvertedType, IncompatibleObjC)) {
2708        if (IncompatibleObjC)
2709          return false;
2710        // Okay, we have an Objective-C pointer conversion.
2711      } else
2712        // Argument types are too different. Abort.
2713        return false;
2714    }
2715 
2716    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2717    bool CanUseToFPT, CanUseFromFPT;
2718    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2719                                       CanUseToFPT, CanUseFromFPT,
2720                                       NewParamInfos))
2721      return false;
2722 
2723    ConvertedType = ToType;
2724    return true;
2725 }
2726 
2727 enum {
2728   ft_default,
2729   ft_different_class,
2730   ft_parameter_arity,
2731   ft_parameter_mismatch,
2732   ft_return_type,
2733   ft_qualifer_mismatch,
2734   ft_noexcept
2735 };
2736 
2737 /// Attempts to get the FunctionProtoType from a Type. Handles
2738 /// MemberFunctionPointers properly.
2739 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2740   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2741     return FPT;
2742 
2743   if (auto *MPT = FromType->getAs<MemberPointerType>())
2744     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2745 
2746   return nullptr;
2747 }
2748 
2749 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2750 /// function types.  Catches different number of parameter, mismatch in
2751 /// parameter types, and different return types.
2752 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2753                                       QualType FromType, QualType ToType) {
2754   // If either type is not valid, include no extra info.
2755   if (FromType.isNull() || ToType.isNull()) {
2756     PDiag << ft_default;
2757     return;
2758   }
2759 
2760   // Get the function type from the pointers.
2761   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2762     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2763                             *ToMember = ToType->getAs<MemberPointerType>();
2764     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2765       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2766             << QualType(FromMember->getClass(), 0);
2767       return;
2768     }
2769     FromType = FromMember->getPointeeType();
2770     ToType = ToMember->getPointeeType();
2771   }
2772 
2773   if (FromType->isPointerType())
2774     FromType = FromType->getPointeeType();
2775   if (ToType->isPointerType())
2776     ToType = ToType->getPointeeType();
2777 
2778   // Remove references.
2779   FromType = FromType.getNonReferenceType();
2780   ToType = ToType.getNonReferenceType();
2781 
2782   // Don't print extra info for non-specialized template functions.
2783   if (FromType->isInstantiationDependentType() &&
2784       !FromType->getAs<TemplateSpecializationType>()) {
2785     PDiag << ft_default;
2786     return;
2787   }
2788 
2789   // No extra info for same types.
2790   if (Context.hasSameType(FromType, ToType)) {
2791     PDiag << ft_default;
2792     return;
2793   }
2794 
2795   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2796                           *ToFunction = tryGetFunctionProtoType(ToType);
2797 
2798   // Both types need to be function types.
2799   if (!FromFunction || !ToFunction) {
2800     PDiag << ft_default;
2801     return;
2802   }
2803 
2804   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2805     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2806           << FromFunction->getNumParams();
2807     return;
2808   }
2809 
2810   // Handle different parameter types.
2811   unsigned ArgPos;
2812   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2813     PDiag << ft_parameter_mismatch << ArgPos + 1
2814           << ToFunction->getParamType(ArgPos)
2815           << FromFunction->getParamType(ArgPos);
2816     return;
2817   }
2818 
2819   // Handle different return type.
2820   if (!Context.hasSameType(FromFunction->getReturnType(),
2821                            ToFunction->getReturnType())) {
2822     PDiag << ft_return_type << ToFunction->getReturnType()
2823           << FromFunction->getReturnType();
2824     return;
2825   }
2826 
2827   // FIXME: OpenCL: Need to consider address spaces
2828   unsigned FromQuals = FromFunction->getTypeQuals().getCVRUQualifiers();
2829   unsigned ToQuals = ToFunction->getTypeQuals().getCVRUQualifiers();
2830   if (FromQuals != ToQuals) {
2831     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2832     return;
2833   }
2834 
2835   // Handle exception specification differences on canonical type (in C++17
2836   // onwards).
2837   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2838           ->isNothrow() !=
2839       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2840           ->isNothrow()) {
2841     PDiag << ft_noexcept;
2842     return;
2843   }
2844 
2845   // Unable to find a difference, so add no extra info.
2846   PDiag << ft_default;
2847 }
2848 
2849 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2850 /// for equality of their argument types. Caller has already checked that
2851 /// they have same number of arguments.  If the parameters are different,
2852 /// ArgPos will have the parameter index of the first different parameter.
2853 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2854                                       const FunctionProtoType *NewType,
2855                                       unsigned *ArgPos) {
2856   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2857                                               N = NewType->param_type_begin(),
2858                                               E = OldType->param_type_end();
2859        O && (O != E); ++O, ++N) {
2860     if (!Context.hasSameType(O->getUnqualifiedType(),
2861                              N->getUnqualifiedType())) {
2862       if (ArgPos)
2863         *ArgPos = O - OldType->param_type_begin();
2864       return false;
2865     }
2866   }
2867   return true;
2868 }
2869 
2870 /// CheckPointerConversion - Check the pointer conversion from the
2871 /// expression From to the type ToType. This routine checks for
2872 /// ambiguous or inaccessible derived-to-base pointer
2873 /// conversions for which IsPointerConversion has already returned
2874 /// true. It returns true and produces a diagnostic if there was an
2875 /// error, or returns false otherwise.
2876 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2877                                   CastKind &Kind,
2878                                   CXXCastPath& BasePath,
2879                                   bool IgnoreBaseAccess,
2880                                   bool Diagnose) {
2881   QualType FromType = From->getType();
2882   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2883 
2884   Kind = CK_BitCast;
2885 
2886   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2887       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2888           Expr::NPCK_ZeroExpression) {
2889     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2890       DiagRuntimeBehavior(From->getExprLoc(), From,
2891                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2892                             << ToType << From->getSourceRange());
2893     else if (!isUnevaluatedContext())
2894       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2895         << ToType << From->getSourceRange();
2896   }
2897   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2898     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2899       QualType FromPointeeType = FromPtrType->getPointeeType(),
2900                ToPointeeType   = ToPtrType->getPointeeType();
2901 
2902       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2903           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2904         // We must have a derived-to-base conversion. Check an
2905         // ambiguous or inaccessible conversion.
2906         unsigned InaccessibleID = 0;
2907         unsigned AmbigiousID = 0;
2908         if (Diagnose) {
2909           InaccessibleID = diag::err_upcast_to_inaccessible_base;
2910           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2911         }
2912         if (CheckDerivedToBaseConversion(
2913                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2914                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2915                 &BasePath, IgnoreBaseAccess))
2916           return true;
2917 
2918         // The conversion was successful.
2919         Kind = CK_DerivedToBase;
2920       }
2921 
2922       if (Diagnose && !IsCStyleOrFunctionalCast &&
2923           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2924         assert(getLangOpts().MSVCCompat &&
2925                "this should only be possible with MSVCCompat!");
2926         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2927             << From->getSourceRange();
2928       }
2929     }
2930   } else if (const ObjCObjectPointerType *ToPtrType =
2931                ToType->getAs<ObjCObjectPointerType>()) {
2932     if (const ObjCObjectPointerType *FromPtrType =
2933           FromType->getAs<ObjCObjectPointerType>()) {
2934       // Objective-C++ conversions are always okay.
2935       // FIXME: We should have a different class of conversions for the
2936       // Objective-C++ implicit conversions.
2937       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2938         return false;
2939     } else if (FromType->isBlockPointerType()) {
2940       Kind = CK_BlockPointerToObjCPointerCast;
2941     } else {
2942       Kind = CK_CPointerToObjCPointerCast;
2943     }
2944   } else if (ToType->isBlockPointerType()) {
2945     if (!FromType->isBlockPointerType())
2946       Kind = CK_AnyPointerToBlockPointerCast;
2947   }
2948 
2949   // We shouldn't fall into this case unless it's valid for other
2950   // reasons.
2951   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2952     Kind = CK_NullToPointer;
2953 
2954   return false;
2955 }
2956 
2957 /// IsMemberPointerConversion - Determines whether the conversion of the
2958 /// expression From, which has the (possibly adjusted) type FromType, can be
2959 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2960 /// If so, returns true and places the converted type (that might differ from
2961 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2962 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2963                                      QualType ToType,
2964                                      bool InOverloadResolution,
2965                                      QualType &ConvertedType) {
2966   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2967   if (!ToTypePtr)
2968     return false;
2969 
2970   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2971   if (From->isNullPointerConstant(Context,
2972                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2973                                         : Expr::NPC_ValueDependentIsNull)) {
2974     ConvertedType = ToType;
2975     return true;
2976   }
2977 
2978   // Otherwise, both types have to be member pointers.
2979   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2980   if (!FromTypePtr)
2981     return false;
2982 
2983   // A pointer to member of B can be converted to a pointer to member of D,
2984   // where D is derived from B (C++ 4.11p2).
2985   QualType FromClass(FromTypePtr->getClass(), 0);
2986   QualType ToClass(ToTypePtr->getClass(), 0);
2987 
2988   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2989       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
2990     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2991                                                  ToClass.getTypePtr());
2992     return true;
2993   }
2994 
2995   return false;
2996 }
2997 
2998 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2999 /// expression From to the type ToType. This routine checks for ambiguous or
3000 /// virtual or inaccessible base-to-derived member pointer conversions
3001 /// for which IsMemberPointerConversion has already returned true. It returns
3002 /// true and produces a diagnostic if there was an error, or returns false
3003 /// otherwise.
3004 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3005                                         CastKind &Kind,
3006                                         CXXCastPath &BasePath,
3007                                         bool IgnoreBaseAccess) {
3008   QualType FromType = From->getType();
3009   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3010   if (!FromPtrType) {
3011     // This must be a null pointer to member pointer conversion
3012     assert(From->isNullPointerConstant(Context,
3013                                        Expr::NPC_ValueDependentIsNull) &&
3014            "Expr must be null pointer constant!");
3015     Kind = CK_NullToMemberPointer;
3016     return false;
3017   }
3018 
3019   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3020   assert(ToPtrType && "No member pointer cast has a target type "
3021                       "that is not a member pointer.");
3022 
3023   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3024   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3025 
3026   // FIXME: What about dependent types?
3027   assert(FromClass->isRecordType() && "Pointer into non-class.");
3028   assert(ToClass->isRecordType() && "Pointer into non-class.");
3029 
3030   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3031                      /*DetectVirtual=*/true);
3032   bool DerivationOkay =
3033       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3034   assert(DerivationOkay &&
3035          "Should not have been called if derivation isn't OK.");
3036   (void)DerivationOkay;
3037 
3038   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3039                                   getUnqualifiedType())) {
3040     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3041     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3042       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3043     return true;
3044   }
3045 
3046   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3047     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3048       << FromClass << ToClass << QualType(VBase, 0)
3049       << From->getSourceRange();
3050     return true;
3051   }
3052 
3053   if (!IgnoreBaseAccess)
3054     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3055                          Paths.front(),
3056                          diag::err_downcast_from_inaccessible_base);
3057 
3058   // Must be a base to derived member conversion.
3059   BuildBasePathArray(Paths, BasePath);
3060   Kind = CK_BaseToDerivedMemberPointer;
3061   return false;
3062 }
3063 
3064 /// Determine whether the lifetime conversion between the two given
3065 /// qualifiers sets is nontrivial.
3066 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3067                                                Qualifiers ToQuals) {
3068   // Converting anything to const __unsafe_unretained is trivial.
3069   if (ToQuals.hasConst() &&
3070       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3071     return false;
3072 
3073   return true;
3074 }
3075 
3076 /// IsQualificationConversion - Determines whether the conversion from
3077 /// an rvalue of type FromType to ToType is a qualification conversion
3078 /// (C++ 4.4).
3079 ///
3080 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3081 /// when the qualification conversion involves a change in the Objective-C
3082 /// object lifetime.
3083 bool
3084 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3085                                 bool CStyle, bool &ObjCLifetimeConversion) {
3086   FromType = Context.getCanonicalType(FromType);
3087   ToType = Context.getCanonicalType(ToType);
3088   ObjCLifetimeConversion = false;
3089 
3090   // If FromType and ToType are the same type, this is not a
3091   // qualification conversion.
3092   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3093     return false;
3094 
3095   // (C++ 4.4p4):
3096   //   A conversion can add cv-qualifiers at levels other than the first
3097   //   in multi-level pointers, subject to the following rules: [...]
3098   bool PreviousToQualsIncludeConst = true;
3099   bool UnwrappedAnyPointer = false;
3100   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3101     // Within each iteration of the loop, we check the qualifiers to
3102     // determine if this still looks like a qualification
3103     // conversion. Then, if all is well, we unwrap one more level of
3104     // pointers or pointers-to-members and do it all again
3105     // until there are no more pointers or pointers-to-members left to
3106     // unwrap.
3107     UnwrappedAnyPointer = true;
3108 
3109     Qualifiers FromQuals = FromType.getQualifiers();
3110     Qualifiers ToQuals = ToType.getQualifiers();
3111 
3112     // Ignore __unaligned qualifier if this type is void.
3113     if (ToType.getUnqualifiedType()->isVoidType())
3114       FromQuals.removeUnaligned();
3115 
3116     // Objective-C ARC:
3117     //   Check Objective-C lifetime conversions.
3118     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3119         UnwrappedAnyPointer) {
3120       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3121         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3122           ObjCLifetimeConversion = true;
3123         FromQuals.removeObjCLifetime();
3124         ToQuals.removeObjCLifetime();
3125       } else {
3126         // Qualification conversions cannot cast between different
3127         // Objective-C lifetime qualifiers.
3128         return false;
3129       }
3130     }
3131 
3132     // Allow addition/removal of GC attributes but not changing GC attributes.
3133     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3134         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3135       FromQuals.removeObjCGCAttr();
3136       ToQuals.removeObjCGCAttr();
3137     }
3138 
3139     //   -- for every j > 0, if const is in cv 1,j then const is in cv
3140     //      2,j, and similarly for volatile.
3141     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3142       return false;
3143 
3144     //   -- if the cv 1,j and cv 2,j are different, then const is in
3145     //      every cv for 0 < k < j.
3146     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3147         && !PreviousToQualsIncludeConst)
3148       return false;
3149 
3150     // Keep track of whether all prior cv-qualifiers in the "to" type
3151     // include const.
3152     PreviousToQualsIncludeConst
3153       = PreviousToQualsIncludeConst && ToQuals.hasConst();
3154   }
3155 
3156   // Allows address space promotion by language rules implemented in
3157   // Type::Qualifiers::isAddressSpaceSupersetOf.
3158   Qualifiers FromQuals = FromType.getQualifiers();
3159   Qualifiers ToQuals = ToType.getQualifiers();
3160   if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) &&
3161       !FromQuals.isAddressSpaceSupersetOf(ToQuals)) {
3162     return false;
3163   }
3164 
3165   // We are left with FromType and ToType being the pointee types
3166   // after unwrapping the original FromType and ToType the same number
3167   // of types. If we unwrapped any pointers, and if FromType and
3168   // ToType have the same unqualified type (since we checked
3169   // qualifiers above), then this is a qualification conversion.
3170   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3171 }
3172 
3173 /// - Determine whether this is a conversion from a scalar type to an
3174 /// atomic type.
3175 ///
3176 /// If successful, updates \c SCS's second and third steps in the conversion
3177 /// sequence to finish the conversion.
3178 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3179                                 bool InOverloadResolution,
3180                                 StandardConversionSequence &SCS,
3181                                 bool CStyle) {
3182   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3183   if (!ToAtomic)
3184     return false;
3185 
3186   StandardConversionSequence InnerSCS;
3187   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3188                             InOverloadResolution, InnerSCS,
3189                             CStyle, /*AllowObjCWritebackConversion=*/false))
3190     return false;
3191 
3192   SCS.Second = InnerSCS.Second;
3193   SCS.setToType(1, InnerSCS.getToType(1));
3194   SCS.Third = InnerSCS.Third;
3195   SCS.QualificationIncludesObjCLifetime
3196     = InnerSCS.QualificationIncludesObjCLifetime;
3197   SCS.setToType(2, InnerSCS.getToType(2));
3198   return true;
3199 }
3200 
3201 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3202                                               CXXConstructorDecl *Constructor,
3203                                               QualType Type) {
3204   const FunctionProtoType *CtorType =
3205       Constructor->getType()->getAs<FunctionProtoType>();
3206   if (CtorType->getNumParams() > 0) {
3207     QualType FirstArg = CtorType->getParamType(0);
3208     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3209       return true;
3210   }
3211   return false;
3212 }
3213 
3214 static OverloadingResult
3215 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3216                                        CXXRecordDecl *To,
3217                                        UserDefinedConversionSequence &User,
3218                                        OverloadCandidateSet &CandidateSet,
3219                                        bool AllowExplicit) {
3220   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3221   for (auto *D : S.LookupConstructors(To)) {
3222     auto Info = getConstructorInfo(D);
3223     if (!Info)
3224       continue;
3225 
3226     bool Usable = !Info.Constructor->isInvalidDecl() &&
3227                   S.isInitListConstructor(Info.Constructor) &&
3228                   (AllowExplicit || !Info.Constructor->isExplicit());
3229     if (Usable) {
3230       // If the first argument is (a reference to) the target type,
3231       // suppress conversions.
3232       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3233           S.Context, Info.Constructor, ToType);
3234       if (Info.ConstructorTmpl)
3235         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3236                                        /*ExplicitArgs*/ nullptr, From,
3237                                        CandidateSet, SuppressUserConversions);
3238       else
3239         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3240                                CandidateSet, SuppressUserConversions);
3241     }
3242   }
3243 
3244   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3245 
3246   OverloadCandidateSet::iterator Best;
3247   switch (auto Result =
3248               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3249   case OR_Deleted:
3250   case OR_Success: {
3251     // Record the standard conversion we used and the conversion function.
3252     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3253     QualType ThisType = Constructor->getThisType(S.Context);
3254     // Initializer lists don't have conversions as such.
3255     User.Before.setAsIdentityConversion();
3256     User.HadMultipleCandidates = HadMultipleCandidates;
3257     User.ConversionFunction = Constructor;
3258     User.FoundConversionFunction = Best->FoundDecl;
3259     User.After.setAsIdentityConversion();
3260     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3261     User.After.setAllToTypes(ToType);
3262     return Result;
3263   }
3264 
3265   case OR_No_Viable_Function:
3266     return OR_No_Viable_Function;
3267   case OR_Ambiguous:
3268     return OR_Ambiguous;
3269   }
3270 
3271   llvm_unreachable("Invalid OverloadResult!");
3272 }
3273 
3274 /// Determines whether there is a user-defined conversion sequence
3275 /// (C++ [over.ics.user]) that converts expression From to the type
3276 /// ToType. If such a conversion exists, User will contain the
3277 /// user-defined conversion sequence that performs such a conversion
3278 /// and this routine will return true. Otherwise, this routine returns
3279 /// false and User is unspecified.
3280 ///
3281 /// \param AllowExplicit  true if the conversion should consider C++0x
3282 /// "explicit" conversion functions as well as non-explicit conversion
3283 /// functions (C++0x [class.conv.fct]p2).
3284 ///
3285 /// \param AllowObjCConversionOnExplicit true if the conversion should
3286 /// allow an extra Objective-C pointer conversion on uses of explicit
3287 /// constructors. Requires \c AllowExplicit to also be set.
3288 static OverloadingResult
3289 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3290                         UserDefinedConversionSequence &User,
3291                         OverloadCandidateSet &CandidateSet,
3292                         bool AllowExplicit,
3293                         bool AllowObjCConversionOnExplicit) {
3294   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3295   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3296 
3297   // Whether we will only visit constructors.
3298   bool ConstructorsOnly = false;
3299 
3300   // If the type we are conversion to is a class type, enumerate its
3301   // constructors.
3302   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3303     // C++ [over.match.ctor]p1:
3304     //   When objects of class type are direct-initialized (8.5), or
3305     //   copy-initialized from an expression of the same or a
3306     //   derived class type (8.5), overload resolution selects the
3307     //   constructor. [...] For copy-initialization, the candidate
3308     //   functions are all the converting constructors (12.3.1) of
3309     //   that class. The argument list is the expression-list within
3310     //   the parentheses of the initializer.
3311     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3312         (From->getType()->getAs<RecordType>() &&
3313          S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3314       ConstructorsOnly = true;
3315 
3316     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3317       // We're not going to find any constructors.
3318     } else if (CXXRecordDecl *ToRecordDecl
3319                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3320 
3321       Expr **Args = &From;
3322       unsigned NumArgs = 1;
3323       bool ListInitializing = false;
3324       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3325         // But first, see if there is an init-list-constructor that will work.
3326         OverloadingResult Result = IsInitializerListConstructorConversion(
3327             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3328         if (Result != OR_No_Viable_Function)
3329           return Result;
3330         // Never mind.
3331         CandidateSet.clear(
3332             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3333 
3334         // If we're list-initializing, we pass the individual elements as
3335         // arguments, not the entire list.
3336         Args = InitList->getInits();
3337         NumArgs = InitList->getNumInits();
3338         ListInitializing = true;
3339       }
3340 
3341       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3342         auto Info = getConstructorInfo(D);
3343         if (!Info)
3344           continue;
3345 
3346         bool Usable = !Info.Constructor->isInvalidDecl();
3347         if (ListInitializing)
3348           Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3349         else
3350           Usable = Usable &&
3351                    Info.Constructor->isConvertingConstructor(AllowExplicit);
3352         if (Usable) {
3353           bool SuppressUserConversions = !ConstructorsOnly;
3354           if (SuppressUserConversions && ListInitializing) {
3355             SuppressUserConversions = false;
3356             if (NumArgs == 1) {
3357               // If the first argument is (a reference to) the target type,
3358               // suppress conversions.
3359               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3360                   S.Context, Info.Constructor, ToType);
3361             }
3362           }
3363           if (Info.ConstructorTmpl)
3364             S.AddTemplateOverloadCandidate(
3365                 Info.ConstructorTmpl, Info.FoundDecl,
3366                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3367                 CandidateSet, SuppressUserConversions);
3368           else
3369             // Allow one user-defined conversion when user specifies a
3370             // From->ToType conversion via an static cast (c-style, etc).
3371             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3372                                    llvm::makeArrayRef(Args, NumArgs),
3373                                    CandidateSet, SuppressUserConversions);
3374         }
3375       }
3376     }
3377   }
3378 
3379   // Enumerate conversion functions, if we're allowed to.
3380   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3381   } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3382     // No conversion functions from incomplete types.
3383   } else if (const RecordType *FromRecordType =
3384                  From->getType()->getAs<RecordType>()) {
3385     if (CXXRecordDecl *FromRecordDecl
3386          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3387       // Add all of the conversion functions as candidates.
3388       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3389       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3390         DeclAccessPair FoundDecl = I.getPair();
3391         NamedDecl *D = FoundDecl.getDecl();
3392         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3393         if (isa<UsingShadowDecl>(D))
3394           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3395 
3396         CXXConversionDecl *Conv;
3397         FunctionTemplateDecl *ConvTemplate;
3398         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3399           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3400         else
3401           Conv = cast<CXXConversionDecl>(D);
3402 
3403         if (AllowExplicit || !Conv->isExplicit()) {
3404           if (ConvTemplate)
3405             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3406                                              ActingContext, From, ToType,
3407                                              CandidateSet,
3408                                              AllowObjCConversionOnExplicit);
3409           else
3410             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3411                                      From, ToType, CandidateSet,
3412                                      AllowObjCConversionOnExplicit);
3413         }
3414       }
3415     }
3416   }
3417 
3418   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3419 
3420   OverloadCandidateSet::iterator Best;
3421   switch (auto Result =
3422               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3423   case OR_Success:
3424   case OR_Deleted:
3425     // Record the standard conversion we used and the conversion function.
3426     if (CXXConstructorDecl *Constructor
3427           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3428       // C++ [over.ics.user]p1:
3429       //   If the user-defined conversion is specified by a
3430       //   constructor (12.3.1), the initial standard conversion
3431       //   sequence converts the source type to the type required by
3432       //   the argument of the constructor.
3433       //
3434       QualType ThisType = Constructor->getThisType(S.Context);
3435       if (isa<InitListExpr>(From)) {
3436         // Initializer lists don't have conversions as such.
3437         User.Before.setAsIdentityConversion();
3438       } else {
3439         if (Best->Conversions[0].isEllipsis())
3440           User.EllipsisConversion = true;
3441         else {
3442           User.Before = Best->Conversions[0].Standard;
3443           User.EllipsisConversion = false;
3444         }
3445       }
3446       User.HadMultipleCandidates = HadMultipleCandidates;
3447       User.ConversionFunction = Constructor;
3448       User.FoundConversionFunction = Best->FoundDecl;
3449       User.After.setAsIdentityConversion();
3450       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3451       User.After.setAllToTypes(ToType);
3452       return Result;
3453     }
3454     if (CXXConversionDecl *Conversion
3455                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3456       // C++ [over.ics.user]p1:
3457       //
3458       //   [...] If the user-defined conversion is specified by a
3459       //   conversion function (12.3.2), the initial standard
3460       //   conversion sequence converts the source type to the
3461       //   implicit object parameter of the conversion function.
3462       User.Before = Best->Conversions[0].Standard;
3463       User.HadMultipleCandidates = HadMultipleCandidates;
3464       User.ConversionFunction = Conversion;
3465       User.FoundConversionFunction = Best->FoundDecl;
3466       User.EllipsisConversion = false;
3467 
3468       // C++ [over.ics.user]p2:
3469       //   The second standard conversion sequence converts the
3470       //   result of the user-defined conversion to the target type
3471       //   for the sequence. Since an implicit conversion sequence
3472       //   is an initialization, the special rules for
3473       //   initialization by user-defined conversion apply when
3474       //   selecting the best user-defined conversion for a
3475       //   user-defined conversion sequence (see 13.3.3 and
3476       //   13.3.3.1).
3477       User.After = Best->FinalConversion;
3478       return Result;
3479     }
3480     llvm_unreachable("Not a constructor or conversion function?");
3481 
3482   case OR_No_Viable_Function:
3483     return OR_No_Viable_Function;
3484 
3485   case OR_Ambiguous:
3486     return OR_Ambiguous;
3487   }
3488 
3489   llvm_unreachable("Invalid OverloadResult!");
3490 }
3491 
3492 bool
3493 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3494   ImplicitConversionSequence ICS;
3495   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3496                                     OverloadCandidateSet::CSK_Normal);
3497   OverloadingResult OvResult =
3498     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3499                             CandidateSet, false, false);
3500   if (OvResult == OR_Ambiguous)
3501     Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3502         << From->getType() << ToType << From->getSourceRange();
3503   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3504     if (!RequireCompleteType(From->getBeginLoc(), ToType,
3505                              diag::err_typecheck_nonviable_condition_incomplete,
3506                              From->getType(), From->getSourceRange()))
3507       Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3508           << false << From->getType() << From->getSourceRange() << ToType;
3509   } else
3510     return false;
3511   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3512   return true;
3513 }
3514 
3515 /// Compare the user-defined conversion functions or constructors
3516 /// of two user-defined conversion sequences to determine whether any ordering
3517 /// is possible.
3518 static ImplicitConversionSequence::CompareKind
3519 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3520                            FunctionDecl *Function2) {
3521   if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11)
3522     return ImplicitConversionSequence::Indistinguishable;
3523 
3524   // Objective-C++:
3525   //   If both conversion functions are implicitly-declared conversions from
3526   //   a lambda closure type to a function pointer and a block pointer,
3527   //   respectively, always prefer the conversion to a function pointer,
3528   //   because the function pointer is more lightweight and is more likely
3529   //   to keep code working.
3530   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3531   if (!Conv1)
3532     return ImplicitConversionSequence::Indistinguishable;
3533 
3534   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3535   if (!Conv2)
3536     return ImplicitConversionSequence::Indistinguishable;
3537 
3538   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3539     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3540     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3541     if (Block1 != Block2)
3542       return Block1 ? ImplicitConversionSequence::Worse
3543                     : ImplicitConversionSequence::Better;
3544   }
3545 
3546   return ImplicitConversionSequence::Indistinguishable;
3547 }
3548 
3549 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3550     const ImplicitConversionSequence &ICS) {
3551   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3552          (ICS.isUserDefined() &&
3553           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3554 }
3555 
3556 /// CompareImplicitConversionSequences - Compare two implicit
3557 /// conversion sequences to determine whether one is better than the
3558 /// other or if they are indistinguishable (C++ 13.3.3.2).
3559 static ImplicitConversionSequence::CompareKind
3560 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3561                                    const ImplicitConversionSequence& ICS1,
3562                                    const ImplicitConversionSequence& ICS2)
3563 {
3564   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3565   // conversion sequences (as defined in 13.3.3.1)
3566   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3567   //      conversion sequence than a user-defined conversion sequence or
3568   //      an ellipsis conversion sequence, and
3569   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3570   //      conversion sequence than an ellipsis conversion sequence
3571   //      (13.3.3.1.3).
3572   //
3573   // C++0x [over.best.ics]p10:
3574   //   For the purpose of ranking implicit conversion sequences as
3575   //   described in 13.3.3.2, the ambiguous conversion sequence is
3576   //   treated as a user-defined sequence that is indistinguishable
3577   //   from any other user-defined conversion sequence.
3578 
3579   // String literal to 'char *' conversion has been deprecated in C++03. It has
3580   // been removed from C++11. We still accept this conversion, if it happens at
3581   // the best viable function. Otherwise, this conversion is considered worse
3582   // than ellipsis conversion. Consider this as an extension; this is not in the
3583   // standard. For example:
3584   //
3585   // int &f(...);    // #1
3586   // void f(char*);  // #2
3587   // void g() { int &r = f("foo"); }
3588   //
3589   // In C++03, we pick #2 as the best viable function.
3590   // In C++11, we pick #1 as the best viable function, because ellipsis
3591   // conversion is better than string-literal to char* conversion (since there
3592   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3593   // convert arguments, #2 would be the best viable function in C++11.
3594   // If the best viable function has this conversion, a warning will be issued
3595   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3596 
3597   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3598       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3599       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3600     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3601                ? ImplicitConversionSequence::Worse
3602                : ImplicitConversionSequence::Better;
3603 
3604   if (ICS1.getKindRank() < ICS2.getKindRank())
3605     return ImplicitConversionSequence::Better;
3606   if (ICS2.getKindRank() < ICS1.getKindRank())
3607     return ImplicitConversionSequence::Worse;
3608 
3609   // The following checks require both conversion sequences to be of
3610   // the same kind.
3611   if (ICS1.getKind() != ICS2.getKind())
3612     return ImplicitConversionSequence::Indistinguishable;
3613 
3614   ImplicitConversionSequence::CompareKind Result =
3615       ImplicitConversionSequence::Indistinguishable;
3616 
3617   // Two implicit conversion sequences of the same form are
3618   // indistinguishable conversion sequences unless one of the
3619   // following rules apply: (C++ 13.3.3.2p3):
3620 
3621   // List-initialization sequence L1 is a better conversion sequence than
3622   // list-initialization sequence L2 if:
3623   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3624   //   if not that,
3625   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3626   //   and N1 is smaller than N2.,
3627   // even if one of the other rules in this paragraph would otherwise apply.
3628   if (!ICS1.isBad()) {
3629     if (ICS1.isStdInitializerListElement() &&
3630         !ICS2.isStdInitializerListElement())
3631       return ImplicitConversionSequence::Better;
3632     if (!ICS1.isStdInitializerListElement() &&
3633         ICS2.isStdInitializerListElement())
3634       return ImplicitConversionSequence::Worse;
3635   }
3636 
3637   if (ICS1.isStandard())
3638     // Standard conversion sequence S1 is a better conversion sequence than
3639     // standard conversion sequence S2 if [...]
3640     Result = CompareStandardConversionSequences(S, Loc,
3641                                                 ICS1.Standard, ICS2.Standard);
3642   else if (ICS1.isUserDefined()) {
3643     // User-defined conversion sequence U1 is a better conversion
3644     // sequence than another user-defined conversion sequence U2 if
3645     // they contain the same user-defined conversion function or
3646     // constructor and if the second standard conversion sequence of
3647     // U1 is better than the second standard conversion sequence of
3648     // U2 (C++ 13.3.3.2p3).
3649     if (ICS1.UserDefined.ConversionFunction ==
3650           ICS2.UserDefined.ConversionFunction)
3651       Result = CompareStandardConversionSequences(S, Loc,
3652                                                   ICS1.UserDefined.After,
3653                                                   ICS2.UserDefined.After);
3654     else
3655       Result = compareConversionFunctions(S,
3656                                           ICS1.UserDefined.ConversionFunction,
3657                                           ICS2.UserDefined.ConversionFunction);
3658   }
3659 
3660   return Result;
3661 }
3662 
3663 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3664 // determine if one is a proper subset of the other.
3665 static ImplicitConversionSequence::CompareKind
3666 compareStandardConversionSubsets(ASTContext &Context,
3667                                  const StandardConversionSequence& SCS1,
3668                                  const StandardConversionSequence& SCS2) {
3669   ImplicitConversionSequence::CompareKind Result
3670     = ImplicitConversionSequence::Indistinguishable;
3671 
3672   // the identity conversion sequence is considered to be a subsequence of
3673   // any non-identity conversion sequence
3674   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3675     return ImplicitConversionSequence::Better;
3676   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3677     return ImplicitConversionSequence::Worse;
3678 
3679   if (SCS1.Second != SCS2.Second) {
3680     if (SCS1.Second == ICK_Identity)
3681       Result = ImplicitConversionSequence::Better;
3682     else if (SCS2.Second == ICK_Identity)
3683       Result = ImplicitConversionSequence::Worse;
3684     else
3685       return ImplicitConversionSequence::Indistinguishable;
3686   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3687     return ImplicitConversionSequence::Indistinguishable;
3688 
3689   if (SCS1.Third == SCS2.Third) {
3690     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3691                              : ImplicitConversionSequence::Indistinguishable;
3692   }
3693 
3694   if (SCS1.Third == ICK_Identity)
3695     return Result == ImplicitConversionSequence::Worse
3696              ? ImplicitConversionSequence::Indistinguishable
3697              : ImplicitConversionSequence::Better;
3698 
3699   if (SCS2.Third == ICK_Identity)
3700     return Result == ImplicitConversionSequence::Better
3701              ? ImplicitConversionSequence::Indistinguishable
3702              : ImplicitConversionSequence::Worse;
3703 
3704   return ImplicitConversionSequence::Indistinguishable;
3705 }
3706 
3707 /// Determine whether one of the given reference bindings is better
3708 /// than the other based on what kind of bindings they are.
3709 static bool
3710 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3711                              const StandardConversionSequence &SCS2) {
3712   // C++0x [over.ics.rank]p3b4:
3713   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3714   //      implicit object parameter of a non-static member function declared
3715   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3716   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3717   //      lvalue reference to a function lvalue and S2 binds an rvalue
3718   //      reference*.
3719   //
3720   // FIXME: Rvalue references. We're going rogue with the above edits,
3721   // because the semantics in the current C++0x working paper (N3225 at the
3722   // time of this writing) break the standard definition of std::forward
3723   // and std::reference_wrapper when dealing with references to functions.
3724   // Proposed wording changes submitted to CWG for consideration.
3725   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3726       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3727     return false;
3728 
3729   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3730           SCS2.IsLvalueReference) ||
3731          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3732           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3733 }
3734 
3735 /// CompareStandardConversionSequences - Compare two standard
3736 /// conversion sequences to determine whether one is better than the
3737 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3738 static ImplicitConversionSequence::CompareKind
3739 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3740                                    const StandardConversionSequence& SCS1,
3741                                    const StandardConversionSequence& SCS2)
3742 {
3743   // Standard conversion sequence S1 is a better conversion sequence
3744   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3745 
3746   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3747   //     sequences in the canonical form defined by 13.3.3.1.1,
3748   //     excluding any Lvalue Transformation; the identity conversion
3749   //     sequence is considered to be a subsequence of any
3750   //     non-identity conversion sequence) or, if not that,
3751   if (ImplicitConversionSequence::CompareKind CK
3752         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3753     return CK;
3754 
3755   //  -- the rank of S1 is better than the rank of S2 (by the rules
3756   //     defined below), or, if not that,
3757   ImplicitConversionRank Rank1 = SCS1.getRank();
3758   ImplicitConversionRank Rank2 = SCS2.getRank();
3759   if (Rank1 < Rank2)
3760     return ImplicitConversionSequence::Better;
3761   else if (Rank2 < Rank1)
3762     return ImplicitConversionSequence::Worse;
3763 
3764   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3765   // are indistinguishable unless one of the following rules
3766   // applies:
3767 
3768   //   A conversion that is not a conversion of a pointer, or
3769   //   pointer to member, to bool is better than another conversion
3770   //   that is such a conversion.
3771   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3772     return SCS2.isPointerConversionToBool()
3773              ? ImplicitConversionSequence::Better
3774              : ImplicitConversionSequence::Worse;
3775 
3776   // C++ [over.ics.rank]p4b2:
3777   //
3778   //   If class B is derived directly or indirectly from class A,
3779   //   conversion of B* to A* is better than conversion of B* to
3780   //   void*, and conversion of A* to void* is better than conversion
3781   //   of B* to void*.
3782   bool SCS1ConvertsToVoid
3783     = SCS1.isPointerConversionToVoidPointer(S.Context);
3784   bool SCS2ConvertsToVoid
3785     = SCS2.isPointerConversionToVoidPointer(S.Context);
3786   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3787     // Exactly one of the conversion sequences is a conversion to
3788     // a void pointer; it's the worse conversion.
3789     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3790                               : ImplicitConversionSequence::Worse;
3791   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3792     // Neither conversion sequence converts to a void pointer; compare
3793     // their derived-to-base conversions.
3794     if (ImplicitConversionSequence::CompareKind DerivedCK
3795           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3796       return DerivedCK;
3797   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3798              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3799     // Both conversion sequences are conversions to void
3800     // pointers. Compare the source types to determine if there's an
3801     // inheritance relationship in their sources.
3802     QualType FromType1 = SCS1.getFromType();
3803     QualType FromType2 = SCS2.getFromType();
3804 
3805     // Adjust the types we're converting from via the array-to-pointer
3806     // conversion, if we need to.
3807     if (SCS1.First == ICK_Array_To_Pointer)
3808       FromType1 = S.Context.getArrayDecayedType(FromType1);
3809     if (SCS2.First == ICK_Array_To_Pointer)
3810       FromType2 = S.Context.getArrayDecayedType(FromType2);
3811 
3812     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3813     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3814 
3815     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3816       return ImplicitConversionSequence::Better;
3817     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3818       return ImplicitConversionSequence::Worse;
3819 
3820     // Objective-C++: If one interface is more specific than the
3821     // other, it is the better one.
3822     const ObjCObjectPointerType* FromObjCPtr1
3823       = FromType1->getAs<ObjCObjectPointerType>();
3824     const ObjCObjectPointerType* FromObjCPtr2
3825       = FromType2->getAs<ObjCObjectPointerType>();
3826     if (FromObjCPtr1 && FromObjCPtr2) {
3827       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3828                                                           FromObjCPtr2);
3829       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3830                                                            FromObjCPtr1);
3831       if (AssignLeft != AssignRight) {
3832         return AssignLeft? ImplicitConversionSequence::Better
3833                          : ImplicitConversionSequence::Worse;
3834       }
3835     }
3836   }
3837 
3838   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3839   // bullet 3).
3840   if (ImplicitConversionSequence::CompareKind QualCK
3841         = CompareQualificationConversions(S, SCS1, SCS2))
3842     return QualCK;
3843 
3844   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3845     // Check for a better reference binding based on the kind of bindings.
3846     if (isBetterReferenceBindingKind(SCS1, SCS2))
3847       return ImplicitConversionSequence::Better;
3848     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3849       return ImplicitConversionSequence::Worse;
3850 
3851     // C++ [over.ics.rank]p3b4:
3852     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3853     //      which the references refer are the same type except for
3854     //      top-level cv-qualifiers, and the type to which the reference
3855     //      initialized by S2 refers is more cv-qualified than the type
3856     //      to which the reference initialized by S1 refers.
3857     QualType T1 = SCS1.getToType(2);
3858     QualType T2 = SCS2.getToType(2);
3859     T1 = S.Context.getCanonicalType(T1);
3860     T2 = S.Context.getCanonicalType(T2);
3861     Qualifiers T1Quals, T2Quals;
3862     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3863     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3864     if (UnqualT1 == UnqualT2) {
3865       // Objective-C++ ARC: If the references refer to objects with different
3866       // lifetimes, prefer bindings that don't change lifetime.
3867       if (SCS1.ObjCLifetimeConversionBinding !=
3868                                           SCS2.ObjCLifetimeConversionBinding) {
3869         return SCS1.ObjCLifetimeConversionBinding
3870                                            ? ImplicitConversionSequence::Worse
3871                                            : ImplicitConversionSequence::Better;
3872       }
3873 
3874       // If the type is an array type, promote the element qualifiers to the
3875       // type for comparison.
3876       if (isa<ArrayType>(T1) && T1Quals)
3877         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3878       if (isa<ArrayType>(T2) && T2Quals)
3879         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3880       if (T2.isMoreQualifiedThan(T1))
3881         return ImplicitConversionSequence::Better;
3882       else if (T1.isMoreQualifiedThan(T2))
3883         return ImplicitConversionSequence::Worse;
3884     }
3885   }
3886 
3887   // In Microsoft mode, prefer an integral conversion to a
3888   // floating-to-integral conversion if the integral conversion
3889   // is between types of the same size.
3890   // For example:
3891   // void f(float);
3892   // void f(int);
3893   // int main {
3894   //    long a;
3895   //    f(a);
3896   // }
3897   // Here, MSVC will call f(int) instead of generating a compile error
3898   // as clang will do in standard mode.
3899   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3900       SCS2.Second == ICK_Floating_Integral &&
3901       S.Context.getTypeSize(SCS1.getFromType()) ==
3902           S.Context.getTypeSize(SCS1.getToType(2)))
3903     return ImplicitConversionSequence::Better;
3904 
3905   // Prefer a compatible vector conversion over a lax vector conversion
3906   // For example:
3907   //
3908   // typedef float __v4sf __attribute__((__vector_size__(16)));
3909   // void f(vector float);
3910   // void f(vector signed int);
3911   // int main() {
3912   //   __v4sf a;
3913   //   f(a);
3914   // }
3915   // Here, we'd like to choose f(vector float) and not
3916   // report an ambiguous call error
3917   if (SCS1.Second == ICK_Vector_Conversion &&
3918       SCS2.Second == ICK_Vector_Conversion) {
3919     bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
3920         SCS1.getFromType(), SCS1.getToType(2));
3921     bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
3922         SCS2.getFromType(), SCS2.getToType(2));
3923 
3924     if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
3925       return SCS1IsCompatibleVectorConversion
3926                  ? ImplicitConversionSequence::Better
3927                  : ImplicitConversionSequence::Worse;
3928   }
3929 
3930   return ImplicitConversionSequence::Indistinguishable;
3931 }
3932 
3933 /// CompareQualificationConversions - Compares two standard conversion
3934 /// sequences to determine whether they can be ranked based on their
3935 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3936 static ImplicitConversionSequence::CompareKind
3937 CompareQualificationConversions(Sema &S,
3938                                 const StandardConversionSequence& SCS1,
3939                                 const StandardConversionSequence& SCS2) {
3940   // C++ 13.3.3.2p3:
3941   //  -- S1 and S2 differ only in their qualification conversion and
3942   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3943   //     cv-qualification signature of type T1 is a proper subset of
3944   //     the cv-qualification signature of type T2, and S1 is not the
3945   //     deprecated string literal array-to-pointer conversion (4.2).
3946   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3947       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3948     return ImplicitConversionSequence::Indistinguishable;
3949 
3950   // FIXME: the example in the standard doesn't use a qualification
3951   // conversion (!)
3952   QualType T1 = SCS1.getToType(2);
3953   QualType T2 = SCS2.getToType(2);
3954   T1 = S.Context.getCanonicalType(T1);
3955   T2 = S.Context.getCanonicalType(T2);
3956   Qualifiers T1Quals, T2Quals;
3957   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3958   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3959 
3960   // If the types are the same, we won't learn anything by unwrapped
3961   // them.
3962   if (UnqualT1 == UnqualT2)
3963     return ImplicitConversionSequence::Indistinguishable;
3964 
3965   // If the type is an array type, promote the element qualifiers to the type
3966   // for comparison.
3967   if (isa<ArrayType>(T1) && T1Quals)
3968     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3969   if (isa<ArrayType>(T2) && T2Quals)
3970     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3971 
3972   ImplicitConversionSequence::CompareKind Result
3973     = ImplicitConversionSequence::Indistinguishable;
3974 
3975   // Objective-C++ ARC:
3976   //   Prefer qualification conversions not involving a change in lifetime
3977   //   to qualification conversions that do not change lifetime.
3978   if (SCS1.QualificationIncludesObjCLifetime !=
3979                                       SCS2.QualificationIncludesObjCLifetime) {
3980     Result = SCS1.QualificationIncludesObjCLifetime
3981                ? ImplicitConversionSequence::Worse
3982                : ImplicitConversionSequence::Better;
3983   }
3984 
3985   while (S.Context.UnwrapSimilarTypes(T1, T2)) {
3986     // Within each iteration of the loop, we check the qualifiers to
3987     // determine if this still looks like a qualification
3988     // conversion. Then, if all is well, we unwrap one more level of
3989     // pointers or pointers-to-members and do it all again
3990     // until there are no more pointers or pointers-to-members left
3991     // to unwrap. This essentially mimics what
3992     // IsQualificationConversion does, but here we're checking for a
3993     // strict subset of qualifiers.
3994     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3995       // The qualifiers are the same, so this doesn't tell us anything
3996       // about how the sequences rank.
3997       ;
3998     else if (T2.isMoreQualifiedThan(T1)) {
3999       // T1 has fewer qualifiers, so it could be the better sequence.
4000       if (Result == ImplicitConversionSequence::Worse)
4001         // Neither has qualifiers that are a subset of the other's
4002         // qualifiers.
4003         return ImplicitConversionSequence::Indistinguishable;
4004 
4005       Result = ImplicitConversionSequence::Better;
4006     } else if (T1.isMoreQualifiedThan(T2)) {
4007       // T2 has fewer qualifiers, so it could be the better sequence.
4008       if (Result == ImplicitConversionSequence::Better)
4009         // Neither has qualifiers that are a subset of the other's
4010         // qualifiers.
4011         return ImplicitConversionSequence::Indistinguishable;
4012 
4013       Result = ImplicitConversionSequence::Worse;
4014     } else {
4015       // Qualifiers are disjoint.
4016       return ImplicitConversionSequence::Indistinguishable;
4017     }
4018 
4019     // If the types after this point are equivalent, we're done.
4020     if (S.Context.hasSameUnqualifiedType(T1, T2))
4021       break;
4022   }
4023 
4024   // Check that the winning standard conversion sequence isn't using
4025   // the deprecated string literal array to pointer conversion.
4026   switch (Result) {
4027   case ImplicitConversionSequence::Better:
4028     if (SCS1.DeprecatedStringLiteralToCharPtr)
4029       Result = ImplicitConversionSequence::Indistinguishable;
4030     break;
4031 
4032   case ImplicitConversionSequence::Indistinguishable:
4033     break;
4034 
4035   case ImplicitConversionSequence::Worse:
4036     if (SCS2.DeprecatedStringLiteralToCharPtr)
4037       Result = ImplicitConversionSequence::Indistinguishable;
4038     break;
4039   }
4040 
4041   return Result;
4042 }
4043 
4044 /// CompareDerivedToBaseConversions - Compares two standard conversion
4045 /// sequences to determine whether they can be ranked based on their
4046 /// various kinds of derived-to-base conversions (C++
4047 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4048 /// conversions between Objective-C interface types.
4049 static ImplicitConversionSequence::CompareKind
4050 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4051                                 const StandardConversionSequence& SCS1,
4052                                 const StandardConversionSequence& SCS2) {
4053   QualType FromType1 = SCS1.getFromType();
4054   QualType ToType1 = SCS1.getToType(1);
4055   QualType FromType2 = SCS2.getFromType();
4056   QualType ToType2 = SCS2.getToType(1);
4057 
4058   // Adjust the types we're converting from via the array-to-pointer
4059   // conversion, if we need to.
4060   if (SCS1.First == ICK_Array_To_Pointer)
4061     FromType1 = S.Context.getArrayDecayedType(FromType1);
4062   if (SCS2.First == ICK_Array_To_Pointer)
4063     FromType2 = S.Context.getArrayDecayedType(FromType2);
4064 
4065   // Canonicalize all of the types.
4066   FromType1 = S.Context.getCanonicalType(FromType1);
4067   ToType1 = S.Context.getCanonicalType(ToType1);
4068   FromType2 = S.Context.getCanonicalType(FromType2);
4069   ToType2 = S.Context.getCanonicalType(ToType2);
4070 
4071   // C++ [over.ics.rank]p4b3:
4072   //
4073   //   If class B is derived directly or indirectly from class A and
4074   //   class C is derived directly or indirectly from B,
4075   //
4076   // Compare based on pointer conversions.
4077   if (SCS1.Second == ICK_Pointer_Conversion &&
4078       SCS2.Second == ICK_Pointer_Conversion &&
4079       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4080       FromType1->isPointerType() && FromType2->isPointerType() &&
4081       ToType1->isPointerType() && ToType2->isPointerType()) {
4082     QualType FromPointee1
4083       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4084     QualType ToPointee1
4085       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4086     QualType FromPointee2
4087       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4088     QualType ToPointee2
4089       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4090 
4091     //   -- conversion of C* to B* is better than conversion of C* to A*,
4092     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4093       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4094         return ImplicitConversionSequence::Better;
4095       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4096         return ImplicitConversionSequence::Worse;
4097     }
4098 
4099     //   -- conversion of B* to A* is better than conversion of C* to A*,
4100     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4101       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4102         return ImplicitConversionSequence::Better;
4103       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4104         return ImplicitConversionSequence::Worse;
4105     }
4106   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4107              SCS2.Second == ICK_Pointer_Conversion) {
4108     const ObjCObjectPointerType *FromPtr1
4109       = FromType1->getAs<ObjCObjectPointerType>();
4110     const ObjCObjectPointerType *FromPtr2
4111       = FromType2->getAs<ObjCObjectPointerType>();
4112     const ObjCObjectPointerType *ToPtr1
4113       = ToType1->getAs<ObjCObjectPointerType>();
4114     const ObjCObjectPointerType *ToPtr2
4115       = ToType2->getAs<ObjCObjectPointerType>();
4116 
4117     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4118       // Apply the same conversion ranking rules for Objective-C pointer types
4119       // that we do for C++ pointers to class types. However, we employ the
4120       // Objective-C pseudo-subtyping relationship used for assignment of
4121       // Objective-C pointer types.
4122       bool FromAssignLeft
4123         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4124       bool FromAssignRight
4125         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4126       bool ToAssignLeft
4127         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4128       bool ToAssignRight
4129         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4130 
4131       // A conversion to an a non-id object pointer type or qualified 'id'
4132       // type is better than a conversion to 'id'.
4133       if (ToPtr1->isObjCIdType() &&
4134           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4135         return ImplicitConversionSequence::Worse;
4136       if (ToPtr2->isObjCIdType() &&
4137           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4138         return ImplicitConversionSequence::Better;
4139 
4140       // A conversion to a non-id object pointer type is better than a
4141       // conversion to a qualified 'id' type
4142       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4143         return ImplicitConversionSequence::Worse;
4144       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4145         return ImplicitConversionSequence::Better;
4146 
4147       // A conversion to an a non-Class object pointer type or qualified 'Class'
4148       // type is better than a conversion to 'Class'.
4149       if (ToPtr1->isObjCClassType() &&
4150           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4151         return ImplicitConversionSequence::Worse;
4152       if (ToPtr2->isObjCClassType() &&
4153           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4154         return ImplicitConversionSequence::Better;
4155 
4156       // A conversion to a non-Class object pointer type is better than a
4157       // conversion to a qualified 'Class' type.
4158       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4159         return ImplicitConversionSequence::Worse;
4160       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4161         return ImplicitConversionSequence::Better;
4162 
4163       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4164       if (S.Context.hasSameType(FromType1, FromType2) &&
4165           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4166           (ToAssignLeft != ToAssignRight)) {
4167         if (FromPtr1->isSpecialized()) {
4168           // "conversion of B<A> * to B * is better than conversion of B * to
4169           // C *.
4170           bool IsFirstSame =
4171               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4172           bool IsSecondSame =
4173               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4174           if (IsFirstSame) {
4175             if (!IsSecondSame)
4176               return ImplicitConversionSequence::Better;
4177           } else if (IsSecondSame)
4178             return ImplicitConversionSequence::Worse;
4179         }
4180         return ToAssignLeft? ImplicitConversionSequence::Worse
4181                            : ImplicitConversionSequence::Better;
4182       }
4183 
4184       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4185       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4186           (FromAssignLeft != FromAssignRight))
4187         return FromAssignLeft? ImplicitConversionSequence::Better
4188         : ImplicitConversionSequence::Worse;
4189     }
4190   }
4191 
4192   // Ranking of member-pointer types.
4193   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4194       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4195       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4196     const MemberPointerType * FromMemPointer1 =
4197                                         FromType1->getAs<MemberPointerType>();
4198     const MemberPointerType * ToMemPointer1 =
4199                                           ToType1->getAs<MemberPointerType>();
4200     const MemberPointerType * FromMemPointer2 =
4201                                           FromType2->getAs<MemberPointerType>();
4202     const MemberPointerType * ToMemPointer2 =
4203                                           ToType2->getAs<MemberPointerType>();
4204     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4205     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4206     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4207     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4208     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4209     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4210     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4211     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4212     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4213     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4214       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4215         return ImplicitConversionSequence::Worse;
4216       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4217         return ImplicitConversionSequence::Better;
4218     }
4219     // conversion of B::* to C::* is better than conversion of A::* to C::*
4220     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4221       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4222         return ImplicitConversionSequence::Better;
4223       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4224         return ImplicitConversionSequence::Worse;
4225     }
4226   }
4227 
4228   if (SCS1.Second == ICK_Derived_To_Base) {
4229     //   -- conversion of C to B is better than conversion of C to A,
4230     //   -- binding of an expression of type C to a reference of type
4231     //      B& is better than binding an expression of type C to a
4232     //      reference of type A&,
4233     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4234         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4235       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4236         return ImplicitConversionSequence::Better;
4237       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4238         return ImplicitConversionSequence::Worse;
4239     }
4240 
4241     //   -- conversion of B to A is better than conversion of C to A.
4242     //   -- binding of an expression of type B to a reference of type
4243     //      A& is better than binding an expression of type C to a
4244     //      reference of type A&,
4245     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4246         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4247       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4248         return ImplicitConversionSequence::Better;
4249       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4250         return ImplicitConversionSequence::Worse;
4251     }
4252   }
4253 
4254   return ImplicitConversionSequence::Indistinguishable;
4255 }
4256 
4257 /// Determine whether the given type is valid, e.g., it is not an invalid
4258 /// C++ class.
4259 static bool isTypeValid(QualType T) {
4260   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4261     return !Record->isInvalidDecl();
4262 
4263   return true;
4264 }
4265 
4266 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4267 /// determine whether they are reference-related,
4268 /// reference-compatible, reference-compatible with added
4269 /// qualification, or incompatible, for use in C++ initialization by
4270 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4271 /// type, and the first type (T1) is the pointee type of the reference
4272 /// type being initialized.
4273 Sema::ReferenceCompareResult
4274 Sema::CompareReferenceRelationship(SourceLocation Loc,
4275                                    QualType OrigT1, QualType OrigT2,
4276                                    bool &DerivedToBase,
4277                                    bool &ObjCConversion,
4278                                    bool &ObjCLifetimeConversion) {
4279   assert(!OrigT1->isReferenceType() &&
4280     "T1 must be the pointee type of the reference type");
4281   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4282 
4283   QualType T1 = Context.getCanonicalType(OrigT1);
4284   QualType T2 = Context.getCanonicalType(OrigT2);
4285   Qualifiers T1Quals, T2Quals;
4286   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4287   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4288 
4289   // C++ [dcl.init.ref]p4:
4290   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4291   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4292   //   T1 is a base class of T2.
4293   DerivedToBase = false;
4294   ObjCConversion = false;
4295   ObjCLifetimeConversion = false;
4296   QualType ConvertedT2;
4297   if (UnqualT1 == UnqualT2) {
4298     // Nothing to do.
4299   } else if (isCompleteType(Loc, OrigT2) &&
4300              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4301              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4302     DerivedToBase = true;
4303   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4304            UnqualT2->isObjCObjectOrInterfaceType() &&
4305            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4306     ObjCConversion = true;
4307   else if (UnqualT2->isFunctionType() &&
4308            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4309     // C++1z [dcl.init.ref]p4:
4310     //   cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4311     //   function" and T1 is "function"
4312     //
4313     // We extend this to also apply to 'noreturn', so allow any function
4314     // conversion between function types.
4315     return Ref_Compatible;
4316   else
4317     return Ref_Incompatible;
4318 
4319   // At this point, we know that T1 and T2 are reference-related (at
4320   // least).
4321 
4322   // If the type is an array type, promote the element qualifiers to the type
4323   // for comparison.
4324   if (isa<ArrayType>(T1) && T1Quals)
4325     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4326   if (isa<ArrayType>(T2) && T2Quals)
4327     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4328 
4329   // C++ [dcl.init.ref]p4:
4330   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4331   //   reference-related to T2 and cv1 is the same cv-qualification
4332   //   as, or greater cv-qualification than, cv2. For purposes of
4333   //   overload resolution, cases for which cv1 is greater
4334   //   cv-qualification than cv2 are identified as
4335   //   reference-compatible with added qualification (see 13.3.3.2).
4336   //
4337   // Note that we also require equivalence of Objective-C GC and address-space
4338   // qualifiers when performing these computations, so that e.g., an int in
4339   // address space 1 is not reference-compatible with an int in address
4340   // space 2.
4341   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4342       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4343     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4344       ObjCLifetimeConversion = true;
4345 
4346     T1Quals.removeObjCLifetime();
4347     T2Quals.removeObjCLifetime();
4348   }
4349 
4350   // MS compiler ignores __unaligned qualifier for references; do the same.
4351   T1Quals.removeUnaligned();
4352   T2Quals.removeUnaligned();
4353 
4354   if (T1Quals.compatiblyIncludes(T2Quals))
4355     return Ref_Compatible;
4356   else
4357     return Ref_Related;
4358 }
4359 
4360 /// Look for a user-defined conversion to a value reference-compatible
4361 ///        with DeclType. Return true if something definite is found.
4362 static bool
4363 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4364                          QualType DeclType, SourceLocation DeclLoc,
4365                          Expr *Init, QualType T2, bool AllowRvalues,
4366                          bool AllowExplicit) {
4367   assert(T2->isRecordType() && "Can only find conversions of record types.");
4368   CXXRecordDecl *T2RecordDecl
4369     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4370 
4371   OverloadCandidateSet CandidateSet(
4372       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4373   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4374   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4375     NamedDecl *D = *I;
4376     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4377     if (isa<UsingShadowDecl>(D))
4378       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4379 
4380     FunctionTemplateDecl *ConvTemplate
4381       = dyn_cast<FunctionTemplateDecl>(D);
4382     CXXConversionDecl *Conv;
4383     if (ConvTemplate)
4384       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4385     else
4386       Conv = cast<CXXConversionDecl>(D);
4387 
4388     // If this is an explicit conversion, and we're not allowed to consider
4389     // explicit conversions, skip it.
4390     if (!AllowExplicit && Conv->isExplicit())
4391       continue;
4392 
4393     if (AllowRvalues) {
4394       bool DerivedToBase = false;
4395       bool ObjCConversion = false;
4396       bool ObjCLifetimeConversion = false;
4397 
4398       // If we are initializing an rvalue reference, don't permit conversion
4399       // functions that return lvalues.
4400       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4401         const ReferenceType *RefType
4402           = Conv->getConversionType()->getAs<LValueReferenceType>();
4403         if (RefType && !RefType->getPointeeType()->isFunctionType())
4404           continue;
4405       }
4406 
4407       if (!ConvTemplate &&
4408           S.CompareReferenceRelationship(
4409             DeclLoc,
4410             Conv->getConversionType().getNonReferenceType()
4411               .getUnqualifiedType(),
4412             DeclType.getNonReferenceType().getUnqualifiedType(),
4413             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4414           Sema::Ref_Incompatible)
4415         continue;
4416     } else {
4417       // If the conversion function doesn't return a reference type,
4418       // it can't be considered for this conversion. An rvalue reference
4419       // is only acceptable if its referencee is a function type.
4420 
4421       const ReferenceType *RefType =
4422         Conv->getConversionType()->getAs<ReferenceType>();
4423       if (!RefType ||
4424           (!RefType->isLValueReferenceType() &&
4425            !RefType->getPointeeType()->isFunctionType()))
4426         continue;
4427     }
4428 
4429     if (ConvTemplate)
4430       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4431                                        Init, DeclType, CandidateSet,
4432                                        /*AllowObjCConversionOnExplicit=*/false);
4433     else
4434       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4435                                DeclType, CandidateSet,
4436                                /*AllowObjCConversionOnExplicit=*/false);
4437   }
4438 
4439   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4440 
4441   OverloadCandidateSet::iterator Best;
4442   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4443   case OR_Success:
4444     // C++ [over.ics.ref]p1:
4445     //
4446     //   [...] If the parameter binds directly to the result of
4447     //   applying a conversion function to the argument
4448     //   expression, the implicit conversion sequence is a
4449     //   user-defined conversion sequence (13.3.3.1.2), with the
4450     //   second standard conversion sequence either an identity
4451     //   conversion or, if the conversion function returns an
4452     //   entity of a type that is a derived class of the parameter
4453     //   type, a derived-to-base Conversion.
4454     if (!Best->FinalConversion.DirectBinding)
4455       return false;
4456 
4457     ICS.setUserDefined();
4458     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4459     ICS.UserDefined.After = Best->FinalConversion;
4460     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4461     ICS.UserDefined.ConversionFunction = Best->Function;
4462     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4463     ICS.UserDefined.EllipsisConversion = false;
4464     assert(ICS.UserDefined.After.ReferenceBinding &&
4465            ICS.UserDefined.After.DirectBinding &&
4466            "Expected a direct reference binding!");
4467     return true;
4468 
4469   case OR_Ambiguous:
4470     ICS.setAmbiguous();
4471     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4472          Cand != CandidateSet.end(); ++Cand)
4473       if (Cand->Viable)
4474         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4475     return true;
4476 
4477   case OR_No_Viable_Function:
4478   case OR_Deleted:
4479     // There was no suitable conversion, or we found a deleted
4480     // conversion; continue with other checks.
4481     return false;
4482   }
4483 
4484   llvm_unreachable("Invalid OverloadResult!");
4485 }
4486 
4487 /// Compute an implicit conversion sequence for reference
4488 /// initialization.
4489 static ImplicitConversionSequence
4490 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4491                  SourceLocation DeclLoc,
4492                  bool SuppressUserConversions,
4493                  bool AllowExplicit) {
4494   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4495 
4496   // Most paths end in a failed conversion.
4497   ImplicitConversionSequence ICS;
4498   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4499 
4500   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4501   QualType T2 = Init->getType();
4502 
4503   // If the initializer is the address of an overloaded function, try
4504   // to resolve the overloaded function. If all goes well, T2 is the
4505   // type of the resulting function.
4506   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4507     DeclAccessPair Found;
4508     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4509                                                                 false, Found))
4510       T2 = Fn->getType();
4511   }
4512 
4513   // Compute some basic properties of the types and the initializer.
4514   bool isRValRef = DeclType->isRValueReferenceType();
4515   bool DerivedToBase = false;
4516   bool ObjCConversion = false;
4517   bool ObjCLifetimeConversion = false;
4518   Expr::Classification InitCategory = Init->Classify(S.Context);
4519   Sema::ReferenceCompareResult RefRelationship
4520     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4521                                      ObjCConversion, ObjCLifetimeConversion);
4522 
4523 
4524   // C++0x [dcl.init.ref]p5:
4525   //   A reference to type "cv1 T1" is initialized by an expression
4526   //   of type "cv2 T2" as follows:
4527 
4528   //     -- If reference is an lvalue reference and the initializer expression
4529   if (!isRValRef) {
4530     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4531     //        reference-compatible with "cv2 T2," or
4532     //
4533     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4534     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4535       // C++ [over.ics.ref]p1:
4536       //   When a parameter of reference type binds directly (8.5.3)
4537       //   to an argument expression, the implicit conversion sequence
4538       //   is the identity conversion, unless the argument expression
4539       //   has a type that is a derived class of the parameter type,
4540       //   in which case the implicit conversion sequence is a
4541       //   derived-to-base Conversion (13.3.3.1).
4542       ICS.setStandard();
4543       ICS.Standard.First = ICK_Identity;
4544       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4545                          : ObjCConversion? ICK_Compatible_Conversion
4546                          : ICK_Identity;
4547       ICS.Standard.Third = ICK_Identity;
4548       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4549       ICS.Standard.setToType(0, T2);
4550       ICS.Standard.setToType(1, T1);
4551       ICS.Standard.setToType(2, T1);
4552       ICS.Standard.ReferenceBinding = true;
4553       ICS.Standard.DirectBinding = true;
4554       ICS.Standard.IsLvalueReference = !isRValRef;
4555       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4556       ICS.Standard.BindsToRvalue = false;
4557       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4558       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4559       ICS.Standard.CopyConstructor = nullptr;
4560       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4561 
4562       // Nothing more to do: the inaccessibility/ambiguity check for
4563       // derived-to-base conversions is suppressed when we're
4564       // computing the implicit conversion sequence (C++
4565       // [over.best.ics]p2).
4566       return ICS;
4567     }
4568 
4569     //       -- has a class type (i.e., T2 is a class type), where T1 is
4570     //          not reference-related to T2, and can be implicitly
4571     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4572     //          is reference-compatible with "cv3 T3" 92) (this
4573     //          conversion is selected by enumerating the applicable
4574     //          conversion functions (13.3.1.6) and choosing the best
4575     //          one through overload resolution (13.3)),
4576     if (!SuppressUserConversions && T2->isRecordType() &&
4577         S.isCompleteType(DeclLoc, T2) &&
4578         RefRelationship == Sema::Ref_Incompatible) {
4579       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4580                                    Init, T2, /*AllowRvalues=*/false,
4581                                    AllowExplicit))
4582         return ICS;
4583     }
4584   }
4585 
4586   //     -- Otherwise, the reference shall be an lvalue reference to a
4587   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4588   //        shall be an rvalue reference.
4589   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4590     return ICS;
4591 
4592   //       -- If the initializer expression
4593   //
4594   //            -- is an xvalue, class prvalue, array prvalue or function
4595   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4596   if (RefRelationship == Sema::Ref_Compatible &&
4597       (InitCategory.isXValue() ||
4598        (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4599        (InitCategory.isLValue() && T2->isFunctionType()))) {
4600     ICS.setStandard();
4601     ICS.Standard.First = ICK_Identity;
4602     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4603                       : ObjCConversion? ICK_Compatible_Conversion
4604                       : ICK_Identity;
4605     ICS.Standard.Third = ICK_Identity;
4606     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4607     ICS.Standard.setToType(0, T2);
4608     ICS.Standard.setToType(1, T1);
4609     ICS.Standard.setToType(2, T1);
4610     ICS.Standard.ReferenceBinding = true;
4611     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4612     // binding unless we're binding to a class prvalue.
4613     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4614     // allow the use of rvalue references in C++98/03 for the benefit of
4615     // standard library implementors; therefore, we need the xvalue check here.
4616     ICS.Standard.DirectBinding =
4617       S.getLangOpts().CPlusPlus11 ||
4618       !(InitCategory.isPRValue() || T2->isRecordType());
4619     ICS.Standard.IsLvalueReference = !isRValRef;
4620     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4621     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4622     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4623     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4624     ICS.Standard.CopyConstructor = nullptr;
4625     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4626     return ICS;
4627   }
4628 
4629   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4630   //               reference-related to T2, and can be implicitly converted to
4631   //               an xvalue, class prvalue, or function lvalue of type
4632   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4633   //               "cv3 T3",
4634   //
4635   //          then the reference is bound to the value of the initializer
4636   //          expression in the first case and to the result of the conversion
4637   //          in the second case (or, in either case, to an appropriate base
4638   //          class subobject).
4639   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4640       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4641       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4642                                Init, T2, /*AllowRvalues=*/true,
4643                                AllowExplicit)) {
4644     // In the second case, if the reference is an rvalue reference
4645     // and the second standard conversion sequence of the
4646     // user-defined conversion sequence includes an lvalue-to-rvalue
4647     // conversion, the program is ill-formed.
4648     if (ICS.isUserDefined() && isRValRef &&
4649         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4650       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4651 
4652     return ICS;
4653   }
4654 
4655   // A temporary of function type cannot be created; don't even try.
4656   if (T1->isFunctionType())
4657     return ICS;
4658 
4659   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4660   //          initialized from the initializer expression using the
4661   //          rules for a non-reference copy initialization (8.5). The
4662   //          reference is then bound to the temporary. If T1 is
4663   //          reference-related to T2, cv1 must be the same
4664   //          cv-qualification as, or greater cv-qualification than,
4665   //          cv2; otherwise, the program is ill-formed.
4666   if (RefRelationship == Sema::Ref_Related) {
4667     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4668     // we would be reference-compatible or reference-compatible with
4669     // added qualification. But that wasn't the case, so the reference
4670     // initialization fails.
4671     //
4672     // Note that we only want to check address spaces and cvr-qualifiers here.
4673     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4674     Qualifiers T1Quals = T1.getQualifiers();
4675     Qualifiers T2Quals = T2.getQualifiers();
4676     T1Quals.removeObjCGCAttr();
4677     T1Quals.removeObjCLifetime();
4678     T2Quals.removeObjCGCAttr();
4679     T2Quals.removeObjCLifetime();
4680     // MS compiler ignores __unaligned qualifier for references; do the same.
4681     T1Quals.removeUnaligned();
4682     T2Quals.removeUnaligned();
4683     if (!T1Quals.compatiblyIncludes(T2Quals))
4684       return ICS;
4685   }
4686 
4687   // If at least one of the types is a class type, the types are not
4688   // related, and we aren't allowed any user conversions, the
4689   // reference binding fails. This case is important for breaking
4690   // recursion, since TryImplicitConversion below will attempt to
4691   // create a temporary through the use of a copy constructor.
4692   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4693       (T1->isRecordType() || T2->isRecordType()))
4694     return ICS;
4695 
4696   // If T1 is reference-related to T2 and the reference is an rvalue
4697   // reference, the initializer expression shall not be an lvalue.
4698   if (RefRelationship >= Sema::Ref_Related &&
4699       isRValRef && Init->Classify(S.Context).isLValue())
4700     return ICS;
4701 
4702   // C++ [over.ics.ref]p2:
4703   //   When a parameter of reference type is not bound directly to
4704   //   an argument expression, the conversion sequence is the one
4705   //   required to convert the argument expression to the
4706   //   underlying type of the reference according to
4707   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4708   //   to copy-initializing a temporary of the underlying type with
4709   //   the argument expression. Any difference in top-level
4710   //   cv-qualification is subsumed by the initialization itself
4711   //   and does not constitute a conversion.
4712   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4713                               /*AllowExplicit=*/false,
4714                               /*InOverloadResolution=*/false,
4715                               /*CStyle=*/false,
4716                               /*AllowObjCWritebackConversion=*/false,
4717                               /*AllowObjCConversionOnExplicit=*/false);
4718 
4719   // Of course, that's still a reference binding.
4720   if (ICS.isStandard()) {
4721     ICS.Standard.ReferenceBinding = true;
4722     ICS.Standard.IsLvalueReference = !isRValRef;
4723     ICS.Standard.BindsToFunctionLvalue = false;
4724     ICS.Standard.BindsToRvalue = true;
4725     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4726     ICS.Standard.ObjCLifetimeConversionBinding = false;
4727   } else if (ICS.isUserDefined()) {
4728     const ReferenceType *LValRefType =
4729         ICS.UserDefined.ConversionFunction->getReturnType()
4730             ->getAs<LValueReferenceType>();
4731 
4732     // C++ [over.ics.ref]p3:
4733     //   Except for an implicit object parameter, for which see 13.3.1, a
4734     //   standard conversion sequence cannot be formed if it requires [...]
4735     //   binding an rvalue reference to an lvalue other than a function
4736     //   lvalue.
4737     // Note that the function case is not possible here.
4738     if (DeclType->isRValueReferenceType() && LValRefType) {
4739       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4740       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4741       // reference to an rvalue!
4742       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4743       return ICS;
4744     }
4745 
4746     ICS.UserDefined.After.ReferenceBinding = true;
4747     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4748     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4749     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4750     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4751     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4752   }
4753 
4754   return ICS;
4755 }
4756 
4757 static ImplicitConversionSequence
4758 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4759                       bool SuppressUserConversions,
4760                       bool InOverloadResolution,
4761                       bool AllowObjCWritebackConversion,
4762                       bool AllowExplicit = false);
4763 
4764 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4765 /// initializer list From.
4766 static ImplicitConversionSequence
4767 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4768                   bool SuppressUserConversions,
4769                   bool InOverloadResolution,
4770                   bool AllowObjCWritebackConversion) {
4771   // C++11 [over.ics.list]p1:
4772   //   When an argument is an initializer list, it is not an expression and
4773   //   special rules apply for converting it to a parameter type.
4774 
4775   ImplicitConversionSequence Result;
4776   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4777 
4778   // We need a complete type for what follows. Incomplete types can never be
4779   // initialized from init lists.
4780   if (!S.isCompleteType(From->getBeginLoc(), ToType))
4781     return Result;
4782 
4783   // Per DR1467:
4784   //   If the parameter type is a class X and the initializer list has a single
4785   //   element of type cv U, where U is X or a class derived from X, the
4786   //   implicit conversion sequence is the one required to convert the element
4787   //   to the parameter type.
4788   //
4789   //   Otherwise, if the parameter type is a character array [... ]
4790   //   and the initializer list has a single element that is an
4791   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4792   //   implicit conversion sequence is the identity conversion.
4793   if (From->getNumInits() == 1) {
4794     if (ToType->isRecordType()) {
4795       QualType InitType = From->getInit(0)->getType();
4796       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4797           S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
4798         return TryCopyInitialization(S, From->getInit(0), ToType,
4799                                      SuppressUserConversions,
4800                                      InOverloadResolution,
4801                                      AllowObjCWritebackConversion);
4802     }
4803     // FIXME: Check the other conditions here: array of character type,
4804     // initializer is a string literal.
4805     if (ToType->isArrayType()) {
4806       InitializedEntity Entity =
4807         InitializedEntity::InitializeParameter(S.Context, ToType,
4808                                                /*Consumed=*/false);
4809       if (S.CanPerformCopyInitialization(Entity, From)) {
4810         Result.setStandard();
4811         Result.Standard.setAsIdentityConversion();
4812         Result.Standard.setFromType(ToType);
4813         Result.Standard.setAllToTypes(ToType);
4814         return Result;
4815       }
4816     }
4817   }
4818 
4819   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4820   // C++11 [over.ics.list]p2:
4821   //   If the parameter type is std::initializer_list<X> or "array of X" and
4822   //   all the elements can be implicitly converted to X, the implicit
4823   //   conversion sequence is the worst conversion necessary to convert an
4824   //   element of the list to X.
4825   //
4826   // C++14 [over.ics.list]p3:
4827   //   Otherwise, if the parameter type is "array of N X", if the initializer
4828   //   list has exactly N elements or if it has fewer than N elements and X is
4829   //   default-constructible, and if all the elements of the initializer list
4830   //   can be implicitly converted to X, the implicit conversion sequence is
4831   //   the worst conversion necessary to convert an element of the list to X.
4832   //
4833   // FIXME: We're missing a lot of these checks.
4834   bool toStdInitializerList = false;
4835   QualType X;
4836   if (ToType->isArrayType())
4837     X = S.Context.getAsArrayType(ToType)->getElementType();
4838   else
4839     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4840   if (!X.isNull()) {
4841     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4842       Expr *Init = From->getInit(i);
4843       ImplicitConversionSequence ICS =
4844           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4845                                 InOverloadResolution,
4846                                 AllowObjCWritebackConversion);
4847       // If a single element isn't convertible, fail.
4848       if (ICS.isBad()) {
4849         Result = ICS;
4850         break;
4851       }
4852       // Otherwise, look for the worst conversion.
4853       if (Result.isBad() || CompareImplicitConversionSequences(
4854                                 S, From->getBeginLoc(), ICS, Result) ==
4855                                 ImplicitConversionSequence::Worse)
4856         Result = ICS;
4857     }
4858 
4859     // For an empty list, we won't have computed any conversion sequence.
4860     // Introduce the identity conversion sequence.
4861     if (From->getNumInits() == 0) {
4862       Result.setStandard();
4863       Result.Standard.setAsIdentityConversion();
4864       Result.Standard.setFromType(ToType);
4865       Result.Standard.setAllToTypes(ToType);
4866     }
4867 
4868     Result.setStdInitializerListElement(toStdInitializerList);
4869     return Result;
4870   }
4871 
4872   // C++14 [over.ics.list]p4:
4873   // C++11 [over.ics.list]p3:
4874   //   Otherwise, if the parameter is a non-aggregate class X and overload
4875   //   resolution chooses a single best constructor [...] the implicit
4876   //   conversion sequence is a user-defined conversion sequence. If multiple
4877   //   constructors are viable but none is better than the others, the
4878   //   implicit conversion sequence is a user-defined conversion sequence.
4879   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4880     // This function can deal with initializer lists.
4881     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4882                                     /*AllowExplicit=*/false,
4883                                     InOverloadResolution, /*CStyle=*/false,
4884                                     AllowObjCWritebackConversion,
4885                                     /*AllowObjCConversionOnExplicit=*/false);
4886   }
4887 
4888   // C++14 [over.ics.list]p5:
4889   // C++11 [over.ics.list]p4:
4890   //   Otherwise, if the parameter has an aggregate type which can be
4891   //   initialized from the initializer list [...] the implicit conversion
4892   //   sequence is a user-defined conversion sequence.
4893   if (ToType->isAggregateType()) {
4894     // Type is an aggregate, argument is an init list. At this point it comes
4895     // down to checking whether the initialization works.
4896     // FIXME: Find out whether this parameter is consumed or not.
4897     // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4898     // need to call into the initialization code here; overload resolution
4899     // should not be doing that.
4900     InitializedEntity Entity =
4901         InitializedEntity::InitializeParameter(S.Context, ToType,
4902                                                /*Consumed=*/false);
4903     if (S.CanPerformCopyInitialization(Entity, From)) {
4904       Result.setUserDefined();
4905       Result.UserDefined.Before.setAsIdentityConversion();
4906       // Initializer lists don't have a type.
4907       Result.UserDefined.Before.setFromType(QualType());
4908       Result.UserDefined.Before.setAllToTypes(QualType());
4909 
4910       Result.UserDefined.After.setAsIdentityConversion();
4911       Result.UserDefined.After.setFromType(ToType);
4912       Result.UserDefined.After.setAllToTypes(ToType);
4913       Result.UserDefined.ConversionFunction = nullptr;
4914     }
4915     return Result;
4916   }
4917 
4918   // C++14 [over.ics.list]p6:
4919   // C++11 [over.ics.list]p5:
4920   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4921   if (ToType->isReferenceType()) {
4922     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4923     // mention initializer lists in any way. So we go by what list-
4924     // initialization would do and try to extrapolate from that.
4925 
4926     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4927 
4928     // If the initializer list has a single element that is reference-related
4929     // to the parameter type, we initialize the reference from that.
4930     if (From->getNumInits() == 1) {
4931       Expr *Init = From->getInit(0);
4932 
4933       QualType T2 = Init->getType();
4934 
4935       // If the initializer is the address of an overloaded function, try
4936       // to resolve the overloaded function. If all goes well, T2 is the
4937       // type of the resulting function.
4938       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4939         DeclAccessPair Found;
4940         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4941                                    Init, ToType, false, Found))
4942           T2 = Fn->getType();
4943       }
4944 
4945       // Compute some basic properties of the types and the initializer.
4946       bool dummy1 = false;
4947       bool dummy2 = false;
4948       bool dummy3 = false;
4949       Sema::ReferenceCompareResult RefRelationship =
4950           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2, dummy1,
4951                                          dummy2, dummy3);
4952 
4953       if (RefRelationship >= Sema::Ref_Related) {
4954         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
4955                                 SuppressUserConversions,
4956                                 /*AllowExplicit=*/false);
4957       }
4958     }
4959 
4960     // Otherwise, we bind the reference to a temporary created from the
4961     // initializer list.
4962     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4963                                InOverloadResolution,
4964                                AllowObjCWritebackConversion);
4965     if (Result.isFailure())
4966       return Result;
4967     assert(!Result.isEllipsis() &&
4968            "Sub-initialization cannot result in ellipsis conversion.");
4969 
4970     // Can we even bind to a temporary?
4971     if (ToType->isRValueReferenceType() ||
4972         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4973       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4974                                             Result.UserDefined.After;
4975       SCS.ReferenceBinding = true;
4976       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4977       SCS.BindsToRvalue = true;
4978       SCS.BindsToFunctionLvalue = false;
4979       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4980       SCS.ObjCLifetimeConversionBinding = false;
4981     } else
4982       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4983                     From, ToType);
4984     return Result;
4985   }
4986 
4987   // C++14 [over.ics.list]p7:
4988   // C++11 [over.ics.list]p6:
4989   //   Otherwise, if the parameter type is not a class:
4990   if (!ToType->isRecordType()) {
4991     //    - if the initializer list has one element that is not itself an
4992     //      initializer list, the implicit conversion sequence is the one
4993     //      required to convert the element to the parameter type.
4994     unsigned NumInits = From->getNumInits();
4995     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4996       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4997                                      SuppressUserConversions,
4998                                      InOverloadResolution,
4999                                      AllowObjCWritebackConversion);
5000     //    - if the initializer list has no elements, the implicit conversion
5001     //      sequence is the identity conversion.
5002     else if (NumInits == 0) {
5003       Result.setStandard();
5004       Result.Standard.setAsIdentityConversion();
5005       Result.Standard.setFromType(ToType);
5006       Result.Standard.setAllToTypes(ToType);
5007     }
5008     return Result;
5009   }
5010 
5011   // C++14 [over.ics.list]p8:
5012   // C++11 [over.ics.list]p7:
5013   //   In all cases other than those enumerated above, no conversion is possible
5014   return Result;
5015 }
5016 
5017 /// TryCopyInitialization - Try to copy-initialize a value of type
5018 /// ToType from the expression From. Return the implicit conversion
5019 /// sequence required to pass this argument, which may be a bad
5020 /// conversion sequence (meaning that the argument cannot be passed to
5021 /// a parameter of this type). If @p SuppressUserConversions, then we
5022 /// do not permit any user-defined conversion sequences.
5023 static ImplicitConversionSequence
5024 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5025                       bool SuppressUserConversions,
5026                       bool InOverloadResolution,
5027                       bool AllowObjCWritebackConversion,
5028                       bool AllowExplicit) {
5029   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5030     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5031                              InOverloadResolution,AllowObjCWritebackConversion);
5032 
5033   if (ToType->isReferenceType())
5034     return TryReferenceInit(S, From, ToType,
5035                             /*FIXME:*/ From->getBeginLoc(),
5036                             SuppressUserConversions, AllowExplicit);
5037 
5038   return TryImplicitConversion(S, From, ToType,
5039                                SuppressUserConversions,
5040                                /*AllowExplicit=*/false,
5041                                InOverloadResolution,
5042                                /*CStyle=*/false,
5043                                AllowObjCWritebackConversion,
5044                                /*AllowObjCConversionOnExplicit=*/false);
5045 }
5046 
5047 static bool TryCopyInitialization(const CanQualType FromQTy,
5048                                   const CanQualType ToQTy,
5049                                   Sema &S,
5050                                   SourceLocation Loc,
5051                                   ExprValueKind FromVK) {
5052   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5053   ImplicitConversionSequence ICS =
5054     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5055 
5056   return !ICS.isBad();
5057 }
5058 
5059 /// TryObjectArgumentInitialization - Try to initialize the object
5060 /// parameter of the given member function (@c Method) from the
5061 /// expression @p From.
5062 static ImplicitConversionSequence
5063 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5064                                 Expr::Classification FromClassification,
5065                                 CXXMethodDecl *Method,
5066                                 CXXRecordDecl *ActingContext) {
5067   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5068   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5069   //                 const volatile object.
5070   Qualifiers Quals;
5071   if (isa<CXXDestructorDecl>(Method)) {
5072     Quals.addConst();
5073     Quals.addVolatile();
5074   } else {
5075     Quals = Method->getTypeQualifiers();
5076   }
5077 
5078   QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5079 
5080   // Set up the conversion sequence as a "bad" conversion, to allow us
5081   // to exit early.
5082   ImplicitConversionSequence ICS;
5083 
5084   // We need to have an object of class type.
5085   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5086     FromType = PT->getPointeeType();
5087 
5088     // When we had a pointer, it's implicitly dereferenced, so we
5089     // better have an lvalue.
5090     assert(FromClassification.isLValue());
5091   }
5092 
5093   assert(FromType->isRecordType());
5094 
5095   // C++0x [over.match.funcs]p4:
5096   //   For non-static member functions, the type of the implicit object
5097   //   parameter is
5098   //
5099   //     - "lvalue reference to cv X" for functions declared without a
5100   //        ref-qualifier or with the & ref-qualifier
5101   //     - "rvalue reference to cv X" for functions declared with the &&
5102   //        ref-qualifier
5103   //
5104   // where X is the class of which the function is a member and cv is the
5105   // cv-qualification on the member function declaration.
5106   //
5107   // However, when finding an implicit conversion sequence for the argument, we
5108   // are not allowed to perform user-defined conversions
5109   // (C++ [over.match.funcs]p5). We perform a simplified version of
5110   // reference binding here, that allows class rvalues to bind to
5111   // non-constant references.
5112 
5113   // First check the qualifiers.
5114   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5115   if (ImplicitParamType.getCVRQualifiers()
5116                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5117       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5118     ICS.setBad(BadConversionSequence::bad_qualifiers,
5119                FromType, ImplicitParamType);
5120     return ICS;
5121   }
5122 
5123   // Check that we have either the same type or a derived type. It
5124   // affects the conversion rank.
5125   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5126   ImplicitConversionKind SecondKind;
5127   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5128     SecondKind = ICK_Identity;
5129   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5130     SecondKind = ICK_Derived_To_Base;
5131   else {
5132     ICS.setBad(BadConversionSequence::unrelated_class,
5133                FromType, ImplicitParamType);
5134     return ICS;
5135   }
5136 
5137   // Check the ref-qualifier.
5138   switch (Method->getRefQualifier()) {
5139   case RQ_None:
5140     // Do nothing; we don't care about lvalueness or rvalueness.
5141     break;
5142 
5143   case RQ_LValue:
5144     if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5145       // non-const lvalue reference cannot bind to an rvalue
5146       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5147                  ImplicitParamType);
5148       return ICS;
5149     }
5150     break;
5151 
5152   case RQ_RValue:
5153     if (!FromClassification.isRValue()) {
5154       // rvalue reference cannot bind to an lvalue
5155       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5156                  ImplicitParamType);
5157       return ICS;
5158     }
5159     break;
5160   }
5161 
5162   // Success. Mark this as a reference binding.
5163   ICS.setStandard();
5164   ICS.Standard.setAsIdentityConversion();
5165   ICS.Standard.Second = SecondKind;
5166   ICS.Standard.setFromType(FromType);
5167   ICS.Standard.setAllToTypes(ImplicitParamType);
5168   ICS.Standard.ReferenceBinding = true;
5169   ICS.Standard.DirectBinding = true;
5170   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5171   ICS.Standard.BindsToFunctionLvalue = false;
5172   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5173   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5174     = (Method->getRefQualifier() == RQ_None);
5175   return ICS;
5176 }
5177 
5178 /// PerformObjectArgumentInitialization - Perform initialization of
5179 /// the implicit object parameter for the given Method with the given
5180 /// expression.
5181 ExprResult
5182 Sema::PerformObjectArgumentInitialization(Expr *From,
5183                                           NestedNameSpecifier *Qualifier,
5184                                           NamedDecl *FoundDecl,
5185                                           CXXMethodDecl *Method) {
5186   QualType FromRecordType, DestType;
5187   QualType ImplicitParamRecordType  =
5188     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
5189 
5190   Expr::Classification FromClassification;
5191   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5192     FromRecordType = PT->getPointeeType();
5193     DestType = Method->getThisType(Context);
5194     FromClassification = Expr::Classification::makeSimpleLValue();
5195   } else {
5196     FromRecordType = From->getType();
5197     DestType = ImplicitParamRecordType;
5198     FromClassification = From->Classify(Context);
5199 
5200     // When performing member access on an rvalue, materialize a temporary.
5201     if (From->isRValue()) {
5202       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5203                                             Method->getRefQualifier() !=
5204                                                 RefQualifierKind::RQ_RValue);
5205     }
5206   }
5207 
5208   // Note that we always use the true parent context when performing
5209   // the actual argument initialization.
5210   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5211       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5212       Method->getParent());
5213   if (ICS.isBad()) {
5214     switch (ICS.Bad.Kind) {
5215     case BadConversionSequence::bad_qualifiers: {
5216       Qualifiers FromQs = FromRecordType.getQualifiers();
5217       Qualifiers ToQs = DestType.getQualifiers();
5218       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5219       if (CVR) {
5220         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5221             << Method->getDeclName() << FromRecordType << (CVR - 1)
5222             << From->getSourceRange();
5223         Diag(Method->getLocation(), diag::note_previous_decl)
5224           << Method->getDeclName();
5225         return ExprError();
5226       }
5227       break;
5228     }
5229 
5230     case BadConversionSequence::lvalue_ref_to_rvalue:
5231     case BadConversionSequence::rvalue_ref_to_lvalue: {
5232       bool IsRValueQualified =
5233         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5234       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5235           << Method->getDeclName() << FromClassification.isRValue()
5236           << IsRValueQualified;
5237       Diag(Method->getLocation(), diag::note_previous_decl)
5238         << Method->getDeclName();
5239       return ExprError();
5240     }
5241 
5242     case BadConversionSequence::no_conversion:
5243     case BadConversionSequence::unrelated_class:
5244       break;
5245     }
5246 
5247     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5248            << ImplicitParamRecordType << FromRecordType
5249            << From->getSourceRange();
5250   }
5251 
5252   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5253     ExprResult FromRes =
5254       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5255     if (FromRes.isInvalid())
5256       return ExprError();
5257     From = FromRes.get();
5258   }
5259 
5260   if (!Context.hasSameType(From->getType(), DestType)) {
5261     if (From->getType().getAddressSpace() != DestType.getAddressSpace())
5262       From = ImpCastExprToType(From, DestType, CK_AddressSpaceConversion,
5263                              From->getValueKind()).get();
5264     else
5265       From = ImpCastExprToType(From, DestType, CK_NoOp,
5266                              From->getValueKind()).get();
5267   }
5268   return From;
5269 }
5270 
5271 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5272 /// expression From to bool (C++0x [conv]p3).
5273 static ImplicitConversionSequence
5274 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5275   return TryImplicitConversion(S, From, S.Context.BoolTy,
5276                                /*SuppressUserConversions=*/false,
5277                                /*AllowExplicit=*/true,
5278                                /*InOverloadResolution=*/false,
5279                                /*CStyle=*/false,
5280                                /*AllowObjCWritebackConversion=*/false,
5281                                /*AllowObjCConversionOnExplicit=*/false);
5282 }
5283 
5284 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5285 /// of the expression From to bool (C++0x [conv]p3).
5286 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5287   if (checkPlaceholderForOverload(*this, From))
5288     return ExprError();
5289 
5290   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5291   if (!ICS.isBad())
5292     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5293 
5294   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5295     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5296            << From->getType() << From->getSourceRange();
5297   return ExprError();
5298 }
5299 
5300 /// Check that the specified conversion is permitted in a converted constant
5301 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5302 /// is acceptable.
5303 static bool CheckConvertedConstantConversions(Sema &S,
5304                                               StandardConversionSequence &SCS) {
5305   // Since we know that the target type is an integral or unscoped enumeration
5306   // type, most conversion kinds are impossible. All possible First and Third
5307   // conversions are fine.
5308   switch (SCS.Second) {
5309   case ICK_Identity:
5310   case ICK_Function_Conversion:
5311   case ICK_Integral_Promotion:
5312   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5313   case ICK_Zero_Queue_Conversion:
5314     return true;
5315 
5316   case ICK_Boolean_Conversion:
5317     // Conversion from an integral or unscoped enumeration type to bool is
5318     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5319     // conversion, so we allow it in a converted constant expression.
5320     //
5321     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5322     // a lot of popular code. We should at least add a warning for this
5323     // (non-conforming) extension.
5324     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5325            SCS.getToType(2)->isBooleanType();
5326 
5327   case ICK_Pointer_Conversion:
5328   case ICK_Pointer_Member:
5329     // C++1z: null pointer conversions and null member pointer conversions are
5330     // only permitted if the source type is std::nullptr_t.
5331     return SCS.getFromType()->isNullPtrType();
5332 
5333   case ICK_Floating_Promotion:
5334   case ICK_Complex_Promotion:
5335   case ICK_Floating_Conversion:
5336   case ICK_Complex_Conversion:
5337   case ICK_Floating_Integral:
5338   case ICK_Compatible_Conversion:
5339   case ICK_Derived_To_Base:
5340   case ICK_Vector_Conversion:
5341   case ICK_Vector_Splat:
5342   case ICK_Complex_Real:
5343   case ICK_Block_Pointer_Conversion:
5344   case ICK_TransparentUnionConversion:
5345   case ICK_Writeback_Conversion:
5346   case ICK_Zero_Event_Conversion:
5347   case ICK_C_Only_Conversion:
5348   case ICK_Incompatible_Pointer_Conversion:
5349     return false;
5350 
5351   case ICK_Lvalue_To_Rvalue:
5352   case ICK_Array_To_Pointer:
5353   case ICK_Function_To_Pointer:
5354     llvm_unreachable("found a first conversion kind in Second");
5355 
5356   case ICK_Qualification:
5357     llvm_unreachable("found a third conversion kind in Second");
5358 
5359   case ICK_Num_Conversion_Kinds:
5360     break;
5361   }
5362 
5363   llvm_unreachable("unknown conversion kind");
5364 }
5365 
5366 /// CheckConvertedConstantExpression - Check that the expression From is a
5367 /// converted constant expression of type T, perform the conversion and produce
5368 /// the converted expression, per C++11 [expr.const]p3.
5369 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5370                                                    QualType T, APValue &Value,
5371                                                    Sema::CCEKind CCE,
5372                                                    bool RequireInt) {
5373   assert(S.getLangOpts().CPlusPlus11 &&
5374          "converted constant expression outside C++11");
5375 
5376   if (checkPlaceholderForOverload(S, From))
5377     return ExprError();
5378 
5379   // C++1z [expr.const]p3:
5380   //  A converted constant expression of type T is an expression,
5381   //  implicitly converted to type T, where the converted
5382   //  expression is a constant expression and the implicit conversion
5383   //  sequence contains only [... list of conversions ...].
5384   // C++1z [stmt.if]p2:
5385   //  If the if statement is of the form if constexpr, the value of the
5386   //  condition shall be a contextually converted constant expression of type
5387   //  bool.
5388   ImplicitConversionSequence ICS =
5389       CCE == Sema::CCEK_ConstexprIf
5390           ? TryContextuallyConvertToBool(S, From)
5391           : TryCopyInitialization(S, From, T,
5392                                   /*SuppressUserConversions=*/false,
5393                                   /*InOverloadResolution=*/false,
5394                                   /*AllowObjcWritebackConversion=*/false,
5395                                   /*AllowExplicit=*/false);
5396   StandardConversionSequence *SCS = nullptr;
5397   switch (ICS.getKind()) {
5398   case ImplicitConversionSequence::StandardConversion:
5399     SCS = &ICS.Standard;
5400     break;
5401   case ImplicitConversionSequence::UserDefinedConversion:
5402     // We are converting to a non-class type, so the Before sequence
5403     // must be trivial.
5404     SCS = &ICS.UserDefined.After;
5405     break;
5406   case ImplicitConversionSequence::AmbiguousConversion:
5407   case ImplicitConversionSequence::BadConversion:
5408     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5409       return S.Diag(From->getBeginLoc(),
5410                     diag::err_typecheck_converted_constant_expression)
5411              << From->getType() << From->getSourceRange() << T;
5412     return ExprError();
5413 
5414   case ImplicitConversionSequence::EllipsisConversion:
5415     llvm_unreachable("ellipsis conversion in converted constant expression");
5416   }
5417 
5418   // Check that we would only use permitted conversions.
5419   if (!CheckConvertedConstantConversions(S, *SCS)) {
5420     return S.Diag(From->getBeginLoc(),
5421                   diag::err_typecheck_converted_constant_expression_disallowed)
5422            << From->getType() << From->getSourceRange() << T;
5423   }
5424   // [...] and where the reference binding (if any) binds directly.
5425   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5426     return S.Diag(From->getBeginLoc(),
5427                   diag::err_typecheck_converted_constant_expression_indirect)
5428            << From->getType() << From->getSourceRange() << T;
5429   }
5430 
5431   ExprResult Result =
5432       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5433   if (Result.isInvalid())
5434     return Result;
5435 
5436   // Check for a narrowing implicit conversion.
5437   APValue PreNarrowingValue;
5438   QualType PreNarrowingType;
5439   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5440                                 PreNarrowingType)) {
5441   case NK_Dependent_Narrowing:
5442     // Implicit conversion to a narrower type, but the expression is
5443     // value-dependent so we can't tell whether it's actually narrowing.
5444   case NK_Variable_Narrowing:
5445     // Implicit conversion to a narrower type, and the value is not a constant
5446     // expression. We'll diagnose this in a moment.
5447   case NK_Not_Narrowing:
5448     break;
5449 
5450   case NK_Constant_Narrowing:
5451     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5452         << CCE << /*Constant*/ 1
5453         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5454     break;
5455 
5456   case NK_Type_Narrowing:
5457     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5458         << CCE << /*Constant*/ 0 << From->getType() << T;
5459     break;
5460   }
5461 
5462   if (Result.get()->isValueDependent()) {
5463     Value = APValue();
5464     return Result;
5465   }
5466 
5467   // Check the expression is a constant expression.
5468   SmallVector<PartialDiagnosticAt, 8> Notes;
5469   Expr::EvalResult Eval;
5470   Eval.Diag = &Notes;
5471   Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5472                                    ? Expr::EvaluateForMangling
5473                                    : Expr::EvaluateForCodeGen;
5474 
5475   if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5476       (RequireInt && !Eval.Val.isInt())) {
5477     // The expression can't be folded, so we can't keep it at this position in
5478     // the AST.
5479     Result = ExprError();
5480   } else {
5481     Value = Eval.Val;
5482 
5483     if (Notes.empty()) {
5484       // It's a constant expression.
5485       return ConstantExpr::Create(S.Context, Result.get());
5486     }
5487   }
5488 
5489   // It's not a constant expression. Produce an appropriate diagnostic.
5490   if (Notes.size() == 1 &&
5491       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5492     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5493   else {
5494     S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5495         << CCE << From->getSourceRange();
5496     for (unsigned I = 0; I < Notes.size(); ++I)
5497       S.Diag(Notes[I].first, Notes[I].second);
5498   }
5499   return ExprError();
5500 }
5501 
5502 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5503                                                   APValue &Value, CCEKind CCE) {
5504   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5505 }
5506 
5507 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5508                                                   llvm::APSInt &Value,
5509                                                   CCEKind CCE) {
5510   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5511 
5512   APValue V;
5513   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5514   if (!R.isInvalid() && !R.get()->isValueDependent())
5515     Value = V.getInt();
5516   return R;
5517 }
5518 
5519 
5520 /// dropPointerConversions - If the given standard conversion sequence
5521 /// involves any pointer conversions, remove them.  This may change
5522 /// the result type of the conversion sequence.
5523 static void dropPointerConversion(StandardConversionSequence &SCS) {
5524   if (SCS.Second == ICK_Pointer_Conversion) {
5525     SCS.Second = ICK_Identity;
5526     SCS.Third = ICK_Identity;
5527     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5528   }
5529 }
5530 
5531 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5532 /// convert the expression From to an Objective-C pointer type.
5533 static ImplicitConversionSequence
5534 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5535   // Do an implicit conversion to 'id'.
5536   QualType Ty = S.Context.getObjCIdType();
5537   ImplicitConversionSequence ICS
5538     = TryImplicitConversion(S, From, Ty,
5539                             // FIXME: Are these flags correct?
5540                             /*SuppressUserConversions=*/false,
5541                             /*AllowExplicit=*/true,
5542                             /*InOverloadResolution=*/false,
5543                             /*CStyle=*/false,
5544                             /*AllowObjCWritebackConversion=*/false,
5545                             /*AllowObjCConversionOnExplicit=*/true);
5546 
5547   // Strip off any final conversions to 'id'.
5548   switch (ICS.getKind()) {
5549   case ImplicitConversionSequence::BadConversion:
5550   case ImplicitConversionSequence::AmbiguousConversion:
5551   case ImplicitConversionSequence::EllipsisConversion:
5552     break;
5553 
5554   case ImplicitConversionSequence::UserDefinedConversion:
5555     dropPointerConversion(ICS.UserDefined.After);
5556     break;
5557 
5558   case ImplicitConversionSequence::StandardConversion:
5559     dropPointerConversion(ICS.Standard);
5560     break;
5561   }
5562 
5563   return ICS;
5564 }
5565 
5566 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5567 /// conversion of the expression From to an Objective-C pointer type.
5568 /// Returns a valid but null ExprResult if no conversion sequence exists.
5569 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5570   if (checkPlaceholderForOverload(*this, From))
5571     return ExprError();
5572 
5573   QualType Ty = Context.getObjCIdType();
5574   ImplicitConversionSequence ICS =
5575     TryContextuallyConvertToObjCPointer(*this, From);
5576   if (!ICS.isBad())
5577     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5578   return ExprResult();
5579 }
5580 
5581 /// Determine whether the provided type is an integral type, or an enumeration
5582 /// type of a permitted flavor.
5583 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5584   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5585                                  : T->isIntegralOrUnscopedEnumerationType();
5586 }
5587 
5588 static ExprResult
5589 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5590                             Sema::ContextualImplicitConverter &Converter,
5591                             QualType T, UnresolvedSetImpl &ViableConversions) {
5592 
5593   if (Converter.Suppress)
5594     return ExprError();
5595 
5596   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5597   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5598     CXXConversionDecl *Conv =
5599         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5600     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5601     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5602   }
5603   return From;
5604 }
5605 
5606 static bool
5607 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5608                            Sema::ContextualImplicitConverter &Converter,
5609                            QualType T, bool HadMultipleCandidates,
5610                            UnresolvedSetImpl &ExplicitConversions) {
5611   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5612     DeclAccessPair Found = ExplicitConversions[0];
5613     CXXConversionDecl *Conversion =
5614         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5615 
5616     // The user probably meant to invoke the given explicit
5617     // conversion; use it.
5618     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5619     std::string TypeStr;
5620     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5621 
5622     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5623         << FixItHint::CreateInsertion(From->getBeginLoc(),
5624                                       "static_cast<" + TypeStr + ">(")
5625         << FixItHint::CreateInsertion(
5626                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5627     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5628 
5629     // If we aren't in a SFINAE context, build a call to the
5630     // explicit conversion function.
5631     if (SemaRef.isSFINAEContext())
5632       return true;
5633 
5634     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5635     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5636                                                        HadMultipleCandidates);
5637     if (Result.isInvalid())
5638       return true;
5639     // Record usage of conversion in an implicit cast.
5640     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5641                                     CK_UserDefinedConversion, Result.get(),
5642                                     nullptr, Result.get()->getValueKind());
5643   }
5644   return false;
5645 }
5646 
5647 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5648                              Sema::ContextualImplicitConverter &Converter,
5649                              QualType T, bool HadMultipleCandidates,
5650                              DeclAccessPair &Found) {
5651   CXXConversionDecl *Conversion =
5652       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5653   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5654 
5655   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5656   if (!Converter.SuppressConversion) {
5657     if (SemaRef.isSFINAEContext())
5658       return true;
5659 
5660     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5661         << From->getSourceRange();
5662   }
5663 
5664   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5665                                                      HadMultipleCandidates);
5666   if (Result.isInvalid())
5667     return true;
5668   // Record usage of conversion in an implicit cast.
5669   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5670                                   CK_UserDefinedConversion, Result.get(),
5671                                   nullptr, Result.get()->getValueKind());
5672   return false;
5673 }
5674 
5675 static ExprResult finishContextualImplicitConversion(
5676     Sema &SemaRef, SourceLocation Loc, Expr *From,
5677     Sema::ContextualImplicitConverter &Converter) {
5678   if (!Converter.match(From->getType()) && !Converter.Suppress)
5679     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5680         << From->getSourceRange();
5681 
5682   return SemaRef.DefaultLvalueConversion(From);
5683 }
5684 
5685 static void
5686 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5687                                   UnresolvedSetImpl &ViableConversions,
5688                                   OverloadCandidateSet &CandidateSet) {
5689   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5690     DeclAccessPair FoundDecl = ViableConversions[I];
5691     NamedDecl *D = FoundDecl.getDecl();
5692     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5693     if (isa<UsingShadowDecl>(D))
5694       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5695 
5696     CXXConversionDecl *Conv;
5697     FunctionTemplateDecl *ConvTemplate;
5698     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5699       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5700     else
5701       Conv = cast<CXXConversionDecl>(D);
5702 
5703     if (ConvTemplate)
5704       SemaRef.AddTemplateConversionCandidate(
5705         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5706         /*AllowObjCConversionOnExplicit=*/false);
5707     else
5708       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5709                                      ToType, CandidateSet,
5710                                      /*AllowObjCConversionOnExplicit=*/false);
5711   }
5712 }
5713 
5714 /// Attempt to convert the given expression to a type which is accepted
5715 /// by the given converter.
5716 ///
5717 /// This routine will attempt to convert an expression of class type to a
5718 /// type accepted by the specified converter. In C++11 and before, the class
5719 /// must have a single non-explicit conversion function converting to a matching
5720 /// type. In C++1y, there can be multiple such conversion functions, but only
5721 /// one target type.
5722 ///
5723 /// \param Loc The source location of the construct that requires the
5724 /// conversion.
5725 ///
5726 /// \param From The expression we're converting from.
5727 ///
5728 /// \param Converter Used to control and diagnose the conversion process.
5729 ///
5730 /// \returns The expression, converted to an integral or enumeration type if
5731 /// successful.
5732 ExprResult Sema::PerformContextualImplicitConversion(
5733     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5734   // We can't perform any more checking for type-dependent expressions.
5735   if (From->isTypeDependent())
5736     return From;
5737 
5738   // Process placeholders immediately.
5739   if (From->hasPlaceholderType()) {
5740     ExprResult result = CheckPlaceholderExpr(From);
5741     if (result.isInvalid())
5742       return result;
5743     From = result.get();
5744   }
5745 
5746   // If the expression already has a matching type, we're golden.
5747   QualType T = From->getType();
5748   if (Converter.match(T))
5749     return DefaultLvalueConversion(From);
5750 
5751   // FIXME: Check for missing '()' if T is a function type?
5752 
5753   // We can only perform contextual implicit conversions on objects of class
5754   // type.
5755   const RecordType *RecordTy = T->getAs<RecordType>();
5756   if (!RecordTy || !getLangOpts().CPlusPlus) {
5757     if (!Converter.Suppress)
5758       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5759     return From;
5760   }
5761 
5762   // We must have a complete class type.
5763   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5764     ContextualImplicitConverter &Converter;
5765     Expr *From;
5766 
5767     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5768         : Converter(Converter), From(From) {}
5769 
5770     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5771       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5772     }
5773   } IncompleteDiagnoser(Converter, From);
5774 
5775   if (Converter.Suppress ? !isCompleteType(Loc, T)
5776                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5777     return From;
5778 
5779   // Look for a conversion to an integral or enumeration type.
5780   UnresolvedSet<4>
5781       ViableConversions; // These are *potentially* viable in C++1y.
5782   UnresolvedSet<4> ExplicitConversions;
5783   const auto &Conversions =
5784       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5785 
5786   bool HadMultipleCandidates =
5787       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5788 
5789   // To check that there is only one target type, in C++1y:
5790   QualType ToType;
5791   bool HasUniqueTargetType = true;
5792 
5793   // Collect explicit or viable (potentially in C++1y) conversions.
5794   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5795     NamedDecl *D = (*I)->getUnderlyingDecl();
5796     CXXConversionDecl *Conversion;
5797     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5798     if (ConvTemplate) {
5799       if (getLangOpts().CPlusPlus14)
5800         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5801       else
5802         continue; // C++11 does not consider conversion operator templates(?).
5803     } else
5804       Conversion = cast<CXXConversionDecl>(D);
5805 
5806     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5807            "Conversion operator templates are considered potentially "
5808            "viable in C++1y");
5809 
5810     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5811     if (Converter.match(CurToType) || ConvTemplate) {
5812 
5813       if (Conversion->isExplicit()) {
5814         // FIXME: For C++1y, do we need this restriction?
5815         // cf. diagnoseNoViableConversion()
5816         if (!ConvTemplate)
5817           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5818       } else {
5819         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5820           if (ToType.isNull())
5821             ToType = CurToType.getUnqualifiedType();
5822           else if (HasUniqueTargetType &&
5823                    (CurToType.getUnqualifiedType() != ToType))
5824             HasUniqueTargetType = false;
5825         }
5826         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5827       }
5828     }
5829   }
5830 
5831   if (getLangOpts().CPlusPlus14) {
5832     // C++1y [conv]p6:
5833     // ... An expression e of class type E appearing in such a context
5834     // is said to be contextually implicitly converted to a specified
5835     // type T and is well-formed if and only if e can be implicitly
5836     // converted to a type T that is determined as follows: E is searched
5837     // for conversion functions whose return type is cv T or reference to
5838     // cv T such that T is allowed by the context. There shall be
5839     // exactly one such T.
5840 
5841     // If no unique T is found:
5842     if (ToType.isNull()) {
5843       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5844                                      HadMultipleCandidates,
5845                                      ExplicitConversions))
5846         return ExprError();
5847       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5848     }
5849 
5850     // If more than one unique Ts are found:
5851     if (!HasUniqueTargetType)
5852       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5853                                          ViableConversions);
5854 
5855     // If one unique T is found:
5856     // First, build a candidate set from the previously recorded
5857     // potentially viable conversions.
5858     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5859     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5860                                       CandidateSet);
5861 
5862     // Then, perform overload resolution over the candidate set.
5863     OverloadCandidateSet::iterator Best;
5864     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5865     case OR_Success: {
5866       // Apply this conversion.
5867       DeclAccessPair Found =
5868           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5869       if (recordConversion(*this, Loc, From, Converter, T,
5870                            HadMultipleCandidates, Found))
5871         return ExprError();
5872       break;
5873     }
5874     case OR_Ambiguous:
5875       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5876                                          ViableConversions);
5877     case OR_No_Viable_Function:
5878       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5879                                      HadMultipleCandidates,
5880                                      ExplicitConversions))
5881         return ExprError();
5882       LLVM_FALLTHROUGH;
5883     case OR_Deleted:
5884       // We'll complain below about a non-integral condition type.
5885       break;
5886     }
5887   } else {
5888     switch (ViableConversions.size()) {
5889     case 0: {
5890       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5891                                      HadMultipleCandidates,
5892                                      ExplicitConversions))
5893         return ExprError();
5894 
5895       // We'll complain below about a non-integral condition type.
5896       break;
5897     }
5898     case 1: {
5899       // Apply this conversion.
5900       DeclAccessPair Found = ViableConversions[0];
5901       if (recordConversion(*this, Loc, From, Converter, T,
5902                            HadMultipleCandidates, Found))
5903         return ExprError();
5904       break;
5905     }
5906     default:
5907       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5908                                          ViableConversions);
5909     }
5910   }
5911 
5912   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5913 }
5914 
5915 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5916 /// an acceptable non-member overloaded operator for a call whose
5917 /// arguments have types T1 (and, if non-empty, T2). This routine
5918 /// implements the check in C++ [over.match.oper]p3b2 concerning
5919 /// enumeration types.
5920 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5921                                                    FunctionDecl *Fn,
5922                                                    ArrayRef<Expr *> Args) {
5923   QualType T1 = Args[0]->getType();
5924   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5925 
5926   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5927     return true;
5928 
5929   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5930     return true;
5931 
5932   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5933   if (Proto->getNumParams() < 1)
5934     return false;
5935 
5936   if (T1->isEnumeralType()) {
5937     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5938     if (Context.hasSameUnqualifiedType(T1, ArgType))
5939       return true;
5940   }
5941 
5942   if (Proto->getNumParams() < 2)
5943     return false;
5944 
5945   if (!T2.isNull() && T2->isEnumeralType()) {
5946     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5947     if (Context.hasSameUnqualifiedType(T2, ArgType))
5948       return true;
5949   }
5950 
5951   return false;
5952 }
5953 
5954 /// AddOverloadCandidate - Adds the given function to the set of
5955 /// candidate functions, using the given function call arguments.  If
5956 /// @p SuppressUserConversions, then don't allow user-defined
5957 /// conversions via constructors or conversion operators.
5958 ///
5959 /// \param PartialOverloading true if we are performing "partial" overloading
5960 /// based on an incomplete set of function arguments. This feature is used by
5961 /// code completion.
5962 void Sema::AddOverloadCandidate(FunctionDecl *Function,
5963                                 DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
5964                                 OverloadCandidateSet &CandidateSet,
5965                                 bool SuppressUserConversions,
5966                                 bool PartialOverloading, bool AllowExplicit,
5967                                 ADLCallKind IsADLCandidate,
5968                                 ConversionSequenceList EarlyConversions) {
5969   const FunctionProtoType *Proto
5970     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5971   assert(Proto && "Functions without a prototype cannot be overloaded");
5972   assert(!Function->getDescribedFunctionTemplate() &&
5973          "Use AddTemplateOverloadCandidate for function templates");
5974 
5975   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5976     if (!isa<CXXConstructorDecl>(Method)) {
5977       // If we get here, it's because we're calling a member function
5978       // that is named without a member access expression (e.g.,
5979       // "this->f") that was either written explicitly or created
5980       // implicitly. This can happen with a qualified call to a member
5981       // function, e.g., X::f(). We use an empty type for the implied
5982       // object argument (C++ [over.call.func]p3), and the acting context
5983       // is irrelevant.
5984       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
5985                          Expr::Classification::makeSimpleLValue(), Args,
5986                          CandidateSet, SuppressUserConversions,
5987                          PartialOverloading, EarlyConversions);
5988       return;
5989     }
5990     // We treat a constructor like a non-member function, since its object
5991     // argument doesn't participate in overload resolution.
5992   }
5993 
5994   if (!CandidateSet.isNewCandidate(Function))
5995     return;
5996 
5997   // C++ [over.match.oper]p3:
5998   //   if no operand has a class type, only those non-member functions in the
5999   //   lookup set that have a first parameter of type T1 or "reference to
6000   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6001   //   is a right operand) a second parameter of type T2 or "reference to
6002   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
6003   //   candidate functions.
6004   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6005       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6006     return;
6007 
6008   // C++11 [class.copy]p11: [DR1402]
6009   //   A defaulted move constructor that is defined as deleted is ignored by
6010   //   overload resolution.
6011   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6012   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6013       Constructor->isMoveConstructor())
6014     return;
6015 
6016   // Overload resolution is always an unevaluated context.
6017   EnterExpressionEvaluationContext Unevaluated(
6018       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6019 
6020   // Add this candidate
6021   OverloadCandidate &Candidate =
6022       CandidateSet.addCandidate(Args.size(), EarlyConversions);
6023   Candidate.FoundDecl = FoundDecl;
6024   Candidate.Function = Function;
6025   Candidate.Viable = true;
6026   Candidate.IsSurrogate = false;
6027   Candidate.IsADLCandidate = IsADLCandidate;
6028   Candidate.IgnoreObjectArgument = false;
6029   Candidate.ExplicitCallArguments = Args.size();
6030 
6031   if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6032       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6033     Candidate.Viable = false;
6034     Candidate.FailureKind = ovl_non_default_multiversion_function;
6035     return;
6036   }
6037 
6038   if (Constructor) {
6039     // C++ [class.copy]p3:
6040     //   A member function template is never instantiated to perform the copy
6041     //   of a class object to an object of its class type.
6042     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6043     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6044         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6045          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6046                        ClassType))) {
6047       Candidate.Viable = false;
6048       Candidate.FailureKind = ovl_fail_illegal_constructor;
6049       return;
6050     }
6051 
6052     // C++ [over.match.funcs]p8: (proposed DR resolution)
6053     //   A constructor inherited from class type C that has a first parameter
6054     //   of type "reference to P" (including such a constructor instantiated
6055     //   from a template) is excluded from the set of candidate functions when
6056     //   constructing an object of type cv D if the argument list has exactly
6057     //   one argument and D is reference-related to P and P is reference-related
6058     //   to C.
6059     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6060     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6061         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6062       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6063       QualType C = Context.getRecordType(Constructor->getParent());
6064       QualType D = Context.getRecordType(Shadow->getParent());
6065       SourceLocation Loc = Args.front()->getExprLoc();
6066       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6067           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6068         Candidate.Viable = false;
6069         Candidate.FailureKind = ovl_fail_inhctor_slice;
6070         return;
6071       }
6072     }
6073   }
6074 
6075   unsigned NumParams = Proto->getNumParams();
6076 
6077   // (C++ 13.3.2p2): A candidate function having fewer than m
6078   // parameters is viable only if it has an ellipsis in its parameter
6079   // list (8.3.5).
6080   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6081       !Proto->isVariadic()) {
6082     Candidate.Viable = false;
6083     Candidate.FailureKind = ovl_fail_too_many_arguments;
6084     return;
6085   }
6086 
6087   // (C++ 13.3.2p2): A candidate function having more than m parameters
6088   // is viable only if the (m+1)st parameter has a default argument
6089   // (8.3.6). For the purposes of overload resolution, the
6090   // parameter list is truncated on the right, so that there are
6091   // exactly m parameters.
6092   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6093   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6094     // Not enough arguments.
6095     Candidate.Viable = false;
6096     Candidate.FailureKind = ovl_fail_too_few_arguments;
6097     return;
6098   }
6099 
6100   // (CUDA B.1): Check for invalid calls between targets.
6101   if (getLangOpts().CUDA)
6102     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6103       // Skip the check for callers that are implicit members, because in this
6104       // case we may not yet know what the member's target is; the target is
6105       // inferred for the member automatically, based on the bases and fields of
6106       // the class.
6107       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6108         Candidate.Viable = false;
6109         Candidate.FailureKind = ovl_fail_bad_target;
6110         return;
6111       }
6112 
6113   // Determine the implicit conversion sequences for each of the
6114   // arguments.
6115   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6116     if (Candidate.Conversions[ArgIdx].isInitialized()) {
6117       // We already formed a conversion sequence for this parameter during
6118       // template argument deduction.
6119     } else if (ArgIdx < NumParams) {
6120       // (C++ 13.3.2p3): for F to be a viable function, there shall
6121       // exist for each argument an implicit conversion sequence
6122       // (13.3.3.1) that converts that argument to the corresponding
6123       // parameter of F.
6124       QualType ParamType = Proto->getParamType(ArgIdx);
6125       Candidate.Conversions[ArgIdx]
6126         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6127                                 SuppressUserConversions,
6128                                 /*InOverloadResolution=*/true,
6129                                 /*AllowObjCWritebackConversion=*/
6130                                   getLangOpts().ObjCAutoRefCount,
6131                                 AllowExplicit);
6132       if (Candidate.Conversions[ArgIdx].isBad()) {
6133         Candidate.Viable = false;
6134         Candidate.FailureKind = ovl_fail_bad_conversion;
6135         return;
6136       }
6137     } else {
6138       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6139       // argument for which there is no corresponding parameter is
6140       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6141       Candidate.Conversions[ArgIdx].setEllipsis();
6142     }
6143   }
6144 
6145   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6146     Candidate.Viable = false;
6147     Candidate.FailureKind = ovl_fail_enable_if;
6148     Candidate.DeductionFailure.Data = FailedAttr;
6149     return;
6150   }
6151 
6152   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6153     Candidate.Viable = false;
6154     Candidate.FailureKind = ovl_fail_ext_disabled;
6155     return;
6156   }
6157 }
6158 
6159 ObjCMethodDecl *
6160 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6161                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6162   if (Methods.size() <= 1)
6163     return nullptr;
6164 
6165   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6166     bool Match = true;
6167     ObjCMethodDecl *Method = Methods[b];
6168     unsigned NumNamedArgs = Sel.getNumArgs();
6169     // Method might have more arguments than selector indicates. This is due
6170     // to addition of c-style arguments in method.
6171     if (Method->param_size() > NumNamedArgs)
6172       NumNamedArgs = Method->param_size();
6173     if (Args.size() < NumNamedArgs)
6174       continue;
6175 
6176     for (unsigned i = 0; i < NumNamedArgs; i++) {
6177       // We can't do any type-checking on a type-dependent argument.
6178       if (Args[i]->isTypeDependent()) {
6179         Match = false;
6180         break;
6181       }
6182 
6183       ParmVarDecl *param = Method->parameters()[i];
6184       Expr *argExpr = Args[i];
6185       assert(argExpr && "SelectBestMethod(): missing expression");
6186 
6187       // Strip the unbridged-cast placeholder expression off unless it's
6188       // a consumed argument.
6189       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6190           !param->hasAttr<CFConsumedAttr>())
6191         argExpr = stripARCUnbridgedCast(argExpr);
6192 
6193       // If the parameter is __unknown_anytype, move on to the next method.
6194       if (param->getType() == Context.UnknownAnyTy) {
6195         Match = false;
6196         break;
6197       }
6198 
6199       ImplicitConversionSequence ConversionState
6200         = TryCopyInitialization(*this, argExpr, param->getType(),
6201                                 /*SuppressUserConversions*/false,
6202                                 /*InOverloadResolution=*/true,
6203                                 /*AllowObjCWritebackConversion=*/
6204                                 getLangOpts().ObjCAutoRefCount,
6205                                 /*AllowExplicit*/false);
6206       // This function looks for a reasonably-exact match, so we consider
6207       // incompatible pointer conversions to be a failure here.
6208       if (ConversionState.isBad() ||
6209           (ConversionState.isStandard() &&
6210            ConversionState.Standard.Second ==
6211                ICK_Incompatible_Pointer_Conversion)) {
6212         Match = false;
6213         break;
6214       }
6215     }
6216     // Promote additional arguments to variadic methods.
6217     if (Match && Method->isVariadic()) {
6218       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6219         if (Args[i]->isTypeDependent()) {
6220           Match = false;
6221           break;
6222         }
6223         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6224                                                           nullptr);
6225         if (Arg.isInvalid()) {
6226           Match = false;
6227           break;
6228         }
6229       }
6230     } else {
6231       // Check for extra arguments to non-variadic methods.
6232       if (Args.size() != NumNamedArgs)
6233         Match = false;
6234       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6235         // Special case when selectors have no argument. In this case, select
6236         // one with the most general result type of 'id'.
6237         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6238           QualType ReturnT = Methods[b]->getReturnType();
6239           if (ReturnT->isObjCIdType())
6240             return Methods[b];
6241         }
6242       }
6243     }
6244 
6245     if (Match)
6246       return Method;
6247   }
6248   return nullptr;
6249 }
6250 
6251 static bool
6252 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6253                                  ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6254                                  bool MissingImplicitThis, Expr *&ConvertedThis,
6255                                  SmallVectorImpl<Expr *> &ConvertedArgs) {
6256   if (ThisArg) {
6257     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6258     assert(!isa<CXXConstructorDecl>(Method) &&
6259            "Shouldn't have `this` for ctors!");
6260     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6261     ExprResult R = S.PerformObjectArgumentInitialization(
6262         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6263     if (R.isInvalid())
6264       return false;
6265     ConvertedThis = R.get();
6266   } else {
6267     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6268       (void)MD;
6269       assert((MissingImplicitThis || MD->isStatic() ||
6270               isa<CXXConstructorDecl>(MD)) &&
6271              "Expected `this` for non-ctor instance methods");
6272     }
6273     ConvertedThis = nullptr;
6274   }
6275 
6276   // Ignore any variadic arguments. Converting them is pointless, since the
6277   // user can't refer to them in the function condition.
6278   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6279 
6280   // Convert the arguments.
6281   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6282     ExprResult R;
6283     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6284                                         S.Context, Function->getParamDecl(I)),
6285                                     SourceLocation(), Args[I]);
6286 
6287     if (R.isInvalid())
6288       return false;
6289 
6290     ConvertedArgs.push_back(R.get());
6291   }
6292 
6293   if (Trap.hasErrorOccurred())
6294     return false;
6295 
6296   // Push default arguments if needed.
6297   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6298     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6299       ParmVarDecl *P = Function->getParamDecl(i);
6300       Expr *DefArg = P->hasUninstantiatedDefaultArg()
6301                          ? P->getUninstantiatedDefaultArg()
6302                          : P->getDefaultArg();
6303       // This can only happen in code completion, i.e. when PartialOverloading
6304       // is true.
6305       if (!DefArg)
6306         return false;
6307       ExprResult R =
6308           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6309                                           S.Context, Function->getParamDecl(i)),
6310                                       SourceLocation(), DefArg);
6311       if (R.isInvalid())
6312         return false;
6313       ConvertedArgs.push_back(R.get());
6314     }
6315 
6316     if (Trap.hasErrorOccurred())
6317       return false;
6318   }
6319   return true;
6320 }
6321 
6322 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6323                                   bool MissingImplicitThis) {
6324   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6325   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6326     return nullptr;
6327 
6328   SFINAETrap Trap(*this);
6329   SmallVector<Expr *, 16> ConvertedArgs;
6330   // FIXME: We should look into making enable_if late-parsed.
6331   Expr *DiscardedThis;
6332   if (!convertArgsForAvailabilityChecks(
6333           *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6334           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6335     return *EnableIfAttrs.begin();
6336 
6337   for (auto *EIA : EnableIfAttrs) {
6338     APValue Result;
6339     // FIXME: This doesn't consider value-dependent cases, because doing so is
6340     // very difficult. Ideally, we should handle them more gracefully.
6341     if (!EIA->getCond()->EvaluateWithSubstitution(
6342             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6343       return EIA;
6344 
6345     if (!Result.isInt() || !Result.getInt().getBoolValue())
6346       return EIA;
6347   }
6348   return nullptr;
6349 }
6350 
6351 template <typename CheckFn>
6352 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6353                                         bool ArgDependent, SourceLocation Loc,
6354                                         CheckFn &&IsSuccessful) {
6355   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6356   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6357     if (ArgDependent == DIA->getArgDependent())
6358       Attrs.push_back(DIA);
6359   }
6360 
6361   // Common case: No diagnose_if attributes, so we can quit early.
6362   if (Attrs.empty())
6363     return false;
6364 
6365   auto WarningBegin = std::stable_partition(
6366       Attrs.begin(), Attrs.end(),
6367       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6368 
6369   // Note that diagnose_if attributes are late-parsed, so they appear in the
6370   // correct order (unlike enable_if attributes).
6371   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6372                                IsSuccessful);
6373   if (ErrAttr != WarningBegin) {
6374     const DiagnoseIfAttr *DIA = *ErrAttr;
6375     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6376     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6377         << DIA->getParent() << DIA->getCond()->getSourceRange();
6378     return true;
6379   }
6380 
6381   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6382     if (IsSuccessful(DIA)) {
6383       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6384       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6385           << DIA->getParent() << DIA->getCond()->getSourceRange();
6386     }
6387 
6388   return false;
6389 }
6390 
6391 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6392                                                const Expr *ThisArg,
6393                                                ArrayRef<const Expr *> Args,
6394                                                SourceLocation Loc) {
6395   return diagnoseDiagnoseIfAttrsWith(
6396       *this, Function, /*ArgDependent=*/true, Loc,
6397       [&](const DiagnoseIfAttr *DIA) {
6398         APValue Result;
6399         // It's sane to use the same Args for any redecl of this function, since
6400         // EvaluateWithSubstitution only cares about the position of each
6401         // argument in the arg list, not the ParmVarDecl* it maps to.
6402         if (!DIA->getCond()->EvaluateWithSubstitution(
6403                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6404           return false;
6405         return Result.isInt() && Result.getInt().getBoolValue();
6406       });
6407 }
6408 
6409 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6410                                                  SourceLocation Loc) {
6411   return diagnoseDiagnoseIfAttrsWith(
6412       *this, ND, /*ArgDependent=*/false, Loc,
6413       [&](const DiagnoseIfAttr *DIA) {
6414         bool Result;
6415         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6416                Result;
6417       });
6418 }
6419 
6420 /// Add all of the function declarations in the given function set to
6421 /// the overload candidate set.
6422 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6423                                  ArrayRef<Expr *> Args,
6424                                  OverloadCandidateSet &CandidateSet,
6425                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6426                                  bool SuppressUserConversions,
6427                                  bool PartialOverloading,
6428                                  bool FirstArgumentIsBase) {
6429   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6430     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6431     ArrayRef<Expr *> FunctionArgs = Args;
6432 
6433     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6434     FunctionDecl *FD =
6435         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6436 
6437     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6438       QualType ObjectType;
6439       Expr::Classification ObjectClassification;
6440       if (Args.size() > 0) {
6441         if (Expr *E = Args[0]) {
6442           // Use the explicit base to restrict the lookup:
6443           ObjectType = E->getType();
6444           // Pointers in the object arguments are implicitly dereferenced, so we
6445           // always classify them as l-values.
6446           if (!ObjectType.isNull() && ObjectType->isPointerType())
6447             ObjectClassification = Expr::Classification::makeSimpleLValue();
6448           else
6449             ObjectClassification = E->Classify(Context);
6450         } // .. else there is an implicit base.
6451         FunctionArgs = Args.slice(1);
6452       }
6453       if (FunTmpl) {
6454         AddMethodTemplateCandidate(
6455             FunTmpl, F.getPair(),
6456             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6457             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6458             FunctionArgs, CandidateSet, SuppressUserConversions,
6459             PartialOverloading);
6460       } else {
6461         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6462                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6463                            ObjectClassification, FunctionArgs, CandidateSet,
6464                            SuppressUserConversions, PartialOverloading);
6465       }
6466     } else {
6467       // This branch handles both standalone functions and static methods.
6468 
6469       // Slice the first argument (which is the base) when we access
6470       // static method as non-static.
6471       if (Args.size() > 0 &&
6472           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6473                         !isa<CXXConstructorDecl>(FD)))) {
6474         assert(cast<CXXMethodDecl>(FD)->isStatic());
6475         FunctionArgs = Args.slice(1);
6476       }
6477       if (FunTmpl) {
6478         AddTemplateOverloadCandidate(
6479             FunTmpl, F.getPair(), ExplicitTemplateArgs, FunctionArgs,
6480             CandidateSet, SuppressUserConversions, PartialOverloading);
6481       } else {
6482         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6483                              SuppressUserConversions, PartialOverloading);
6484       }
6485     }
6486   }
6487 }
6488 
6489 /// AddMethodCandidate - Adds a named decl (which is some kind of
6490 /// method) as a method candidate to the given overload set.
6491 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6492                               QualType ObjectType,
6493                               Expr::Classification ObjectClassification,
6494                               ArrayRef<Expr *> Args,
6495                               OverloadCandidateSet& CandidateSet,
6496                               bool SuppressUserConversions) {
6497   NamedDecl *Decl = FoundDecl.getDecl();
6498   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6499 
6500   if (isa<UsingShadowDecl>(Decl))
6501     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6502 
6503   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6504     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6505            "Expected a member function template");
6506     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6507                                /*ExplicitArgs*/ nullptr, ObjectType,
6508                                ObjectClassification, Args, CandidateSet,
6509                                SuppressUserConversions);
6510   } else {
6511     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6512                        ObjectType, ObjectClassification, Args, CandidateSet,
6513                        SuppressUserConversions);
6514   }
6515 }
6516 
6517 /// AddMethodCandidate - Adds the given C++ member function to the set
6518 /// of candidate functions, using the given function call arguments
6519 /// and the object argument (@c Object). For example, in a call
6520 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6521 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6522 /// allow user-defined conversions via constructors or conversion
6523 /// operators.
6524 void
6525 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6526                          CXXRecordDecl *ActingContext, QualType ObjectType,
6527                          Expr::Classification ObjectClassification,
6528                          ArrayRef<Expr *> Args,
6529                          OverloadCandidateSet &CandidateSet,
6530                          bool SuppressUserConversions,
6531                          bool PartialOverloading,
6532                          ConversionSequenceList EarlyConversions) {
6533   const FunctionProtoType *Proto
6534     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6535   assert(Proto && "Methods without a prototype cannot be overloaded");
6536   assert(!isa<CXXConstructorDecl>(Method) &&
6537          "Use AddOverloadCandidate for constructors");
6538 
6539   if (!CandidateSet.isNewCandidate(Method))
6540     return;
6541 
6542   // C++11 [class.copy]p23: [DR1402]
6543   //   A defaulted move assignment operator that is defined as deleted is
6544   //   ignored by overload resolution.
6545   if (Method->isDefaulted() && Method->isDeleted() &&
6546       Method->isMoveAssignmentOperator())
6547     return;
6548 
6549   // Overload resolution is always an unevaluated context.
6550   EnterExpressionEvaluationContext Unevaluated(
6551       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6552 
6553   // Add this candidate
6554   OverloadCandidate &Candidate =
6555       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6556   Candidate.FoundDecl = FoundDecl;
6557   Candidate.Function = Method;
6558   Candidate.IsSurrogate = false;
6559   Candidate.IgnoreObjectArgument = false;
6560   Candidate.ExplicitCallArguments = Args.size();
6561 
6562   unsigned NumParams = Proto->getNumParams();
6563 
6564   // (C++ 13.3.2p2): A candidate function having fewer than m
6565   // parameters is viable only if it has an ellipsis in its parameter
6566   // list (8.3.5).
6567   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6568       !Proto->isVariadic()) {
6569     Candidate.Viable = false;
6570     Candidate.FailureKind = ovl_fail_too_many_arguments;
6571     return;
6572   }
6573 
6574   // (C++ 13.3.2p2): A candidate function having more than m parameters
6575   // is viable only if the (m+1)st parameter has a default argument
6576   // (8.3.6). For the purposes of overload resolution, the
6577   // parameter list is truncated on the right, so that there are
6578   // exactly m parameters.
6579   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6580   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6581     // Not enough arguments.
6582     Candidate.Viable = false;
6583     Candidate.FailureKind = ovl_fail_too_few_arguments;
6584     return;
6585   }
6586 
6587   Candidate.Viable = true;
6588 
6589   if (Method->isStatic() || ObjectType.isNull())
6590     // The implicit object argument is ignored.
6591     Candidate.IgnoreObjectArgument = true;
6592   else {
6593     // Determine the implicit conversion sequence for the object
6594     // parameter.
6595     Candidate.Conversions[0] = TryObjectArgumentInitialization(
6596         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6597         Method, ActingContext);
6598     if (Candidate.Conversions[0].isBad()) {
6599       Candidate.Viable = false;
6600       Candidate.FailureKind = ovl_fail_bad_conversion;
6601       return;
6602     }
6603   }
6604 
6605   // (CUDA B.1): Check for invalid calls between targets.
6606   if (getLangOpts().CUDA)
6607     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6608       if (!IsAllowedCUDACall(Caller, Method)) {
6609         Candidate.Viable = false;
6610         Candidate.FailureKind = ovl_fail_bad_target;
6611         return;
6612       }
6613 
6614   // Determine the implicit conversion sequences for each of the
6615   // arguments.
6616   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6617     if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6618       // We already formed a conversion sequence for this parameter during
6619       // template argument deduction.
6620     } else if (ArgIdx < NumParams) {
6621       // (C++ 13.3.2p3): for F to be a viable function, there shall
6622       // exist for each argument an implicit conversion sequence
6623       // (13.3.3.1) that converts that argument to the corresponding
6624       // parameter of F.
6625       QualType ParamType = Proto->getParamType(ArgIdx);
6626       Candidate.Conversions[ArgIdx + 1]
6627         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6628                                 SuppressUserConversions,
6629                                 /*InOverloadResolution=*/true,
6630                                 /*AllowObjCWritebackConversion=*/
6631                                   getLangOpts().ObjCAutoRefCount);
6632       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6633         Candidate.Viable = false;
6634         Candidate.FailureKind = ovl_fail_bad_conversion;
6635         return;
6636       }
6637     } else {
6638       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6639       // argument for which there is no corresponding parameter is
6640       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6641       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6642     }
6643   }
6644 
6645   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6646     Candidate.Viable = false;
6647     Candidate.FailureKind = ovl_fail_enable_if;
6648     Candidate.DeductionFailure.Data = FailedAttr;
6649     return;
6650   }
6651 
6652   if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6653       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6654     Candidate.Viable = false;
6655     Candidate.FailureKind = ovl_non_default_multiversion_function;
6656   }
6657 }
6658 
6659 /// Add a C++ member function template as a candidate to the candidate
6660 /// set, using template argument deduction to produce an appropriate member
6661 /// function template specialization.
6662 void
6663 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6664                                  DeclAccessPair FoundDecl,
6665                                  CXXRecordDecl *ActingContext,
6666                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6667                                  QualType ObjectType,
6668                                  Expr::Classification ObjectClassification,
6669                                  ArrayRef<Expr *> Args,
6670                                  OverloadCandidateSet& CandidateSet,
6671                                  bool SuppressUserConversions,
6672                                  bool PartialOverloading) {
6673   if (!CandidateSet.isNewCandidate(MethodTmpl))
6674     return;
6675 
6676   // C++ [over.match.funcs]p7:
6677   //   In each case where a candidate is a function template, candidate
6678   //   function template specializations are generated using template argument
6679   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6680   //   candidate functions in the usual way.113) A given name can refer to one
6681   //   or more function templates and also to a set of overloaded non-template
6682   //   functions. In such a case, the candidate functions generated from each
6683   //   function template are combined with the set of non-template candidate
6684   //   functions.
6685   TemplateDeductionInfo Info(CandidateSet.getLocation());
6686   FunctionDecl *Specialization = nullptr;
6687   ConversionSequenceList Conversions;
6688   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6689           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6690           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6691             return CheckNonDependentConversions(
6692                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6693                 SuppressUserConversions, ActingContext, ObjectType,
6694                 ObjectClassification);
6695           })) {
6696     OverloadCandidate &Candidate =
6697         CandidateSet.addCandidate(Conversions.size(), Conversions);
6698     Candidate.FoundDecl = FoundDecl;
6699     Candidate.Function = MethodTmpl->getTemplatedDecl();
6700     Candidate.Viable = false;
6701     Candidate.IsSurrogate = false;
6702     Candidate.IgnoreObjectArgument =
6703         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6704         ObjectType.isNull();
6705     Candidate.ExplicitCallArguments = Args.size();
6706     if (Result == TDK_NonDependentConversionFailure)
6707       Candidate.FailureKind = ovl_fail_bad_conversion;
6708     else {
6709       Candidate.FailureKind = ovl_fail_bad_deduction;
6710       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6711                                                             Info);
6712     }
6713     return;
6714   }
6715 
6716   // Add the function template specialization produced by template argument
6717   // deduction as a candidate.
6718   assert(Specialization && "Missing member function template specialization?");
6719   assert(isa<CXXMethodDecl>(Specialization) &&
6720          "Specialization is not a member function?");
6721   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6722                      ActingContext, ObjectType, ObjectClassification, Args,
6723                      CandidateSet, SuppressUserConversions, PartialOverloading,
6724                      Conversions);
6725 }
6726 
6727 /// Add a C++ function template specialization as a candidate
6728 /// in the candidate set, using template argument deduction to produce
6729 /// an appropriate function template specialization.
6730 void Sema::AddTemplateOverloadCandidate(
6731     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
6732     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6733     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6734     bool PartialOverloading, ADLCallKind IsADLCandidate) {
6735   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6736     return;
6737 
6738   // C++ [over.match.funcs]p7:
6739   //   In each case where a candidate is a function template, candidate
6740   //   function template specializations are generated using template argument
6741   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6742   //   candidate functions in the usual way.113) A given name can refer to one
6743   //   or more function templates and also to a set of overloaded non-template
6744   //   functions. In such a case, the candidate functions generated from each
6745   //   function template are combined with the set of non-template candidate
6746   //   functions.
6747   TemplateDeductionInfo Info(CandidateSet.getLocation());
6748   FunctionDecl *Specialization = nullptr;
6749   ConversionSequenceList Conversions;
6750   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6751           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6752           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6753             return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6754                                                 Args, CandidateSet, Conversions,
6755                                                 SuppressUserConversions);
6756           })) {
6757     OverloadCandidate &Candidate =
6758         CandidateSet.addCandidate(Conversions.size(), Conversions);
6759     Candidate.FoundDecl = FoundDecl;
6760     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6761     Candidate.Viable = false;
6762     Candidate.IsSurrogate = false;
6763     Candidate.IsADLCandidate = IsADLCandidate;
6764     // Ignore the object argument if there is one, since we don't have an object
6765     // type.
6766     Candidate.IgnoreObjectArgument =
6767         isa<CXXMethodDecl>(Candidate.Function) &&
6768         !isa<CXXConstructorDecl>(Candidate.Function);
6769     Candidate.ExplicitCallArguments = Args.size();
6770     if (Result == TDK_NonDependentConversionFailure)
6771       Candidate.FailureKind = ovl_fail_bad_conversion;
6772     else {
6773       Candidate.FailureKind = ovl_fail_bad_deduction;
6774       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6775                                                             Info);
6776     }
6777     return;
6778   }
6779 
6780   // Add the function template specialization produced by template argument
6781   // deduction as a candidate.
6782   assert(Specialization && "Missing function template specialization?");
6783   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6784                        SuppressUserConversions, PartialOverloading,
6785                        /*AllowExplicit*/ false, IsADLCandidate, Conversions);
6786 }
6787 
6788 /// Check that implicit conversion sequences can be formed for each argument
6789 /// whose corresponding parameter has a non-dependent type, per DR1391's
6790 /// [temp.deduct.call]p10.
6791 bool Sema::CheckNonDependentConversions(
6792     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6793     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6794     ConversionSequenceList &Conversions, bool SuppressUserConversions,
6795     CXXRecordDecl *ActingContext, QualType ObjectType,
6796     Expr::Classification ObjectClassification) {
6797   // FIXME: The cases in which we allow explicit conversions for constructor
6798   // arguments never consider calling a constructor template. It's not clear
6799   // that is correct.
6800   const bool AllowExplicit = false;
6801 
6802   auto *FD = FunctionTemplate->getTemplatedDecl();
6803   auto *Method = dyn_cast<CXXMethodDecl>(FD);
6804   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6805   unsigned ThisConversions = HasThisConversion ? 1 : 0;
6806 
6807   Conversions =
6808       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6809 
6810   // Overload resolution is always an unevaluated context.
6811   EnterExpressionEvaluationContext Unevaluated(
6812       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6813 
6814   // For a method call, check the 'this' conversion here too. DR1391 doesn't
6815   // require that, but this check should never result in a hard error, and
6816   // overload resolution is permitted to sidestep instantiations.
6817   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6818       !ObjectType.isNull()) {
6819     Conversions[0] = TryObjectArgumentInitialization(
6820         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6821         Method, ActingContext);
6822     if (Conversions[0].isBad())
6823       return true;
6824   }
6825 
6826   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6827        ++I) {
6828     QualType ParamType = ParamTypes[I];
6829     if (!ParamType->isDependentType()) {
6830       Conversions[ThisConversions + I]
6831         = TryCopyInitialization(*this, Args[I], ParamType,
6832                                 SuppressUserConversions,
6833                                 /*InOverloadResolution=*/true,
6834                                 /*AllowObjCWritebackConversion=*/
6835                                   getLangOpts().ObjCAutoRefCount,
6836                                 AllowExplicit);
6837       if (Conversions[ThisConversions + I].isBad())
6838         return true;
6839     }
6840   }
6841 
6842   return false;
6843 }
6844 
6845 /// Determine whether this is an allowable conversion from the result
6846 /// of an explicit conversion operator to the expected type, per C++
6847 /// [over.match.conv]p1 and [over.match.ref]p1.
6848 ///
6849 /// \param ConvType The return type of the conversion function.
6850 ///
6851 /// \param ToType The type we are converting to.
6852 ///
6853 /// \param AllowObjCPointerConversion Allow a conversion from one
6854 /// Objective-C pointer to another.
6855 ///
6856 /// \returns true if the conversion is allowable, false otherwise.
6857 static bool isAllowableExplicitConversion(Sema &S,
6858                                           QualType ConvType, QualType ToType,
6859                                           bool AllowObjCPointerConversion) {
6860   QualType ToNonRefType = ToType.getNonReferenceType();
6861 
6862   // Easy case: the types are the same.
6863   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6864     return true;
6865 
6866   // Allow qualification conversions.
6867   bool ObjCLifetimeConversion;
6868   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6869                                   ObjCLifetimeConversion))
6870     return true;
6871 
6872   // If we're not allowed to consider Objective-C pointer conversions,
6873   // we're done.
6874   if (!AllowObjCPointerConversion)
6875     return false;
6876 
6877   // Is this an Objective-C pointer conversion?
6878   bool IncompatibleObjC = false;
6879   QualType ConvertedType;
6880   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6881                                    IncompatibleObjC);
6882 }
6883 
6884 /// AddConversionCandidate - Add a C++ conversion function as a
6885 /// candidate in the candidate set (C++ [over.match.conv],
6886 /// C++ [over.match.copy]). From is the expression we're converting from,
6887 /// and ToType is the type that we're eventually trying to convert to
6888 /// (which may or may not be the same type as the type that the
6889 /// conversion function produces).
6890 void
6891 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6892                              DeclAccessPair FoundDecl,
6893                              CXXRecordDecl *ActingContext,
6894                              Expr *From, QualType ToType,
6895                              OverloadCandidateSet& CandidateSet,
6896                              bool AllowObjCConversionOnExplicit,
6897                              bool AllowResultConversion) {
6898   assert(!Conversion->getDescribedFunctionTemplate() &&
6899          "Conversion function templates use AddTemplateConversionCandidate");
6900   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6901   if (!CandidateSet.isNewCandidate(Conversion))
6902     return;
6903 
6904   // If the conversion function has an undeduced return type, trigger its
6905   // deduction now.
6906   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6907     if (DeduceReturnType(Conversion, From->getExprLoc()))
6908       return;
6909     ConvType = Conversion->getConversionType().getNonReferenceType();
6910   }
6911 
6912   // If we don't allow any conversion of the result type, ignore conversion
6913   // functions that don't convert to exactly (possibly cv-qualified) T.
6914   if (!AllowResultConversion &&
6915       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
6916     return;
6917 
6918   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6919   // operator is only a candidate if its return type is the target type or
6920   // can be converted to the target type with a qualification conversion.
6921   if (Conversion->isExplicit() &&
6922       !isAllowableExplicitConversion(*this, ConvType, ToType,
6923                                      AllowObjCConversionOnExplicit))
6924     return;
6925 
6926   // Overload resolution is always an unevaluated context.
6927   EnterExpressionEvaluationContext Unevaluated(
6928       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6929 
6930   // Add this candidate
6931   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6932   Candidate.FoundDecl = FoundDecl;
6933   Candidate.Function = Conversion;
6934   Candidate.IsSurrogate = false;
6935   Candidate.IgnoreObjectArgument = false;
6936   Candidate.FinalConversion.setAsIdentityConversion();
6937   Candidate.FinalConversion.setFromType(ConvType);
6938   Candidate.FinalConversion.setAllToTypes(ToType);
6939   Candidate.Viable = true;
6940   Candidate.ExplicitCallArguments = 1;
6941 
6942   // C++ [over.match.funcs]p4:
6943   //   For conversion functions, the function is considered to be a member of
6944   //   the class of the implicit implied object argument for the purpose of
6945   //   defining the type of the implicit object parameter.
6946   //
6947   // Determine the implicit conversion sequence for the implicit
6948   // object parameter.
6949   QualType ImplicitParamType = From->getType();
6950   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6951     ImplicitParamType = FromPtrType->getPointeeType();
6952   CXXRecordDecl *ConversionContext
6953     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6954 
6955   Candidate.Conversions[0] = TryObjectArgumentInitialization(
6956       *this, CandidateSet.getLocation(), From->getType(),
6957       From->Classify(Context), Conversion, ConversionContext);
6958 
6959   if (Candidate.Conversions[0].isBad()) {
6960     Candidate.Viable = false;
6961     Candidate.FailureKind = ovl_fail_bad_conversion;
6962     return;
6963   }
6964 
6965   // We won't go through a user-defined type conversion function to convert a
6966   // derived to base as such conversions are given Conversion Rank. They only
6967   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6968   QualType FromCanon
6969     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6970   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6971   if (FromCanon == ToCanon ||
6972       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6973     Candidate.Viable = false;
6974     Candidate.FailureKind = ovl_fail_trivial_conversion;
6975     return;
6976   }
6977 
6978   // To determine what the conversion from the result of calling the
6979   // conversion function to the type we're eventually trying to
6980   // convert to (ToType), we need to synthesize a call to the
6981   // conversion function and attempt copy initialization from it. This
6982   // makes sure that we get the right semantics with respect to
6983   // lvalues/rvalues and the type. Fortunately, we can allocate this
6984   // call on the stack and we don't need its arguments to be
6985   // well-formed.
6986   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), VK_LValue,
6987                             From->getBeginLoc());
6988   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6989                                 Context.getPointerType(Conversion->getType()),
6990                                 CK_FunctionToPointerDecay,
6991                                 &ConversionRef, VK_RValue);
6992 
6993   QualType ConversionType = Conversion->getConversionType();
6994   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
6995     Candidate.Viable = false;
6996     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6997     return;
6998   }
6999 
7000   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7001 
7002   // Note that it is safe to allocate CallExpr on the stack here because
7003   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7004   // allocator).
7005   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7006   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
7007                 From->getBeginLoc());
7008   ImplicitConversionSequence ICS =
7009     TryCopyInitialization(*this, &Call, ToType,
7010                           /*SuppressUserConversions=*/true,
7011                           /*InOverloadResolution=*/false,
7012                           /*AllowObjCWritebackConversion=*/false);
7013 
7014   switch (ICS.getKind()) {
7015   case ImplicitConversionSequence::StandardConversion:
7016     Candidate.FinalConversion = ICS.Standard;
7017 
7018     // C++ [over.ics.user]p3:
7019     //   If the user-defined conversion is specified by a specialization of a
7020     //   conversion function template, the second standard conversion sequence
7021     //   shall have exact match rank.
7022     if (Conversion->getPrimaryTemplate() &&
7023         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7024       Candidate.Viable = false;
7025       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7026       return;
7027     }
7028 
7029     // C++0x [dcl.init.ref]p5:
7030     //    In the second case, if the reference is an rvalue reference and
7031     //    the second standard conversion sequence of the user-defined
7032     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7033     //    program is ill-formed.
7034     if (ToType->isRValueReferenceType() &&
7035         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7036       Candidate.Viable = false;
7037       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7038       return;
7039     }
7040     break;
7041 
7042   case ImplicitConversionSequence::BadConversion:
7043     Candidate.Viable = false;
7044     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7045     return;
7046 
7047   default:
7048     llvm_unreachable(
7049            "Can only end up with a standard conversion sequence or failure");
7050   }
7051 
7052   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7053     Candidate.Viable = false;
7054     Candidate.FailureKind = ovl_fail_enable_if;
7055     Candidate.DeductionFailure.Data = FailedAttr;
7056     return;
7057   }
7058 
7059   if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7060       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7061     Candidate.Viable = false;
7062     Candidate.FailureKind = ovl_non_default_multiversion_function;
7063   }
7064 }
7065 
7066 /// Adds a conversion function template specialization
7067 /// candidate to the overload set, using template argument deduction
7068 /// to deduce the template arguments of the conversion function
7069 /// template from the type that we are converting to (C++
7070 /// [temp.deduct.conv]).
7071 void
7072 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
7073                                      DeclAccessPair FoundDecl,
7074                                      CXXRecordDecl *ActingDC,
7075                                      Expr *From, QualType ToType,
7076                                      OverloadCandidateSet &CandidateSet,
7077                                      bool AllowObjCConversionOnExplicit,
7078                                      bool AllowResultConversion) {
7079   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7080          "Only conversion function templates permitted here");
7081 
7082   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7083     return;
7084 
7085   TemplateDeductionInfo Info(CandidateSet.getLocation());
7086   CXXConversionDecl *Specialization = nullptr;
7087   if (TemplateDeductionResult Result
7088         = DeduceTemplateArguments(FunctionTemplate, ToType,
7089                                   Specialization, Info)) {
7090     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7091     Candidate.FoundDecl = FoundDecl;
7092     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7093     Candidate.Viable = false;
7094     Candidate.FailureKind = ovl_fail_bad_deduction;
7095     Candidate.IsSurrogate = false;
7096     Candidate.IgnoreObjectArgument = false;
7097     Candidate.ExplicitCallArguments = 1;
7098     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7099                                                           Info);
7100     return;
7101   }
7102 
7103   // Add the conversion function template specialization produced by
7104   // template argument deduction as a candidate.
7105   assert(Specialization && "Missing function template specialization?");
7106   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7107                          CandidateSet, AllowObjCConversionOnExplicit,
7108                          AllowResultConversion);
7109 }
7110 
7111 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7112 /// converts the given @c Object to a function pointer via the
7113 /// conversion function @c Conversion, and then attempts to call it
7114 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7115 /// the type of function that we'll eventually be calling.
7116 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7117                                  DeclAccessPair FoundDecl,
7118                                  CXXRecordDecl *ActingContext,
7119                                  const FunctionProtoType *Proto,
7120                                  Expr *Object,
7121                                  ArrayRef<Expr *> Args,
7122                                  OverloadCandidateSet& CandidateSet) {
7123   if (!CandidateSet.isNewCandidate(Conversion))
7124     return;
7125 
7126   // Overload resolution is always an unevaluated context.
7127   EnterExpressionEvaluationContext Unevaluated(
7128       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7129 
7130   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7131   Candidate.FoundDecl = FoundDecl;
7132   Candidate.Function = nullptr;
7133   Candidate.Surrogate = Conversion;
7134   Candidate.Viable = true;
7135   Candidate.IsSurrogate = true;
7136   Candidate.IgnoreObjectArgument = false;
7137   Candidate.ExplicitCallArguments = Args.size();
7138 
7139   // Determine the implicit conversion sequence for the implicit
7140   // object parameter.
7141   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7142       *this, CandidateSet.getLocation(), Object->getType(),
7143       Object->Classify(Context), Conversion, ActingContext);
7144   if (ObjectInit.isBad()) {
7145     Candidate.Viable = false;
7146     Candidate.FailureKind = ovl_fail_bad_conversion;
7147     Candidate.Conversions[0] = ObjectInit;
7148     return;
7149   }
7150 
7151   // The first conversion is actually a user-defined conversion whose
7152   // first conversion is ObjectInit's standard conversion (which is
7153   // effectively a reference binding). Record it as such.
7154   Candidate.Conversions[0].setUserDefined();
7155   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7156   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7157   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7158   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7159   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7160   Candidate.Conversions[0].UserDefined.After
7161     = Candidate.Conversions[0].UserDefined.Before;
7162   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7163 
7164   // Find the
7165   unsigned NumParams = Proto->getNumParams();
7166 
7167   // (C++ 13.3.2p2): A candidate function having fewer than m
7168   // parameters is viable only if it has an ellipsis in its parameter
7169   // list (8.3.5).
7170   if (Args.size() > NumParams && !Proto->isVariadic()) {
7171     Candidate.Viable = false;
7172     Candidate.FailureKind = ovl_fail_too_many_arguments;
7173     return;
7174   }
7175 
7176   // Function types don't have any default arguments, so just check if
7177   // we have enough arguments.
7178   if (Args.size() < NumParams) {
7179     // Not enough arguments.
7180     Candidate.Viable = false;
7181     Candidate.FailureKind = ovl_fail_too_few_arguments;
7182     return;
7183   }
7184 
7185   // Determine the implicit conversion sequences for each of the
7186   // arguments.
7187   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7188     if (ArgIdx < NumParams) {
7189       // (C++ 13.3.2p3): for F to be a viable function, there shall
7190       // exist for each argument an implicit conversion sequence
7191       // (13.3.3.1) that converts that argument to the corresponding
7192       // parameter of F.
7193       QualType ParamType = Proto->getParamType(ArgIdx);
7194       Candidate.Conversions[ArgIdx + 1]
7195         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7196                                 /*SuppressUserConversions=*/false,
7197                                 /*InOverloadResolution=*/false,
7198                                 /*AllowObjCWritebackConversion=*/
7199                                   getLangOpts().ObjCAutoRefCount);
7200       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7201         Candidate.Viable = false;
7202         Candidate.FailureKind = ovl_fail_bad_conversion;
7203         return;
7204       }
7205     } else {
7206       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7207       // argument for which there is no corresponding parameter is
7208       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7209       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7210     }
7211   }
7212 
7213   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7214     Candidate.Viable = false;
7215     Candidate.FailureKind = ovl_fail_enable_if;
7216     Candidate.DeductionFailure.Data = FailedAttr;
7217     return;
7218   }
7219 }
7220 
7221 /// Add overload candidates for overloaded operators that are
7222 /// member functions.
7223 ///
7224 /// Add the overloaded operator candidates that are member functions
7225 /// for the operator Op that was used in an operator expression such
7226 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7227 /// CandidateSet will store the added overload candidates. (C++
7228 /// [over.match.oper]).
7229 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7230                                        SourceLocation OpLoc,
7231                                        ArrayRef<Expr *> Args,
7232                                        OverloadCandidateSet& CandidateSet,
7233                                        SourceRange OpRange) {
7234   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7235 
7236   // C++ [over.match.oper]p3:
7237   //   For a unary operator @ with an operand of a type whose
7238   //   cv-unqualified version is T1, and for a binary operator @ with
7239   //   a left operand of a type whose cv-unqualified version is T1 and
7240   //   a right operand of a type whose cv-unqualified version is T2,
7241   //   three sets of candidate functions, designated member
7242   //   candidates, non-member candidates and built-in candidates, are
7243   //   constructed as follows:
7244   QualType T1 = Args[0]->getType();
7245 
7246   //     -- If T1 is a complete class type or a class currently being
7247   //        defined, the set of member candidates is the result of the
7248   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7249   //        the set of member candidates is empty.
7250   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7251     // Complete the type if it can be completed.
7252     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7253       return;
7254     // If the type is neither complete nor being defined, bail out now.
7255     if (!T1Rec->getDecl()->getDefinition())
7256       return;
7257 
7258     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7259     LookupQualifiedName(Operators, T1Rec->getDecl());
7260     Operators.suppressDiagnostics();
7261 
7262     for (LookupResult::iterator Oper = Operators.begin(),
7263                              OperEnd = Operators.end();
7264          Oper != OperEnd;
7265          ++Oper)
7266       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7267                          Args[0]->Classify(Context), Args.slice(1),
7268                          CandidateSet, /*SuppressUserConversions=*/false);
7269   }
7270 }
7271 
7272 /// AddBuiltinCandidate - Add a candidate for a built-in
7273 /// operator. ResultTy and ParamTys are the result and parameter types
7274 /// of the built-in candidate, respectively. Args and NumArgs are the
7275 /// arguments being passed to the candidate. IsAssignmentOperator
7276 /// should be true when this built-in candidate is an assignment
7277 /// operator. NumContextualBoolArguments is the number of arguments
7278 /// (at the beginning of the argument list) that will be contextually
7279 /// converted to bool.
7280 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7281                                OverloadCandidateSet& CandidateSet,
7282                                bool IsAssignmentOperator,
7283                                unsigned NumContextualBoolArguments) {
7284   // Overload resolution is always an unevaluated context.
7285   EnterExpressionEvaluationContext Unevaluated(
7286       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7287 
7288   // Add this candidate
7289   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7290   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7291   Candidate.Function = nullptr;
7292   Candidate.IsSurrogate = false;
7293   Candidate.IgnoreObjectArgument = false;
7294   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7295 
7296   // Determine the implicit conversion sequences for each of the
7297   // arguments.
7298   Candidate.Viable = true;
7299   Candidate.ExplicitCallArguments = Args.size();
7300   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7301     // C++ [over.match.oper]p4:
7302     //   For the built-in assignment operators, conversions of the
7303     //   left operand are restricted as follows:
7304     //     -- no temporaries are introduced to hold the left operand, and
7305     //     -- no user-defined conversions are applied to the left
7306     //        operand to achieve a type match with the left-most
7307     //        parameter of a built-in candidate.
7308     //
7309     // We block these conversions by turning off user-defined
7310     // conversions, since that is the only way that initialization of
7311     // a reference to a non-class type can occur from something that
7312     // is not of the same type.
7313     if (ArgIdx < NumContextualBoolArguments) {
7314       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7315              "Contextual conversion to bool requires bool type");
7316       Candidate.Conversions[ArgIdx]
7317         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7318     } else {
7319       Candidate.Conversions[ArgIdx]
7320         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7321                                 ArgIdx == 0 && IsAssignmentOperator,
7322                                 /*InOverloadResolution=*/false,
7323                                 /*AllowObjCWritebackConversion=*/
7324                                   getLangOpts().ObjCAutoRefCount);
7325     }
7326     if (Candidate.Conversions[ArgIdx].isBad()) {
7327       Candidate.Viable = false;
7328       Candidate.FailureKind = ovl_fail_bad_conversion;
7329       break;
7330     }
7331   }
7332 }
7333 
7334 namespace {
7335 
7336 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7337 /// candidate operator functions for built-in operators (C++
7338 /// [over.built]). The types are separated into pointer types and
7339 /// enumeration types.
7340 class BuiltinCandidateTypeSet  {
7341   /// TypeSet - A set of types.
7342   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7343                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7344 
7345   /// PointerTypes - The set of pointer types that will be used in the
7346   /// built-in candidates.
7347   TypeSet PointerTypes;
7348 
7349   /// MemberPointerTypes - The set of member pointer types that will be
7350   /// used in the built-in candidates.
7351   TypeSet MemberPointerTypes;
7352 
7353   /// EnumerationTypes - The set of enumeration types that will be
7354   /// used in the built-in candidates.
7355   TypeSet EnumerationTypes;
7356 
7357   /// The set of vector types that will be used in the built-in
7358   /// candidates.
7359   TypeSet VectorTypes;
7360 
7361   /// A flag indicating non-record types are viable candidates
7362   bool HasNonRecordTypes;
7363 
7364   /// A flag indicating whether either arithmetic or enumeration types
7365   /// were present in the candidate set.
7366   bool HasArithmeticOrEnumeralTypes;
7367 
7368   /// A flag indicating whether the nullptr type was present in the
7369   /// candidate set.
7370   bool HasNullPtrType;
7371 
7372   /// Sema - The semantic analysis instance where we are building the
7373   /// candidate type set.
7374   Sema &SemaRef;
7375 
7376   /// Context - The AST context in which we will build the type sets.
7377   ASTContext &Context;
7378 
7379   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7380                                                const Qualifiers &VisibleQuals);
7381   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7382 
7383 public:
7384   /// iterator - Iterates through the types that are part of the set.
7385   typedef TypeSet::iterator iterator;
7386 
7387   BuiltinCandidateTypeSet(Sema &SemaRef)
7388     : HasNonRecordTypes(false),
7389       HasArithmeticOrEnumeralTypes(false),
7390       HasNullPtrType(false),
7391       SemaRef(SemaRef),
7392       Context(SemaRef.Context) { }
7393 
7394   void AddTypesConvertedFrom(QualType Ty,
7395                              SourceLocation Loc,
7396                              bool AllowUserConversions,
7397                              bool AllowExplicitConversions,
7398                              const Qualifiers &VisibleTypeConversionsQuals);
7399 
7400   /// pointer_begin - First pointer type found;
7401   iterator pointer_begin() { return PointerTypes.begin(); }
7402 
7403   /// pointer_end - Past the last pointer type found;
7404   iterator pointer_end() { return PointerTypes.end(); }
7405 
7406   /// member_pointer_begin - First member pointer type found;
7407   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7408 
7409   /// member_pointer_end - Past the last member pointer type found;
7410   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7411 
7412   /// enumeration_begin - First enumeration type found;
7413   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7414 
7415   /// enumeration_end - Past the last enumeration type found;
7416   iterator enumeration_end() { return EnumerationTypes.end(); }
7417 
7418   iterator vector_begin() { return VectorTypes.begin(); }
7419   iterator vector_end() { return VectorTypes.end(); }
7420 
7421   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7422   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7423   bool hasNullPtrType() const { return HasNullPtrType; }
7424 };
7425 
7426 } // end anonymous namespace
7427 
7428 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7429 /// the set of pointer types along with any more-qualified variants of
7430 /// that type. For example, if @p Ty is "int const *", this routine
7431 /// will add "int const *", "int const volatile *", "int const
7432 /// restrict *", and "int const volatile restrict *" to the set of
7433 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7434 /// false otherwise.
7435 ///
7436 /// FIXME: what to do about extended qualifiers?
7437 bool
7438 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7439                                              const Qualifiers &VisibleQuals) {
7440 
7441   // Insert this type.
7442   if (!PointerTypes.insert(Ty))
7443     return false;
7444 
7445   QualType PointeeTy;
7446   const PointerType *PointerTy = Ty->getAs<PointerType>();
7447   bool buildObjCPtr = false;
7448   if (!PointerTy) {
7449     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7450     PointeeTy = PTy->getPointeeType();
7451     buildObjCPtr = true;
7452   } else {
7453     PointeeTy = PointerTy->getPointeeType();
7454   }
7455 
7456   // Don't add qualified variants of arrays. For one, they're not allowed
7457   // (the qualifier would sink to the element type), and for another, the
7458   // only overload situation where it matters is subscript or pointer +- int,
7459   // and those shouldn't have qualifier variants anyway.
7460   if (PointeeTy->isArrayType())
7461     return true;
7462 
7463   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7464   bool hasVolatile = VisibleQuals.hasVolatile();
7465   bool hasRestrict = VisibleQuals.hasRestrict();
7466 
7467   // Iterate through all strict supersets of BaseCVR.
7468   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7469     if ((CVR | BaseCVR) != CVR) continue;
7470     // Skip over volatile if no volatile found anywhere in the types.
7471     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7472 
7473     // Skip over restrict if no restrict found anywhere in the types, or if
7474     // the type cannot be restrict-qualified.
7475     if ((CVR & Qualifiers::Restrict) &&
7476         (!hasRestrict ||
7477          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7478       continue;
7479 
7480     // Build qualified pointee type.
7481     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7482 
7483     // Build qualified pointer type.
7484     QualType QPointerTy;
7485     if (!buildObjCPtr)
7486       QPointerTy = Context.getPointerType(QPointeeTy);
7487     else
7488       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7489 
7490     // Insert qualified pointer type.
7491     PointerTypes.insert(QPointerTy);
7492   }
7493 
7494   return true;
7495 }
7496 
7497 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7498 /// to the set of pointer types along with any more-qualified variants of
7499 /// that type. For example, if @p Ty is "int const *", this routine
7500 /// will add "int const *", "int const volatile *", "int const
7501 /// restrict *", and "int const volatile restrict *" to the set of
7502 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7503 /// false otherwise.
7504 ///
7505 /// FIXME: what to do about extended qualifiers?
7506 bool
7507 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7508     QualType Ty) {
7509   // Insert this type.
7510   if (!MemberPointerTypes.insert(Ty))
7511     return false;
7512 
7513   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7514   assert(PointerTy && "type was not a member pointer type!");
7515 
7516   QualType PointeeTy = PointerTy->getPointeeType();
7517   // Don't add qualified variants of arrays. For one, they're not allowed
7518   // (the qualifier would sink to the element type), and for another, the
7519   // only overload situation where it matters is subscript or pointer +- int,
7520   // and those shouldn't have qualifier variants anyway.
7521   if (PointeeTy->isArrayType())
7522     return true;
7523   const Type *ClassTy = PointerTy->getClass();
7524 
7525   // Iterate through all strict supersets of the pointee type's CVR
7526   // qualifiers.
7527   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7528   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7529     if ((CVR | BaseCVR) != CVR) continue;
7530 
7531     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7532     MemberPointerTypes.insert(
7533       Context.getMemberPointerType(QPointeeTy, ClassTy));
7534   }
7535 
7536   return true;
7537 }
7538 
7539 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7540 /// Ty can be implicit converted to the given set of @p Types. We're
7541 /// primarily interested in pointer types and enumeration types. We also
7542 /// take member pointer types, for the conditional operator.
7543 /// AllowUserConversions is true if we should look at the conversion
7544 /// functions of a class type, and AllowExplicitConversions if we
7545 /// should also include the explicit conversion functions of a class
7546 /// type.
7547 void
7548 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7549                                                SourceLocation Loc,
7550                                                bool AllowUserConversions,
7551                                                bool AllowExplicitConversions,
7552                                                const Qualifiers &VisibleQuals) {
7553   // Only deal with canonical types.
7554   Ty = Context.getCanonicalType(Ty);
7555 
7556   // Look through reference types; they aren't part of the type of an
7557   // expression for the purposes of conversions.
7558   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7559     Ty = RefTy->getPointeeType();
7560 
7561   // If we're dealing with an array type, decay to the pointer.
7562   if (Ty->isArrayType())
7563     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7564 
7565   // Otherwise, we don't care about qualifiers on the type.
7566   Ty = Ty.getLocalUnqualifiedType();
7567 
7568   // Flag if we ever add a non-record type.
7569   const RecordType *TyRec = Ty->getAs<RecordType>();
7570   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7571 
7572   // Flag if we encounter an arithmetic type.
7573   HasArithmeticOrEnumeralTypes =
7574     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7575 
7576   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7577     PointerTypes.insert(Ty);
7578   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7579     // Insert our type, and its more-qualified variants, into the set
7580     // of types.
7581     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7582       return;
7583   } else if (Ty->isMemberPointerType()) {
7584     // Member pointers are far easier, since the pointee can't be converted.
7585     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7586       return;
7587   } else if (Ty->isEnumeralType()) {
7588     HasArithmeticOrEnumeralTypes = true;
7589     EnumerationTypes.insert(Ty);
7590   } else if (Ty->isVectorType()) {
7591     // We treat vector types as arithmetic types in many contexts as an
7592     // extension.
7593     HasArithmeticOrEnumeralTypes = true;
7594     VectorTypes.insert(Ty);
7595   } else if (Ty->isNullPtrType()) {
7596     HasNullPtrType = true;
7597   } else if (AllowUserConversions && TyRec) {
7598     // No conversion functions in incomplete types.
7599     if (!SemaRef.isCompleteType(Loc, Ty))
7600       return;
7601 
7602     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7603     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7604       if (isa<UsingShadowDecl>(D))
7605         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7606 
7607       // Skip conversion function templates; they don't tell us anything
7608       // about which builtin types we can convert to.
7609       if (isa<FunctionTemplateDecl>(D))
7610         continue;
7611 
7612       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7613       if (AllowExplicitConversions || !Conv->isExplicit()) {
7614         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7615                               VisibleQuals);
7616       }
7617     }
7618   }
7619 }
7620 
7621 /// Helper function for AddBuiltinOperatorCandidates() that adds
7622 /// the volatile- and non-volatile-qualified assignment operators for the
7623 /// given type to the candidate set.
7624 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7625                                                    QualType T,
7626                                                    ArrayRef<Expr *> Args,
7627                                     OverloadCandidateSet &CandidateSet) {
7628   QualType ParamTypes[2];
7629 
7630   // T& operator=(T&, T)
7631   ParamTypes[0] = S.Context.getLValueReferenceType(T);
7632   ParamTypes[1] = T;
7633   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7634                         /*IsAssignmentOperator=*/true);
7635 
7636   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7637     // volatile T& operator=(volatile T&, T)
7638     ParamTypes[0]
7639       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7640     ParamTypes[1] = T;
7641     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7642                           /*IsAssignmentOperator=*/true);
7643   }
7644 }
7645 
7646 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7647 /// if any, found in visible type conversion functions found in ArgExpr's type.
7648 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7649     Qualifiers VRQuals;
7650     const RecordType *TyRec;
7651     if (const MemberPointerType *RHSMPType =
7652         ArgExpr->getType()->getAs<MemberPointerType>())
7653       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7654     else
7655       TyRec = ArgExpr->getType()->getAs<RecordType>();
7656     if (!TyRec) {
7657       // Just to be safe, assume the worst case.
7658       VRQuals.addVolatile();
7659       VRQuals.addRestrict();
7660       return VRQuals;
7661     }
7662 
7663     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7664     if (!ClassDecl->hasDefinition())
7665       return VRQuals;
7666 
7667     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7668       if (isa<UsingShadowDecl>(D))
7669         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7670       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7671         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7672         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7673           CanTy = ResTypeRef->getPointeeType();
7674         // Need to go down the pointer/mempointer chain and add qualifiers
7675         // as see them.
7676         bool done = false;
7677         while (!done) {
7678           if (CanTy.isRestrictQualified())
7679             VRQuals.addRestrict();
7680           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7681             CanTy = ResTypePtr->getPointeeType();
7682           else if (const MemberPointerType *ResTypeMPtr =
7683                 CanTy->getAs<MemberPointerType>())
7684             CanTy = ResTypeMPtr->getPointeeType();
7685           else
7686             done = true;
7687           if (CanTy.isVolatileQualified())
7688             VRQuals.addVolatile();
7689           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7690             return VRQuals;
7691         }
7692       }
7693     }
7694     return VRQuals;
7695 }
7696 
7697 namespace {
7698 
7699 /// Helper class to manage the addition of builtin operator overload
7700 /// candidates. It provides shared state and utility methods used throughout
7701 /// the process, as well as a helper method to add each group of builtin
7702 /// operator overloads from the standard to a candidate set.
7703 class BuiltinOperatorOverloadBuilder {
7704   // Common instance state available to all overload candidate addition methods.
7705   Sema &S;
7706   ArrayRef<Expr *> Args;
7707   Qualifiers VisibleTypeConversionsQuals;
7708   bool HasArithmeticOrEnumeralCandidateType;
7709   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7710   OverloadCandidateSet &CandidateSet;
7711 
7712   static constexpr int ArithmeticTypesCap = 24;
7713   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
7714 
7715   // Define some indices used to iterate over the arithemetic types in
7716   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
7717   // types are that preserved by promotion (C++ [over.built]p2).
7718   unsigned FirstIntegralType,
7719            LastIntegralType;
7720   unsigned FirstPromotedIntegralType,
7721            LastPromotedIntegralType;
7722   unsigned FirstPromotedArithmeticType,
7723            LastPromotedArithmeticType;
7724   unsigned NumArithmeticTypes;
7725 
7726   void InitArithmeticTypes() {
7727     // Start of promoted types.
7728     FirstPromotedArithmeticType = 0;
7729     ArithmeticTypes.push_back(S.Context.FloatTy);
7730     ArithmeticTypes.push_back(S.Context.DoubleTy);
7731     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7732     if (S.Context.getTargetInfo().hasFloat128Type())
7733       ArithmeticTypes.push_back(S.Context.Float128Ty);
7734 
7735     // Start of integral types.
7736     FirstIntegralType = ArithmeticTypes.size();
7737     FirstPromotedIntegralType = ArithmeticTypes.size();
7738     ArithmeticTypes.push_back(S.Context.IntTy);
7739     ArithmeticTypes.push_back(S.Context.LongTy);
7740     ArithmeticTypes.push_back(S.Context.LongLongTy);
7741     if (S.Context.getTargetInfo().hasInt128Type())
7742       ArithmeticTypes.push_back(S.Context.Int128Ty);
7743     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7744     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7745     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7746     if (S.Context.getTargetInfo().hasInt128Type())
7747       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7748     LastPromotedIntegralType = ArithmeticTypes.size();
7749     LastPromotedArithmeticType = ArithmeticTypes.size();
7750     // End of promoted types.
7751 
7752     ArithmeticTypes.push_back(S.Context.BoolTy);
7753     ArithmeticTypes.push_back(S.Context.CharTy);
7754     ArithmeticTypes.push_back(S.Context.WCharTy);
7755     if (S.Context.getLangOpts().Char8)
7756       ArithmeticTypes.push_back(S.Context.Char8Ty);
7757     ArithmeticTypes.push_back(S.Context.Char16Ty);
7758     ArithmeticTypes.push_back(S.Context.Char32Ty);
7759     ArithmeticTypes.push_back(S.Context.SignedCharTy);
7760     ArithmeticTypes.push_back(S.Context.ShortTy);
7761     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7762     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7763     LastIntegralType = ArithmeticTypes.size();
7764     NumArithmeticTypes = ArithmeticTypes.size();
7765     // End of integral types.
7766     // FIXME: What about complex? What about half?
7767 
7768     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
7769            "Enough inline storage for all arithmetic types.");
7770   }
7771 
7772   /// Helper method to factor out the common pattern of adding overloads
7773   /// for '++' and '--' builtin operators.
7774   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7775                                            bool HasVolatile,
7776                                            bool HasRestrict) {
7777     QualType ParamTypes[2] = {
7778       S.Context.getLValueReferenceType(CandidateTy),
7779       S.Context.IntTy
7780     };
7781 
7782     // Non-volatile version.
7783     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7784 
7785     // Use a heuristic to reduce number of builtin candidates in the set:
7786     // add volatile version only if there are conversions to a volatile type.
7787     if (HasVolatile) {
7788       ParamTypes[0] =
7789         S.Context.getLValueReferenceType(
7790           S.Context.getVolatileType(CandidateTy));
7791       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7792     }
7793 
7794     // Add restrict version only if there are conversions to a restrict type
7795     // and our candidate type is a non-restrict-qualified pointer.
7796     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7797         !CandidateTy.isRestrictQualified()) {
7798       ParamTypes[0]
7799         = S.Context.getLValueReferenceType(
7800             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7801       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7802 
7803       if (HasVolatile) {
7804         ParamTypes[0]
7805           = S.Context.getLValueReferenceType(
7806               S.Context.getCVRQualifiedType(CandidateTy,
7807                                             (Qualifiers::Volatile |
7808                                              Qualifiers::Restrict)));
7809         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7810       }
7811     }
7812 
7813   }
7814 
7815 public:
7816   BuiltinOperatorOverloadBuilder(
7817     Sema &S, ArrayRef<Expr *> Args,
7818     Qualifiers VisibleTypeConversionsQuals,
7819     bool HasArithmeticOrEnumeralCandidateType,
7820     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7821     OverloadCandidateSet &CandidateSet)
7822     : S(S), Args(Args),
7823       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7824       HasArithmeticOrEnumeralCandidateType(
7825         HasArithmeticOrEnumeralCandidateType),
7826       CandidateTypes(CandidateTypes),
7827       CandidateSet(CandidateSet) {
7828 
7829     InitArithmeticTypes();
7830   }
7831 
7832   // Increment is deprecated for bool since C++17.
7833   //
7834   // C++ [over.built]p3:
7835   //
7836   //   For every pair (T, VQ), where T is an arithmetic type other
7837   //   than bool, and VQ is either volatile or empty, there exist
7838   //   candidate operator functions of the form
7839   //
7840   //       VQ T&      operator++(VQ T&);
7841   //       T          operator++(VQ T&, int);
7842   //
7843   // C++ [over.built]p4:
7844   //
7845   //   For every pair (T, VQ), where T is an arithmetic type other
7846   //   than bool, and VQ is either volatile or empty, there exist
7847   //   candidate operator functions of the form
7848   //
7849   //       VQ T&      operator--(VQ T&);
7850   //       T          operator--(VQ T&, int);
7851   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7852     if (!HasArithmeticOrEnumeralCandidateType)
7853       return;
7854 
7855     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
7856       const auto TypeOfT = ArithmeticTypes[Arith];
7857       if (TypeOfT == S.Context.BoolTy) {
7858         if (Op == OO_MinusMinus)
7859           continue;
7860         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
7861           continue;
7862       }
7863       addPlusPlusMinusMinusStyleOverloads(
7864         TypeOfT,
7865         VisibleTypeConversionsQuals.hasVolatile(),
7866         VisibleTypeConversionsQuals.hasRestrict());
7867     }
7868   }
7869 
7870   // C++ [over.built]p5:
7871   //
7872   //   For every pair (T, VQ), where T is a cv-qualified or
7873   //   cv-unqualified object type, and VQ is either volatile or
7874   //   empty, there exist candidate operator functions of the form
7875   //
7876   //       T*VQ&      operator++(T*VQ&);
7877   //       T*VQ&      operator--(T*VQ&);
7878   //       T*         operator++(T*VQ&, int);
7879   //       T*         operator--(T*VQ&, int);
7880   void addPlusPlusMinusMinusPointerOverloads() {
7881     for (BuiltinCandidateTypeSet::iterator
7882               Ptr = CandidateTypes[0].pointer_begin(),
7883            PtrEnd = CandidateTypes[0].pointer_end();
7884          Ptr != PtrEnd; ++Ptr) {
7885       // Skip pointer types that aren't pointers to object types.
7886       if (!(*Ptr)->getPointeeType()->isObjectType())
7887         continue;
7888 
7889       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7890         (!(*Ptr).isVolatileQualified() &&
7891          VisibleTypeConversionsQuals.hasVolatile()),
7892         (!(*Ptr).isRestrictQualified() &&
7893          VisibleTypeConversionsQuals.hasRestrict()));
7894     }
7895   }
7896 
7897   // C++ [over.built]p6:
7898   //   For every cv-qualified or cv-unqualified object type T, there
7899   //   exist candidate operator functions of the form
7900   //
7901   //       T&         operator*(T*);
7902   //
7903   // C++ [over.built]p7:
7904   //   For every function type T that does not have cv-qualifiers or a
7905   //   ref-qualifier, there exist candidate operator functions of the form
7906   //       T&         operator*(T*);
7907   void addUnaryStarPointerOverloads() {
7908     for (BuiltinCandidateTypeSet::iterator
7909               Ptr = CandidateTypes[0].pointer_begin(),
7910            PtrEnd = CandidateTypes[0].pointer_end();
7911          Ptr != PtrEnd; ++Ptr) {
7912       QualType ParamTy = *Ptr;
7913       QualType PointeeTy = ParamTy->getPointeeType();
7914       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7915         continue;
7916 
7917       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7918         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7919           continue;
7920 
7921       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7922     }
7923   }
7924 
7925   // C++ [over.built]p9:
7926   //  For every promoted arithmetic type T, there exist candidate
7927   //  operator functions of the form
7928   //
7929   //       T         operator+(T);
7930   //       T         operator-(T);
7931   void addUnaryPlusOrMinusArithmeticOverloads() {
7932     if (!HasArithmeticOrEnumeralCandidateType)
7933       return;
7934 
7935     for (unsigned Arith = FirstPromotedArithmeticType;
7936          Arith < LastPromotedArithmeticType; ++Arith) {
7937       QualType ArithTy = ArithmeticTypes[Arith];
7938       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
7939     }
7940 
7941     // Extension: We also add these operators for vector types.
7942     for (BuiltinCandidateTypeSet::iterator
7943               Vec = CandidateTypes[0].vector_begin(),
7944            VecEnd = CandidateTypes[0].vector_end();
7945          Vec != VecEnd; ++Vec) {
7946       QualType VecTy = *Vec;
7947       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7948     }
7949   }
7950 
7951   // C++ [over.built]p8:
7952   //   For every type T, there exist candidate operator functions of
7953   //   the form
7954   //
7955   //       T*         operator+(T*);
7956   void addUnaryPlusPointerOverloads() {
7957     for (BuiltinCandidateTypeSet::iterator
7958               Ptr = CandidateTypes[0].pointer_begin(),
7959            PtrEnd = CandidateTypes[0].pointer_end();
7960          Ptr != PtrEnd; ++Ptr) {
7961       QualType ParamTy = *Ptr;
7962       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7963     }
7964   }
7965 
7966   // C++ [over.built]p10:
7967   //   For every promoted integral type T, there exist candidate
7968   //   operator functions of the form
7969   //
7970   //        T         operator~(T);
7971   void addUnaryTildePromotedIntegralOverloads() {
7972     if (!HasArithmeticOrEnumeralCandidateType)
7973       return;
7974 
7975     for (unsigned Int = FirstPromotedIntegralType;
7976          Int < LastPromotedIntegralType; ++Int) {
7977       QualType IntTy = ArithmeticTypes[Int];
7978       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
7979     }
7980 
7981     // Extension: We also add this operator for vector types.
7982     for (BuiltinCandidateTypeSet::iterator
7983               Vec = CandidateTypes[0].vector_begin(),
7984            VecEnd = CandidateTypes[0].vector_end();
7985          Vec != VecEnd; ++Vec) {
7986       QualType VecTy = *Vec;
7987       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7988     }
7989   }
7990 
7991   // C++ [over.match.oper]p16:
7992   //   For every pointer to member type T or type std::nullptr_t, there
7993   //   exist candidate operator functions of the form
7994   //
7995   //        bool operator==(T,T);
7996   //        bool operator!=(T,T);
7997   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
7998     /// Set of (canonical) types that we've already handled.
7999     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8000 
8001     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8002       for (BuiltinCandidateTypeSet::iterator
8003                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8004              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8005            MemPtr != MemPtrEnd;
8006            ++MemPtr) {
8007         // Don't add the same builtin candidate twice.
8008         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8009           continue;
8010 
8011         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8012         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8013       }
8014 
8015       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8016         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8017         if (AddedTypes.insert(NullPtrTy).second) {
8018           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8019           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8020         }
8021       }
8022     }
8023   }
8024 
8025   // C++ [over.built]p15:
8026   //
8027   //   For every T, where T is an enumeration type or a pointer type,
8028   //   there exist candidate operator functions of the form
8029   //
8030   //        bool       operator<(T, T);
8031   //        bool       operator>(T, T);
8032   //        bool       operator<=(T, T);
8033   //        bool       operator>=(T, T);
8034   //        bool       operator==(T, T);
8035   //        bool       operator!=(T, T);
8036   //           R       operator<=>(T, T)
8037   void addGenericBinaryPointerOrEnumeralOverloads() {
8038     // C++ [over.match.oper]p3:
8039     //   [...]the built-in candidates include all of the candidate operator
8040     //   functions defined in 13.6 that, compared to the given operator, [...]
8041     //   do not have the same parameter-type-list as any non-template non-member
8042     //   candidate.
8043     //
8044     // Note that in practice, this only affects enumeration types because there
8045     // aren't any built-in candidates of record type, and a user-defined operator
8046     // must have an operand of record or enumeration type. Also, the only other
8047     // overloaded operator with enumeration arguments, operator=,
8048     // cannot be overloaded for enumeration types, so this is the only place
8049     // where we must suppress candidates like this.
8050     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8051       UserDefinedBinaryOperators;
8052 
8053     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8054       if (CandidateTypes[ArgIdx].enumeration_begin() !=
8055           CandidateTypes[ArgIdx].enumeration_end()) {
8056         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8057                                          CEnd = CandidateSet.end();
8058              C != CEnd; ++C) {
8059           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8060             continue;
8061 
8062           if (C->Function->isFunctionTemplateSpecialization())
8063             continue;
8064 
8065           QualType FirstParamType =
8066             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
8067           QualType SecondParamType =
8068             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
8069 
8070           // Skip if either parameter isn't of enumeral type.
8071           if (!FirstParamType->isEnumeralType() ||
8072               !SecondParamType->isEnumeralType())
8073             continue;
8074 
8075           // Add this operator to the set of known user-defined operators.
8076           UserDefinedBinaryOperators.insert(
8077             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8078                            S.Context.getCanonicalType(SecondParamType)));
8079         }
8080       }
8081     }
8082 
8083     /// Set of (canonical) types that we've already handled.
8084     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8085 
8086     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8087       for (BuiltinCandidateTypeSet::iterator
8088                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8089              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8090            Ptr != PtrEnd; ++Ptr) {
8091         // Don't add the same builtin candidate twice.
8092         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8093           continue;
8094 
8095         QualType ParamTypes[2] = { *Ptr, *Ptr };
8096         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8097       }
8098       for (BuiltinCandidateTypeSet::iterator
8099                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8100              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8101            Enum != EnumEnd; ++Enum) {
8102         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8103 
8104         // Don't add the same builtin candidate twice, or if a user defined
8105         // candidate exists.
8106         if (!AddedTypes.insert(CanonType).second ||
8107             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8108                                                             CanonType)))
8109           continue;
8110         QualType ParamTypes[2] = { *Enum, *Enum };
8111         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8112       }
8113     }
8114   }
8115 
8116   // C++ [over.built]p13:
8117   //
8118   //   For every cv-qualified or cv-unqualified object type T
8119   //   there exist candidate operator functions of the form
8120   //
8121   //      T*         operator+(T*, ptrdiff_t);
8122   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8123   //      T*         operator-(T*, ptrdiff_t);
8124   //      T*         operator+(ptrdiff_t, T*);
8125   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8126   //
8127   // C++ [over.built]p14:
8128   //
8129   //   For every T, where T is a pointer to object type, there
8130   //   exist candidate operator functions of the form
8131   //
8132   //      ptrdiff_t  operator-(T, T);
8133   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8134     /// Set of (canonical) types that we've already handled.
8135     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8136 
8137     for (int Arg = 0; Arg < 2; ++Arg) {
8138       QualType AsymmetricParamTypes[2] = {
8139         S.Context.getPointerDiffType(),
8140         S.Context.getPointerDiffType(),
8141       };
8142       for (BuiltinCandidateTypeSet::iterator
8143                 Ptr = CandidateTypes[Arg].pointer_begin(),
8144              PtrEnd = CandidateTypes[Arg].pointer_end();
8145            Ptr != PtrEnd; ++Ptr) {
8146         QualType PointeeTy = (*Ptr)->getPointeeType();
8147         if (!PointeeTy->isObjectType())
8148           continue;
8149 
8150         AsymmetricParamTypes[Arg] = *Ptr;
8151         if (Arg == 0 || Op == OO_Plus) {
8152           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8153           // T* operator+(ptrdiff_t, T*);
8154           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8155         }
8156         if (Op == OO_Minus) {
8157           // ptrdiff_t operator-(T, T);
8158           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8159             continue;
8160 
8161           QualType ParamTypes[2] = { *Ptr, *Ptr };
8162           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8163         }
8164       }
8165     }
8166   }
8167 
8168   // C++ [over.built]p12:
8169   //
8170   //   For every pair of promoted arithmetic types L and R, there
8171   //   exist candidate operator functions of the form
8172   //
8173   //        LR         operator*(L, R);
8174   //        LR         operator/(L, R);
8175   //        LR         operator+(L, R);
8176   //        LR         operator-(L, R);
8177   //        bool       operator<(L, R);
8178   //        bool       operator>(L, R);
8179   //        bool       operator<=(L, R);
8180   //        bool       operator>=(L, R);
8181   //        bool       operator==(L, R);
8182   //        bool       operator!=(L, R);
8183   //
8184   //   where LR is the result of the usual arithmetic conversions
8185   //   between types L and R.
8186   //
8187   // C++ [over.built]p24:
8188   //
8189   //   For every pair of promoted arithmetic types L and R, there exist
8190   //   candidate operator functions of the form
8191   //
8192   //        LR       operator?(bool, L, R);
8193   //
8194   //   where LR is the result of the usual arithmetic conversions
8195   //   between types L and R.
8196   // Our candidates ignore the first parameter.
8197   void addGenericBinaryArithmeticOverloads() {
8198     if (!HasArithmeticOrEnumeralCandidateType)
8199       return;
8200 
8201     for (unsigned Left = FirstPromotedArithmeticType;
8202          Left < LastPromotedArithmeticType; ++Left) {
8203       for (unsigned Right = FirstPromotedArithmeticType;
8204            Right < LastPromotedArithmeticType; ++Right) {
8205         QualType LandR[2] = { ArithmeticTypes[Left],
8206                               ArithmeticTypes[Right] };
8207         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8208       }
8209     }
8210 
8211     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8212     // conditional operator for vector types.
8213     for (BuiltinCandidateTypeSet::iterator
8214               Vec1 = CandidateTypes[0].vector_begin(),
8215            Vec1End = CandidateTypes[0].vector_end();
8216          Vec1 != Vec1End; ++Vec1) {
8217       for (BuiltinCandidateTypeSet::iterator
8218                 Vec2 = CandidateTypes[1].vector_begin(),
8219              Vec2End = CandidateTypes[1].vector_end();
8220            Vec2 != Vec2End; ++Vec2) {
8221         QualType LandR[2] = { *Vec1, *Vec2 };
8222         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8223       }
8224     }
8225   }
8226 
8227   // C++2a [over.built]p14:
8228   //
8229   //   For every integral type T there exists a candidate operator function
8230   //   of the form
8231   //
8232   //        std::strong_ordering operator<=>(T, T)
8233   //
8234   // C++2a [over.built]p15:
8235   //
8236   //   For every pair of floating-point types L and R, there exists a candidate
8237   //   operator function of the form
8238   //
8239   //       std::partial_ordering operator<=>(L, R);
8240   //
8241   // FIXME: The current specification for integral types doesn't play nice with
8242   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8243   // comparisons. Under the current spec this can lead to ambiguity during
8244   // overload resolution. For example:
8245   //
8246   //   enum A : int {a};
8247   //   auto x = (a <=> (long)42);
8248   //
8249   //   error: call is ambiguous for arguments 'A' and 'long'.
8250   //   note: candidate operator<=>(int, int)
8251   //   note: candidate operator<=>(long, long)
8252   //
8253   // To avoid this error, this function deviates from the specification and adds
8254   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8255   // arithmetic types (the same as the generic relational overloads).
8256   //
8257   // For now this function acts as a placeholder.
8258   void addThreeWayArithmeticOverloads() {
8259     addGenericBinaryArithmeticOverloads();
8260   }
8261 
8262   // C++ [over.built]p17:
8263   //
8264   //   For every pair of promoted integral types L and R, there
8265   //   exist candidate operator functions of the form
8266   //
8267   //      LR         operator%(L, R);
8268   //      LR         operator&(L, R);
8269   //      LR         operator^(L, R);
8270   //      LR         operator|(L, R);
8271   //      L          operator<<(L, R);
8272   //      L          operator>>(L, R);
8273   //
8274   //   where LR is the result of the usual arithmetic conversions
8275   //   between types L and R.
8276   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8277     if (!HasArithmeticOrEnumeralCandidateType)
8278       return;
8279 
8280     for (unsigned Left = FirstPromotedIntegralType;
8281          Left < LastPromotedIntegralType; ++Left) {
8282       for (unsigned Right = FirstPromotedIntegralType;
8283            Right < LastPromotedIntegralType; ++Right) {
8284         QualType LandR[2] = { ArithmeticTypes[Left],
8285                               ArithmeticTypes[Right] };
8286         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8287       }
8288     }
8289   }
8290 
8291   // C++ [over.built]p20:
8292   //
8293   //   For every pair (T, VQ), where T is an enumeration or
8294   //   pointer to member type and VQ is either volatile or
8295   //   empty, there exist candidate operator functions of the form
8296   //
8297   //        VQ T&      operator=(VQ T&, T);
8298   void addAssignmentMemberPointerOrEnumeralOverloads() {
8299     /// Set of (canonical) types that we've already handled.
8300     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8301 
8302     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8303       for (BuiltinCandidateTypeSet::iterator
8304                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8305              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8306            Enum != EnumEnd; ++Enum) {
8307         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8308           continue;
8309 
8310         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8311       }
8312 
8313       for (BuiltinCandidateTypeSet::iterator
8314                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8315              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8316            MemPtr != MemPtrEnd; ++MemPtr) {
8317         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8318           continue;
8319 
8320         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8321       }
8322     }
8323   }
8324 
8325   // C++ [over.built]p19:
8326   //
8327   //   For every pair (T, VQ), where T is any type and VQ is either
8328   //   volatile or empty, there exist candidate operator functions
8329   //   of the form
8330   //
8331   //        T*VQ&      operator=(T*VQ&, T*);
8332   //
8333   // C++ [over.built]p21:
8334   //
8335   //   For every pair (T, VQ), where T is a cv-qualified or
8336   //   cv-unqualified object type and VQ is either volatile or
8337   //   empty, there exist candidate operator functions of the form
8338   //
8339   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8340   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8341   void addAssignmentPointerOverloads(bool isEqualOp) {
8342     /// Set of (canonical) types that we've already handled.
8343     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8344 
8345     for (BuiltinCandidateTypeSet::iterator
8346               Ptr = CandidateTypes[0].pointer_begin(),
8347            PtrEnd = CandidateTypes[0].pointer_end();
8348          Ptr != PtrEnd; ++Ptr) {
8349       // If this is operator=, keep track of the builtin candidates we added.
8350       if (isEqualOp)
8351         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8352       else if (!(*Ptr)->getPointeeType()->isObjectType())
8353         continue;
8354 
8355       // non-volatile version
8356       QualType ParamTypes[2] = {
8357         S.Context.getLValueReferenceType(*Ptr),
8358         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8359       };
8360       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8361                             /*IsAssigmentOperator=*/ isEqualOp);
8362 
8363       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8364                           VisibleTypeConversionsQuals.hasVolatile();
8365       if (NeedVolatile) {
8366         // volatile version
8367         ParamTypes[0] =
8368           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8369         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8370                               /*IsAssigmentOperator=*/isEqualOp);
8371       }
8372 
8373       if (!(*Ptr).isRestrictQualified() &&
8374           VisibleTypeConversionsQuals.hasRestrict()) {
8375         // restrict version
8376         ParamTypes[0]
8377           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8378         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8379                               /*IsAssigmentOperator=*/isEqualOp);
8380 
8381         if (NeedVolatile) {
8382           // volatile restrict version
8383           ParamTypes[0]
8384             = S.Context.getLValueReferenceType(
8385                 S.Context.getCVRQualifiedType(*Ptr,
8386                                               (Qualifiers::Volatile |
8387                                                Qualifiers::Restrict)));
8388           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8389                                 /*IsAssigmentOperator=*/isEqualOp);
8390         }
8391       }
8392     }
8393 
8394     if (isEqualOp) {
8395       for (BuiltinCandidateTypeSet::iterator
8396                 Ptr = CandidateTypes[1].pointer_begin(),
8397              PtrEnd = CandidateTypes[1].pointer_end();
8398            Ptr != PtrEnd; ++Ptr) {
8399         // Make sure we don't add the same candidate twice.
8400         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8401           continue;
8402 
8403         QualType ParamTypes[2] = {
8404           S.Context.getLValueReferenceType(*Ptr),
8405           *Ptr,
8406         };
8407 
8408         // non-volatile version
8409         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8410                               /*IsAssigmentOperator=*/true);
8411 
8412         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8413                            VisibleTypeConversionsQuals.hasVolatile();
8414         if (NeedVolatile) {
8415           // volatile version
8416           ParamTypes[0] =
8417             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8418           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8419                                 /*IsAssigmentOperator=*/true);
8420         }
8421 
8422         if (!(*Ptr).isRestrictQualified() &&
8423             VisibleTypeConversionsQuals.hasRestrict()) {
8424           // restrict version
8425           ParamTypes[0]
8426             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8427           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8428                                 /*IsAssigmentOperator=*/true);
8429 
8430           if (NeedVolatile) {
8431             // volatile restrict version
8432             ParamTypes[0]
8433               = S.Context.getLValueReferenceType(
8434                   S.Context.getCVRQualifiedType(*Ptr,
8435                                                 (Qualifiers::Volatile |
8436                                                  Qualifiers::Restrict)));
8437             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8438                                   /*IsAssigmentOperator=*/true);
8439           }
8440         }
8441       }
8442     }
8443   }
8444 
8445   // C++ [over.built]p18:
8446   //
8447   //   For every triple (L, VQ, R), where L is an arithmetic type,
8448   //   VQ is either volatile or empty, and R is a promoted
8449   //   arithmetic type, there exist candidate operator functions of
8450   //   the form
8451   //
8452   //        VQ L&      operator=(VQ L&, R);
8453   //        VQ L&      operator*=(VQ L&, R);
8454   //        VQ L&      operator/=(VQ L&, R);
8455   //        VQ L&      operator+=(VQ L&, R);
8456   //        VQ L&      operator-=(VQ L&, R);
8457   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8458     if (!HasArithmeticOrEnumeralCandidateType)
8459       return;
8460 
8461     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8462       for (unsigned Right = FirstPromotedArithmeticType;
8463            Right < LastPromotedArithmeticType; ++Right) {
8464         QualType ParamTypes[2];
8465         ParamTypes[1] = ArithmeticTypes[Right];
8466 
8467         // Add this built-in operator as a candidate (VQ is empty).
8468         ParamTypes[0] =
8469           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8470         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8471                               /*IsAssigmentOperator=*/isEqualOp);
8472 
8473         // Add this built-in operator as a candidate (VQ is 'volatile').
8474         if (VisibleTypeConversionsQuals.hasVolatile()) {
8475           ParamTypes[0] =
8476             S.Context.getVolatileType(ArithmeticTypes[Left]);
8477           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8478           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8479                                 /*IsAssigmentOperator=*/isEqualOp);
8480         }
8481       }
8482     }
8483 
8484     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8485     for (BuiltinCandidateTypeSet::iterator
8486               Vec1 = CandidateTypes[0].vector_begin(),
8487            Vec1End = CandidateTypes[0].vector_end();
8488          Vec1 != Vec1End; ++Vec1) {
8489       for (BuiltinCandidateTypeSet::iterator
8490                 Vec2 = CandidateTypes[1].vector_begin(),
8491              Vec2End = CandidateTypes[1].vector_end();
8492            Vec2 != Vec2End; ++Vec2) {
8493         QualType ParamTypes[2];
8494         ParamTypes[1] = *Vec2;
8495         // Add this built-in operator as a candidate (VQ is empty).
8496         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8497         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8498                               /*IsAssigmentOperator=*/isEqualOp);
8499 
8500         // Add this built-in operator as a candidate (VQ is 'volatile').
8501         if (VisibleTypeConversionsQuals.hasVolatile()) {
8502           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8503           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8504           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8505                                 /*IsAssigmentOperator=*/isEqualOp);
8506         }
8507       }
8508     }
8509   }
8510 
8511   // C++ [over.built]p22:
8512   //
8513   //   For every triple (L, VQ, R), where L is an integral type, VQ
8514   //   is either volatile or empty, and R is a promoted integral
8515   //   type, there exist candidate operator functions of the form
8516   //
8517   //        VQ L&       operator%=(VQ L&, R);
8518   //        VQ L&       operator<<=(VQ L&, R);
8519   //        VQ L&       operator>>=(VQ L&, R);
8520   //        VQ L&       operator&=(VQ L&, R);
8521   //        VQ L&       operator^=(VQ L&, R);
8522   //        VQ L&       operator|=(VQ L&, R);
8523   void addAssignmentIntegralOverloads() {
8524     if (!HasArithmeticOrEnumeralCandidateType)
8525       return;
8526 
8527     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8528       for (unsigned Right = FirstPromotedIntegralType;
8529            Right < LastPromotedIntegralType; ++Right) {
8530         QualType ParamTypes[2];
8531         ParamTypes[1] = ArithmeticTypes[Right];
8532 
8533         // Add this built-in operator as a candidate (VQ is empty).
8534         ParamTypes[0] =
8535           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8536         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8537         if (VisibleTypeConversionsQuals.hasVolatile()) {
8538           // Add this built-in operator as a candidate (VQ is 'volatile').
8539           ParamTypes[0] = ArithmeticTypes[Left];
8540           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8541           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8542           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8543         }
8544       }
8545     }
8546   }
8547 
8548   // C++ [over.operator]p23:
8549   //
8550   //   There also exist candidate operator functions of the form
8551   //
8552   //        bool        operator!(bool);
8553   //        bool        operator&&(bool, bool);
8554   //        bool        operator||(bool, bool);
8555   void addExclaimOverload() {
8556     QualType ParamTy = S.Context.BoolTy;
8557     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8558                           /*IsAssignmentOperator=*/false,
8559                           /*NumContextualBoolArguments=*/1);
8560   }
8561   void addAmpAmpOrPipePipeOverload() {
8562     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8563     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8564                           /*IsAssignmentOperator=*/false,
8565                           /*NumContextualBoolArguments=*/2);
8566   }
8567 
8568   // C++ [over.built]p13:
8569   //
8570   //   For every cv-qualified or cv-unqualified object type T there
8571   //   exist candidate operator functions of the form
8572   //
8573   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8574   //        T&         operator[](T*, ptrdiff_t);
8575   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8576   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8577   //        T&         operator[](ptrdiff_t, T*);
8578   void addSubscriptOverloads() {
8579     for (BuiltinCandidateTypeSet::iterator
8580               Ptr = CandidateTypes[0].pointer_begin(),
8581            PtrEnd = CandidateTypes[0].pointer_end();
8582          Ptr != PtrEnd; ++Ptr) {
8583       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8584       QualType PointeeType = (*Ptr)->getPointeeType();
8585       if (!PointeeType->isObjectType())
8586         continue;
8587 
8588       // T& operator[](T*, ptrdiff_t)
8589       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8590     }
8591 
8592     for (BuiltinCandidateTypeSet::iterator
8593               Ptr = CandidateTypes[1].pointer_begin(),
8594            PtrEnd = CandidateTypes[1].pointer_end();
8595          Ptr != PtrEnd; ++Ptr) {
8596       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8597       QualType PointeeType = (*Ptr)->getPointeeType();
8598       if (!PointeeType->isObjectType())
8599         continue;
8600 
8601       // T& operator[](ptrdiff_t, T*)
8602       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8603     }
8604   }
8605 
8606   // C++ [over.built]p11:
8607   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8608   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8609   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8610   //    there exist candidate operator functions of the form
8611   //
8612   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8613   //
8614   //    where CV12 is the union of CV1 and CV2.
8615   void addArrowStarOverloads() {
8616     for (BuiltinCandidateTypeSet::iterator
8617              Ptr = CandidateTypes[0].pointer_begin(),
8618            PtrEnd = CandidateTypes[0].pointer_end();
8619          Ptr != PtrEnd; ++Ptr) {
8620       QualType C1Ty = (*Ptr);
8621       QualType C1;
8622       QualifierCollector Q1;
8623       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8624       if (!isa<RecordType>(C1))
8625         continue;
8626       // heuristic to reduce number of builtin candidates in the set.
8627       // Add volatile/restrict version only if there are conversions to a
8628       // volatile/restrict type.
8629       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8630         continue;
8631       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8632         continue;
8633       for (BuiltinCandidateTypeSet::iterator
8634                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8635              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8636            MemPtr != MemPtrEnd; ++MemPtr) {
8637         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8638         QualType C2 = QualType(mptr->getClass(), 0);
8639         C2 = C2.getUnqualifiedType();
8640         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8641           break;
8642         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8643         // build CV12 T&
8644         QualType T = mptr->getPointeeType();
8645         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8646             T.isVolatileQualified())
8647           continue;
8648         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8649             T.isRestrictQualified())
8650           continue;
8651         T = Q1.apply(S.Context, T);
8652         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8653       }
8654     }
8655   }
8656 
8657   // Note that we don't consider the first argument, since it has been
8658   // contextually converted to bool long ago. The candidates below are
8659   // therefore added as binary.
8660   //
8661   // C++ [over.built]p25:
8662   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8663   //   enumeration type, there exist candidate operator functions of the form
8664   //
8665   //        T        operator?(bool, T, T);
8666   //
8667   void addConditionalOperatorOverloads() {
8668     /// Set of (canonical) types that we've already handled.
8669     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8670 
8671     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8672       for (BuiltinCandidateTypeSet::iterator
8673                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8674              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8675            Ptr != PtrEnd; ++Ptr) {
8676         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8677           continue;
8678 
8679         QualType ParamTypes[2] = { *Ptr, *Ptr };
8680         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8681       }
8682 
8683       for (BuiltinCandidateTypeSet::iterator
8684                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8685              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8686            MemPtr != MemPtrEnd; ++MemPtr) {
8687         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8688           continue;
8689 
8690         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8691         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8692       }
8693 
8694       if (S.getLangOpts().CPlusPlus11) {
8695         for (BuiltinCandidateTypeSet::iterator
8696                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8697                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8698              Enum != EnumEnd; ++Enum) {
8699           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8700             continue;
8701 
8702           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8703             continue;
8704 
8705           QualType ParamTypes[2] = { *Enum, *Enum };
8706           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8707         }
8708       }
8709     }
8710   }
8711 };
8712 
8713 } // end anonymous namespace
8714 
8715 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8716 /// operator overloads to the candidate set (C++ [over.built]), based
8717 /// on the operator @p Op and the arguments given. For example, if the
8718 /// operator is a binary '+', this routine might add "int
8719 /// operator+(int, int)" to cover integer addition.
8720 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8721                                         SourceLocation OpLoc,
8722                                         ArrayRef<Expr *> Args,
8723                                         OverloadCandidateSet &CandidateSet) {
8724   // Find all of the types that the arguments can convert to, but only
8725   // if the operator we're looking at has built-in operator candidates
8726   // that make use of these types. Also record whether we encounter non-record
8727   // candidate types or either arithmetic or enumeral candidate types.
8728   Qualifiers VisibleTypeConversionsQuals;
8729   VisibleTypeConversionsQuals.addConst();
8730   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8731     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8732 
8733   bool HasNonRecordCandidateType = false;
8734   bool HasArithmeticOrEnumeralCandidateType = false;
8735   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8736   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8737     CandidateTypes.emplace_back(*this);
8738     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8739                                                  OpLoc,
8740                                                  true,
8741                                                  (Op == OO_Exclaim ||
8742                                                   Op == OO_AmpAmp ||
8743                                                   Op == OO_PipePipe),
8744                                                  VisibleTypeConversionsQuals);
8745     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8746         CandidateTypes[ArgIdx].hasNonRecordTypes();
8747     HasArithmeticOrEnumeralCandidateType =
8748         HasArithmeticOrEnumeralCandidateType ||
8749         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8750   }
8751 
8752   // Exit early when no non-record types have been added to the candidate set
8753   // for any of the arguments to the operator.
8754   //
8755   // We can't exit early for !, ||, or &&, since there we have always have
8756   // 'bool' overloads.
8757   if (!HasNonRecordCandidateType &&
8758       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8759     return;
8760 
8761   // Setup an object to manage the common state for building overloads.
8762   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8763                                            VisibleTypeConversionsQuals,
8764                                            HasArithmeticOrEnumeralCandidateType,
8765                                            CandidateTypes, CandidateSet);
8766 
8767   // Dispatch over the operation to add in only those overloads which apply.
8768   switch (Op) {
8769   case OO_None:
8770   case NUM_OVERLOADED_OPERATORS:
8771     llvm_unreachable("Expected an overloaded operator");
8772 
8773   case OO_New:
8774   case OO_Delete:
8775   case OO_Array_New:
8776   case OO_Array_Delete:
8777   case OO_Call:
8778     llvm_unreachable(
8779                     "Special operators don't use AddBuiltinOperatorCandidates");
8780 
8781   case OO_Comma:
8782   case OO_Arrow:
8783   case OO_Coawait:
8784     // C++ [over.match.oper]p3:
8785     //   -- For the operator ',', the unary operator '&', the
8786     //      operator '->', or the operator 'co_await', the
8787     //      built-in candidates set is empty.
8788     break;
8789 
8790   case OO_Plus: // '+' is either unary or binary
8791     if (Args.size() == 1)
8792       OpBuilder.addUnaryPlusPointerOverloads();
8793     LLVM_FALLTHROUGH;
8794 
8795   case OO_Minus: // '-' is either unary or binary
8796     if (Args.size() == 1) {
8797       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8798     } else {
8799       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8800       OpBuilder.addGenericBinaryArithmeticOverloads();
8801     }
8802     break;
8803 
8804   case OO_Star: // '*' is either unary or binary
8805     if (Args.size() == 1)
8806       OpBuilder.addUnaryStarPointerOverloads();
8807     else
8808       OpBuilder.addGenericBinaryArithmeticOverloads();
8809     break;
8810 
8811   case OO_Slash:
8812     OpBuilder.addGenericBinaryArithmeticOverloads();
8813     break;
8814 
8815   case OO_PlusPlus:
8816   case OO_MinusMinus:
8817     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8818     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8819     break;
8820 
8821   case OO_EqualEqual:
8822   case OO_ExclaimEqual:
8823     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8824     LLVM_FALLTHROUGH;
8825 
8826   case OO_Less:
8827   case OO_Greater:
8828   case OO_LessEqual:
8829   case OO_GreaterEqual:
8830     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8831     OpBuilder.addGenericBinaryArithmeticOverloads();
8832     break;
8833 
8834   case OO_Spaceship:
8835     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8836     OpBuilder.addThreeWayArithmeticOverloads();
8837     break;
8838 
8839   case OO_Percent:
8840   case OO_Caret:
8841   case OO_Pipe:
8842   case OO_LessLess:
8843   case OO_GreaterGreater:
8844     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8845     break;
8846 
8847   case OO_Amp: // '&' is either unary or binary
8848     if (Args.size() == 1)
8849       // C++ [over.match.oper]p3:
8850       //   -- For the operator ',', the unary operator '&', or the
8851       //      operator '->', the built-in candidates set is empty.
8852       break;
8853 
8854     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8855     break;
8856 
8857   case OO_Tilde:
8858     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8859     break;
8860 
8861   case OO_Equal:
8862     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8863     LLVM_FALLTHROUGH;
8864 
8865   case OO_PlusEqual:
8866   case OO_MinusEqual:
8867     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8868     LLVM_FALLTHROUGH;
8869 
8870   case OO_StarEqual:
8871   case OO_SlashEqual:
8872     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8873     break;
8874 
8875   case OO_PercentEqual:
8876   case OO_LessLessEqual:
8877   case OO_GreaterGreaterEqual:
8878   case OO_AmpEqual:
8879   case OO_CaretEqual:
8880   case OO_PipeEqual:
8881     OpBuilder.addAssignmentIntegralOverloads();
8882     break;
8883 
8884   case OO_Exclaim:
8885     OpBuilder.addExclaimOverload();
8886     break;
8887 
8888   case OO_AmpAmp:
8889   case OO_PipePipe:
8890     OpBuilder.addAmpAmpOrPipePipeOverload();
8891     break;
8892 
8893   case OO_Subscript:
8894     OpBuilder.addSubscriptOverloads();
8895     break;
8896 
8897   case OO_ArrowStar:
8898     OpBuilder.addArrowStarOverloads();
8899     break;
8900 
8901   case OO_Conditional:
8902     OpBuilder.addConditionalOperatorOverloads();
8903     OpBuilder.addGenericBinaryArithmeticOverloads();
8904     break;
8905   }
8906 }
8907 
8908 /// Add function candidates found via argument-dependent lookup
8909 /// to the set of overloading candidates.
8910 ///
8911 /// This routine performs argument-dependent name lookup based on the
8912 /// given function name (which may also be an operator name) and adds
8913 /// all of the overload candidates found by ADL to the overload
8914 /// candidate set (C++ [basic.lookup.argdep]).
8915 void
8916 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8917                                            SourceLocation Loc,
8918                                            ArrayRef<Expr *> Args,
8919                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8920                                            OverloadCandidateSet& CandidateSet,
8921                                            bool PartialOverloading) {
8922   ADLResult Fns;
8923 
8924   // FIXME: This approach for uniquing ADL results (and removing
8925   // redundant candidates from the set) relies on pointer-equality,
8926   // which means we need to key off the canonical decl.  However,
8927   // always going back to the canonical decl might not get us the
8928   // right set of default arguments.  What default arguments are
8929   // we supposed to consider on ADL candidates, anyway?
8930 
8931   // FIXME: Pass in the explicit template arguments?
8932   ArgumentDependentLookup(Name, Loc, Args, Fns);
8933 
8934   // Erase all of the candidates we already knew about.
8935   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8936                                    CandEnd = CandidateSet.end();
8937        Cand != CandEnd; ++Cand)
8938     if (Cand->Function) {
8939       Fns.erase(Cand->Function);
8940       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8941         Fns.erase(FunTmpl);
8942     }
8943 
8944   // For each of the ADL candidates we found, add it to the overload
8945   // set.
8946   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8947     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8948 
8949     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8950       if (ExplicitTemplateArgs)
8951         continue;
8952 
8953       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet,
8954                            /*SupressUserConversions=*/false, PartialOverloading,
8955                            /*AllowExplicit=*/false, ADLCallKind::UsesADL);
8956     } else {
8957       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), FoundDecl,
8958                                    ExplicitTemplateArgs, Args, CandidateSet,
8959                                    /*SupressUserConversions=*/false,
8960                                    PartialOverloading, ADLCallKind::UsesADL);
8961     }
8962   }
8963 }
8964 
8965 namespace {
8966 enum class Comparison { Equal, Better, Worse };
8967 }
8968 
8969 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8970 /// overload resolution.
8971 ///
8972 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8973 /// Cand1's first N enable_if attributes have precisely the same conditions as
8974 /// Cand2's first N enable_if attributes (where N = the number of enable_if
8975 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8976 ///
8977 /// Note that you can have a pair of candidates such that Cand1's enable_if
8978 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8979 /// worse than Cand1's.
8980 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8981                                        const FunctionDecl *Cand2) {
8982   // Common case: One (or both) decls don't have enable_if attrs.
8983   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8984   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8985   if (!Cand1Attr || !Cand2Attr) {
8986     if (Cand1Attr == Cand2Attr)
8987       return Comparison::Equal;
8988     return Cand1Attr ? Comparison::Better : Comparison::Worse;
8989   }
8990 
8991   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
8992   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
8993 
8994   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8995   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
8996     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
8997     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
8998 
8999     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9000     // has fewer enable_if attributes than Cand2, and vice versa.
9001     if (!Cand1A)
9002       return Comparison::Worse;
9003     if (!Cand2A)
9004       return Comparison::Better;
9005 
9006     Cand1ID.clear();
9007     Cand2ID.clear();
9008 
9009     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9010     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9011     if (Cand1ID != Cand2ID)
9012       return Comparison::Worse;
9013   }
9014 
9015   return Comparison::Equal;
9016 }
9017 
9018 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9019                                           const OverloadCandidate &Cand2) {
9020   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9021       !Cand2.Function->isMultiVersion())
9022     return false;
9023 
9024   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9025   // cpu_dispatch, else arbitrarily based on the identifiers.
9026   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9027   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9028   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9029   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9030 
9031   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9032     return false;
9033 
9034   if (Cand1CPUDisp && !Cand2CPUDisp)
9035     return true;
9036   if (Cand2CPUDisp && !Cand1CPUDisp)
9037     return false;
9038 
9039   if (Cand1CPUSpec && Cand2CPUSpec) {
9040     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9041       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size();
9042 
9043     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9044         FirstDiff = std::mismatch(
9045             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9046             Cand2CPUSpec->cpus_begin(),
9047             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9048               return LHS->getName() == RHS->getName();
9049             });
9050 
9051     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9052            "Two different cpu-specific versions should not have the same "
9053            "identifier list, otherwise they'd be the same decl!");
9054     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName();
9055   }
9056   llvm_unreachable("No way to get here unless both had cpu_dispatch");
9057 }
9058 
9059 /// isBetterOverloadCandidate - Determines whether the first overload
9060 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9061 bool clang::isBetterOverloadCandidate(
9062     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9063     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9064   // Define viable functions to be better candidates than non-viable
9065   // functions.
9066   if (!Cand2.Viable)
9067     return Cand1.Viable;
9068   else if (!Cand1.Viable)
9069     return false;
9070 
9071   // C++ [over.match.best]p1:
9072   //
9073   //   -- if F is a static member function, ICS1(F) is defined such
9074   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9075   //      any function G, and, symmetrically, ICS1(G) is neither
9076   //      better nor worse than ICS1(F).
9077   unsigned StartArg = 0;
9078   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9079     StartArg = 1;
9080 
9081   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9082     // We don't allow incompatible pointer conversions in C++.
9083     if (!S.getLangOpts().CPlusPlus)
9084       return ICS.isStandard() &&
9085              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9086 
9087     // The only ill-formed conversion we allow in C++ is the string literal to
9088     // char* conversion, which is only considered ill-formed after C++11.
9089     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9090            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9091   };
9092 
9093   // Define functions that don't require ill-formed conversions for a given
9094   // argument to be better candidates than functions that do.
9095   unsigned NumArgs = Cand1.Conversions.size();
9096   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9097   bool HasBetterConversion = false;
9098   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9099     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9100     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9101     if (Cand1Bad != Cand2Bad) {
9102       if (Cand1Bad)
9103         return false;
9104       HasBetterConversion = true;
9105     }
9106   }
9107 
9108   if (HasBetterConversion)
9109     return true;
9110 
9111   // C++ [over.match.best]p1:
9112   //   A viable function F1 is defined to be a better function than another
9113   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9114   //   conversion sequence than ICSi(F2), and then...
9115   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9116     switch (CompareImplicitConversionSequences(S, Loc,
9117                                                Cand1.Conversions[ArgIdx],
9118                                                Cand2.Conversions[ArgIdx])) {
9119     case ImplicitConversionSequence::Better:
9120       // Cand1 has a better conversion sequence.
9121       HasBetterConversion = true;
9122       break;
9123 
9124     case ImplicitConversionSequence::Worse:
9125       // Cand1 can't be better than Cand2.
9126       return false;
9127 
9128     case ImplicitConversionSequence::Indistinguishable:
9129       // Do nothing.
9130       break;
9131     }
9132   }
9133 
9134   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9135   //       ICSj(F2), or, if not that,
9136   if (HasBetterConversion)
9137     return true;
9138 
9139   //   -- the context is an initialization by user-defined conversion
9140   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9141   //      from the return type of F1 to the destination type (i.e.,
9142   //      the type of the entity being initialized) is a better
9143   //      conversion sequence than the standard conversion sequence
9144   //      from the return type of F2 to the destination type.
9145   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9146       Cand1.Function && Cand2.Function &&
9147       isa<CXXConversionDecl>(Cand1.Function) &&
9148       isa<CXXConversionDecl>(Cand2.Function)) {
9149     // First check whether we prefer one of the conversion functions over the
9150     // other. This only distinguishes the results in non-standard, extension
9151     // cases such as the conversion from a lambda closure type to a function
9152     // pointer or block.
9153     ImplicitConversionSequence::CompareKind Result =
9154         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9155     if (Result == ImplicitConversionSequence::Indistinguishable)
9156       Result = CompareStandardConversionSequences(S, Loc,
9157                                                   Cand1.FinalConversion,
9158                                                   Cand2.FinalConversion);
9159 
9160     if (Result != ImplicitConversionSequence::Indistinguishable)
9161       return Result == ImplicitConversionSequence::Better;
9162 
9163     // FIXME: Compare kind of reference binding if conversion functions
9164     // convert to a reference type used in direct reference binding, per
9165     // C++14 [over.match.best]p1 section 2 bullet 3.
9166   }
9167 
9168   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9169   // as combined with the resolution to CWG issue 243.
9170   //
9171   // When the context is initialization by constructor ([over.match.ctor] or
9172   // either phase of [over.match.list]), a constructor is preferred over
9173   // a conversion function.
9174   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9175       Cand1.Function && Cand2.Function &&
9176       isa<CXXConstructorDecl>(Cand1.Function) !=
9177           isa<CXXConstructorDecl>(Cand2.Function))
9178     return isa<CXXConstructorDecl>(Cand1.Function);
9179 
9180   //    -- F1 is a non-template function and F2 is a function template
9181   //       specialization, or, if not that,
9182   bool Cand1IsSpecialization = Cand1.Function &&
9183                                Cand1.Function->getPrimaryTemplate();
9184   bool Cand2IsSpecialization = Cand2.Function &&
9185                                Cand2.Function->getPrimaryTemplate();
9186   if (Cand1IsSpecialization != Cand2IsSpecialization)
9187     return Cand2IsSpecialization;
9188 
9189   //   -- F1 and F2 are function template specializations, and the function
9190   //      template for F1 is more specialized than the template for F2
9191   //      according to the partial ordering rules described in 14.5.5.2, or,
9192   //      if not that,
9193   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9194     if (FunctionTemplateDecl *BetterTemplate
9195           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9196                                          Cand2.Function->getPrimaryTemplate(),
9197                                          Loc,
9198                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9199                                                              : TPOC_Call,
9200                                          Cand1.ExplicitCallArguments,
9201                                          Cand2.ExplicitCallArguments))
9202       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9203   }
9204 
9205   // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9206   // A derived-class constructor beats an (inherited) base class constructor.
9207   bool Cand1IsInherited =
9208       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9209   bool Cand2IsInherited =
9210       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9211   if (Cand1IsInherited != Cand2IsInherited)
9212     return Cand2IsInherited;
9213   else if (Cand1IsInherited) {
9214     assert(Cand2IsInherited);
9215     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9216     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9217     if (Cand1Class->isDerivedFrom(Cand2Class))
9218       return true;
9219     if (Cand2Class->isDerivedFrom(Cand1Class))
9220       return false;
9221     // Inherited from sibling base classes: still ambiguous.
9222   }
9223 
9224   // Check C++17 tie-breakers for deduction guides.
9225   {
9226     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9227     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9228     if (Guide1 && Guide2) {
9229       //  -- F1 is generated from a deduction-guide and F2 is not
9230       if (Guide1->isImplicit() != Guide2->isImplicit())
9231         return Guide2->isImplicit();
9232 
9233       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9234       if (Guide1->isCopyDeductionCandidate())
9235         return true;
9236     }
9237   }
9238 
9239   // Check for enable_if value-based overload resolution.
9240   if (Cand1.Function && Cand2.Function) {
9241     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9242     if (Cmp != Comparison::Equal)
9243       return Cmp == Comparison::Better;
9244   }
9245 
9246   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9247     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9248     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9249            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9250   }
9251 
9252   bool HasPS1 = Cand1.Function != nullptr &&
9253                 functionHasPassObjectSizeParams(Cand1.Function);
9254   bool HasPS2 = Cand2.Function != nullptr &&
9255                 functionHasPassObjectSizeParams(Cand2.Function);
9256   if (HasPS1 != HasPS2 && HasPS1)
9257     return true;
9258 
9259   return isBetterMultiversionCandidate(Cand1, Cand2);
9260 }
9261 
9262 /// Determine whether two declarations are "equivalent" for the purposes of
9263 /// name lookup and overload resolution. This applies when the same internal/no
9264 /// linkage entity is defined by two modules (probably by textually including
9265 /// the same header). In such a case, we don't consider the declarations to
9266 /// declare the same entity, but we also don't want lookups with both
9267 /// declarations visible to be ambiguous in some cases (this happens when using
9268 /// a modularized libstdc++).
9269 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9270                                                   const NamedDecl *B) {
9271   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9272   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9273   if (!VA || !VB)
9274     return false;
9275 
9276   // The declarations must be declaring the same name as an internal linkage
9277   // entity in different modules.
9278   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9279           VB->getDeclContext()->getRedeclContext()) ||
9280       getOwningModule(const_cast<ValueDecl *>(VA)) ==
9281           getOwningModule(const_cast<ValueDecl *>(VB)) ||
9282       VA->isExternallyVisible() || VB->isExternallyVisible())
9283     return false;
9284 
9285   // Check that the declarations appear to be equivalent.
9286   //
9287   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9288   // For constants and functions, we should check the initializer or body is
9289   // the same. For non-constant variables, we shouldn't allow it at all.
9290   if (Context.hasSameType(VA->getType(), VB->getType()))
9291     return true;
9292 
9293   // Enum constants within unnamed enumerations will have different types, but
9294   // may still be similar enough to be interchangeable for our purposes.
9295   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9296     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9297       // Only handle anonymous enums. If the enumerations were named and
9298       // equivalent, they would have been merged to the same type.
9299       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9300       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9301       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9302           !Context.hasSameType(EnumA->getIntegerType(),
9303                                EnumB->getIntegerType()))
9304         return false;
9305       // Allow this only if the value is the same for both enumerators.
9306       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9307     }
9308   }
9309 
9310   // Nothing else is sufficiently similar.
9311   return false;
9312 }
9313 
9314 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9315     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9316   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9317 
9318   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9319   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9320       << !M << (M ? M->getFullModuleName() : "");
9321 
9322   for (auto *E : Equiv) {
9323     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9324     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9325         << !M << (M ? M->getFullModuleName() : "");
9326   }
9327 }
9328 
9329 /// Computes the best viable function (C++ 13.3.3)
9330 /// within an overload candidate set.
9331 ///
9332 /// \param Loc The location of the function name (or operator symbol) for
9333 /// which overload resolution occurs.
9334 ///
9335 /// \param Best If overload resolution was successful or found a deleted
9336 /// function, \p Best points to the candidate function found.
9337 ///
9338 /// \returns The result of overload resolution.
9339 OverloadingResult
9340 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9341                                          iterator &Best) {
9342   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9343   std::transform(begin(), end(), std::back_inserter(Candidates),
9344                  [](OverloadCandidate &Cand) { return &Cand; });
9345 
9346   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9347   // are accepted by both clang and NVCC. However, during a particular
9348   // compilation mode only one call variant is viable. We need to
9349   // exclude non-viable overload candidates from consideration based
9350   // only on their host/device attributes. Specifically, if one
9351   // candidate call is WrongSide and the other is SameSide, we ignore
9352   // the WrongSide candidate.
9353   if (S.getLangOpts().CUDA) {
9354     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9355     bool ContainsSameSideCandidate =
9356         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9357           return Cand->Function &&
9358                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9359                      Sema::CFP_SameSide;
9360         });
9361     if (ContainsSameSideCandidate) {
9362       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9363         return Cand->Function &&
9364                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9365                    Sema::CFP_WrongSide;
9366       };
9367       llvm::erase_if(Candidates, IsWrongSideCandidate);
9368     }
9369   }
9370 
9371   // Find the best viable function.
9372   Best = end();
9373   for (auto *Cand : Candidates)
9374     if (Cand->Viable)
9375       if (Best == end() ||
9376           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9377         Best = Cand;
9378 
9379   // If we didn't find any viable functions, abort.
9380   if (Best == end())
9381     return OR_No_Viable_Function;
9382 
9383   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9384 
9385   // Make sure that this function is better than every other viable
9386   // function. If not, we have an ambiguity.
9387   for (auto *Cand : Candidates) {
9388     if (Cand->Viable && Cand != Best &&
9389         !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
9390       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9391                                                    Cand->Function)) {
9392         EquivalentCands.push_back(Cand->Function);
9393         continue;
9394       }
9395 
9396       Best = end();
9397       return OR_Ambiguous;
9398     }
9399   }
9400 
9401   // Best is the best viable function.
9402   if (Best->Function &&
9403       (Best->Function->isDeleted() ||
9404        S.isFunctionConsideredUnavailable(Best->Function)))
9405     return OR_Deleted;
9406 
9407   if (!EquivalentCands.empty())
9408     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9409                                                     EquivalentCands);
9410 
9411   return OR_Success;
9412 }
9413 
9414 namespace {
9415 
9416 enum OverloadCandidateKind {
9417   oc_function,
9418   oc_method,
9419   oc_constructor,
9420   oc_implicit_default_constructor,
9421   oc_implicit_copy_constructor,
9422   oc_implicit_move_constructor,
9423   oc_implicit_copy_assignment,
9424   oc_implicit_move_assignment,
9425   oc_inherited_constructor
9426 };
9427 
9428 enum OverloadCandidateSelect {
9429   ocs_non_template,
9430   ocs_template,
9431   ocs_described_template,
9432 };
9433 
9434 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
9435 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9436                           std::string &Description) {
9437 
9438   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9439   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9440     isTemplate = true;
9441     Description = S.getTemplateArgumentBindingsText(
9442         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9443   }
9444 
9445   OverloadCandidateSelect Select = [&]() {
9446     if (!Description.empty())
9447       return ocs_described_template;
9448     return isTemplate ? ocs_template : ocs_non_template;
9449   }();
9450 
9451   OverloadCandidateKind Kind = [&]() {
9452     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9453       if (!Ctor->isImplicit()) {
9454         if (isa<ConstructorUsingShadowDecl>(Found))
9455           return oc_inherited_constructor;
9456         else
9457           return oc_constructor;
9458       }
9459 
9460       if (Ctor->isDefaultConstructor())
9461         return oc_implicit_default_constructor;
9462 
9463       if (Ctor->isMoveConstructor())
9464         return oc_implicit_move_constructor;
9465 
9466       assert(Ctor->isCopyConstructor() &&
9467              "unexpected sort of implicit constructor");
9468       return oc_implicit_copy_constructor;
9469     }
9470 
9471     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9472       // This actually gets spelled 'candidate function' for now, but
9473       // it doesn't hurt to split it out.
9474       if (!Meth->isImplicit())
9475         return oc_method;
9476 
9477       if (Meth->isMoveAssignmentOperator())
9478         return oc_implicit_move_assignment;
9479 
9480       if (Meth->isCopyAssignmentOperator())
9481         return oc_implicit_copy_assignment;
9482 
9483       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9484       return oc_method;
9485     }
9486 
9487     return oc_function;
9488   }();
9489 
9490   return std::make_pair(Kind, Select);
9491 }
9492 
9493 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9494   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9495   // set.
9496   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9497     S.Diag(FoundDecl->getLocation(),
9498            diag::note_ovl_candidate_inherited_constructor)
9499       << Shadow->getNominatedBaseClass();
9500 }
9501 
9502 } // end anonymous namespace
9503 
9504 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9505                                     const FunctionDecl *FD) {
9506   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9507     bool AlwaysTrue;
9508     if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9509       return false;
9510     if (!AlwaysTrue)
9511       return false;
9512   }
9513   return true;
9514 }
9515 
9516 /// Returns true if we can take the address of the function.
9517 ///
9518 /// \param Complain - If true, we'll emit a diagnostic
9519 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9520 ///   we in overload resolution?
9521 /// \param Loc - The location of the statement we're complaining about. Ignored
9522 ///   if we're not complaining, or if we're in overload resolution.
9523 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9524                                               bool Complain,
9525                                               bool InOverloadResolution,
9526                                               SourceLocation Loc) {
9527   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9528     if (Complain) {
9529       if (InOverloadResolution)
9530         S.Diag(FD->getBeginLoc(),
9531                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9532       else
9533         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9534     }
9535     return false;
9536   }
9537 
9538   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9539     return P->hasAttr<PassObjectSizeAttr>();
9540   });
9541   if (I == FD->param_end())
9542     return true;
9543 
9544   if (Complain) {
9545     // Add one to ParamNo because it's user-facing
9546     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9547     if (InOverloadResolution)
9548       S.Diag(FD->getLocation(),
9549              diag::note_ovl_candidate_has_pass_object_size_params)
9550           << ParamNo;
9551     else
9552       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9553           << FD << ParamNo;
9554   }
9555   return false;
9556 }
9557 
9558 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9559                                                const FunctionDecl *FD) {
9560   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9561                                            /*InOverloadResolution=*/true,
9562                                            /*Loc=*/SourceLocation());
9563 }
9564 
9565 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9566                                              bool Complain,
9567                                              SourceLocation Loc) {
9568   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9569                                              /*InOverloadResolution=*/false,
9570                                              Loc);
9571 }
9572 
9573 // Notes the location of an overload candidate.
9574 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9575                                  QualType DestType, bool TakingAddress) {
9576   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9577     return;
9578   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
9579       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
9580     return;
9581 
9582   std::string FnDesc;
9583   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
9584       ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9585   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9586                          << (unsigned)KSPair.first << (unsigned)KSPair.second
9587                          << Fn << FnDesc;
9588 
9589   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9590   Diag(Fn->getLocation(), PD);
9591   MaybeEmitInheritedConstructorNote(*this, Found);
9592 }
9593 
9594 // Notes the location of all overload candidates designated through
9595 // OverloadedExpr
9596 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9597                                      bool TakingAddress) {
9598   assert(OverloadedExpr->getType() == Context.OverloadTy);
9599 
9600   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9601   OverloadExpr *OvlExpr = Ovl.Expression;
9602 
9603   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9604                             IEnd = OvlExpr->decls_end();
9605        I != IEnd; ++I) {
9606     if (FunctionTemplateDecl *FunTmpl =
9607                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9608       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9609                             TakingAddress);
9610     } else if (FunctionDecl *Fun
9611                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9612       NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9613     }
9614   }
9615 }
9616 
9617 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9618 /// "lead" diagnostic; it will be given two arguments, the source and
9619 /// target types of the conversion.
9620 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9621                                  Sema &S,
9622                                  SourceLocation CaretLoc,
9623                                  const PartialDiagnostic &PDiag) const {
9624   S.Diag(CaretLoc, PDiag)
9625     << Ambiguous.getFromType() << Ambiguous.getToType();
9626   // FIXME: The note limiting machinery is borrowed from
9627   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9628   // refactoring here.
9629   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9630   unsigned CandsShown = 0;
9631   AmbiguousConversionSequence::const_iterator I, E;
9632   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9633     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9634       break;
9635     ++CandsShown;
9636     S.NoteOverloadCandidate(I->first, I->second);
9637   }
9638   if (I != E)
9639     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9640 }
9641 
9642 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9643                                   unsigned I, bool TakingCandidateAddress) {
9644   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9645   assert(Conv.isBad());
9646   assert(Cand->Function && "for now, candidate must be a function");
9647   FunctionDecl *Fn = Cand->Function;
9648 
9649   // There's a conversion slot for the object argument if this is a
9650   // non-constructor method.  Note that 'I' corresponds the
9651   // conversion-slot index.
9652   bool isObjectArgument = false;
9653   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9654     if (I == 0)
9655       isObjectArgument = true;
9656     else
9657       I--;
9658   }
9659 
9660   std::string FnDesc;
9661   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
9662       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9663 
9664   Expr *FromExpr = Conv.Bad.FromExpr;
9665   QualType FromTy = Conv.Bad.getFromType();
9666   QualType ToTy = Conv.Bad.getToType();
9667 
9668   if (FromTy == S.Context.OverloadTy) {
9669     assert(FromExpr && "overload set argument came from implicit argument?");
9670     Expr *E = FromExpr->IgnoreParens();
9671     if (isa<UnaryOperator>(E))
9672       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9673     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9674 
9675     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9676         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9677         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
9678         << Name << I + 1;
9679     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9680     return;
9681   }
9682 
9683   // Do some hand-waving analysis to see if the non-viability is due
9684   // to a qualifier mismatch.
9685   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9686   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9687   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9688     CToTy = RT->getPointeeType();
9689   else {
9690     // TODO: detect and diagnose the full richness of const mismatches.
9691     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9692       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9693         CFromTy = FromPT->getPointeeType();
9694         CToTy = ToPT->getPointeeType();
9695       }
9696   }
9697 
9698   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9699       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9700     Qualifiers FromQs = CFromTy.getQualifiers();
9701     Qualifiers ToQs = CToTy.getQualifiers();
9702 
9703     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9704       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9705           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9706           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9707           << ToTy << (unsigned)isObjectArgument << I + 1;
9708       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9709       return;
9710     }
9711 
9712     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9713       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9714           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9715           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9716           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9717           << (unsigned)isObjectArgument << I + 1;
9718       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9719       return;
9720     }
9721 
9722     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9723       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9724           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9725           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9726           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9727           << (unsigned)isObjectArgument << I + 1;
9728       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9729       return;
9730     }
9731 
9732     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9733       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9734           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9735           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9736           << FromQs.hasUnaligned() << I + 1;
9737       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9738       return;
9739     }
9740 
9741     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9742     assert(CVR && "unexpected qualifiers mismatch");
9743 
9744     if (isObjectArgument) {
9745       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9746           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9747           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9748           << (CVR - 1);
9749     } else {
9750       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9751           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9752           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9753           << (CVR - 1) << I + 1;
9754     }
9755     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9756     return;
9757   }
9758 
9759   // Special diagnostic for failure to convert an initializer list, since
9760   // telling the user that it has type void is not useful.
9761   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9762     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9763         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9764         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9765         << ToTy << (unsigned)isObjectArgument << I + 1;
9766     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9767     return;
9768   }
9769 
9770   // Diagnose references or pointers to incomplete types differently,
9771   // since it's far from impossible that the incompleteness triggered
9772   // the failure.
9773   QualType TempFromTy = FromTy.getNonReferenceType();
9774   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9775     TempFromTy = PTy->getPointeeType();
9776   if (TempFromTy->isIncompleteType()) {
9777     // Emit the generic diagnostic and, optionally, add the hints to it.
9778     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9779         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9780         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9781         << ToTy << (unsigned)isObjectArgument << I + 1
9782         << (unsigned)(Cand->Fix.Kind);
9783 
9784     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9785     return;
9786   }
9787 
9788   // Diagnose base -> derived pointer conversions.
9789   unsigned BaseToDerivedConversion = 0;
9790   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9791     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9792       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9793                                                FromPtrTy->getPointeeType()) &&
9794           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9795           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9796           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9797                           FromPtrTy->getPointeeType()))
9798         BaseToDerivedConversion = 1;
9799     }
9800   } else if (const ObjCObjectPointerType *FromPtrTy
9801                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9802     if (const ObjCObjectPointerType *ToPtrTy
9803                                         = ToTy->getAs<ObjCObjectPointerType>())
9804       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9805         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9806           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9807                                                 FromPtrTy->getPointeeType()) &&
9808               FromIface->isSuperClassOf(ToIface))
9809             BaseToDerivedConversion = 2;
9810   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9811     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9812         !FromTy->isIncompleteType() &&
9813         !ToRefTy->getPointeeType()->isIncompleteType() &&
9814         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9815       BaseToDerivedConversion = 3;
9816     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9817                ToTy.getNonReferenceType().getCanonicalType() ==
9818                FromTy.getNonReferenceType().getCanonicalType()) {
9819       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9820           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9821           << (unsigned)isObjectArgument << I + 1
9822           << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
9823       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9824       return;
9825     }
9826   }
9827 
9828   if (BaseToDerivedConversion) {
9829     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
9830         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9831         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9832         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
9833     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9834     return;
9835   }
9836 
9837   if (isa<ObjCObjectPointerType>(CFromTy) &&
9838       isa<PointerType>(CToTy)) {
9839       Qualifiers FromQs = CFromTy.getQualifiers();
9840       Qualifiers ToQs = CToTy.getQualifiers();
9841       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9842         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9843             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9844             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9845             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
9846         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9847         return;
9848       }
9849   }
9850 
9851   if (TakingCandidateAddress &&
9852       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9853     return;
9854 
9855   // Emit the generic diagnostic and, optionally, add the hints to it.
9856   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9857   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9858         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9859         << ToTy << (unsigned)isObjectArgument << I + 1
9860         << (unsigned)(Cand->Fix.Kind);
9861 
9862   // If we can fix the conversion, suggest the FixIts.
9863   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9864        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9865     FDiag << *HI;
9866   S.Diag(Fn->getLocation(), FDiag);
9867 
9868   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9869 }
9870 
9871 /// Additional arity mismatch diagnosis specific to a function overload
9872 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9873 /// over a candidate in any candidate set.
9874 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9875                                unsigned NumArgs) {
9876   FunctionDecl *Fn = Cand->Function;
9877   unsigned MinParams = Fn->getMinRequiredArguments();
9878 
9879   // With invalid overloaded operators, it's possible that we think we
9880   // have an arity mismatch when in fact it looks like we have the
9881   // right number of arguments, because only overloaded operators have
9882   // the weird behavior of overloading member and non-member functions.
9883   // Just don't report anything.
9884   if (Fn->isInvalidDecl() &&
9885       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9886     return true;
9887 
9888   if (NumArgs < MinParams) {
9889     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9890            (Cand->FailureKind == ovl_fail_bad_deduction &&
9891             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9892   } else {
9893     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9894            (Cand->FailureKind == ovl_fail_bad_deduction &&
9895             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9896   }
9897 
9898   return false;
9899 }
9900 
9901 /// General arity mismatch diagnosis over a candidate in a candidate set.
9902 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9903                                   unsigned NumFormalArgs) {
9904   assert(isa<FunctionDecl>(D) &&
9905       "The templated declaration should at least be a function"
9906       " when diagnosing bad template argument deduction due to too many"
9907       " or too few arguments");
9908 
9909   FunctionDecl *Fn = cast<FunctionDecl>(D);
9910 
9911   // TODO: treat calls to a missing default constructor as a special case
9912   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9913   unsigned MinParams = Fn->getMinRequiredArguments();
9914 
9915   // at least / at most / exactly
9916   unsigned mode, modeCount;
9917   if (NumFormalArgs < MinParams) {
9918     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9919         FnTy->isTemplateVariadic())
9920       mode = 0; // "at least"
9921     else
9922       mode = 2; // "exactly"
9923     modeCount = MinParams;
9924   } else {
9925     if (MinParams != FnTy->getNumParams())
9926       mode = 1; // "at most"
9927     else
9928       mode = 2; // "exactly"
9929     modeCount = FnTy->getNumParams();
9930   }
9931 
9932   std::string Description;
9933   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
9934       ClassifyOverloadCandidate(S, Found, Fn, Description);
9935 
9936   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9937     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9938         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9939         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
9940   else
9941     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9942         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9943         << Description << mode << modeCount << NumFormalArgs;
9944 
9945   MaybeEmitInheritedConstructorNote(S, Found);
9946 }
9947 
9948 /// Arity mismatch diagnosis specific to a function overload candidate.
9949 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9950                                   unsigned NumFormalArgs) {
9951   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9952     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9953 }
9954 
9955 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9956   if (TemplateDecl *TD = Templated->getDescribedTemplate())
9957     return TD;
9958   llvm_unreachable("Unsupported: Getting the described template declaration"
9959                    " for bad deduction diagnosis");
9960 }
9961 
9962 /// Diagnose a failed template-argument deduction.
9963 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9964                                  DeductionFailureInfo &DeductionFailure,
9965                                  unsigned NumArgs,
9966                                  bool TakingCandidateAddress) {
9967   TemplateParameter Param = DeductionFailure.getTemplateParameter();
9968   NamedDecl *ParamD;
9969   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9970   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9971   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9972   switch (DeductionFailure.Result) {
9973   case Sema::TDK_Success:
9974     llvm_unreachable("TDK_success while diagnosing bad deduction");
9975 
9976   case Sema::TDK_Incomplete: {
9977     assert(ParamD && "no parameter found for incomplete deduction result");
9978     S.Diag(Templated->getLocation(),
9979            diag::note_ovl_candidate_incomplete_deduction)
9980         << ParamD->getDeclName();
9981     MaybeEmitInheritedConstructorNote(S, Found);
9982     return;
9983   }
9984 
9985   case Sema::TDK_IncompletePack: {
9986     assert(ParamD && "no parameter found for incomplete deduction result");
9987     S.Diag(Templated->getLocation(),
9988            diag::note_ovl_candidate_incomplete_deduction_pack)
9989         << ParamD->getDeclName()
9990         << (DeductionFailure.getFirstArg()->pack_size() + 1)
9991         << *DeductionFailure.getFirstArg();
9992     MaybeEmitInheritedConstructorNote(S, Found);
9993     return;
9994   }
9995 
9996   case Sema::TDK_Underqualified: {
9997     assert(ParamD && "no parameter found for bad qualifiers deduction result");
9998     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9999 
10000     QualType Param = DeductionFailure.getFirstArg()->getAsType();
10001 
10002     // Param will have been canonicalized, but it should just be a
10003     // qualified version of ParamD, so move the qualifiers to that.
10004     QualifierCollector Qs;
10005     Qs.strip(Param);
10006     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10007     assert(S.Context.hasSameType(Param, NonCanonParam));
10008 
10009     // Arg has also been canonicalized, but there's nothing we can do
10010     // about that.  It also doesn't matter as much, because it won't
10011     // have any template parameters in it (because deduction isn't
10012     // done on dependent types).
10013     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10014 
10015     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10016         << ParamD->getDeclName() << Arg << NonCanonParam;
10017     MaybeEmitInheritedConstructorNote(S, Found);
10018     return;
10019   }
10020 
10021   case Sema::TDK_Inconsistent: {
10022     assert(ParamD && "no parameter found for inconsistent deduction result");
10023     int which = 0;
10024     if (isa<TemplateTypeParmDecl>(ParamD))
10025       which = 0;
10026     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10027       // Deduction might have failed because we deduced arguments of two
10028       // different types for a non-type template parameter.
10029       // FIXME: Use a different TDK value for this.
10030       QualType T1 =
10031           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10032       QualType T2 =
10033           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10034       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10035         S.Diag(Templated->getLocation(),
10036                diag::note_ovl_candidate_inconsistent_deduction_types)
10037           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10038           << *DeductionFailure.getSecondArg() << T2;
10039         MaybeEmitInheritedConstructorNote(S, Found);
10040         return;
10041       }
10042 
10043       which = 1;
10044     } else {
10045       which = 2;
10046     }
10047 
10048     S.Diag(Templated->getLocation(),
10049            diag::note_ovl_candidate_inconsistent_deduction)
10050         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10051         << *DeductionFailure.getSecondArg();
10052     MaybeEmitInheritedConstructorNote(S, Found);
10053     return;
10054   }
10055 
10056   case Sema::TDK_InvalidExplicitArguments:
10057     assert(ParamD && "no parameter found for invalid explicit arguments");
10058     if (ParamD->getDeclName())
10059       S.Diag(Templated->getLocation(),
10060              diag::note_ovl_candidate_explicit_arg_mismatch_named)
10061           << ParamD->getDeclName();
10062     else {
10063       int index = 0;
10064       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10065         index = TTP->getIndex();
10066       else if (NonTypeTemplateParmDecl *NTTP
10067                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10068         index = NTTP->getIndex();
10069       else
10070         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10071       S.Diag(Templated->getLocation(),
10072              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10073           << (index + 1);
10074     }
10075     MaybeEmitInheritedConstructorNote(S, Found);
10076     return;
10077 
10078   case Sema::TDK_TooManyArguments:
10079   case Sema::TDK_TooFewArguments:
10080     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10081     return;
10082 
10083   case Sema::TDK_InstantiationDepth:
10084     S.Diag(Templated->getLocation(),
10085            diag::note_ovl_candidate_instantiation_depth);
10086     MaybeEmitInheritedConstructorNote(S, Found);
10087     return;
10088 
10089   case Sema::TDK_SubstitutionFailure: {
10090     // Format the template argument list into the argument string.
10091     SmallString<128> TemplateArgString;
10092     if (TemplateArgumentList *Args =
10093             DeductionFailure.getTemplateArgumentList()) {
10094       TemplateArgString = " ";
10095       TemplateArgString += S.getTemplateArgumentBindingsText(
10096           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10097     }
10098 
10099     // If this candidate was disabled by enable_if, say so.
10100     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10101     if (PDiag && PDiag->second.getDiagID() ==
10102           diag::err_typename_nested_not_found_enable_if) {
10103       // FIXME: Use the source range of the condition, and the fully-qualified
10104       //        name of the enable_if template. These are both present in PDiag.
10105       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10106         << "'enable_if'" << TemplateArgString;
10107       return;
10108     }
10109 
10110     // We found a specific requirement that disabled the enable_if.
10111     if (PDiag && PDiag->second.getDiagID() ==
10112         diag::err_typename_nested_not_found_requirement) {
10113       S.Diag(Templated->getLocation(),
10114              diag::note_ovl_candidate_disabled_by_requirement)
10115         << PDiag->second.getStringArg(0) << TemplateArgString;
10116       return;
10117     }
10118 
10119     // Format the SFINAE diagnostic into the argument string.
10120     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10121     //        formatted message in another diagnostic.
10122     SmallString<128> SFINAEArgString;
10123     SourceRange R;
10124     if (PDiag) {
10125       SFINAEArgString = ": ";
10126       R = SourceRange(PDiag->first, PDiag->first);
10127       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10128     }
10129 
10130     S.Diag(Templated->getLocation(),
10131            diag::note_ovl_candidate_substitution_failure)
10132         << TemplateArgString << SFINAEArgString << R;
10133     MaybeEmitInheritedConstructorNote(S, Found);
10134     return;
10135   }
10136 
10137   case Sema::TDK_DeducedMismatch:
10138   case Sema::TDK_DeducedMismatchNested: {
10139     // Format the template argument list into the argument string.
10140     SmallString<128> TemplateArgString;
10141     if (TemplateArgumentList *Args =
10142             DeductionFailure.getTemplateArgumentList()) {
10143       TemplateArgString = " ";
10144       TemplateArgString += S.getTemplateArgumentBindingsText(
10145           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10146     }
10147 
10148     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10149         << (*DeductionFailure.getCallArgIndex() + 1)
10150         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10151         << TemplateArgString
10152         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10153     break;
10154   }
10155 
10156   case Sema::TDK_NonDeducedMismatch: {
10157     // FIXME: Provide a source location to indicate what we couldn't match.
10158     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10159     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10160     if (FirstTA.getKind() == TemplateArgument::Template &&
10161         SecondTA.getKind() == TemplateArgument::Template) {
10162       TemplateName FirstTN = FirstTA.getAsTemplate();
10163       TemplateName SecondTN = SecondTA.getAsTemplate();
10164       if (FirstTN.getKind() == TemplateName::Template &&
10165           SecondTN.getKind() == TemplateName::Template) {
10166         if (FirstTN.getAsTemplateDecl()->getName() ==
10167             SecondTN.getAsTemplateDecl()->getName()) {
10168           // FIXME: This fixes a bad diagnostic where both templates are named
10169           // the same.  This particular case is a bit difficult since:
10170           // 1) It is passed as a string to the diagnostic printer.
10171           // 2) The diagnostic printer only attempts to find a better
10172           //    name for types, not decls.
10173           // Ideally, this should folded into the diagnostic printer.
10174           S.Diag(Templated->getLocation(),
10175                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10176               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10177           return;
10178         }
10179       }
10180     }
10181 
10182     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10183         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10184       return;
10185 
10186     // FIXME: For generic lambda parameters, check if the function is a lambda
10187     // call operator, and if so, emit a prettier and more informative
10188     // diagnostic that mentions 'auto' and lambda in addition to
10189     // (or instead of?) the canonical template type parameters.
10190     S.Diag(Templated->getLocation(),
10191            diag::note_ovl_candidate_non_deduced_mismatch)
10192         << FirstTA << SecondTA;
10193     return;
10194   }
10195   // TODO: diagnose these individually, then kill off
10196   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10197   case Sema::TDK_MiscellaneousDeductionFailure:
10198     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10199     MaybeEmitInheritedConstructorNote(S, Found);
10200     return;
10201   case Sema::TDK_CUDATargetMismatch:
10202     S.Diag(Templated->getLocation(),
10203            diag::note_cuda_ovl_candidate_target_mismatch);
10204     return;
10205   }
10206 }
10207 
10208 /// Diagnose a failed template-argument deduction, for function calls.
10209 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10210                                  unsigned NumArgs,
10211                                  bool TakingCandidateAddress) {
10212   unsigned TDK = Cand->DeductionFailure.Result;
10213   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10214     if (CheckArityMismatch(S, Cand, NumArgs))
10215       return;
10216   }
10217   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10218                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10219 }
10220 
10221 /// CUDA: diagnose an invalid call across targets.
10222 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10223   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10224   FunctionDecl *Callee = Cand->Function;
10225 
10226   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10227                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10228 
10229   std::string FnDesc;
10230   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10231       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
10232 
10233   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10234       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10235       << FnDesc /* Ignored */
10236       << CalleeTarget << CallerTarget;
10237 
10238   // This could be an implicit constructor for which we could not infer the
10239   // target due to a collsion. Diagnose that case.
10240   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10241   if (Meth != nullptr && Meth->isImplicit()) {
10242     CXXRecordDecl *ParentClass = Meth->getParent();
10243     Sema::CXXSpecialMember CSM;
10244 
10245     switch (FnKindPair.first) {
10246     default:
10247       return;
10248     case oc_implicit_default_constructor:
10249       CSM = Sema::CXXDefaultConstructor;
10250       break;
10251     case oc_implicit_copy_constructor:
10252       CSM = Sema::CXXCopyConstructor;
10253       break;
10254     case oc_implicit_move_constructor:
10255       CSM = Sema::CXXMoveConstructor;
10256       break;
10257     case oc_implicit_copy_assignment:
10258       CSM = Sema::CXXCopyAssignment;
10259       break;
10260     case oc_implicit_move_assignment:
10261       CSM = Sema::CXXMoveAssignment;
10262       break;
10263     };
10264 
10265     bool ConstRHS = false;
10266     if (Meth->getNumParams()) {
10267       if (const ReferenceType *RT =
10268               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10269         ConstRHS = RT->getPointeeType().isConstQualified();
10270       }
10271     }
10272 
10273     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10274                                               /* ConstRHS */ ConstRHS,
10275                                               /* Diagnose */ true);
10276   }
10277 }
10278 
10279 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10280   FunctionDecl *Callee = Cand->Function;
10281   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10282 
10283   S.Diag(Callee->getLocation(),
10284          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10285       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10286 }
10287 
10288 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10289   FunctionDecl *Callee = Cand->Function;
10290 
10291   S.Diag(Callee->getLocation(),
10292          diag::note_ovl_candidate_disabled_by_extension)
10293     << S.getOpenCLExtensionsFromDeclExtMap(Callee);
10294 }
10295 
10296 /// Generates a 'note' diagnostic for an overload candidate.  We've
10297 /// already generated a primary error at the call site.
10298 ///
10299 /// It really does need to be a single diagnostic with its caret
10300 /// pointed at the candidate declaration.  Yes, this creates some
10301 /// major challenges of technical writing.  Yes, this makes pointing
10302 /// out problems with specific arguments quite awkward.  It's still
10303 /// better than generating twenty screens of text for every failed
10304 /// overload.
10305 ///
10306 /// It would be great to be able to express per-candidate problems
10307 /// more richly for those diagnostic clients that cared, but we'd
10308 /// still have to be just as careful with the default diagnostics.
10309 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10310                                   unsigned NumArgs,
10311                                   bool TakingCandidateAddress) {
10312   FunctionDecl *Fn = Cand->Function;
10313 
10314   // Note deleted candidates, but only if they're viable.
10315   if (Cand->Viable) {
10316     if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10317       std::string FnDesc;
10318       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10319           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
10320 
10321       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10322           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10323           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10324       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10325       return;
10326     }
10327 
10328     // We don't really have anything else to say about viable candidates.
10329     S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10330     return;
10331   }
10332 
10333   switch (Cand->FailureKind) {
10334   case ovl_fail_too_many_arguments:
10335   case ovl_fail_too_few_arguments:
10336     return DiagnoseArityMismatch(S, Cand, NumArgs);
10337 
10338   case ovl_fail_bad_deduction:
10339     return DiagnoseBadDeduction(S, Cand, NumArgs,
10340                                 TakingCandidateAddress);
10341 
10342   case ovl_fail_illegal_constructor: {
10343     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10344       << (Fn->getPrimaryTemplate() ? 1 : 0);
10345     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10346     return;
10347   }
10348 
10349   case ovl_fail_trivial_conversion:
10350   case ovl_fail_bad_final_conversion:
10351   case ovl_fail_final_conversion_not_exact:
10352     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10353 
10354   case ovl_fail_bad_conversion: {
10355     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10356     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10357       if (Cand->Conversions[I].isBad())
10358         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10359 
10360     // FIXME: this currently happens when we're called from SemaInit
10361     // when user-conversion overload fails.  Figure out how to handle
10362     // those conditions and diagnose them well.
10363     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10364   }
10365 
10366   case ovl_fail_bad_target:
10367     return DiagnoseBadTarget(S, Cand);
10368 
10369   case ovl_fail_enable_if:
10370     return DiagnoseFailedEnableIfAttr(S, Cand);
10371 
10372   case ovl_fail_ext_disabled:
10373     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10374 
10375   case ovl_fail_inhctor_slice:
10376     // It's generally not interesting to note copy/move constructors here.
10377     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10378       return;
10379     S.Diag(Fn->getLocation(),
10380            diag::note_ovl_candidate_inherited_constructor_slice)
10381       << (Fn->getPrimaryTemplate() ? 1 : 0)
10382       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10383     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10384     return;
10385 
10386   case ovl_fail_addr_not_available: {
10387     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10388     (void)Available;
10389     assert(!Available);
10390     break;
10391   }
10392   case ovl_non_default_multiversion_function:
10393     // Do nothing, these should simply be ignored.
10394     break;
10395   }
10396 }
10397 
10398 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10399   // Desugar the type of the surrogate down to a function type,
10400   // retaining as many typedefs as possible while still showing
10401   // the function type (and, therefore, its parameter types).
10402   QualType FnType = Cand->Surrogate->getConversionType();
10403   bool isLValueReference = false;
10404   bool isRValueReference = false;
10405   bool isPointer = false;
10406   if (const LValueReferenceType *FnTypeRef =
10407         FnType->getAs<LValueReferenceType>()) {
10408     FnType = FnTypeRef->getPointeeType();
10409     isLValueReference = true;
10410   } else if (const RValueReferenceType *FnTypeRef =
10411                FnType->getAs<RValueReferenceType>()) {
10412     FnType = FnTypeRef->getPointeeType();
10413     isRValueReference = true;
10414   }
10415   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10416     FnType = FnTypePtr->getPointeeType();
10417     isPointer = true;
10418   }
10419   // Desugar down to a function type.
10420   FnType = QualType(FnType->getAs<FunctionType>(), 0);
10421   // Reconstruct the pointer/reference as appropriate.
10422   if (isPointer) FnType = S.Context.getPointerType(FnType);
10423   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10424   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10425 
10426   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10427     << FnType;
10428 }
10429 
10430 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10431                                          SourceLocation OpLoc,
10432                                          OverloadCandidate *Cand) {
10433   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10434   std::string TypeStr("operator");
10435   TypeStr += Opc;
10436   TypeStr += "(";
10437   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
10438   if (Cand->Conversions.size() == 1) {
10439     TypeStr += ")";
10440     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10441   } else {
10442     TypeStr += ", ";
10443     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
10444     TypeStr += ")";
10445     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10446   }
10447 }
10448 
10449 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10450                                          OverloadCandidate *Cand) {
10451   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10452     if (ICS.isBad()) break; // all meaningless after first invalid
10453     if (!ICS.isAmbiguous()) continue;
10454 
10455     ICS.DiagnoseAmbiguousConversion(
10456         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10457   }
10458 }
10459 
10460 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10461   if (Cand->Function)
10462     return Cand->Function->getLocation();
10463   if (Cand->IsSurrogate)
10464     return Cand->Surrogate->getLocation();
10465   return SourceLocation();
10466 }
10467 
10468 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10469   switch ((Sema::TemplateDeductionResult)DFI.Result) {
10470   case Sema::TDK_Success:
10471   case Sema::TDK_NonDependentConversionFailure:
10472     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10473 
10474   case Sema::TDK_Invalid:
10475   case Sema::TDK_Incomplete:
10476   case Sema::TDK_IncompletePack:
10477     return 1;
10478 
10479   case Sema::TDK_Underqualified:
10480   case Sema::TDK_Inconsistent:
10481     return 2;
10482 
10483   case Sema::TDK_SubstitutionFailure:
10484   case Sema::TDK_DeducedMismatch:
10485   case Sema::TDK_DeducedMismatchNested:
10486   case Sema::TDK_NonDeducedMismatch:
10487   case Sema::TDK_MiscellaneousDeductionFailure:
10488   case Sema::TDK_CUDATargetMismatch:
10489     return 3;
10490 
10491   case Sema::TDK_InstantiationDepth:
10492     return 4;
10493 
10494   case Sema::TDK_InvalidExplicitArguments:
10495     return 5;
10496 
10497   case Sema::TDK_TooManyArguments:
10498   case Sema::TDK_TooFewArguments:
10499     return 6;
10500   }
10501   llvm_unreachable("Unhandled deduction result");
10502 }
10503 
10504 namespace {
10505 struct CompareOverloadCandidatesForDisplay {
10506   Sema &S;
10507   SourceLocation Loc;
10508   size_t NumArgs;
10509   OverloadCandidateSet::CandidateSetKind CSK;
10510 
10511   CompareOverloadCandidatesForDisplay(
10512       Sema &S, SourceLocation Loc, size_t NArgs,
10513       OverloadCandidateSet::CandidateSetKind CSK)
10514       : S(S), NumArgs(NArgs), CSK(CSK) {}
10515 
10516   bool operator()(const OverloadCandidate *L,
10517                   const OverloadCandidate *R) {
10518     // Fast-path this check.
10519     if (L == R) return false;
10520 
10521     // Order first by viability.
10522     if (L->Viable) {
10523       if (!R->Viable) return true;
10524 
10525       // TODO: introduce a tri-valued comparison for overload
10526       // candidates.  Would be more worthwhile if we had a sort
10527       // that could exploit it.
10528       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10529         return true;
10530       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10531         return false;
10532     } else if (R->Viable)
10533       return false;
10534 
10535     assert(L->Viable == R->Viable);
10536 
10537     // Criteria by which we can sort non-viable candidates:
10538     if (!L->Viable) {
10539       // 1. Arity mismatches come after other candidates.
10540       if (L->FailureKind == ovl_fail_too_many_arguments ||
10541           L->FailureKind == ovl_fail_too_few_arguments) {
10542         if (R->FailureKind == ovl_fail_too_many_arguments ||
10543             R->FailureKind == ovl_fail_too_few_arguments) {
10544           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10545           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10546           if (LDist == RDist) {
10547             if (L->FailureKind == R->FailureKind)
10548               // Sort non-surrogates before surrogates.
10549               return !L->IsSurrogate && R->IsSurrogate;
10550             // Sort candidates requiring fewer parameters than there were
10551             // arguments given after candidates requiring more parameters
10552             // than there were arguments given.
10553             return L->FailureKind == ovl_fail_too_many_arguments;
10554           }
10555           return LDist < RDist;
10556         }
10557         return false;
10558       }
10559       if (R->FailureKind == ovl_fail_too_many_arguments ||
10560           R->FailureKind == ovl_fail_too_few_arguments)
10561         return true;
10562 
10563       // 2. Bad conversions come first and are ordered by the number
10564       // of bad conversions and quality of good conversions.
10565       if (L->FailureKind == ovl_fail_bad_conversion) {
10566         if (R->FailureKind != ovl_fail_bad_conversion)
10567           return true;
10568 
10569         // The conversion that can be fixed with a smaller number of changes,
10570         // comes first.
10571         unsigned numLFixes = L->Fix.NumConversionsFixed;
10572         unsigned numRFixes = R->Fix.NumConversionsFixed;
10573         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10574         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10575         if (numLFixes != numRFixes) {
10576           return numLFixes < numRFixes;
10577         }
10578 
10579         // If there's any ordering between the defined conversions...
10580         // FIXME: this might not be transitive.
10581         assert(L->Conversions.size() == R->Conversions.size());
10582 
10583         int leftBetter = 0;
10584         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10585         for (unsigned E = L->Conversions.size(); I != E; ++I) {
10586           switch (CompareImplicitConversionSequences(S, Loc,
10587                                                      L->Conversions[I],
10588                                                      R->Conversions[I])) {
10589           case ImplicitConversionSequence::Better:
10590             leftBetter++;
10591             break;
10592 
10593           case ImplicitConversionSequence::Worse:
10594             leftBetter--;
10595             break;
10596 
10597           case ImplicitConversionSequence::Indistinguishable:
10598             break;
10599           }
10600         }
10601         if (leftBetter > 0) return true;
10602         if (leftBetter < 0) return false;
10603 
10604       } else if (R->FailureKind == ovl_fail_bad_conversion)
10605         return false;
10606 
10607       if (L->FailureKind == ovl_fail_bad_deduction) {
10608         if (R->FailureKind != ovl_fail_bad_deduction)
10609           return true;
10610 
10611         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10612           return RankDeductionFailure(L->DeductionFailure)
10613                < RankDeductionFailure(R->DeductionFailure);
10614       } else if (R->FailureKind == ovl_fail_bad_deduction)
10615         return false;
10616 
10617       // TODO: others?
10618     }
10619 
10620     // Sort everything else by location.
10621     SourceLocation LLoc = GetLocationForCandidate(L);
10622     SourceLocation RLoc = GetLocationForCandidate(R);
10623 
10624     // Put candidates without locations (e.g. builtins) at the end.
10625     if (LLoc.isInvalid()) return false;
10626     if (RLoc.isInvalid()) return true;
10627 
10628     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10629   }
10630 };
10631 }
10632 
10633 /// CompleteNonViableCandidate - Normally, overload resolution only
10634 /// computes up to the first bad conversion. Produces the FixIt set if
10635 /// possible.
10636 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10637                                        ArrayRef<Expr *> Args) {
10638   assert(!Cand->Viable);
10639 
10640   // Don't do anything on failures other than bad conversion.
10641   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10642 
10643   // We only want the FixIts if all the arguments can be corrected.
10644   bool Unfixable = false;
10645   // Use a implicit copy initialization to check conversion fixes.
10646   Cand->Fix.setConversionChecker(TryCopyInitialization);
10647 
10648   // Attempt to fix the bad conversion.
10649   unsigned ConvCount = Cand->Conversions.size();
10650   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10651        ++ConvIdx) {
10652     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10653     if (Cand->Conversions[ConvIdx].isInitialized() &&
10654         Cand->Conversions[ConvIdx].isBad()) {
10655       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10656       break;
10657     }
10658   }
10659 
10660   // FIXME: this should probably be preserved from the overload
10661   // operation somehow.
10662   bool SuppressUserConversions = false;
10663 
10664   unsigned ConvIdx = 0;
10665   ArrayRef<QualType> ParamTypes;
10666 
10667   if (Cand->IsSurrogate) {
10668     QualType ConvType
10669       = Cand->Surrogate->getConversionType().getNonReferenceType();
10670     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10671       ConvType = ConvPtrType->getPointeeType();
10672     ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10673     // Conversion 0 is 'this', which doesn't have a corresponding argument.
10674     ConvIdx = 1;
10675   } else if (Cand->Function) {
10676     ParamTypes =
10677         Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
10678     if (isa<CXXMethodDecl>(Cand->Function) &&
10679         !isa<CXXConstructorDecl>(Cand->Function)) {
10680       // Conversion 0 is 'this', which doesn't have a corresponding argument.
10681       ConvIdx = 1;
10682     }
10683   } else {
10684     // Builtin operator.
10685     assert(ConvCount <= 3);
10686     ParamTypes = Cand->BuiltinParamTypes;
10687   }
10688 
10689   // Fill in the rest of the conversions.
10690   for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10691     if (Cand->Conversions[ConvIdx].isInitialized()) {
10692       // We've already checked this conversion.
10693     } else if (ArgIdx < ParamTypes.size()) {
10694       if (ParamTypes[ArgIdx]->isDependentType())
10695         Cand->Conversions[ConvIdx].setAsIdentityConversion(
10696             Args[ArgIdx]->getType());
10697       else {
10698         Cand->Conversions[ConvIdx] =
10699             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10700                                   SuppressUserConversions,
10701                                   /*InOverloadResolution=*/true,
10702                                   /*AllowObjCWritebackConversion=*/
10703                                   S.getLangOpts().ObjCAutoRefCount);
10704         // Store the FixIt in the candidate if it exists.
10705         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10706           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10707       }
10708     } else
10709       Cand->Conversions[ConvIdx].setEllipsis();
10710   }
10711 }
10712 
10713 /// When overload resolution fails, prints diagnostic messages containing the
10714 /// candidates in the candidate set.
10715 void OverloadCandidateSet::NoteCandidates(
10716     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10717     StringRef Opc, SourceLocation OpLoc,
10718     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10719   // Sort the candidates by viability and position.  Sorting directly would
10720   // be prohibitive, so we make a set of pointers and sort those.
10721   SmallVector<OverloadCandidate*, 32> Cands;
10722   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10723   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10724     if (!Filter(*Cand))
10725       continue;
10726     if (Cand->Viable)
10727       Cands.push_back(Cand);
10728     else if (OCD == OCD_AllCandidates) {
10729       CompleteNonViableCandidate(S, Cand, Args);
10730       if (Cand->Function || Cand->IsSurrogate)
10731         Cands.push_back(Cand);
10732       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10733       // want to list every possible builtin candidate.
10734     }
10735   }
10736 
10737   std::stable_sort(Cands.begin(), Cands.end(),
10738             CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
10739 
10740   bool ReportedAmbiguousConversions = false;
10741 
10742   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10743   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10744   unsigned CandsShown = 0;
10745   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10746     OverloadCandidate *Cand = *I;
10747 
10748     // Set an arbitrary limit on the number of candidate functions we'll spam
10749     // the user with.  FIXME: This limit should depend on details of the
10750     // candidate list.
10751     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10752       break;
10753     }
10754     ++CandsShown;
10755 
10756     if (Cand->Function)
10757       NoteFunctionCandidate(S, Cand, Args.size(),
10758                             /*TakingCandidateAddress=*/false);
10759     else if (Cand->IsSurrogate)
10760       NoteSurrogateCandidate(S, Cand);
10761     else {
10762       assert(Cand->Viable &&
10763              "Non-viable built-in candidates are not added to Cands.");
10764       // Generally we only see ambiguities including viable builtin
10765       // operators if overload resolution got screwed up by an
10766       // ambiguous user-defined conversion.
10767       //
10768       // FIXME: It's quite possible for different conversions to see
10769       // different ambiguities, though.
10770       if (!ReportedAmbiguousConversions) {
10771         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10772         ReportedAmbiguousConversions = true;
10773       }
10774 
10775       // If this is a viable builtin, print it.
10776       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10777     }
10778   }
10779 
10780   if (I != E)
10781     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10782 }
10783 
10784 static SourceLocation
10785 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10786   return Cand->Specialization ? Cand->Specialization->getLocation()
10787                               : SourceLocation();
10788 }
10789 
10790 namespace {
10791 struct CompareTemplateSpecCandidatesForDisplay {
10792   Sema &S;
10793   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10794 
10795   bool operator()(const TemplateSpecCandidate *L,
10796                   const TemplateSpecCandidate *R) {
10797     // Fast-path this check.
10798     if (L == R)
10799       return false;
10800 
10801     // Assuming that both candidates are not matches...
10802 
10803     // Sort by the ranking of deduction failures.
10804     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10805       return RankDeductionFailure(L->DeductionFailure) <
10806              RankDeductionFailure(R->DeductionFailure);
10807 
10808     // Sort everything else by location.
10809     SourceLocation LLoc = GetLocationForCandidate(L);
10810     SourceLocation RLoc = GetLocationForCandidate(R);
10811 
10812     // Put candidates without locations (e.g. builtins) at the end.
10813     if (LLoc.isInvalid())
10814       return false;
10815     if (RLoc.isInvalid())
10816       return true;
10817 
10818     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10819   }
10820 };
10821 }
10822 
10823 /// Diagnose a template argument deduction failure.
10824 /// We are treating these failures as overload failures due to bad
10825 /// deductions.
10826 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10827                                                  bool ForTakingAddress) {
10828   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10829                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10830 }
10831 
10832 void TemplateSpecCandidateSet::destroyCandidates() {
10833   for (iterator i = begin(), e = end(); i != e; ++i) {
10834     i->DeductionFailure.Destroy();
10835   }
10836 }
10837 
10838 void TemplateSpecCandidateSet::clear() {
10839   destroyCandidates();
10840   Candidates.clear();
10841 }
10842 
10843 /// NoteCandidates - When no template specialization match is found, prints
10844 /// diagnostic messages containing the non-matching specializations that form
10845 /// the candidate set.
10846 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10847 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10848 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10849   // Sort the candidates by position (assuming no candidate is a match).
10850   // Sorting directly would be prohibitive, so we make a set of pointers
10851   // and sort those.
10852   SmallVector<TemplateSpecCandidate *, 32> Cands;
10853   Cands.reserve(size());
10854   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10855     if (Cand->Specialization)
10856       Cands.push_back(Cand);
10857     // Otherwise, this is a non-matching builtin candidate.  We do not,
10858     // in general, want to list every possible builtin candidate.
10859   }
10860 
10861   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
10862 
10863   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10864   // for generalization purposes (?).
10865   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10866 
10867   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10868   unsigned CandsShown = 0;
10869   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10870     TemplateSpecCandidate *Cand = *I;
10871 
10872     // Set an arbitrary limit on the number of candidates we'll spam
10873     // the user with.  FIXME: This limit should depend on details of the
10874     // candidate list.
10875     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10876       break;
10877     ++CandsShown;
10878 
10879     assert(Cand->Specialization &&
10880            "Non-matching built-in candidates are not added to Cands.");
10881     Cand->NoteDeductionFailure(S, ForTakingAddress);
10882   }
10883 
10884   if (I != E)
10885     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10886 }
10887 
10888 // [PossiblyAFunctionType]  -->   [Return]
10889 // NonFunctionType --> NonFunctionType
10890 // R (A) --> R(A)
10891 // R (*)(A) --> R (A)
10892 // R (&)(A) --> R (A)
10893 // R (S::*)(A) --> R (A)
10894 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10895   QualType Ret = PossiblyAFunctionType;
10896   if (const PointerType *ToTypePtr =
10897     PossiblyAFunctionType->getAs<PointerType>())
10898     Ret = ToTypePtr->getPointeeType();
10899   else if (const ReferenceType *ToTypeRef =
10900     PossiblyAFunctionType->getAs<ReferenceType>())
10901     Ret = ToTypeRef->getPointeeType();
10902   else if (const MemberPointerType *MemTypePtr =
10903     PossiblyAFunctionType->getAs<MemberPointerType>())
10904     Ret = MemTypePtr->getPointeeType();
10905   Ret =
10906     Context.getCanonicalType(Ret).getUnqualifiedType();
10907   return Ret;
10908 }
10909 
10910 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10911                                  bool Complain = true) {
10912   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10913       S.DeduceReturnType(FD, Loc, Complain))
10914     return true;
10915 
10916   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10917   if (S.getLangOpts().CPlusPlus17 &&
10918       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10919       !S.ResolveExceptionSpec(Loc, FPT))
10920     return true;
10921 
10922   return false;
10923 }
10924 
10925 namespace {
10926 // A helper class to help with address of function resolution
10927 // - allows us to avoid passing around all those ugly parameters
10928 class AddressOfFunctionResolver {
10929   Sema& S;
10930   Expr* SourceExpr;
10931   const QualType& TargetType;
10932   QualType TargetFunctionType; // Extracted function type from target type
10933 
10934   bool Complain;
10935   //DeclAccessPair& ResultFunctionAccessPair;
10936   ASTContext& Context;
10937 
10938   bool TargetTypeIsNonStaticMemberFunction;
10939   bool FoundNonTemplateFunction;
10940   bool StaticMemberFunctionFromBoundPointer;
10941   bool HasComplained;
10942 
10943   OverloadExpr::FindResult OvlExprInfo;
10944   OverloadExpr *OvlExpr;
10945   TemplateArgumentListInfo OvlExplicitTemplateArgs;
10946   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10947   TemplateSpecCandidateSet FailedCandidates;
10948 
10949 public:
10950   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10951                             const QualType &TargetType, bool Complain)
10952       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10953         Complain(Complain), Context(S.getASTContext()),
10954         TargetTypeIsNonStaticMemberFunction(
10955             !!TargetType->getAs<MemberPointerType>()),
10956         FoundNonTemplateFunction(false),
10957         StaticMemberFunctionFromBoundPointer(false),
10958         HasComplained(false),
10959         OvlExprInfo(OverloadExpr::find(SourceExpr)),
10960         OvlExpr(OvlExprInfo.Expression),
10961         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10962     ExtractUnqualifiedFunctionTypeFromTargetType();
10963 
10964     if (TargetFunctionType->isFunctionType()) {
10965       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10966         if (!UME->isImplicitAccess() &&
10967             !S.ResolveSingleFunctionTemplateSpecialization(UME))
10968           StaticMemberFunctionFromBoundPointer = true;
10969     } else if (OvlExpr->hasExplicitTemplateArgs()) {
10970       DeclAccessPair dap;
10971       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10972               OvlExpr, false, &dap)) {
10973         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10974           if (!Method->isStatic()) {
10975             // If the target type is a non-function type and the function found
10976             // is a non-static member function, pretend as if that was the
10977             // target, it's the only possible type to end up with.
10978             TargetTypeIsNonStaticMemberFunction = true;
10979 
10980             // And skip adding the function if its not in the proper form.
10981             // We'll diagnose this due to an empty set of functions.
10982             if (!OvlExprInfo.HasFormOfMemberPointer)
10983               return;
10984           }
10985 
10986         Matches.push_back(std::make_pair(dap, Fn));
10987       }
10988       return;
10989     }
10990 
10991     if (OvlExpr->hasExplicitTemplateArgs())
10992       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10993 
10994     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10995       // C++ [over.over]p4:
10996       //   If more than one function is selected, [...]
10997       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10998         if (FoundNonTemplateFunction)
10999           EliminateAllTemplateMatches();
11000         else
11001           EliminateAllExceptMostSpecializedTemplate();
11002       }
11003     }
11004 
11005     if (S.getLangOpts().CUDA && Matches.size() > 1)
11006       EliminateSuboptimalCudaMatches();
11007   }
11008 
11009   bool hasComplained() const { return HasComplained; }
11010 
11011 private:
11012   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
11013     QualType Discard;
11014     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
11015            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
11016   }
11017 
11018   /// \return true if A is considered a better overload candidate for the
11019   /// desired type than B.
11020   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
11021     // If A doesn't have exactly the correct type, we don't want to classify it
11022     // as "better" than anything else. This way, the user is required to
11023     // disambiguate for us if there are multiple candidates and no exact match.
11024     return candidateHasExactlyCorrectType(A) &&
11025            (!candidateHasExactlyCorrectType(B) ||
11026             compareEnableIfAttrs(S, A, B) == Comparison::Better);
11027   }
11028 
11029   /// \return true if we were able to eliminate all but one overload candidate,
11030   /// false otherwise.
11031   bool eliminiateSuboptimalOverloadCandidates() {
11032     // Same algorithm as overload resolution -- one pass to pick the "best",
11033     // another pass to be sure that nothing is better than the best.
11034     auto Best = Matches.begin();
11035     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11036       if (isBetterCandidate(I->second, Best->second))
11037         Best = I;
11038 
11039     const FunctionDecl *BestFn = Best->second;
11040     auto IsBestOrInferiorToBest = [this, BestFn](
11041         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11042       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11043     };
11044 
11045     // Note: We explicitly leave Matches unmodified if there isn't a clear best
11046     // option, so we can potentially give the user a better error
11047     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
11048       return false;
11049     Matches[0] = *Best;
11050     Matches.resize(1);
11051     return true;
11052   }
11053 
11054   bool isTargetTypeAFunction() const {
11055     return TargetFunctionType->isFunctionType();
11056   }
11057 
11058   // [ToType]     [Return]
11059 
11060   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11061   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11062   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11063   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11064     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11065   }
11066 
11067   // return true if any matching specializations were found
11068   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
11069                                    const DeclAccessPair& CurAccessFunPair) {
11070     if (CXXMethodDecl *Method
11071               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11072       // Skip non-static function templates when converting to pointer, and
11073       // static when converting to member pointer.
11074       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11075         return false;
11076     }
11077     else if (TargetTypeIsNonStaticMemberFunction)
11078       return false;
11079 
11080     // C++ [over.over]p2:
11081     //   If the name is a function template, template argument deduction is
11082     //   done (14.8.2.2), and if the argument deduction succeeds, the
11083     //   resulting template argument list is used to generate a single
11084     //   function template specialization, which is added to the set of
11085     //   overloaded functions considered.
11086     FunctionDecl *Specialization = nullptr;
11087     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11088     if (Sema::TemplateDeductionResult Result
11089           = S.DeduceTemplateArguments(FunctionTemplate,
11090                                       &OvlExplicitTemplateArgs,
11091                                       TargetFunctionType, Specialization,
11092                                       Info, /*IsAddressOfFunction*/true)) {
11093       // Make a note of the failed deduction for diagnostics.
11094       FailedCandidates.addCandidate()
11095           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
11096                MakeDeductionFailureInfo(Context, Result, Info));
11097       return false;
11098     }
11099 
11100     // Template argument deduction ensures that we have an exact match or
11101     // compatible pointer-to-function arguments that would be adjusted by ICS.
11102     // This function template specicalization works.
11103     assert(S.isSameOrCompatibleFunctionType(
11104               Context.getCanonicalType(Specialization->getType()),
11105               Context.getCanonicalType(TargetFunctionType)));
11106 
11107     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11108       return false;
11109 
11110     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11111     return true;
11112   }
11113 
11114   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11115                                       const DeclAccessPair& CurAccessFunPair) {
11116     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11117       // Skip non-static functions when converting to pointer, and static
11118       // when converting to member pointer.
11119       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11120         return false;
11121     }
11122     else if (TargetTypeIsNonStaticMemberFunction)
11123       return false;
11124 
11125     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11126       if (S.getLangOpts().CUDA)
11127         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11128           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11129             return false;
11130       if (FunDecl->isMultiVersion()) {
11131         const auto *TA = FunDecl->getAttr<TargetAttr>();
11132         if (TA && !TA->isDefaultVersion())
11133           return false;
11134       }
11135 
11136       // If any candidate has a placeholder return type, trigger its deduction
11137       // now.
11138       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
11139                                Complain)) {
11140         HasComplained |= Complain;
11141         return false;
11142       }
11143 
11144       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11145         return false;
11146 
11147       // If we're in C, we need to support types that aren't exactly identical.
11148       if (!S.getLangOpts().CPlusPlus ||
11149           candidateHasExactlyCorrectType(FunDecl)) {
11150         Matches.push_back(std::make_pair(
11151             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11152         FoundNonTemplateFunction = true;
11153         return true;
11154       }
11155     }
11156 
11157     return false;
11158   }
11159 
11160   bool FindAllFunctionsThatMatchTargetTypeExactly() {
11161     bool Ret = false;
11162 
11163     // If the overload expression doesn't have the form of a pointer to
11164     // member, don't try to convert it to a pointer-to-member type.
11165     if (IsInvalidFormOfPointerToMemberFunction())
11166       return false;
11167 
11168     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11169                                E = OvlExpr->decls_end();
11170          I != E; ++I) {
11171       // Look through any using declarations to find the underlying function.
11172       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11173 
11174       // C++ [over.over]p3:
11175       //   Non-member functions and static member functions match
11176       //   targets of type "pointer-to-function" or "reference-to-function."
11177       //   Nonstatic member functions match targets of
11178       //   type "pointer-to-member-function."
11179       // Note that according to DR 247, the containing class does not matter.
11180       if (FunctionTemplateDecl *FunctionTemplate
11181                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11182         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11183           Ret = true;
11184       }
11185       // If we have explicit template arguments supplied, skip non-templates.
11186       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11187                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11188         Ret = true;
11189     }
11190     assert(Ret || Matches.empty());
11191     return Ret;
11192   }
11193 
11194   void EliminateAllExceptMostSpecializedTemplate() {
11195     //   [...] and any given function template specialization F1 is
11196     //   eliminated if the set contains a second function template
11197     //   specialization whose function template is more specialized
11198     //   than the function template of F1 according to the partial
11199     //   ordering rules of 14.5.5.2.
11200 
11201     // The algorithm specified above is quadratic. We instead use a
11202     // two-pass algorithm (similar to the one used to identify the
11203     // best viable function in an overload set) that identifies the
11204     // best function template (if it exists).
11205 
11206     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11207     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11208       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11209 
11210     // TODO: It looks like FailedCandidates does not serve much purpose
11211     // here, since the no_viable diagnostic has index 0.
11212     UnresolvedSetIterator Result = S.getMostSpecialized(
11213         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11214         SourceExpr->getBeginLoc(), S.PDiag(),
11215         S.PDiag(diag::err_addr_ovl_ambiguous)
11216             << Matches[0].second->getDeclName(),
11217         S.PDiag(diag::note_ovl_candidate)
11218             << (unsigned)oc_function << (unsigned)ocs_described_template,
11219         Complain, TargetFunctionType);
11220 
11221     if (Result != MatchesCopy.end()) {
11222       // Make it the first and only element
11223       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11224       Matches[0].second = cast<FunctionDecl>(*Result);
11225       Matches.resize(1);
11226     } else
11227       HasComplained |= Complain;
11228   }
11229 
11230   void EliminateAllTemplateMatches() {
11231     //   [...] any function template specializations in the set are
11232     //   eliminated if the set also contains a non-template function, [...]
11233     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11234       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11235         ++I;
11236       else {
11237         Matches[I] = Matches[--N];
11238         Matches.resize(N);
11239       }
11240     }
11241   }
11242 
11243   void EliminateSuboptimalCudaMatches() {
11244     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11245   }
11246 
11247 public:
11248   void ComplainNoMatchesFound() const {
11249     assert(Matches.empty());
11250     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
11251         << OvlExpr->getName() << TargetFunctionType
11252         << OvlExpr->getSourceRange();
11253     if (FailedCandidates.empty())
11254       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11255                                   /*TakingAddress=*/true);
11256     else {
11257       // We have some deduction failure messages. Use them to diagnose
11258       // the function templates, and diagnose the non-template candidates
11259       // normally.
11260       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11261                                  IEnd = OvlExpr->decls_end();
11262            I != IEnd; ++I)
11263         if (FunctionDecl *Fun =
11264                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11265           if (!functionHasPassObjectSizeParams(Fun))
11266             S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
11267                                     /*TakingAddress=*/true);
11268       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
11269     }
11270   }
11271 
11272   bool IsInvalidFormOfPointerToMemberFunction() const {
11273     return TargetTypeIsNonStaticMemberFunction &&
11274       !OvlExprInfo.HasFormOfMemberPointer;
11275   }
11276 
11277   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11278       // TODO: Should we condition this on whether any functions might
11279       // have matched, or is it more appropriate to do that in callers?
11280       // TODO: a fixit wouldn't hurt.
11281       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11282         << TargetType << OvlExpr->getSourceRange();
11283   }
11284 
11285   bool IsStaticMemberFunctionFromBoundPointer() const {
11286     return StaticMemberFunctionFromBoundPointer;
11287   }
11288 
11289   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11290     S.Diag(OvlExpr->getBeginLoc(),
11291            diag::err_invalid_form_pointer_member_function)
11292         << OvlExpr->getSourceRange();
11293   }
11294 
11295   void ComplainOfInvalidConversion() const {
11296     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
11297         << OvlExpr->getName() << TargetType;
11298   }
11299 
11300   void ComplainMultipleMatchesFound() const {
11301     assert(Matches.size() > 1);
11302     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
11303         << OvlExpr->getName() << OvlExpr->getSourceRange();
11304     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11305                                 /*TakingAddress=*/true);
11306   }
11307 
11308   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11309 
11310   int getNumMatches() const { return Matches.size(); }
11311 
11312   FunctionDecl* getMatchingFunctionDecl() const {
11313     if (Matches.size() != 1) return nullptr;
11314     return Matches[0].second;
11315   }
11316 
11317   const DeclAccessPair* getMatchingFunctionAccessPair() const {
11318     if (Matches.size() != 1) return nullptr;
11319     return &Matches[0].first;
11320   }
11321 };
11322 }
11323 
11324 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11325 /// an overloaded function (C++ [over.over]), where @p From is an
11326 /// expression with overloaded function type and @p ToType is the type
11327 /// we're trying to resolve to. For example:
11328 ///
11329 /// @code
11330 /// int f(double);
11331 /// int f(int);
11332 ///
11333 /// int (*pfd)(double) = f; // selects f(double)
11334 /// @endcode
11335 ///
11336 /// This routine returns the resulting FunctionDecl if it could be
11337 /// resolved, and NULL otherwise. When @p Complain is true, this
11338 /// routine will emit diagnostics if there is an error.
11339 FunctionDecl *
11340 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11341                                          QualType TargetType,
11342                                          bool Complain,
11343                                          DeclAccessPair &FoundResult,
11344                                          bool *pHadMultipleCandidates) {
11345   assert(AddressOfExpr->getType() == Context.OverloadTy);
11346 
11347   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11348                                      Complain);
11349   int NumMatches = Resolver.getNumMatches();
11350   FunctionDecl *Fn = nullptr;
11351   bool ShouldComplain = Complain && !Resolver.hasComplained();
11352   if (NumMatches == 0 && ShouldComplain) {
11353     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11354       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11355     else
11356       Resolver.ComplainNoMatchesFound();
11357   }
11358   else if (NumMatches > 1 && ShouldComplain)
11359     Resolver.ComplainMultipleMatchesFound();
11360   else if (NumMatches == 1) {
11361     Fn = Resolver.getMatchingFunctionDecl();
11362     assert(Fn);
11363     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11364       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11365     FoundResult = *Resolver.getMatchingFunctionAccessPair();
11366     if (Complain) {
11367       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11368         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11369       else
11370         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11371     }
11372   }
11373 
11374   if (pHadMultipleCandidates)
11375     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11376   return Fn;
11377 }
11378 
11379 /// Given an expression that refers to an overloaded function, try to
11380 /// resolve that function to a single function that can have its address taken.
11381 /// This will modify `Pair` iff it returns non-null.
11382 ///
11383 /// This routine can only realistically succeed if all but one candidates in the
11384 /// overload set for SrcExpr cannot have their addresses taken.
11385 FunctionDecl *
11386 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11387                                                   DeclAccessPair &Pair) {
11388   OverloadExpr::FindResult R = OverloadExpr::find(E);
11389   OverloadExpr *Ovl = R.Expression;
11390   FunctionDecl *Result = nullptr;
11391   DeclAccessPair DAP;
11392   // Don't use the AddressOfResolver because we're specifically looking for
11393   // cases where we have one overload candidate that lacks
11394   // enable_if/pass_object_size/...
11395   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11396     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11397     if (!FD)
11398       return nullptr;
11399 
11400     if (!checkAddressOfFunctionIsAvailable(FD))
11401       continue;
11402 
11403     // We have more than one result; quit.
11404     if (Result)
11405       return nullptr;
11406     DAP = I.getPair();
11407     Result = FD;
11408   }
11409 
11410   if (Result)
11411     Pair = DAP;
11412   return Result;
11413 }
11414 
11415 /// Given an overloaded function, tries to turn it into a non-overloaded
11416 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11417 /// will perform access checks, diagnose the use of the resultant decl, and, if
11418 /// requested, potentially perform a function-to-pointer decay.
11419 ///
11420 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11421 /// Otherwise, returns true. This may emit diagnostics and return true.
11422 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11423     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
11424   Expr *E = SrcExpr.get();
11425   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11426 
11427   DeclAccessPair DAP;
11428   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11429   if (!Found || Found->isCPUDispatchMultiVersion() ||
11430       Found->isCPUSpecificMultiVersion())
11431     return false;
11432 
11433   // Emitting multiple diagnostics for a function that is both inaccessible and
11434   // unavailable is consistent with our behavior elsewhere. So, always check
11435   // for both.
11436   DiagnoseUseOfDecl(Found, E->getExprLoc());
11437   CheckAddressOfMemberAccess(E, DAP);
11438   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11439   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
11440     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11441   else
11442     SrcExpr = Fixed;
11443   return true;
11444 }
11445 
11446 /// Given an expression that refers to an overloaded function, try to
11447 /// resolve that overloaded function expression down to a single function.
11448 ///
11449 /// This routine can only resolve template-ids that refer to a single function
11450 /// template, where that template-id refers to a single template whose template
11451 /// arguments are either provided by the template-id or have defaults,
11452 /// as described in C++0x [temp.arg.explicit]p3.
11453 ///
11454 /// If no template-ids are found, no diagnostics are emitted and NULL is
11455 /// returned.
11456 FunctionDecl *
11457 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11458                                                   bool Complain,
11459                                                   DeclAccessPair *FoundResult) {
11460   // C++ [over.over]p1:
11461   //   [...] [Note: any redundant set of parentheses surrounding the
11462   //   overloaded function name is ignored (5.1). ]
11463   // C++ [over.over]p1:
11464   //   [...] The overloaded function name can be preceded by the &
11465   //   operator.
11466 
11467   // If we didn't actually find any template-ids, we're done.
11468   if (!ovl->hasExplicitTemplateArgs())
11469     return nullptr;
11470 
11471   TemplateArgumentListInfo ExplicitTemplateArgs;
11472   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11473   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11474 
11475   // Look through all of the overloaded functions, searching for one
11476   // whose type matches exactly.
11477   FunctionDecl *Matched = nullptr;
11478   for (UnresolvedSetIterator I = ovl->decls_begin(),
11479          E = ovl->decls_end(); I != E; ++I) {
11480     // C++0x [temp.arg.explicit]p3:
11481     //   [...] In contexts where deduction is done and fails, or in contexts
11482     //   where deduction is not done, if a template argument list is
11483     //   specified and it, along with any default template arguments,
11484     //   identifies a single function template specialization, then the
11485     //   template-id is an lvalue for the function template specialization.
11486     FunctionTemplateDecl *FunctionTemplate
11487       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11488 
11489     // C++ [over.over]p2:
11490     //   If the name is a function template, template argument deduction is
11491     //   done (14.8.2.2), and if the argument deduction succeeds, the
11492     //   resulting template argument list is used to generate a single
11493     //   function template specialization, which is added to the set of
11494     //   overloaded functions considered.
11495     FunctionDecl *Specialization = nullptr;
11496     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11497     if (TemplateDeductionResult Result
11498           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11499                                     Specialization, Info,
11500                                     /*IsAddressOfFunction*/true)) {
11501       // Make a note of the failed deduction for diagnostics.
11502       // TODO: Actually use the failed-deduction info?
11503       FailedCandidates.addCandidate()
11504           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11505                MakeDeductionFailureInfo(Context, Result, Info));
11506       continue;
11507     }
11508 
11509     assert(Specialization && "no specialization and no error?");
11510 
11511     // Multiple matches; we can't resolve to a single declaration.
11512     if (Matched) {
11513       if (Complain) {
11514         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11515           << ovl->getName();
11516         NoteAllOverloadCandidates(ovl);
11517       }
11518       return nullptr;
11519     }
11520 
11521     Matched = Specialization;
11522     if (FoundResult) *FoundResult = I.getPair();
11523   }
11524 
11525   if (Matched &&
11526       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11527     return nullptr;
11528 
11529   return Matched;
11530 }
11531 
11532 // Resolve and fix an overloaded expression that can be resolved
11533 // because it identifies a single function template specialization.
11534 //
11535 // Last three arguments should only be supplied if Complain = true
11536 //
11537 // Return true if it was logically possible to so resolve the
11538 // expression, regardless of whether or not it succeeded.  Always
11539 // returns true if 'complain' is set.
11540 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11541                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
11542                       bool complain, SourceRange OpRangeForComplaining,
11543                                            QualType DestTypeForComplaining,
11544                                             unsigned DiagIDForComplaining) {
11545   assert(SrcExpr.get()->getType() == Context.OverloadTy);
11546 
11547   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11548 
11549   DeclAccessPair found;
11550   ExprResult SingleFunctionExpression;
11551   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11552                            ovl.Expression, /*complain*/ false, &found)) {
11553     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
11554       SrcExpr = ExprError();
11555       return true;
11556     }
11557 
11558     // It is only correct to resolve to an instance method if we're
11559     // resolving a form that's permitted to be a pointer to member.
11560     // Otherwise we'll end up making a bound member expression, which
11561     // is illegal in all the contexts we resolve like this.
11562     if (!ovl.HasFormOfMemberPointer &&
11563         isa<CXXMethodDecl>(fn) &&
11564         cast<CXXMethodDecl>(fn)->isInstance()) {
11565       if (!complain) return false;
11566 
11567       Diag(ovl.Expression->getExprLoc(),
11568            diag::err_bound_member_function)
11569         << 0 << ovl.Expression->getSourceRange();
11570 
11571       // TODO: I believe we only end up here if there's a mix of
11572       // static and non-static candidates (otherwise the expression
11573       // would have 'bound member' type, not 'overload' type).
11574       // Ideally we would note which candidate was chosen and why
11575       // the static candidates were rejected.
11576       SrcExpr = ExprError();
11577       return true;
11578     }
11579 
11580     // Fix the expression to refer to 'fn'.
11581     SingleFunctionExpression =
11582         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11583 
11584     // If desired, do function-to-pointer decay.
11585     if (doFunctionPointerConverion) {
11586       SingleFunctionExpression =
11587         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11588       if (SingleFunctionExpression.isInvalid()) {
11589         SrcExpr = ExprError();
11590         return true;
11591       }
11592     }
11593   }
11594 
11595   if (!SingleFunctionExpression.isUsable()) {
11596     if (complain) {
11597       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11598         << ovl.Expression->getName()
11599         << DestTypeForComplaining
11600         << OpRangeForComplaining
11601         << ovl.Expression->getQualifierLoc().getSourceRange();
11602       NoteAllOverloadCandidates(SrcExpr.get());
11603 
11604       SrcExpr = ExprError();
11605       return true;
11606     }
11607 
11608     return false;
11609   }
11610 
11611   SrcExpr = SingleFunctionExpression;
11612   return true;
11613 }
11614 
11615 /// Add a single candidate to the overload set.
11616 static void AddOverloadedCallCandidate(Sema &S,
11617                                        DeclAccessPair FoundDecl,
11618                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
11619                                        ArrayRef<Expr *> Args,
11620                                        OverloadCandidateSet &CandidateSet,
11621                                        bool PartialOverloading,
11622                                        bool KnownValid) {
11623   NamedDecl *Callee = FoundDecl.getDecl();
11624   if (isa<UsingShadowDecl>(Callee))
11625     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11626 
11627   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11628     if (ExplicitTemplateArgs) {
11629       assert(!KnownValid && "Explicit template arguments?");
11630       return;
11631     }
11632     // Prevent ill-formed function decls to be added as overload candidates.
11633     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11634       return;
11635 
11636     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11637                            /*SuppressUsedConversions=*/false,
11638                            PartialOverloading);
11639     return;
11640   }
11641 
11642   if (FunctionTemplateDecl *FuncTemplate
11643       = dyn_cast<FunctionTemplateDecl>(Callee)) {
11644     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11645                                    ExplicitTemplateArgs, Args, CandidateSet,
11646                                    /*SuppressUsedConversions=*/false,
11647                                    PartialOverloading);
11648     return;
11649   }
11650 
11651   assert(!KnownValid && "unhandled case in overloaded call candidate");
11652 }
11653 
11654 /// Add the overload candidates named by callee and/or found by argument
11655 /// dependent lookup to the given overload set.
11656 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11657                                        ArrayRef<Expr *> Args,
11658                                        OverloadCandidateSet &CandidateSet,
11659                                        bool PartialOverloading) {
11660 
11661 #ifndef NDEBUG
11662   // Verify that ArgumentDependentLookup is consistent with the rules
11663   // in C++0x [basic.lookup.argdep]p3:
11664   //
11665   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11666   //   and let Y be the lookup set produced by argument dependent
11667   //   lookup (defined as follows). If X contains
11668   //
11669   //     -- a declaration of a class member, or
11670   //
11671   //     -- a block-scope function declaration that is not a
11672   //        using-declaration, or
11673   //
11674   //     -- a declaration that is neither a function or a function
11675   //        template
11676   //
11677   //   then Y is empty.
11678 
11679   if (ULE->requiresADL()) {
11680     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11681            E = ULE->decls_end(); I != E; ++I) {
11682       assert(!(*I)->getDeclContext()->isRecord());
11683       assert(isa<UsingShadowDecl>(*I) ||
11684              !(*I)->getDeclContext()->isFunctionOrMethod());
11685       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11686     }
11687   }
11688 #endif
11689 
11690   // It would be nice to avoid this copy.
11691   TemplateArgumentListInfo TABuffer;
11692   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11693   if (ULE->hasExplicitTemplateArgs()) {
11694     ULE->copyTemplateArgumentsInto(TABuffer);
11695     ExplicitTemplateArgs = &TABuffer;
11696   }
11697 
11698   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11699          E = ULE->decls_end(); I != E; ++I)
11700     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11701                                CandidateSet, PartialOverloading,
11702                                /*KnownValid*/ true);
11703 
11704   if (ULE->requiresADL())
11705     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11706                                          Args, ExplicitTemplateArgs,
11707                                          CandidateSet, PartialOverloading);
11708 }
11709 
11710 /// Determine whether a declaration with the specified name could be moved into
11711 /// a different namespace.
11712 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11713   switch (Name.getCXXOverloadedOperator()) {
11714   case OO_New: case OO_Array_New:
11715   case OO_Delete: case OO_Array_Delete:
11716     return false;
11717 
11718   default:
11719     return true;
11720   }
11721 }
11722 
11723 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11724 /// template, where the non-dependent name was declared after the template
11725 /// was defined. This is common in code written for a compilers which do not
11726 /// correctly implement two-stage name lookup.
11727 ///
11728 /// Returns true if a viable candidate was found and a diagnostic was issued.
11729 static bool
11730 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11731                        const CXXScopeSpec &SS, LookupResult &R,
11732                        OverloadCandidateSet::CandidateSetKind CSK,
11733                        TemplateArgumentListInfo *ExplicitTemplateArgs,
11734                        ArrayRef<Expr *> Args,
11735                        bool *DoDiagnoseEmptyLookup = nullptr) {
11736   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
11737     return false;
11738 
11739   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11740     if (DC->isTransparentContext())
11741       continue;
11742 
11743     SemaRef.LookupQualifiedName(R, DC);
11744 
11745     if (!R.empty()) {
11746       R.suppressDiagnostics();
11747 
11748       if (isa<CXXRecordDecl>(DC)) {
11749         // Don't diagnose names we find in classes; we get much better
11750         // diagnostics for these from DiagnoseEmptyLookup.
11751         R.clear();
11752         if (DoDiagnoseEmptyLookup)
11753           *DoDiagnoseEmptyLookup = true;
11754         return false;
11755       }
11756 
11757       OverloadCandidateSet Candidates(FnLoc, CSK);
11758       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11759         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11760                                    ExplicitTemplateArgs, Args,
11761                                    Candidates, false, /*KnownValid*/ false);
11762 
11763       OverloadCandidateSet::iterator Best;
11764       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11765         // No viable functions. Don't bother the user with notes for functions
11766         // which don't work and shouldn't be found anyway.
11767         R.clear();
11768         return false;
11769       }
11770 
11771       // Find the namespaces where ADL would have looked, and suggest
11772       // declaring the function there instead.
11773       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11774       Sema::AssociatedClassSet AssociatedClasses;
11775       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11776                                                  AssociatedNamespaces,
11777                                                  AssociatedClasses);
11778       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11779       if (canBeDeclaredInNamespace(R.getLookupName())) {
11780         DeclContext *Std = SemaRef.getStdNamespace();
11781         for (Sema::AssociatedNamespaceSet::iterator
11782                it = AssociatedNamespaces.begin(),
11783                end = AssociatedNamespaces.end(); it != end; ++it) {
11784           // Never suggest declaring a function within namespace 'std'.
11785           if (Std && Std->Encloses(*it))
11786             continue;
11787 
11788           // Never suggest declaring a function within a namespace with a
11789           // reserved name, like __gnu_cxx.
11790           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11791           if (NS &&
11792               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11793             continue;
11794 
11795           SuggestedNamespaces.insert(*it);
11796         }
11797       }
11798 
11799       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11800         << R.getLookupName();
11801       if (SuggestedNamespaces.empty()) {
11802         SemaRef.Diag(Best->Function->getLocation(),
11803                      diag::note_not_found_by_two_phase_lookup)
11804           << R.getLookupName() << 0;
11805       } else if (SuggestedNamespaces.size() == 1) {
11806         SemaRef.Diag(Best->Function->getLocation(),
11807                      diag::note_not_found_by_two_phase_lookup)
11808           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11809       } else {
11810         // FIXME: It would be useful to list the associated namespaces here,
11811         // but the diagnostics infrastructure doesn't provide a way to produce
11812         // a localized representation of a list of items.
11813         SemaRef.Diag(Best->Function->getLocation(),
11814                      diag::note_not_found_by_two_phase_lookup)
11815           << R.getLookupName() << 2;
11816       }
11817 
11818       // Try to recover by calling this function.
11819       return true;
11820     }
11821 
11822     R.clear();
11823   }
11824 
11825   return false;
11826 }
11827 
11828 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11829 /// template, where the non-dependent operator was declared after the template
11830 /// was defined.
11831 ///
11832 /// Returns true if a viable candidate was found and a diagnostic was issued.
11833 static bool
11834 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11835                                SourceLocation OpLoc,
11836                                ArrayRef<Expr *> Args) {
11837   DeclarationName OpName =
11838     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11839   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11840   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11841                                 OverloadCandidateSet::CSK_Operator,
11842                                 /*ExplicitTemplateArgs=*/nullptr, Args);
11843 }
11844 
11845 namespace {
11846 class BuildRecoveryCallExprRAII {
11847   Sema &SemaRef;
11848 public:
11849   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11850     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11851     SemaRef.IsBuildingRecoveryCallExpr = true;
11852   }
11853 
11854   ~BuildRecoveryCallExprRAII() {
11855     SemaRef.IsBuildingRecoveryCallExpr = false;
11856   }
11857 };
11858 
11859 }
11860 
11861 static std::unique_ptr<CorrectionCandidateCallback>
11862 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11863               bool HasTemplateArgs, bool AllowTypoCorrection) {
11864   if (!AllowTypoCorrection)
11865     return llvm::make_unique<NoTypoCorrectionCCC>();
11866   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11867                                                   HasTemplateArgs, ME);
11868 }
11869 
11870 /// Attempts to recover from a call where no functions were found.
11871 ///
11872 /// Returns true if new candidates were found.
11873 static ExprResult
11874 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11875                       UnresolvedLookupExpr *ULE,
11876                       SourceLocation LParenLoc,
11877                       MutableArrayRef<Expr *> Args,
11878                       SourceLocation RParenLoc,
11879                       bool EmptyLookup, bool AllowTypoCorrection) {
11880   // Do not try to recover if it is already building a recovery call.
11881   // This stops infinite loops for template instantiations like
11882   //
11883   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11884   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11885   //
11886   if (SemaRef.IsBuildingRecoveryCallExpr)
11887     return ExprError();
11888   BuildRecoveryCallExprRAII RCE(SemaRef);
11889 
11890   CXXScopeSpec SS;
11891   SS.Adopt(ULE->getQualifierLoc());
11892   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11893 
11894   TemplateArgumentListInfo TABuffer;
11895   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11896   if (ULE->hasExplicitTemplateArgs()) {
11897     ULE->copyTemplateArgumentsInto(TABuffer);
11898     ExplicitTemplateArgs = &TABuffer;
11899   }
11900 
11901   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11902                  Sema::LookupOrdinaryName);
11903   bool DoDiagnoseEmptyLookup = EmptyLookup;
11904   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11905                               OverloadCandidateSet::CSK_Normal,
11906                               ExplicitTemplateArgs, Args,
11907                               &DoDiagnoseEmptyLookup) &&
11908     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11909         S, SS, R,
11910         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11911                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11912         ExplicitTemplateArgs, Args)))
11913     return ExprError();
11914 
11915   assert(!R.empty() && "lookup results empty despite recovery");
11916 
11917   // If recovery created an ambiguity, just bail out.
11918   if (R.isAmbiguous()) {
11919     R.suppressDiagnostics();
11920     return ExprError();
11921   }
11922 
11923   // Build an implicit member call if appropriate.  Just drop the
11924   // casts and such from the call, we don't really care.
11925   ExprResult NewFn = ExprError();
11926   if ((*R.begin())->isCXXClassMember())
11927     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11928                                                     ExplicitTemplateArgs, S);
11929   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11930     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11931                                         ExplicitTemplateArgs);
11932   else
11933     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11934 
11935   if (NewFn.isInvalid())
11936     return ExprError();
11937 
11938   // This shouldn't cause an infinite loop because we're giving it
11939   // an expression with viable lookup results, which should never
11940   // end up here.
11941   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11942                                MultiExprArg(Args.data(), Args.size()),
11943                                RParenLoc);
11944 }
11945 
11946 /// Constructs and populates an OverloadedCandidateSet from
11947 /// the given function.
11948 /// \returns true when an the ExprResult output parameter has been set.
11949 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11950                                   UnresolvedLookupExpr *ULE,
11951                                   MultiExprArg Args,
11952                                   SourceLocation RParenLoc,
11953                                   OverloadCandidateSet *CandidateSet,
11954                                   ExprResult *Result) {
11955 #ifndef NDEBUG
11956   if (ULE->requiresADL()) {
11957     // To do ADL, we must have found an unqualified name.
11958     assert(!ULE->getQualifier() && "qualified name with ADL");
11959 
11960     // We don't perform ADL for implicit declarations of builtins.
11961     // Verify that this was correctly set up.
11962     FunctionDecl *F;
11963     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11964         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11965         F->getBuiltinID() && F->isImplicit())
11966       llvm_unreachable("performing ADL for builtin");
11967 
11968     // We don't perform ADL in C.
11969     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11970   }
11971 #endif
11972 
11973   UnbridgedCastsSet UnbridgedCasts;
11974   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11975     *Result = ExprError();
11976     return true;
11977   }
11978 
11979   // Add the functions denoted by the callee to the set of candidate
11980   // functions, including those from argument-dependent lookup.
11981   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11982 
11983   if (getLangOpts().MSVCCompat &&
11984       CurContext->isDependentContext() && !isSFINAEContext() &&
11985       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11986 
11987     OverloadCandidateSet::iterator Best;
11988     if (CandidateSet->empty() ||
11989         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
11990             OR_No_Viable_Function) {
11991       // In Microsoft mode, if we are inside a template class member function then
11992       // create a type dependent CallExpr. The goal is to postpone name lookup
11993       // to instantiation time to be able to search into type dependent base
11994       // classes.
11995       CallExpr *CE = new (Context) CallExpr(
11996           Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11997       CE->setTypeDependent(true);
11998       CE->setValueDependent(true);
11999       CE->setInstantiationDependent(true);
12000       *Result = CE;
12001       return true;
12002     }
12003   }
12004 
12005   if (CandidateSet->empty())
12006     return false;
12007 
12008   UnbridgedCasts.restore();
12009   return false;
12010 }
12011 
12012 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
12013 /// the completed call expression. If overload resolution fails, emits
12014 /// diagnostics and returns ExprError()
12015 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12016                                            UnresolvedLookupExpr *ULE,
12017                                            SourceLocation LParenLoc,
12018                                            MultiExprArg Args,
12019                                            SourceLocation RParenLoc,
12020                                            Expr *ExecConfig,
12021                                            OverloadCandidateSet *CandidateSet,
12022                                            OverloadCandidateSet::iterator *Best,
12023                                            OverloadingResult OverloadResult,
12024                                            bool AllowTypoCorrection) {
12025   if (CandidateSet->empty())
12026     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
12027                                  RParenLoc, /*EmptyLookup=*/true,
12028                                  AllowTypoCorrection);
12029 
12030   switch (OverloadResult) {
12031   case OR_Success: {
12032     FunctionDecl *FDecl = (*Best)->Function;
12033     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
12034     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
12035       return ExprError();
12036     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12037     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12038                                          ExecConfig, /*IsExecConfig=*/false,
12039                                          (*Best)->IsADLCandidate);
12040   }
12041 
12042   case OR_No_Viable_Function: {
12043     // Try to recover by looking for viable functions which the user might
12044     // have meant to call.
12045     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
12046                                                 Args, RParenLoc,
12047                                                 /*EmptyLookup=*/false,
12048                                                 AllowTypoCorrection);
12049     if (!Recovery.isInvalid())
12050       return Recovery;
12051 
12052     // If the user passes in a function that we can't take the address of, we
12053     // generally end up emitting really bad error messages. Here, we attempt to
12054     // emit better ones.
12055     for (const Expr *Arg : Args) {
12056       if (!Arg->getType()->isFunctionType())
12057         continue;
12058       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12059         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12060         if (FD &&
12061             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12062                                                        Arg->getExprLoc()))
12063           return ExprError();
12064       }
12065     }
12066 
12067     SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_no_viable_function_in_call)
12068         << ULE->getName() << Fn->getSourceRange();
12069     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
12070     break;
12071   }
12072 
12073   case OR_Ambiguous:
12074     SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_ambiguous_call)
12075         << ULE->getName() << Fn->getSourceRange();
12076     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
12077     break;
12078 
12079   case OR_Deleted: {
12080     SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_deleted_call)
12081         << (*Best)->Function->isDeleted() << ULE->getName()
12082         << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
12083         << Fn->getSourceRange();
12084     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
12085 
12086     // We emitted an error for the unavailable/deleted function call but keep
12087     // the call in the AST.
12088     FunctionDecl *FDecl = (*Best)->Function;
12089     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12090     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12091                                          ExecConfig, /*IsExecConfig=*/false,
12092                                          (*Best)->IsADLCandidate);
12093   }
12094   }
12095 
12096   // Overload resolution failed.
12097   return ExprError();
12098 }
12099 
12100 static void markUnaddressableCandidatesUnviable(Sema &S,
12101                                                 OverloadCandidateSet &CS) {
12102   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12103     if (I->Viable &&
12104         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12105       I->Viable = false;
12106       I->FailureKind = ovl_fail_addr_not_available;
12107     }
12108   }
12109 }
12110 
12111 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
12112 /// (which eventually refers to the declaration Func) and the call
12113 /// arguments Args/NumArgs, attempt to resolve the function call down
12114 /// to a specific function. If overload resolution succeeds, returns
12115 /// the call expression produced by overload resolution.
12116 /// Otherwise, emits diagnostics and returns ExprError.
12117 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12118                                          UnresolvedLookupExpr *ULE,
12119                                          SourceLocation LParenLoc,
12120                                          MultiExprArg Args,
12121                                          SourceLocation RParenLoc,
12122                                          Expr *ExecConfig,
12123                                          bool AllowTypoCorrection,
12124                                          bool CalleesAddressIsTaken) {
12125   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12126                                     OverloadCandidateSet::CSK_Normal);
12127   ExprResult result;
12128 
12129   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12130                              &result))
12131     return result;
12132 
12133   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12134   // functions that aren't addressible are considered unviable.
12135   if (CalleesAddressIsTaken)
12136     markUnaddressableCandidatesUnviable(*this, CandidateSet);
12137 
12138   OverloadCandidateSet::iterator Best;
12139   OverloadingResult OverloadResult =
12140       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
12141 
12142   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
12143                                   RParenLoc, ExecConfig, &CandidateSet,
12144                                   &Best, OverloadResult,
12145                                   AllowTypoCorrection);
12146 }
12147 
12148 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
12149   return Functions.size() > 1 ||
12150     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12151 }
12152 
12153 /// Create a unary operation that may resolve to an overloaded
12154 /// operator.
12155 ///
12156 /// \param OpLoc The location of the operator itself (e.g., '*').
12157 ///
12158 /// \param Opc The UnaryOperatorKind that describes this operator.
12159 ///
12160 /// \param Fns The set of non-member functions that will be
12161 /// considered by overload resolution. The caller needs to build this
12162 /// set based on the context using, e.g.,
12163 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12164 /// set should not contain any member functions; those will be added
12165 /// by CreateOverloadedUnaryOp().
12166 ///
12167 /// \param Input The input argument.
12168 ExprResult
12169 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12170                               const UnresolvedSetImpl &Fns,
12171                               Expr *Input, bool PerformADL) {
12172   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12173   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12174   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12175   // TODO: provide better source location info.
12176   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12177 
12178   if (checkPlaceholderForOverload(*this, Input))
12179     return ExprError();
12180 
12181   Expr *Args[2] = { Input, nullptr };
12182   unsigned NumArgs = 1;
12183 
12184   // For post-increment and post-decrement, add the implicit '0' as
12185   // the second argument, so that we know this is a post-increment or
12186   // post-decrement.
12187   if (Opc == UO_PostInc || Opc == UO_PostDec) {
12188     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12189     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12190                                      SourceLocation());
12191     NumArgs = 2;
12192   }
12193 
12194   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12195 
12196   if (Input->isTypeDependent()) {
12197     if (Fns.empty())
12198       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12199                                          VK_RValue, OK_Ordinary, OpLoc, false);
12200 
12201     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12202     UnresolvedLookupExpr *Fn
12203       = UnresolvedLookupExpr::Create(Context, NamingClass,
12204                                      NestedNameSpecifierLoc(), OpNameInfo,
12205                                      /*ADL*/ true, IsOverloaded(Fns),
12206                                      Fns.begin(), Fns.end());
12207     return new (Context)
12208         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
12209                             VK_RValue, OpLoc, FPOptions());
12210   }
12211 
12212   // Build an empty overload set.
12213   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12214 
12215   // Add the candidates from the given function set.
12216   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
12217 
12218   // Add operator candidates that are member functions.
12219   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12220 
12221   // Add candidates from ADL.
12222   if (PerformADL) {
12223     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12224                                          /*ExplicitTemplateArgs*/nullptr,
12225                                          CandidateSet);
12226   }
12227 
12228   // Add builtin operator candidates.
12229   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12230 
12231   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12232 
12233   // Perform overload resolution.
12234   OverloadCandidateSet::iterator Best;
12235   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12236   case OR_Success: {
12237     // We found a built-in operator or an overloaded operator.
12238     FunctionDecl *FnDecl = Best->Function;
12239 
12240     if (FnDecl) {
12241       Expr *Base = nullptr;
12242       // We matched an overloaded operator. Build a call to that
12243       // operator.
12244 
12245       // Convert the arguments.
12246       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12247         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12248 
12249         ExprResult InputRes =
12250           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12251                                               Best->FoundDecl, Method);
12252         if (InputRes.isInvalid())
12253           return ExprError();
12254         Base = Input = InputRes.get();
12255       } else {
12256         // Convert the arguments.
12257         ExprResult InputInit
12258           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12259                                                       Context,
12260                                                       FnDecl->getParamDecl(0)),
12261                                       SourceLocation(),
12262                                       Input);
12263         if (InputInit.isInvalid())
12264           return ExprError();
12265         Input = InputInit.get();
12266       }
12267 
12268       // Build the actual expression node.
12269       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12270                                                 Base, HadMultipleCandidates,
12271                                                 OpLoc);
12272       if (FnExpr.isInvalid())
12273         return ExprError();
12274 
12275       // Determine the result type.
12276       QualType ResultTy = FnDecl->getReturnType();
12277       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12278       ResultTy = ResultTy.getNonLValueExprType(Context);
12279 
12280       Args[0] = Input;
12281       CallExpr *TheCall = new (Context)
12282           CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, ResultTy,
12283                               VK, OpLoc, FPOptions(), Best->IsADLCandidate);
12284 
12285       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12286         return ExprError();
12287 
12288       if (CheckFunctionCall(FnDecl, TheCall,
12289                             FnDecl->getType()->castAs<FunctionProtoType>()))
12290         return ExprError();
12291 
12292       return MaybeBindToTemporary(TheCall);
12293     } else {
12294       // We matched a built-in operator. Convert the arguments, then
12295       // break out so that we will build the appropriate built-in
12296       // operator node.
12297       ExprResult InputRes = PerformImplicitConversion(
12298           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
12299           CCK_ForBuiltinOverloadedOp);
12300       if (InputRes.isInvalid())
12301         return ExprError();
12302       Input = InputRes.get();
12303       break;
12304     }
12305   }
12306 
12307   case OR_No_Viable_Function:
12308     // This is an erroneous use of an operator which can be overloaded by
12309     // a non-member function. Check for non-member operators which were
12310     // defined too late to be candidates.
12311     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12312       // FIXME: Recover by calling the found function.
12313       return ExprError();
12314 
12315     // No viable function; fall through to handling this as a
12316     // built-in operator, which will produce an error message for us.
12317     break;
12318 
12319   case OR_Ambiguous:
12320     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12321         << UnaryOperator::getOpcodeStr(Opc)
12322         << Input->getType()
12323         << Input->getSourceRange();
12324     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
12325                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12326     return ExprError();
12327 
12328   case OR_Deleted:
12329     Diag(OpLoc, diag::err_ovl_deleted_oper)
12330       << Best->Function->isDeleted()
12331       << UnaryOperator::getOpcodeStr(Opc)
12332       << getDeletedOrUnavailableSuffix(Best->Function)
12333       << Input->getSourceRange();
12334     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
12335                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12336     return ExprError();
12337   }
12338 
12339   // Either we found no viable overloaded operator or we matched a
12340   // built-in operator. In either case, fall through to trying to
12341   // build a built-in operation.
12342   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12343 }
12344 
12345 /// Create a binary operation that may resolve to an overloaded
12346 /// operator.
12347 ///
12348 /// \param OpLoc The location of the operator itself (e.g., '+').
12349 ///
12350 /// \param Opc The BinaryOperatorKind that describes this operator.
12351 ///
12352 /// \param Fns The set of non-member functions that will be
12353 /// considered by overload resolution. The caller needs to build this
12354 /// set based on the context using, e.g.,
12355 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12356 /// set should not contain any member functions; those will be added
12357 /// by CreateOverloadedBinOp().
12358 ///
12359 /// \param LHS Left-hand argument.
12360 /// \param RHS Right-hand argument.
12361 ExprResult
12362 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12363                             BinaryOperatorKind Opc,
12364                             const UnresolvedSetImpl &Fns,
12365                             Expr *LHS, Expr *RHS, bool PerformADL) {
12366   Expr *Args[2] = { LHS, RHS };
12367   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12368 
12369   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12370   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12371 
12372   // If either side is type-dependent, create an appropriate dependent
12373   // expression.
12374   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12375     if (Fns.empty()) {
12376       // If there are no functions to store, just build a dependent
12377       // BinaryOperator or CompoundAssignment.
12378       if (Opc <= BO_Assign || Opc > BO_OrAssign)
12379         return new (Context) BinaryOperator(
12380             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12381             OpLoc, FPFeatures);
12382 
12383       return new (Context) CompoundAssignOperator(
12384           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12385           Context.DependentTy, Context.DependentTy, OpLoc,
12386           FPFeatures);
12387     }
12388 
12389     // FIXME: save results of ADL from here?
12390     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12391     // TODO: provide better source location info in DNLoc component.
12392     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12393     UnresolvedLookupExpr *Fn
12394       = UnresolvedLookupExpr::Create(Context, NamingClass,
12395                                      NestedNameSpecifierLoc(), OpNameInfo,
12396                                      /*ADL*/PerformADL, IsOverloaded(Fns),
12397                                      Fns.begin(), Fns.end());
12398     return new (Context)
12399         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
12400                             VK_RValue, OpLoc, FPFeatures);
12401   }
12402 
12403   // Always do placeholder-like conversions on the RHS.
12404   if (checkPlaceholderForOverload(*this, Args[1]))
12405     return ExprError();
12406 
12407   // Do placeholder-like conversion on the LHS; note that we should
12408   // not get here with a PseudoObject LHS.
12409   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12410   if (checkPlaceholderForOverload(*this, Args[0]))
12411     return ExprError();
12412 
12413   // If this is the assignment operator, we only perform overload resolution
12414   // if the left-hand side is a class or enumeration type. This is actually
12415   // a hack. The standard requires that we do overload resolution between the
12416   // various built-in candidates, but as DR507 points out, this can lead to
12417   // problems. So we do it this way, which pretty much follows what GCC does.
12418   // Note that we go the traditional code path for compound assignment forms.
12419   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12420     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12421 
12422   // If this is the .* operator, which is not overloadable, just
12423   // create a built-in binary operator.
12424   if (Opc == BO_PtrMemD)
12425     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12426 
12427   // Build an empty overload set.
12428   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12429 
12430   // Add the candidates from the given function set.
12431   AddFunctionCandidates(Fns, Args, CandidateSet);
12432 
12433   // Add operator candidates that are member functions.
12434   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12435 
12436   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12437   // performed for an assignment operator (nor for operator[] nor operator->,
12438   // which don't get here).
12439   if (Opc != BO_Assign && PerformADL)
12440     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12441                                          /*ExplicitTemplateArgs*/ nullptr,
12442                                          CandidateSet);
12443 
12444   // Add builtin operator candidates.
12445   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12446 
12447   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12448 
12449   // Perform overload resolution.
12450   OverloadCandidateSet::iterator Best;
12451   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12452     case OR_Success: {
12453       // We found a built-in operator or an overloaded operator.
12454       FunctionDecl *FnDecl = Best->Function;
12455 
12456       if (FnDecl) {
12457         Expr *Base = nullptr;
12458         // We matched an overloaded operator. Build a call to that
12459         // operator.
12460 
12461         // Convert the arguments.
12462         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12463           // Best->Access is only meaningful for class members.
12464           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12465 
12466           ExprResult Arg1 =
12467             PerformCopyInitialization(
12468               InitializedEntity::InitializeParameter(Context,
12469                                                      FnDecl->getParamDecl(0)),
12470               SourceLocation(), Args[1]);
12471           if (Arg1.isInvalid())
12472             return ExprError();
12473 
12474           ExprResult Arg0 =
12475             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12476                                                 Best->FoundDecl, Method);
12477           if (Arg0.isInvalid())
12478             return ExprError();
12479           Base = Args[0] = Arg0.getAs<Expr>();
12480           Args[1] = RHS = Arg1.getAs<Expr>();
12481         } else {
12482           // Convert the arguments.
12483           ExprResult Arg0 = PerformCopyInitialization(
12484             InitializedEntity::InitializeParameter(Context,
12485                                                    FnDecl->getParamDecl(0)),
12486             SourceLocation(), Args[0]);
12487           if (Arg0.isInvalid())
12488             return ExprError();
12489 
12490           ExprResult Arg1 =
12491             PerformCopyInitialization(
12492               InitializedEntity::InitializeParameter(Context,
12493                                                      FnDecl->getParamDecl(1)),
12494               SourceLocation(), Args[1]);
12495           if (Arg1.isInvalid())
12496             return ExprError();
12497           Args[0] = LHS = Arg0.getAs<Expr>();
12498           Args[1] = RHS = Arg1.getAs<Expr>();
12499         }
12500 
12501         // Build the actual expression node.
12502         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12503                                                   Best->FoundDecl, Base,
12504                                                   HadMultipleCandidates, OpLoc);
12505         if (FnExpr.isInvalid())
12506           return ExprError();
12507 
12508         // Determine the result type.
12509         QualType ResultTy = FnDecl->getReturnType();
12510         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12511         ResultTy = ResultTy.getNonLValueExprType(Context);
12512 
12513         CXXOperatorCallExpr *TheCall = new (Context)
12514             CXXOperatorCallExpr(Context, Op, FnExpr.get(), Args, ResultTy, VK,
12515                                 OpLoc, FPFeatures, Best->IsADLCandidate);
12516 
12517         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12518                                 FnDecl))
12519           return ExprError();
12520 
12521         ArrayRef<const Expr *> ArgsArray(Args, 2);
12522         const Expr *ImplicitThis = nullptr;
12523         // Cut off the implicit 'this'.
12524         if (isa<CXXMethodDecl>(FnDecl)) {
12525           ImplicitThis = ArgsArray[0];
12526           ArgsArray = ArgsArray.slice(1);
12527         }
12528 
12529         // Check for a self move.
12530         if (Op == OO_Equal)
12531           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12532 
12533         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12534                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12535                   VariadicDoesNotApply);
12536 
12537         return MaybeBindToTemporary(TheCall);
12538       } else {
12539         // We matched a built-in operator. Convert the arguments, then
12540         // break out so that we will build the appropriate built-in
12541         // operator node.
12542         ExprResult ArgsRes0 = PerformImplicitConversion(
12543             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12544             AA_Passing, CCK_ForBuiltinOverloadedOp);
12545         if (ArgsRes0.isInvalid())
12546           return ExprError();
12547         Args[0] = ArgsRes0.get();
12548 
12549         ExprResult ArgsRes1 = PerformImplicitConversion(
12550             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12551             AA_Passing, CCK_ForBuiltinOverloadedOp);
12552         if (ArgsRes1.isInvalid())
12553           return ExprError();
12554         Args[1] = ArgsRes1.get();
12555         break;
12556       }
12557     }
12558 
12559     case OR_No_Viable_Function: {
12560       // C++ [over.match.oper]p9:
12561       //   If the operator is the operator , [...] and there are no
12562       //   viable functions, then the operator is assumed to be the
12563       //   built-in operator and interpreted according to clause 5.
12564       if (Opc == BO_Comma)
12565         break;
12566 
12567       // For class as left operand for assignment or compound assignment
12568       // operator do not fall through to handling in built-in, but report that
12569       // no overloaded assignment operator found
12570       ExprResult Result = ExprError();
12571       if (Args[0]->getType()->isRecordType() &&
12572           Opc >= BO_Assign && Opc <= BO_OrAssign) {
12573         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
12574              << BinaryOperator::getOpcodeStr(Opc)
12575              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12576         if (Args[0]->getType()->isIncompleteType()) {
12577           Diag(OpLoc, diag::note_assign_lhs_incomplete)
12578             << Args[0]->getType()
12579             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12580         }
12581       } else {
12582         // This is an erroneous use of an operator which can be overloaded by
12583         // a non-member function. Check for non-member operators which were
12584         // defined too late to be candidates.
12585         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12586           // FIXME: Recover by calling the found function.
12587           return ExprError();
12588 
12589         // No viable function; try to create a built-in operation, which will
12590         // produce an error. Then, show the non-viable candidates.
12591         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12592       }
12593       assert(Result.isInvalid() &&
12594              "C++ binary operator overloading is missing candidates!");
12595       if (Result.isInvalid())
12596         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12597                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
12598       return Result;
12599     }
12600 
12601     case OR_Ambiguous:
12602       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
12603           << BinaryOperator::getOpcodeStr(Opc)
12604           << Args[0]->getType() << Args[1]->getType()
12605           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12606       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12607                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12608       return ExprError();
12609 
12610     case OR_Deleted:
12611       if (isImplicitlyDeleted(Best->Function)) {
12612         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12613         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12614           << Context.getRecordType(Method->getParent())
12615           << getSpecialMember(Method);
12616 
12617         // The user probably meant to call this special member. Just
12618         // explain why it's deleted.
12619         NoteDeletedFunction(Method);
12620         return ExprError();
12621       } else {
12622         Diag(OpLoc, diag::err_ovl_deleted_oper)
12623           << Best->Function->isDeleted()
12624           << BinaryOperator::getOpcodeStr(Opc)
12625           << getDeletedOrUnavailableSuffix(Best->Function)
12626           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12627       }
12628       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12629                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12630       return ExprError();
12631   }
12632 
12633   // We matched a built-in operator; build it.
12634   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12635 }
12636 
12637 ExprResult
12638 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12639                                          SourceLocation RLoc,
12640                                          Expr *Base, Expr *Idx) {
12641   Expr *Args[2] = { Base, Idx };
12642   DeclarationName OpName =
12643       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12644 
12645   // If either side is type-dependent, create an appropriate dependent
12646   // expression.
12647   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12648 
12649     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12650     // CHECKME: no 'operator' keyword?
12651     DeclarationNameInfo OpNameInfo(OpName, LLoc);
12652     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12653     UnresolvedLookupExpr *Fn
12654       = UnresolvedLookupExpr::Create(Context, NamingClass,
12655                                      NestedNameSpecifierLoc(), OpNameInfo,
12656                                      /*ADL*/ true, /*Overloaded*/ false,
12657                                      UnresolvedSetIterator(),
12658                                      UnresolvedSetIterator());
12659     // Can't add any actual overloads yet
12660 
12661     return new (Context)
12662         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12663                             Context.DependentTy, VK_RValue, RLoc, FPOptions());
12664   }
12665 
12666   // Handle placeholders on both operands.
12667   if (checkPlaceholderForOverload(*this, Args[0]))
12668     return ExprError();
12669   if (checkPlaceholderForOverload(*this, Args[1]))
12670     return ExprError();
12671 
12672   // Build an empty overload set.
12673   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12674 
12675   // Subscript can only be overloaded as a member function.
12676 
12677   // Add operator candidates that are member functions.
12678   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12679 
12680   // Add builtin operator candidates.
12681   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12682 
12683   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12684 
12685   // Perform overload resolution.
12686   OverloadCandidateSet::iterator Best;
12687   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12688     case OR_Success: {
12689       // We found a built-in operator or an overloaded operator.
12690       FunctionDecl *FnDecl = Best->Function;
12691 
12692       if (FnDecl) {
12693         // We matched an overloaded operator. Build a call to that
12694         // operator.
12695 
12696         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12697 
12698         // Convert the arguments.
12699         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12700         ExprResult Arg0 =
12701           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12702                                               Best->FoundDecl, Method);
12703         if (Arg0.isInvalid())
12704           return ExprError();
12705         Args[0] = Arg0.get();
12706 
12707         // Convert the arguments.
12708         ExprResult InputInit
12709           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12710                                                       Context,
12711                                                       FnDecl->getParamDecl(0)),
12712                                       SourceLocation(),
12713                                       Args[1]);
12714         if (InputInit.isInvalid())
12715           return ExprError();
12716 
12717         Args[1] = InputInit.getAs<Expr>();
12718 
12719         // Build the actual expression node.
12720         DeclarationNameInfo OpLocInfo(OpName, LLoc);
12721         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12722         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12723                                                   Best->FoundDecl,
12724                                                   Base,
12725                                                   HadMultipleCandidates,
12726                                                   OpLocInfo.getLoc(),
12727                                                   OpLocInfo.getInfo());
12728         if (FnExpr.isInvalid())
12729           return ExprError();
12730 
12731         // Determine the result type
12732         QualType ResultTy = FnDecl->getReturnType();
12733         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12734         ResultTy = ResultTy.getNonLValueExprType(Context);
12735 
12736         CXXOperatorCallExpr *TheCall =
12737           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12738                                             FnExpr.get(), Args,
12739                                             ResultTy, VK, RLoc,
12740                                             FPOptions());
12741 
12742         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12743           return ExprError();
12744 
12745         if (CheckFunctionCall(Method, TheCall,
12746                               Method->getType()->castAs<FunctionProtoType>()))
12747           return ExprError();
12748 
12749         return MaybeBindToTemporary(TheCall);
12750       } else {
12751         // We matched a built-in operator. Convert the arguments, then
12752         // break out so that we will build the appropriate built-in
12753         // operator node.
12754         ExprResult ArgsRes0 = PerformImplicitConversion(
12755             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12756             AA_Passing, CCK_ForBuiltinOverloadedOp);
12757         if (ArgsRes0.isInvalid())
12758           return ExprError();
12759         Args[0] = ArgsRes0.get();
12760 
12761         ExprResult ArgsRes1 = PerformImplicitConversion(
12762             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12763             AA_Passing, CCK_ForBuiltinOverloadedOp);
12764         if (ArgsRes1.isInvalid())
12765           return ExprError();
12766         Args[1] = ArgsRes1.get();
12767 
12768         break;
12769       }
12770     }
12771 
12772     case OR_No_Viable_Function: {
12773       if (CandidateSet.empty())
12774         Diag(LLoc, diag::err_ovl_no_oper)
12775           << Args[0]->getType() << /*subscript*/ 0
12776           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12777       else
12778         Diag(LLoc, diag::err_ovl_no_viable_subscript)
12779           << Args[0]->getType()
12780           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12781       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12782                                   "[]", LLoc);
12783       return ExprError();
12784     }
12785 
12786     case OR_Ambiguous:
12787       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
12788           << "[]"
12789           << Args[0]->getType() << Args[1]->getType()
12790           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12791       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12792                                   "[]", LLoc);
12793       return ExprError();
12794 
12795     case OR_Deleted:
12796       Diag(LLoc, diag::err_ovl_deleted_oper)
12797         << Best->Function->isDeleted() << "[]"
12798         << getDeletedOrUnavailableSuffix(Best->Function)
12799         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12800       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12801                                   "[]", LLoc);
12802       return ExprError();
12803     }
12804 
12805   // We matched a built-in operator; build it.
12806   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12807 }
12808 
12809 /// BuildCallToMemberFunction - Build a call to a member
12810 /// function. MemExpr is the expression that refers to the member
12811 /// function (and includes the object parameter), Args/NumArgs are the
12812 /// arguments to the function call (not including the object
12813 /// parameter). The caller needs to validate that the member
12814 /// expression refers to a non-static member function or an overloaded
12815 /// member function.
12816 ExprResult
12817 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12818                                 SourceLocation LParenLoc,
12819                                 MultiExprArg Args,
12820                                 SourceLocation RParenLoc) {
12821   assert(MemExprE->getType() == Context.BoundMemberTy ||
12822          MemExprE->getType() == Context.OverloadTy);
12823 
12824   // Dig out the member expression. This holds both the object
12825   // argument and the member function we're referring to.
12826   Expr *NakedMemExpr = MemExprE->IgnoreParens();
12827 
12828   // Determine whether this is a call to a pointer-to-member function.
12829   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12830     assert(op->getType() == Context.BoundMemberTy);
12831     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12832 
12833     QualType fnType =
12834       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12835 
12836     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12837     QualType resultType = proto->getCallResultType(Context);
12838     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12839 
12840     // Check that the object type isn't more qualified than the
12841     // member function we're calling.
12842     Qualifiers funcQuals = proto->getTypeQuals();
12843 
12844     QualType objectType = op->getLHS()->getType();
12845     if (op->getOpcode() == BO_PtrMemI)
12846       objectType = objectType->castAs<PointerType>()->getPointeeType();
12847     Qualifiers objectQuals = objectType.getQualifiers();
12848 
12849     Qualifiers difference = objectQuals - funcQuals;
12850     difference.removeObjCGCAttr();
12851     difference.removeAddressSpace();
12852     if (difference) {
12853       std::string qualsString = difference.getAsString();
12854       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12855         << fnType.getUnqualifiedType()
12856         << qualsString
12857         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12858     }
12859 
12860     CXXMemberCallExpr *call
12861       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12862                                         resultType, valueKind, RParenLoc,
12863                                         proto->getNumParams());
12864 
12865     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
12866                             call, nullptr))
12867       return ExprError();
12868 
12869     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12870       return ExprError();
12871 
12872     if (CheckOtherCall(call, proto))
12873       return ExprError();
12874 
12875     return MaybeBindToTemporary(call);
12876   }
12877 
12878   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12879     return new (Context)
12880         CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12881 
12882   UnbridgedCastsSet UnbridgedCasts;
12883   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12884     return ExprError();
12885 
12886   MemberExpr *MemExpr;
12887   CXXMethodDecl *Method = nullptr;
12888   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12889   NestedNameSpecifier *Qualifier = nullptr;
12890   if (isa<MemberExpr>(NakedMemExpr)) {
12891     MemExpr = cast<MemberExpr>(NakedMemExpr);
12892     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12893     FoundDecl = MemExpr->getFoundDecl();
12894     Qualifier = MemExpr->getQualifier();
12895     UnbridgedCasts.restore();
12896   } else {
12897     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12898     Qualifier = UnresExpr->getQualifier();
12899 
12900     QualType ObjectType = UnresExpr->getBaseType();
12901     Expr::Classification ObjectClassification
12902       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12903                             : UnresExpr->getBase()->Classify(Context);
12904 
12905     // Add overload candidates
12906     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12907                                       OverloadCandidateSet::CSK_Normal);
12908 
12909     // FIXME: avoid copy.
12910     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12911     if (UnresExpr->hasExplicitTemplateArgs()) {
12912       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12913       TemplateArgs = &TemplateArgsBuffer;
12914     }
12915 
12916     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12917            E = UnresExpr->decls_end(); I != E; ++I) {
12918 
12919       NamedDecl *Func = *I;
12920       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12921       if (isa<UsingShadowDecl>(Func))
12922         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12923 
12924 
12925       // Microsoft supports direct constructor calls.
12926       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12927         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12928                              Args, CandidateSet);
12929       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12930         // If explicit template arguments were provided, we can't call a
12931         // non-template member function.
12932         if (TemplateArgs)
12933           continue;
12934 
12935         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12936                            ObjectClassification, Args, CandidateSet,
12937                            /*SuppressUserConversions=*/false);
12938       } else {
12939         AddMethodTemplateCandidate(
12940             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
12941             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
12942             /*SuppressUsedConversions=*/false);
12943       }
12944     }
12945 
12946     DeclarationName DeclName = UnresExpr->getMemberName();
12947 
12948     UnbridgedCasts.restore();
12949 
12950     OverloadCandidateSet::iterator Best;
12951     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
12952                                             Best)) {
12953     case OR_Success:
12954       Method = cast<CXXMethodDecl>(Best->Function);
12955       FoundDecl = Best->FoundDecl;
12956       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12957       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12958         return ExprError();
12959       // If FoundDecl is different from Method (such as if one is a template
12960       // and the other a specialization), make sure DiagnoseUseOfDecl is
12961       // called on both.
12962       // FIXME: This would be more comprehensively addressed by modifying
12963       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12964       // being used.
12965       if (Method != FoundDecl.getDecl() &&
12966                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12967         return ExprError();
12968       break;
12969 
12970     case OR_No_Viable_Function:
12971       Diag(UnresExpr->getMemberLoc(),
12972            diag::err_ovl_no_viable_member_function_in_call)
12973         << DeclName << MemExprE->getSourceRange();
12974       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12975       // FIXME: Leaking incoming expressions!
12976       return ExprError();
12977 
12978     case OR_Ambiguous:
12979       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12980         << DeclName << MemExprE->getSourceRange();
12981       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12982       // FIXME: Leaking incoming expressions!
12983       return ExprError();
12984 
12985     case OR_Deleted:
12986       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12987         << Best->Function->isDeleted()
12988         << DeclName
12989         << getDeletedOrUnavailableSuffix(Best->Function)
12990         << MemExprE->getSourceRange();
12991       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12992       // FIXME: Leaking incoming expressions!
12993       return ExprError();
12994     }
12995 
12996     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12997 
12998     // If overload resolution picked a static member, build a
12999     // non-member call based on that function.
13000     if (Method->isStatic()) {
13001       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
13002                                    RParenLoc);
13003     }
13004 
13005     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
13006   }
13007 
13008   QualType ResultType = Method->getReturnType();
13009   ExprValueKind VK = Expr::getValueKindForType(ResultType);
13010   ResultType = ResultType.getNonLValueExprType(Context);
13011 
13012   assert(Method && "Member call to something that isn't a method?");
13013   const auto *Proto = Method->getType()->getAs<FunctionProtoType>();
13014   CXXMemberCallExpr *TheCall =
13015     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
13016                                     ResultType, VK, RParenLoc,
13017                                     Proto->getNumParams());
13018 
13019   // Check for a valid return type.
13020   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
13021                           TheCall, Method))
13022     return ExprError();
13023 
13024   // Convert the object argument (for a non-static member function call).
13025   // We only need to do this if there was actually an overload; otherwise
13026   // it was done at lookup.
13027   if (!Method->isStatic()) {
13028     ExprResult ObjectArg =
13029       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
13030                                           FoundDecl, Method);
13031     if (ObjectArg.isInvalid())
13032       return ExprError();
13033     MemExpr->setBase(ObjectArg.get());
13034   }
13035 
13036   // Convert the rest of the arguments
13037   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
13038                               RParenLoc))
13039     return ExprError();
13040 
13041   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13042 
13043   if (CheckFunctionCall(Method, TheCall, Proto))
13044     return ExprError();
13045 
13046   // In the case the method to call was not selected by the overloading
13047   // resolution process, we still need to handle the enable_if attribute. Do
13048   // that here, so it will not hide previous -- and more relevant -- errors.
13049   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
13050     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
13051       Diag(MemE->getMemberLoc(),
13052            diag::err_ovl_no_viable_member_function_in_call)
13053           << Method << Method->getSourceRange();
13054       Diag(Method->getLocation(),
13055            diag::note_ovl_candidate_disabled_by_function_cond_attr)
13056           << Attr->getCond()->getSourceRange() << Attr->getMessage();
13057       return ExprError();
13058     }
13059   }
13060 
13061   if ((isa<CXXConstructorDecl>(CurContext) ||
13062        isa<CXXDestructorDecl>(CurContext)) &&
13063       TheCall->getMethodDecl()->isPure()) {
13064     const CXXMethodDecl *MD = TheCall->getMethodDecl();
13065 
13066     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
13067         MemExpr->performsVirtualDispatch(getLangOpts())) {
13068       Diag(MemExpr->getBeginLoc(),
13069            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
13070           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
13071           << MD->getParent()->getDeclName();
13072 
13073       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
13074       if (getLangOpts().AppleKext)
13075         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
13076             << MD->getParent()->getDeclName() << MD->getDeclName();
13077     }
13078   }
13079 
13080   if (CXXDestructorDecl *DD =
13081           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
13082     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
13083     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
13084     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
13085                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
13086                          MemExpr->getMemberLoc());
13087   }
13088 
13089   return MaybeBindToTemporary(TheCall);
13090 }
13091 
13092 /// BuildCallToObjectOfClassType - Build a call to an object of class
13093 /// type (C++ [over.call.object]), which can end up invoking an
13094 /// overloaded function call operator (@c operator()) or performing a
13095 /// user-defined conversion on the object argument.
13096 ExprResult
13097 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
13098                                    SourceLocation LParenLoc,
13099                                    MultiExprArg Args,
13100                                    SourceLocation RParenLoc) {
13101   if (checkPlaceholderForOverload(*this, Obj))
13102     return ExprError();
13103   ExprResult Object = Obj;
13104 
13105   UnbridgedCastsSet UnbridgedCasts;
13106   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13107     return ExprError();
13108 
13109   assert(Object.get()->getType()->isRecordType() &&
13110          "Requires object type argument");
13111   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
13112 
13113   // C++ [over.call.object]p1:
13114   //  If the primary-expression E in the function call syntax
13115   //  evaluates to a class object of type "cv T", then the set of
13116   //  candidate functions includes at least the function call
13117   //  operators of T. The function call operators of T are obtained by
13118   //  ordinary lookup of the name operator() in the context of
13119   //  (E).operator().
13120   OverloadCandidateSet CandidateSet(LParenLoc,
13121                                     OverloadCandidateSet::CSK_Operator);
13122   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
13123 
13124   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
13125                           diag::err_incomplete_object_call, Object.get()))
13126     return true;
13127 
13128   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
13129   LookupQualifiedName(R, Record->getDecl());
13130   R.suppressDiagnostics();
13131 
13132   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13133        Oper != OperEnd; ++Oper) {
13134     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
13135                        Object.get()->Classify(Context), Args, CandidateSet,
13136                        /*SuppressUserConversions=*/false);
13137   }
13138 
13139   // C++ [over.call.object]p2:
13140   //   In addition, for each (non-explicit in C++0x) conversion function
13141   //   declared in T of the form
13142   //
13143   //        operator conversion-type-id () cv-qualifier;
13144   //
13145   //   where cv-qualifier is the same cv-qualification as, or a
13146   //   greater cv-qualification than, cv, and where conversion-type-id
13147   //   denotes the type "pointer to function of (P1,...,Pn) returning
13148   //   R", or the type "reference to pointer to function of
13149   //   (P1,...,Pn) returning R", or the type "reference to function
13150   //   of (P1,...,Pn) returning R", a surrogate call function [...]
13151   //   is also considered as a candidate function. Similarly,
13152   //   surrogate call functions are added to the set of candidate
13153   //   functions for each conversion function declared in an
13154   //   accessible base class provided the function is not hidden
13155   //   within T by another intervening declaration.
13156   const auto &Conversions =
13157       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
13158   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
13159     NamedDecl *D = *I;
13160     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
13161     if (isa<UsingShadowDecl>(D))
13162       D = cast<UsingShadowDecl>(D)->getTargetDecl();
13163 
13164     // Skip over templated conversion functions; they aren't
13165     // surrogates.
13166     if (isa<FunctionTemplateDecl>(D))
13167       continue;
13168 
13169     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
13170     if (!Conv->isExplicit()) {
13171       // Strip the reference type (if any) and then the pointer type (if
13172       // any) to get down to what might be a function type.
13173       QualType ConvType = Conv->getConversionType().getNonReferenceType();
13174       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13175         ConvType = ConvPtrType->getPointeeType();
13176 
13177       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13178       {
13179         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
13180                               Object.get(), Args, CandidateSet);
13181       }
13182     }
13183   }
13184 
13185   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13186 
13187   // Perform overload resolution.
13188   OverloadCandidateSet::iterator Best;
13189   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
13190                                           Best)) {
13191   case OR_Success:
13192     // Overload resolution succeeded; we'll build the appropriate call
13193     // below.
13194     break;
13195 
13196   case OR_No_Viable_Function:
13197     if (CandidateSet.empty())
13198       Diag(Object.get()->getBeginLoc(), diag::err_ovl_no_oper)
13199           << Object.get()->getType() << /*call*/ 1
13200           << Object.get()->getSourceRange();
13201     else
13202       Diag(Object.get()->getBeginLoc(), diag::err_ovl_no_viable_object_call)
13203           << Object.get()->getType() << Object.get()->getSourceRange();
13204     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13205     break;
13206 
13207   case OR_Ambiguous:
13208     Diag(Object.get()->getBeginLoc(), diag::err_ovl_ambiguous_object_call)
13209         << Object.get()->getType() << Object.get()->getSourceRange();
13210     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13211     break;
13212 
13213   case OR_Deleted:
13214     Diag(Object.get()->getBeginLoc(), diag::err_ovl_deleted_object_call)
13215         << Best->Function->isDeleted() << Object.get()->getType()
13216         << getDeletedOrUnavailableSuffix(Best->Function)
13217         << Object.get()->getSourceRange();
13218     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13219     break;
13220   }
13221 
13222   if (Best == CandidateSet.end())
13223     return true;
13224 
13225   UnbridgedCasts.restore();
13226 
13227   if (Best->Function == nullptr) {
13228     // Since there is no function declaration, this is one of the
13229     // surrogate candidates. Dig out the conversion function.
13230     CXXConversionDecl *Conv
13231       = cast<CXXConversionDecl>(
13232                          Best->Conversions[0].UserDefined.ConversionFunction);
13233 
13234     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13235                               Best->FoundDecl);
13236     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13237       return ExprError();
13238     assert(Conv == Best->FoundDecl.getDecl() &&
13239              "Found Decl & conversion-to-functionptr should be same, right?!");
13240     // We selected one of the surrogate functions that converts the
13241     // object parameter to a function pointer. Perform the conversion
13242     // on the object argument, then let ActOnCallExpr finish the job.
13243 
13244     // Create an implicit member expr to refer to the conversion operator.
13245     // and then call it.
13246     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13247                                              Conv, HadMultipleCandidates);
13248     if (Call.isInvalid())
13249       return ExprError();
13250     // Record usage of conversion in an implicit cast.
13251     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13252                                     CK_UserDefinedConversion, Call.get(),
13253                                     nullptr, VK_RValue);
13254 
13255     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13256   }
13257 
13258   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13259 
13260   // We found an overloaded operator(). Build a CXXOperatorCallExpr
13261   // that calls this method, using Object for the implicit object
13262   // parameter and passing along the remaining arguments.
13263   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13264 
13265   // An error diagnostic has already been printed when parsing the declaration.
13266   if (Method->isInvalidDecl())
13267     return ExprError();
13268 
13269   const FunctionProtoType *Proto =
13270     Method->getType()->getAs<FunctionProtoType>();
13271 
13272   unsigned NumParams = Proto->getNumParams();
13273 
13274   DeclarationNameInfo OpLocInfo(
13275                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13276   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13277   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13278                                            Obj, HadMultipleCandidates,
13279                                            OpLocInfo.getLoc(),
13280                                            OpLocInfo.getInfo());
13281   if (NewFn.isInvalid())
13282     return true;
13283 
13284   // The number of argument slots to allocate in the call. If we have default
13285   // arguments we need to allocate space for them as well. We additionally
13286   // need one more slot for the object parameter.
13287   unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
13288 
13289   // Build the full argument list for the method call (the implicit object
13290   // parameter is placed at the beginning of the list).
13291   SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
13292 
13293   bool IsError = false;
13294 
13295   // Initialize the implicit object parameter.
13296   ExprResult ObjRes =
13297     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13298                                         Best->FoundDecl, Method);
13299   if (ObjRes.isInvalid())
13300     IsError = true;
13301   else
13302     Object = ObjRes;
13303   MethodArgs[0] = Object.get();
13304 
13305   // Check the argument types.
13306   for (unsigned i = 0; i != NumParams; i++) {
13307     Expr *Arg;
13308     if (i < Args.size()) {
13309       Arg = Args[i];
13310 
13311       // Pass the argument.
13312 
13313       ExprResult InputInit
13314         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13315                                                     Context,
13316                                                     Method->getParamDecl(i)),
13317                                     SourceLocation(), Arg);
13318 
13319       IsError |= InputInit.isInvalid();
13320       Arg = InputInit.getAs<Expr>();
13321     } else {
13322       ExprResult DefArg
13323         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13324       if (DefArg.isInvalid()) {
13325         IsError = true;
13326         break;
13327       }
13328 
13329       Arg = DefArg.getAs<Expr>();
13330     }
13331 
13332     MethodArgs[i + 1] = Arg;
13333   }
13334 
13335   // If this is a variadic call, handle args passed through "...".
13336   if (Proto->isVariadic()) {
13337     // Promote the arguments (C99 6.5.2.2p7).
13338     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
13339       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13340                                                         nullptr);
13341       IsError |= Arg.isInvalid();
13342       MethodArgs[i + 1] = Arg.get();
13343     }
13344   }
13345 
13346   if (IsError)
13347     return true;
13348 
13349   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13350 
13351   // Once we've built TheCall, all of the expressions are properly owned.
13352   QualType ResultTy = Method->getReturnType();
13353   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13354   ResultTy = ResultTy.getNonLValueExprType(Context);
13355 
13356   CXXOperatorCallExpr *TheCall = new (Context)
13357       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
13358                           VK, RParenLoc, FPOptions());
13359 
13360   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
13361     return true;
13362 
13363   if (CheckFunctionCall(Method, TheCall, Proto))
13364     return true;
13365 
13366   return MaybeBindToTemporary(TheCall);
13367 }
13368 
13369 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13370 ///  (if one exists), where @c Base is an expression of class type and
13371 /// @c Member is the name of the member we're trying to find.
13372 ExprResult
13373 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13374                                bool *NoArrowOperatorFound) {
13375   assert(Base->getType()->isRecordType() &&
13376          "left-hand side must have class type");
13377 
13378   if (checkPlaceholderForOverload(*this, Base))
13379     return ExprError();
13380 
13381   SourceLocation Loc = Base->getExprLoc();
13382 
13383   // C++ [over.ref]p1:
13384   //
13385   //   [...] An expression x->m is interpreted as (x.operator->())->m
13386   //   for a class object x of type T if T::operator->() exists and if
13387   //   the operator is selected as the best match function by the
13388   //   overload resolution mechanism (13.3).
13389   DeclarationName OpName =
13390     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13391   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
13392   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13393 
13394   if (RequireCompleteType(Loc, Base->getType(),
13395                           diag::err_typecheck_incomplete_tag, Base))
13396     return ExprError();
13397 
13398   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13399   LookupQualifiedName(R, BaseRecord->getDecl());
13400   R.suppressDiagnostics();
13401 
13402   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13403        Oper != OperEnd; ++Oper) {
13404     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13405                        None, CandidateSet, /*SuppressUserConversions=*/false);
13406   }
13407 
13408   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13409 
13410   // Perform overload resolution.
13411   OverloadCandidateSet::iterator Best;
13412   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13413   case OR_Success:
13414     // Overload resolution succeeded; we'll build the call below.
13415     break;
13416 
13417   case OR_No_Viable_Function:
13418     if (CandidateSet.empty()) {
13419       QualType BaseType = Base->getType();
13420       if (NoArrowOperatorFound) {
13421         // Report this specific error to the caller instead of emitting a
13422         // diagnostic, as requested.
13423         *NoArrowOperatorFound = true;
13424         return ExprError();
13425       }
13426       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13427         << BaseType << Base->getSourceRange();
13428       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13429         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13430           << FixItHint::CreateReplacement(OpLoc, ".");
13431       }
13432     } else
13433       Diag(OpLoc, diag::err_ovl_no_viable_oper)
13434         << "operator->" << Base->getSourceRange();
13435     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13436     return ExprError();
13437 
13438   case OR_Ambiguous:
13439     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
13440       << "->" << Base->getType() << Base->getSourceRange();
13441     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
13442     return ExprError();
13443 
13444   case OR_Deleted:
13445     Diag(OpLoc,  diag::err_ovl_deleted_oper)
13446       << Best->Function->isDeleted()
13447       << "->"
13448       << getDeletedOrUnavailableSuffix(Best->Function)
13449       << Base->getSourceRange();
13450     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13451     return ExprError();
13452   }
13453 
13454   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13455 
13456   // Convert the object parameter.
13457   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13458   ExprResult BaseResult =
13459     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13460                                         Best->FoundDecl, Method);
13461   if (BaseResult.isInvalid())
13462     return ExprError();
13463   Base = BaseResult.get();
13464 
13465   // Build the operator call.
13466   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13467                                             Base, HadMultipleCandidates, OpLoc);
13468   if (FnExpr.isInvalid())
13469     return ExprError();
13470 
13471   QualType ResultTy = Method->getReturnType();
13472   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13473   ResultTy = ResultTy.getNonLValueExprType(Context);
13474   CXXOperatorCallExpr *TheCall =
13475     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
13476                                       Base, ResultTy, VK, OpLoc, FPOptions());
13477 
13478   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13479     return ExprError();
13480 
13481   if (CheckFunctionCall(Method, TheCall,
13482                         Method->getType()->castAs<FunctionProtoType>()))
13483     return ExprError();
13484 
13485   return MaybeBindToTemporary(TheCall);
13486 }
13487 
13488 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13489 /// a literal operator described by the provided lookup results.
13490 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13491                                           DeclarationNameInfo &SuffixInfo,
13492                                           ArrayRef<Expr*> Args,
13493                                           SourceLocation LitEndLoc,
13494                                        TemplateArgumentListInfo *TemplateArgs) {
13495   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13496 
13497   OverloadCandidateSet CandidateSet(UDSuffixLoc,
13498                                     OverloadCandidateSet::CSK_Normal);
13499   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13500                         /*SuppressUserConversions=*/true);
13501 
13502   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13503 
13504   // Perform overload resolution. This will usually be trivial, but might need
13505   // to perform substitutions for a literal operator template.
13506   OverloadCandidateSet::iterator Best;
13507   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13508   case OR_Success:
13509   case OR_Deleted:
13510     break;
13511 
13512   case OR_No_Viable_Function:
13513     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13514       << R.getLookupName();
13515     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13516     return ExprError();
13517 
13518   case OR_Ambiguous:
13519     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13520     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13521     return ExprError();
13522   }
13523 
13524   FunctionDecl *FD = Best->Function;
13525   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13526                                         nullptr, HadMultipleCandidates,
13527                                         SuffixInfo.getLoc(),
13528                                         SuffixInfo.getInfo());
13529   if (Fn.isInvalid())
13530     return true;
13531 
13532   // Check the argument types. This should almost always be a no-op, except
13533   // that array-to-pointer decay is applied to string literals.
13534   Expr *ConvArgs[2];
13535   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13536     ExprResult InputInit = PerformCopyInitialization(
13537       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13538       SourceLocation(), Args[ArgIdx]);
13539     if (InputInit.isInvalid())
13540       return true;
13541     ConvArgs[ArgIdx] = InputInit.get();
13542   }
13543 
13544   QualType ResultTy = FD->getReturnType();
13545   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13546   ResultTy = ResultTy.getNonLValueExprType(Context);
13547 
13548   UserDefinedLiteral *UDL =
13549     new (Context) UserDefinedLiteral(Context, Fn.get(),
13550                                      llvm::makeArrayRef(ConvArgs, Args.size()),
13551                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
13552 
13553   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13554     return ExprError();
13555 
13556   if (CheckFunctionCall(FD, UDL, nullptr))
13557     return ExprError();
13558 
13559   return MaybeBindToTemporary(UDL);
13560 }
13561 
13562 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13563 /// given LookupResult is non-empty, it is assumed to describe a member which
13564 /// will be invoked. Otherwise, the function will be found via argument
13565 /// dependent lookup.
13566 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13567 /// otherwise CallExpr is set to ExprError() and some non-success value
13568 /// is returned.
13569 Sema::ForRangeStatus
13570 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13571                                 SourceLocation RangeLoc,
13572                                 const DeclarationNameInfo &NameInfo,
13573                                 LookupResult &MemberLookup,
13574                                 OverloadCandidateSet *CandidateSet,
13575                                 Expr *Range, ExprResult *CallExpr) {
13576   Scope *S = nullptr;
13577 
13578   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
13579   if (!MemberLookup.empty()) {
13580     ExprResult MemberRef =
13581         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13582                                  /*IsPtr=*/false, CXXScopeSpec(),
13583                                  /*TemplateKWLoc=*/SourceLocation(),
13584                                  /*FirstQualifierInScope=*/nullptr,
13585                                  MemberLookup,
13586                                  /*TemplateArgs=*/nullptr, S);
13587     if (MemberRef.isInvalid()) {
13588       *CallExpr = ExprError();
13589       return FRS_DiagnosticIssued;
13590     }
13591     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13592     if (CallExpr->isInvalid()) {
13593       *CallExpr = ExprError();
13594       return FRS_DiagnosticIssued;
13595     }
13596   } else {
13597     UnresolvedSet<0> FoundNames;
13598     UnresolvedLookupExpr *Fn =
13599       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13600                                    NestedNameSpecifierLoc(), NameInfo,
13601                                    /*NeedsADL=*/true, /*Overloaded=*/false,
13602                                    FoundNames.begin(), FoundNames.end());
13603 
13604     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13605                                                     CandidateSet, CallExpr);
13606     if (CandidateSet->empty() || CandidateSetError) {
13607       *CallExpr = ExprError();
13608       return FRS_NoViableFunction;
13609     }
13610     OverloadCandidateSet::iterator Best;
13611     OverloadingResult OverloadResult =
13612         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
13613 
13614     if (OverloadResult == OR_No_Viable_Function) {
13615       *CallExpr = ExprError();
13616       return FRS_NoViableFunction;
13617     }
13618     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13619                                          Loc, nullptr, CandidateSet, &Best,
13620                                          OverloadResult,
13621                                          /*AllowTypoCorrection=*/false);
13622     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13623       *CallExpr = ExprError();
13624       return FRS_DiagnosticIssued;
13625     }
13626   }
13627   return FRS_Success;
13628 }
13629 
13630 
13631 /// FixOverloadedFunctionReference - E is an expression that refers to
13632 /// a C++ overloaded function (possibly with some parentheses and
13633 /// perhaps a '&' around it). We have resolved the overloaded function
13634 /// to the function declaration Fn, so patch up the expression E to
13635 /// refer (possibly indirectly) to Fn. Returns the new expr.
13636 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13637                                            FunctionDecl *Fn) {
13638   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13639     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13640                                                    Found, Fn);
13641     if (SubExpr == PE->getSubExpr())
13642       return PE;
13643 
13644     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13645   }
13646 
13647   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13648     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13649                                                    Found, Fn);
13650     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13651                                SubExpr->getType()) &&
13652            "Implicit cast type cannot be determined from overload");
13653     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13654     if (SubExpr == ICE->getSubExpr())
13655       return ICE;
13656 
13657     return ImplicitCastExpr::Create(Context, ICE->getType(),
13658                                     ICE->getCastKind(),
13659                                     SubExpr, nullptr,
13660                                     ICE->getValueKind());
13661   }
13662 
13663   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13664     if (!GSE->isResultDependent()) {
13665       Expr *SubExpr =
13666           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13667       if (SubExpr == GSE->getResultExpr())
13668         return GSE;
13669 
13670       // Replace the resulting type information before rebuilding the generic
13671       // selection expression.
13672       ArrayRef<Expr *> A = GSE->getAssocExprs();
13673       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13674       unsigned ResultIdx = GSE->getResultIndex();
13675       AssocExprs[ResultIdx] = SubExpr;
13676 
13677       return new (Context) GenericSelectionExpr(
13678           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13679           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13680           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13681           ResultIdx);
13682     }
13683     // Rather than fall through to the unreachable, return the original generic
13684     // selection expression.
13685     return GSE;
13686   }
13687 
13688   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13689     assert(UnOp->getOpcode() == UO_AddrOf &&
13690            "Can only take the address of an overloaded function");
13691     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13692       if (Method->isStatic()) {
13693         // Do nothing: static member functions aren't any different
13694         // from non-member functions.
13695       } else {
13696         // Fix the subexpression, which really has to be an
13697         // UnresolvedLookupExpr holding an overloaded member function
13698         // or template.
13699         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13700                                                        Found, Fn);
13701         if (SubExpr == UnOp->getSubExpr())
13702           return UnOp;
13703 
13704         assert(isa<DeclRefExpr>(SubExpr)
13705                && "fixed to something other than a decl ref");
13706         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13707                && "fixed to a member ref with no nested name qualifier");
13708 
13709         // We have taken the address of a pointer to member
13710         // function. Perform the computation here so that we get the
13711         // appropriate pointer to member type.
13712         QualType ClassType
13713           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13714         QualType MemPtrType
13715           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13716         // Under the MS ABI, lock down the inheritance model now.
13717         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13718           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13719 
13720         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13721                                            VK_RValue, OK_Ordinary,
13722                                            UnOp->getOperatorLoc(), false);
13723       }
13724     }
13725     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13726                                                    Found, Fn);
13727     if (SubExpr == UnOp->getSubExpr())
13728       return UnOp;
13729 
13730     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13731                                      Context.getPointerType(SubExpr->getType()),
13732                                        VK_RValue, OK_Ordinary,
13733                                        UnOp->getOperatorLoc(), false);
13734   }
13735 
13736   // C++ [except.spec]p17:
13737   //   An exception-specification is considered to be needed when:
13738   //   - in an expression the function is the unique lookup result or the
13739   //     selected member of a set of overloaded functions
13740   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13741     ResolveExceptionSpec(E->getExprLoc(), FPT);
13742 
13743   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13744     // FIXME: avoid copy.
13745     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13746     if (ULE->hasExplicitTemplateArgs()) {
13747       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13748       TemplateArgs = &TemplateArgsBuffer;
13749     }
13750 
13751     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13752                                            ULE->getQualifierLoc(),
13753                                            ULE->getTemplateKeywordLoc(),
13754                                            Fn,
13755                                            /*enclosing*/ false, // FIXME?
13756                                            ULE->getNameLoc(),
13757                                            Fn->getType(),
13758                                            VK_LValue,
13759                                            Found.getDecl(),
13760                                            TemplateArgs);
13761     MarkDeclRefReferenced(DRE);
13762     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13763     return DRE;
13764   }
13765 
13766   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13767     // FIXME: avoid copy.
13768     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13769     if (MemExpr->hasExplicitTemplateArgs()) {
13770       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13771       TemplateArgs = &TemplateArgsBuffer;
13772     }
13773 
13774     Expr *Base;
13775 
13776     // If we're filling in a static method where we used to have an
13777     // implicit member access, rewrite to a simple decl ref.
13778     if (MemExpr->isImplicitAccess()) {
13779       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13780         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13781                                                MemExpr->getQualifierLoc(),
13782                                                MemExpr->getTemplateKeywordLoc(),
13783                                                Fn,
13784                                                /*enclosing*/ false,
13785                                                MemExpr->getMemberLoc(),
13786                                                Fn->getType(),
13787                                                VK_LValue,
13788                                                Found.getDecl(),
13789                                                TemplateArgs);
13790         MarkDeclRefReferenced(DRE);
13791         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13792         return DRE;
13793       } else {
13794         SourceLocation Loc = MemExpr->getMemberLoc();
13795         if (MemExpr->getQualifier())
13796           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13797         CheckCXXThisCapture(Loc);
13798         Base = new (Context) CXXThisExpr(Loc,
13799                                          MemExpr->getBaseType(),
13800                                          /*isImplicit=*/true);
13801       }
13802     } else
13803       Base = MemExpr->getBase();
13804 
13805     ExprValueKind valueKind;
13806     QualType type;
13807     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13808       valueKind = VK_LValue;
13809       type = Fn->getType();
13810     } else {
13811       valueKind = VK_RValue;
13812       type = Context.BoundMemberTy;
13813     }
13814 
13815     MemberExpr *ME = MemberExpr::Create(
13816         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13817         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13818         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13819         OK_Ordinary);
13820     ME->setHadMultipleCandidates(true);
13821     MarkMemberReferenced(ME);
13822     return ME;
13823   }
13824 
13825   llvm_unreachable("Invalid reference to overloaded function");
13826 }
13827 
13828 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13829                                                 DeclAccessPair Found,
13830                                                 FunctionDecl *Fn) {
13831   return FixOverloadedFunctionReference(E.get(), Found, Fn);
13832 }
13833