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()->isObjCObjectPointerType() ||
227        getFromType()->isBlockPointerType() ||
228        getFromType()->isNullPtrType() ||
229        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
230     return true;
231 
232   return false;
233 }
234 
235 /// isPointerConversionToVoidPointer - Determines whether this
236 /// conversion is a conversion of a pointer to a void pointer. This is
237 /// used as part of the ranking of standard conversion sequences (C++
238 /// 13.3.3.2p4).
239 bool
240 StandardConversionSequence::
241 isPointerConversionToVoidPointer(ASTContext& Context) const {
242   QualType FromType = getFromType();
243   QualType ToType = getToType(1);
244 
245   // Note that FromType has not necessarily been transformed by the
246   // array-to-pointer implicit conversion, so check for its presence
247   // and redo the conversion to get a pointer.
248   if (First == ICK_Array_To_Pointer)
249     FromType = Context.getArrayDecayedType(FromType);
250 
251   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
252     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
253       return ToPtrType->getPointeeType()->isVoidType();
254 
255   return false;
256 }
257 
258 /// Skip any implicit casts which could be either part of a narrowing conversion
259 /// or after one in an implicit conversion.
260 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
261   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
262     switch (ICE->getCastKind()) {
263     case CK_NoOp:
264     case CK_IntegralCast:
265     case CK_IntegralToBoolean:
266     case CK_IntegralToFloating:
267     case CK_BooleanToSignedIntegral:
268     case CK_FloatingToIntegral:
269     case CK_FloatingToBoolean:
270     case CK_FloatingCast:
271       Converted = ICE->getSubExpr();
272       continue;
273 
274     default:
275       return Converted;
276     }
277   }
278 
279   return Converted;
280 }
281 
282 /// Check if this standard conversion sequence represents a narrowing
283 /// conversion, according to C++11 [dcl.init.list]p7.
284 ///
285 /// \param Ctx  The AST context.
286 /// \param Converted  The result of applying this standard conversion sequence.
287 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
288 ///        value of the expression prior to the narrowing conversion.
289 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
290 ///        type of the expression prior to the narrowing conversion.
291 NarrowingKind
292 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
293                                              const Expr *Converted,
294                                              APValue &ConstantValue,
295                                              QualType &ConstantType) const {
296   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
297 
298   // C++11 [dcl.init.list]p7:
299   //   A narrowing conversion is an implicit conversion ...
300   QualType FromType = getToType(0);
301   QualType ToType = getToType(1);
302 
303   // A conversion to an enumeration type is narrowing if the conversion to
304   // the underlying type is narrowing. This only arises for expressions of
305   // the form 'Enum{init}'.
306   if (auto *ET = ToType->getAs<EnumType>())
307     ToType = ET->getDecl()->getIntegerType();
308 
309   switch (Second) {
310   // 'bool' is an integral type; dispatch to the right place to handle it.
311   case ICK_Boolean_Conversion:
312     if (FromType->isRealFloatingType())
313       goto FloatingIntegralConversion;
314     if (FromType->isIntegralOrUnscopedEnumerationType())
315       goto IntegralConversion;
316     // Boolean conversions can be from pointers and pointers to members
317     // [conv.bool], and those aren't considered narrowing conversions.
318     return NK_Not_Narrowing;
319 
320   // -- from a floating-point type to an integer type, or
321   //
322   // -- from an integer type or unscoped enumeration type to a floating-point
323   //    type, except where the source is a constant expression and the actual
324   //    value after conversion will fit into the target type and will produce
325   //    the original value when converted back to the original type, or
326   case ICK_Floating_Integral:
327   FloatingIntegralConversion:
328     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
329       return NK_Type_Narrowing;
330     } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
331       llvm::APSInt IntConstantValue;
332       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
333       assert(Initializer && "Unknown conversion expression");
334 
335       // If it's value-dependent, we can't tell whether it's narrowing.
336       if (Initializer->isValueDependent())
337         return NK_Dependent_Narrowing;
338 
339       if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
340         // Convert the integer to the floating type.
341         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
342         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
343                                 llvm::APFloat::rmNearestTiesToEven);
344         // And back.
345         llvm::APSInt ConvertedValue = IntConstantValue;
346         bool ignored;
347         Result.convertToInteger(ConvertedValue,
348                                 llvm::APFloat::rmTowardZero, &ignored);
349         // If the resulting value is different, this was a narrowing conversion.
350         if (IntConstantValue != ConvertedValue) {
351           ConstantValue = APValue(IntConstantValue);
352           ConstantType = Initializer->getType();
353           return NK_Constant_Narrowing;
354         }
355       } else {
356         // Variables are always narrowings.
357         return NK_Variable_Narrowing;
358       }
359     }
360     return NK_Not_Narrowing;
361 
362   // -- from long double to double or float, or from double to float, except
363   //    where the source is a constant expression and the actual value after
364   //    conversion is within the range of values that can be represented (even
365   //    if it cannot be represented exactly), or
366   case ICK_Floating_Conversion:
367     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
368         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
369       // FromType is larger than ToType.
370       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
371 
372       // If it's value-dependent, we can't tell whether it's narrowing.
373       if (Initializer->isValueDependent())
374         return NK_Dependent_Narrowing;
375 
376       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
377         // Constant!
378         assert(ConstantValue.isFloat());
379         llvm::APFloat FloatVal = ConstantValue.getFloat();
380         // Convert the source value into the target type.
381         bool ignored;
382         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
383           Ctx.getFloatTypeSemantics(ToType),
384           llvm::APFloat::rmNearestTiesToEven, &ignored);
385         // If there was no overflow, the source value is within the range of
386         // values that can be represented.
387         if (ConvertStatus & llvm::APFloat::opOverflow) {
388           ConstantType = Initializer->getType();
389           return NK_Constant_Narrowing;
390         }
391       } else {
392         return NK_Variable_Narrowing;
393       }
394     }
395     return NK_Not_Narrowing;
396 
397   // -- from an integer type or unscoped enumeration type to an integer type
398   //    that cannot represent all the values of the original type, except where
399   //    the source is a constant expression and the actual value after
400   //    conversion will fit into the target type and will produce the original
401   //    value when converted back to the original type.
402   case ICK_Integral_Conversion:
403   IntegralConversion: {
404     assert(FromType->isIntegralOrUnscopedEnumerationType());
405     assert(ToType->isIntegralOrUnscopedEnumerationType());
406     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
407     const unsigned FromWidth = Ctx.getIntWidth(FromType);
408     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
409     const unsigned ToWidth = Ctx.getIntWidth(ToType);
410 
411     if (FromWidth > ToWidth ||
412         (FromWidth == ToWidth && FromSigned != ToSigned) ||
413         (FromSigned && !ToSigned)) {
414       // Not all values of FromType can be represented in ToType.
415       llvm::APSInt InitializerValue;
416       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
417 
418       // If it's value-dependent, we can't tell whether it's narrowing.
419       if (Initializer->isValueDependent())
420         return NK_Dependent_Narrowing;
421 
422       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
423         // Such conversions on variables are always narrowing.
424         return NK_Variable_Narrowing;
425       }
426       bool Narrowing = false;
427       if (FromWidth < ToWidth) {
428         // Negative -> unsigned is narrowing. Otherwise, more bits is never
429         // narrowing.
430         if (InitializerValue.isSigned() && InitializerValue.isNegative())
431           Narrowing = true;
432       } else {
433         // Add a bit to the InitializerValue so we don't have to worry about
434         // signed vs. unsigned comparisons.
435         InitializerValue = InitializerValue.extend(
436           InitializerValue.getBitWidth() + 1);
437         // Convert the initializer to and from the target width and signed-ness.
438         llvm::APSInt ConvertedValue = InitializerValue;
439         ConvertedValue = ConvertedValue.trunc(ToWidth);
440         ConvertedValue.setIsSigned(ToSigned);
441         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
442         ConvertedValue.setIsSigned(InitializerValue.isSigned());
443         // If the result is different, this was a narrowing conversion.
444         if (ConvertedValue != InitializerValue)
445           Narrowing = true;
446       }
447       if (Narrowing) {
448         ConstantType = Initializer->getType();
449         ConstantValue = APValue(InitializerValue);
450         return NK_Constant_Narrowing;
451       }
452     }
453     return NK_Not_Narrowing;
454   }
455 
456   default:
457     // Other kinds of conversions are not narrowings.
458     return NK_Not_Narrowing;
459   }
460 }
461 
462 /// dump - Print this standard conversion sequence to standard
463 /// error. Useful for debugging overloading issues.
464 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
465   raw_ostream &OS = llvm::errs();
466   bool PrintedSomething = false;
467   if (First != ICK_Identity) {
468     OS << GetImplicitConversionName(First);
469     PrintedSomething = true;
470   }
471 
472   if (Second != ICK_Identity) {
473     if (PrintedSomething) {
474       OS << " -> ";
475     }
476     OS << GetImplicitConversionName(Second);
477 
478     if (CopyConstructor) {
479       OS << " (by copy constructor)";
480     } else if (DirectBinding) {
481       OS << " (direct reference binding)";
482     } else if (ReferenceBinding) {
483       OS << " (reference binding)";
484     }
485     PrintedSomething = true;
486   }
487 
488   if (Third != ICK_Identity) {
489     if (PrintedSomething) {
490       OS << " -> ";
491     }
492     OS << GetImplicitConversionName(Third);
493     PrintedSomething = true;
494   }
495 
496   if (!PrintedSomething) {
497     OS << "No conversions required";
498   }
499 }
500 
501 /// dump - Print this user-defined conversion sequence to standard
502 /// error. Useful for debugging overloading issues.
503 void UserDefinedConversionSequence::dump() const {
504   raw_ostream &OS = llvm::errs();
505   if (Before.First || Before.Second || Before.Third) {
506     Before.dump();
507     OS << " -> ";
508   }
509   if (ConversionFunction)
510     OS << '\'' << *ConversionFunction << '\'';
511   else
512     OS << "aggregate initialization";
513   if (After.First || After.Second || After.Third) {
514     OS << " -> ";
515     After.dump();
516   }
517 }
518 
519 /// dump - Print this implicit conversion sequence to standard
520 /// error. Useful for debugging overloading issues.
521 void ImplicitConversionSequence::dump() const {
522   raw_ostream &OS = llvm::errs();
523   if (isStdInitializerListElement())
524     OS << "Worst std::initializer_list element conversion: ";
525   switch (ConversionKind) {
526   case StandardConversion:
527     OS << "Standard conversion: ";
528     Standard.dump();
529     break;
530   case UserDefinedConversion:
531     OS << "User-defined conversion: ";
532     UserDefined.dump();
533     break;
534   case EllipsisConversion:
535     OS << "Ellipsis conversion";
536     break;
537   case AmbiguousConversion:
538     OS << "Ambiguous conversion";
539     break;
540   case BadConversion:
541     OS << "Bad conversion";
542     break;
543   }
544 
545   OS << "\n";
546 }
547 
548 void AmbiguousConversionSequence::construct() {
549   new (&conversions()) ConversionSet();
550 }
551 
552 void AmbiguousConversionSequence::destruct() {
553   conversions().~ConversionSet();
554 }
555 
556 void
557 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
558   FromTypePtr = O.FromTypePtr;
559   ToTypePtr = O.ToTypePtr;
560   new (&conversions()) ConversionSet(O.conversions());
561 }
562 
563 namespace {
564   // Structure used by DeductionFailureInfo to store
565   // template argument information.
566   struct DFIArguments {
567     TemplateArgument FirstArg;
568     TemplateArgument SecondArg;
569   };
570   // Structure used by DeductionFailureInfo to store
571   // template parameter and template argument information.
572   struct DFIParamWithArguments : DFIArguments {
573     TemplateParameter Param;
574   };
575   // Structure used by DeductionFailureInfo to store template argument
576   // information and the index of the problematic call argument.
577   struct DFIDeducedMismatchArgs : DFIArguments {
578     TemplateArgumentList *TemplateArgs;
579     unsigned CallArgIndex;
580   };
581 }
582 
583 /// \brief Convert from Sema's representation of template deduction information
584 /// to the form used in overload-candidate information.
585 DeductionFailureInfo
586 clang::MakeDeductionFailureInfo(ASTContext &Context,
587                                 Sema::TemplateDeductionResult TDK,
588                                 TemplateDeductionInfo &Info) {
589   DeductionFailureInfo Result;
590   Result.Result = static_cast<unsigned>(TDK);
591   Result.HasDiagnostic = false;
592   switch (TDK) {
593   case Sema::TDK_Invalid:
594   case Sema::TDK_InstantiationDepth:
595   case Sema::TDK_TooManyArguments:
596   case Sema::TDK_TooFewArguments:
597   case Sema::TDK_MiscellaneousDeductionFailure:
598   case Sema::TDK_CUDATargetMismatch:
599     Result.Data = nullptr;
600     break;
601 
602   case Sema::TDK_Incomplete:
603   case Sema::TDK_InvalidExplicitArguments:
604     Result.Data = Info.Param.getOpaqueValue();
605     break;
606 
607   case Sema::TDK_DeducedMismatch:
608   case Sema::TDK_DeducedMismatchNested: {
609     // FIXME: Should allocate from normal heap so that we can free this later.
610     auto *Saved = new (Context) DFIDeducedMismatchArgs;
611     Saved->FirstArg = Info.FirstArg;
612     Saved->SecondArg = Info.SecondArg;
613     Saved->TemplateArgs = Info.take();
614     Saved->CallArgIndex = Info.CallArgIndex;
615     Result.Data = Saved;
616     break;
617   }
618 
619   case Sema::TDK_NonDeducedMismatch: {
620     // FIXME: Should allocate from normal heap so that we can free this later.
621     DFIArguments *Saved = new (Context) DFIArguments;
622     Saved->FirstArg = Info.FirstArg;
623     Saved->SecondArg = Info.SecondArg;
624     Result.Data = Saved;
625     break;
626   }
627 
628   case Sema::TDK_Inconsistent:
629   case Sema::TDK_Underqualified: {
630     // FIXME: Should allocate from normal heap so that we can free this later.
631     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
632     Saved->Param = Info.Param;
633     Saved->FirstArg = Info.FirstArg;
634     Saved->SecondArg = Info.SecondArg;
635     Result.Data = Saved;
636     break;
637   }
638 
639   case Sema::TDK_SubstitutionFailure:
640     Result.Data = Info.take();
641     if (Info.hasSFINAEDiagnostic()) {
642       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
643           SourceLocation(), PartialDiagnostic::NullDiagnostic());
644       Info.takeSFINAEDiagnostic(*Diag);
645       Result.HasDiagnostic = true;
646     }
647     break;
648 
649   case Sema::TDK_Success:
650   case Sema::TDK_NonDependentConversionFailure:
651     llvm_unreachable("not a deduction failure");
652   }
653 
654   return Result;
655 }
656 
657 void DeductionFailureInfo::Destroy() {
658   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
659   case Sema::TDK_Success:
660   case Sema::TDK_Invalid:
661   case Sema::TDK_InstantiationDepth:
662   case Sema::TDK_Incomplete:
663   case Sema::TDK_TooManyArguments:
664   case Sema::TDK_TooFewArguments:
665   case Sema::TDK_InvalidExplicitArguments:
666   case Sema::TDK_CUDATargetMismatch:
667   case Sema::TDK_NonDependentConversionFailure:
668     break;
669 
670   case Sema::TDK_Inconsistent:
671   case Sema::TDK_Underqualified:
672   case Sema::TDK_DeducedMismatch:
673   case Sema::TDK_DeducedMismatchNested:
674   case Sema::TDK_NonDeducedMismatch:
675     // FIXME: Destroy the data?
676     Data = nullptr;
677     break;
678 
679   case Sema::TDK_SubstitutionFailure:
680     // FIXME: Destroy the template argument list?
681     Data = nullptr;
682     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
683       Diag->~PartialDiagnosticAt();
684       HasDiagnostic = false;
685     }
686     break;
687 
688   // Unhandled
689   case Sema::TDK_MiscellaneousDeductionFailure:
690     break;
691   }
692 }
693 
694 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
695   if (HasDiagnostic)
696     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
697   return nullptr;
698 }
699 
700 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
701   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
702   case Sema::TDK_Success:
703   case Sema::TDK_Invalid:
704   case Sema::TDK_InstantiationDepth:
705   case Sema::TDK_TooManyArguments:
706   case Sema::TDK_TooFewArguments:
707   case Sema::TDK_SubstitutionFailure:
708   case Sema::TDK_DeducedMismatch:
709   case Sema::TDK_DeducedMismatchNested:
710   case Sema::TDK_NonDeducedMismatch:
711   case Sema::TDK_CUDATargetMismatch:
712   case Sema::TDK_NonDependentConversionFailure:
713     return TemplateParameter();
714 
715   case Sema::TDK_Incomplete:
716   case Sema::TDK_InvalidExplicitArguments:
717     return TemplateParameter::getFromOpaqueValue(Data);
718 
719   case Sema::TDK_Inconsistent:
720   case Sema::TDK_Underqualified:
721     return static_cast<DFIParamWithArguments*>(Data)->Param;
722 
723   // Unhandled
724   case Sema::TDK_MiscellaneousDeductionFailure:
725     break;
726   }
727 
728   return TemplateParameter();
729 }
730 
731 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
732   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
733   case Sema::TDK_Success:
734   case Sema::TDK_Invalid:
735   case Sema::TDK_InstantiationDepth:
736   case Sema::TDK_TooManyArguments:
737   case Sema::TDK_TooFewArguments:
738   case Sema::TDK_Incomplete:
739   case Sema::TDK_InvalidExplicitArguments:
740   case Sema::TDK_Inconsistent:
741   case Sema::TDK_Underqualified:
742   case Sema::TDK_NonDeducedMismatch:
743   case Sema::TDK_CUDATargetMismatch:
744   case Sema::TDK_NonDependentConversionFailure:
745     return nullptr;
746 
747   case Sema::TDK_DeducedMismatch:
748   case Sema::TDK_DeducedMismatchNested:
749     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
750 
751   case Sema::TDK_SubstitutionFailure:
752     return static_cast<TemplateArgumentList*>(Data);
753 
754   // Unhandled
755   case Sema::TDK_MiscellaneousDeductionFailure:
756     break;
757   }
758 
759   return nullptr;
760 }
761 
762 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
763   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
764   case Sema::TDK_Success:
765   case Sema::TDK_Invalid:
766   case Sema::TDK_InstantiationDepth:
767   case Sema::TDK_Incomplete:
768   case Sema::TDK_TooManyArguments:
769   case Sema::TDK_TooFewArguments:
770   case Sema::TDK_InvalidExplicitArguments:
771   case Sema::TDK_SubstitutionFailure:
772   case Sema::TDK_CUDATargetMismatch:
773   case Sema::TDK_NonDependentConversionFailure:
774     return nullptr;
775 
776   case Sema::TDK_Inconsistent:
777   case Sema::TDK_Underqualified:
778   case Sema::TDK_DeducedMismatch:
779   case Sema::TDK_DeducedMismatchNested:
780   case Sema::TDK_NonDeducedMismatch:
781     return &static_cast<DFIArguments*>(Data)->FirstArg;
782 
783   // Unhandled
784   case Sema::TDK_MiscellaneousDeductionFailure:
785     break;
786   }
787 
788   return nullptr;
789 }
790 
791 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
792   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
793   case Sema::TDK_Success:
794   case Sema::TDK_Invalid:
795   case Sema::TDK_InstantiationDepth:
796   case Sema::TDK_Incomplete:
797   case Sema::TDK_TooManyArguments:
798   case Sema::TDK_TooFewArguments:
799   case Sema::TDK_InvalidExplicitArguments:
800   case Sema::TDK_SubstitutionFailure:
801   case Sema::TDK_CUDATargetMismatch:
802   case Sema::TDK_NonDependentConversionFailure:
803     return nullptr;
804 
805   case Sema::TDK_Inconsistent:
806   case Sema::TDK_Underqualified:
807   case Sema::TDK_DeducedMismatch:
808   case Sema::TDK_DeducedMismatchNested:
809   case Sema::TDK_NonDeducedMismatch:
810     return &static_cast<DFIArguments*>(Data)->SecondArg;
811 
812   // Unhandled
813   case Sema::TDK_MiscellaneousDeductionFailure:
814     break;
815   }
816 
817   return nullptr;
818 }
819 
820 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
821   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
822   case Sema::TDK_DeducedMismatch:
823   case Sema::TDK_DeducedMismatchNested:
824     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
825 
826   default:
827     return llvm::None;
828   }
829 }
830 
831 void OverloadCandidateSet::destroyCandidates() {
832   for (iterator i = begin(), e = end(); i != e; ++i) {
833     for (auto &C : i->Conversions)
834       C.~ImplicitConversionSequence();
835     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
836       i->DeductionFailure.Destroy();
837   }
838 }
839 
840 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
841   destroyCandidates();
842   SlabAllocator.Reset();
843   NumInlineBytesUsed = 0;
844   Candidates.clear();
845   Functions.clear();
846   Kind = CSK;
847 }
848 
849 namespace {
850   class UnbridgedCastsSet {
851     struct Entry {
852       Expr **Addr;
853       Expr *Saved;
854     };
855     SmallVector<Entry, 2> Entries;
856 
857   public:
858     void save(Sema &S, Expr *&E) {
859       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
860       Entry entry = { &E, E };
861       Entries.push_back(entry);
862       E = S.stripARCUnbridgedCast(E);
863     }
864 
865     void restore() {
866       for (SmallVectorImpl<Entry>::iterator
867              i = Entries.begin(), e = Entries.end(); i != e; ++i)
868         *i->Addr = i->Saved;
869     }
870   };
871 }
872 
873 /// checkPlaceholderForOverload - Do any interesting placeholder-like
874 /// preprocessing on the given expression.
875 ///
876 /// \param unbridgedCasts a collection to which to add unbridged casts;
877 ///   without this, they will be immediately diagnosed as errors
878 ///
879 /// Return true on unrecoverable error.
880 static bool
881 checkPlaceholderForOverload(Sema &S, Expr *&E,
882                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
883   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
884     // We can't handle overloaded expressions here because overload
885     // resolution might reasonably tweak them.
886     if (placeholder->getKind() == BuiltinType::Overload) return false;
887 
888     // If the context potentially accepts unbridged ARC casts, strip
889     // the unbridged cast and add it to the collection for later restoration.
890     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
891         unbridgedCasts) {
892       unbridgedCasts->save(S, E);
893       return false;
894     }
895 
896     // Go ahead and check everything else.
897     ExprResult result = S.CheckPlaceholderExpr(E);
898     if (result.isInvalid())
899       return true;
900 
901     E = result.get();
902     return false;
903   }
904 
905   // Nothing to do.
906   return false;
907 }
908 
909 /// checkArgPlaceholdersForOverload - Check a set of call operands for
910 /// placeholders.
911 static bool checkArgPlaceholdersForOverload(Sema &S,
912                                             MultiExprArg Args,
913                                             UnbridgedCastsSet &unbridged) {
914   for (unsigned i = 0, e = Args.size(); i != e; ++i)
915     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
916       return true;
917 
918   return false;
919 }
920 
921 /// Determine whether the given New declaration is an overload of the
922 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
923 /// New and Old cannot be overloaded, e.g., if New has the same signature as
924 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
925 /// functions (or function templates) at all. When it does return Ovl_Match or
926 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
927 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
928 /// declaration.
929 ///
930 /// Example: Given the following input:
931 ///
932 ///   void f(int, float); // #1
933 ///   void f(int, int); // #2
934 ///   int f(int, int); // #3
935 ///
936 /// When we process #1, there is no previous declaration of "f", so IsOverload
937 /// will not be used.
938 ///
939 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
940 /// the parameter types, we see that #1 and #2 are overloaded (since they have
941 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
942 /// unchanged.
943 ///
944 /// When we process #3, Old is an overload set containing #1 and #2. We compare
945 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
946 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
947 /// functions are not part of the signature), IsOverload returns Ovl_Match and
948 /// MatchedDecl will be set to point to the FunctionDecl for #2.
949 ///
950 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
951 /// by a using declaration. The rules for whether to hide shadow declarations
952 /// ignore some properties which otherwise figure into a function template's
953 /// signature.
954 Sema::OverloadKind
955 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
956                     NamedDecl *&Match, bool NewIsUsingDecl) {
957   for (LookupResult::iterator I = Old.begin(), E = Old.end();
958          I != E; ++I) {
959     NamedDecl *OldD = *I;
960 
961     bool OldIsUsingDecl = false;
962     if (isa<UsingShadowDecl>(OldD)) {
963       OldIsUsingDecl = true;
964 
965       // We can always introduce two using declarations into the same
966       // context, even if they have identical signatures.
967       if (NewIsUsingDecl) continue;
968 
969       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
970     }
971 
972     // A using-declaration does not conflict with another declaration
973     // if one of them is hidden.
974     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
975       continue;
976 
977     // If either declaration was introduced by a using declaration,
978     // we'll need to use slightly different rules for matching.
979     // Essentially, these rules are the normal rules, except that
980     // function templates hide function templates with different
981     // return types or template parameter lists.
982     bool UseMemberUsingDeclRules =
983       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
984       !New->getFriendObjectKind();
985 
986     if (FunctionDecl *OldF = OldD->getAsFunction()) {
987       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
988         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
989           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
990           continue;
991         }
992 
993         if (!isa<FunctionTemplateDecl>(OldD) &&
994             !shouldLinkPossiblyHiddenDecl(*I, New))
995           continue;
996 
997         Match = *I;
998         return Ovl_Match;
999       }
1000     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1001       // We can overload with these, which can show up when doing
1002       // redeclaration checks for UsingDecls.
1003       assert(Old.getLookupKind() == LookupUsingDeclName);
1004     } else if (isa<TagDecl>(OldD)) {
1005       // We can always overload with tags by hiding them.
1006     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1007       // Optimistically assume that an unresolved using decl will
1008       // overload; if it doesn't, we'll have to diagnose during
1009       // template instantiation.
1010       //
1011       // Exception: if the scope is dependent and this is not a class
1012       // member, the using declaration can only introduce an enumerator.
1013       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1014         Match = *I;
1015         return Ovl_NonFunction;
1016       }
1017     } else {
1018       // (C++ 13p1):
1019       //   Only function declarations can be overloaded; object and type
1020       //   declarations cannot be overloaded.
1021       Match = *I;
1022       return Ovl_NonFunction;
1023     }
1024   }
1025 
1026   return Ovl_Overload;
1027 }
1028 
1029 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1030                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1031   // C++ [basic.start.main]p2: This function shall not be overloaded.
1032   if (New->isMain())
1033     return false;
1034 
1035   // MSVCRT user defined entry points cannot be overloaded.
1036   if (New->isMSVCRTEntryPoint())
1037     return false;
1038 
1039   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1040   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1041 
1042   // C++ [temp.fct]p2:
1043   //   A function template can be overloaded with other function templates
1044   //   and with normal (non-template) functions.
1045   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1046     return true;
1047 
1048   // Is the function New an overload of the function Old?
1049   QualType OldQType = Context.getCanonicalType(Old->getType());
1050   QualType NewQType = Context.getCanonicalType(New->getType());
1051 
1052   // Compare the signatures (C++ 1.3.10) of the two functions to
1053   // determine whether they are overloads. If we find any mismatch
1054   // in the signature, they are overloads.
1055 
1056   // If either of these functions is a K&R-style function (no
1057   // prototype), then we consider them to have matching signatures.
1058   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1059       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1060     return false;
1061 
1062   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1063   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1064 
1065   // The signature of a function includes the types of its
1066   // parameters (C++ 1.3.10), which includes the presence or absence
1067   // of the ellipsis; see C++ DR 357).
1068   if (OldQType != NewQType &&
1069       (OldType->getNumParams() != NewType->getNumParams() ||
1070        OldType->isVariadic() != NewType->isVariadic() ||
1071        !FunctionParamTypesAreEqual(OldType, NewType)))
1072     return true;
1073 
1074   // C++ [temp.over.link]p4:
1075   //   The signature of a function template consists of its function
1076   //   signature, its return type and its template parameter list. The names
1077   //   of the template parameters are significant only for establishing the
1078   //   relationship between the template parameters and the rest of the
1079   //   signature.
1080   //
1081   // We check the return type and template parameter lists for function
1082   // templates first; the remaining checks follow.
1083   //
1084   // However, we don't consider either of these when deciding whether
1085   // a member introduced by a shadow declaration is hidden.
1086   if (!UseMemberUsingDeclRules && NewTemplate &&
1087       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1088                                        OldTemplate->getTemplateParameters(),
1089                                        false, TPL_TemplateMatch) ||
1090        OldType->getReturnType() != NewType->getReturnType()))
1091     return true;
1092 
1093   // If the function is a class member, its signature includes the
1094   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1095   //
1096   // As part of this, also check whether one of the member functions
1097   // is static, in which case they are not overloads (C++
1098   // 13.1p2). While not part of the definition of the signature,
1099   // this check is important to determine whether these functions
1100   // can be overloaded.
1101   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1102   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1103   if (OldMethod && NewMethod &&
1104       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1105     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1106       if (!UseMemberUsingDeclRules &&
1107           (OldMethod->getRefQualifier() == RQ_None ||
1108            NewMethod->getRefQualifier() == RQ_None)) {
1109         // C++0x [over.load]p2:
1110         //   - Member function declarations with the same name and the same
1111         //     parameter-type-list as well as member function template
1112         //     declarations with the same name, the same parameter-type-list, and
1113         //     the same template parameter lists cannot be overloaded if any of
1114         //     them, but not all, have a ref-qualifier (8.3.5).
1115         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1116           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1117         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1118       }
1119       return true;
1120     }
1121 
1122     // We may not have applied the implicit const for a constexpr member
1123     // function yet (because we haven't yet resolved whether this is a static
1124     // or non-static member function). Add it now, on the assumption that this
1125     // is a redeclaration of OldMethod.
1126     unsigned OldQuals = OldMethod->getTypeQualifiers();
1127     unsigned NewQuals = NewMethod->getTypeQualifiers();
1128     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1129         !isa<CXXConstructorDecl>(NewMethod))
1130       NewQuals |= Qualifiers::Const;
1131 
1132     // We do not allow overloading based off of '__restrict'.
1133     OldQuals &= ~Qualifiers::Restrict;
1134     NewQuals &= ~Qualifiers::Restrict;
1135     if (OldQuals != NewQuals)
1136       return true;
1137   }
1138 
1139   // Though pass_object_size is placed on parameters and takes an argument, we
1140   // consider it to be a function-level modifier for the sake of function
1141   // identity. Either the function has one or more parameters with
1142   // pass_object_size or it doesn't.
1143   if (functionHasPassObjectSizeParams(New) !=
1144       functionHasPassObjectSizeParams(Old))
1145     return true;
1146 
1147   // enable_if attributes are an order-sensitive part of the signature.
1148   for (specific_attr_iterator<EnableIfAttr>
1149          NewI = New->specific_attr_begin<EnableIfAttr>(),
1150          NewE = New->specific_attr_end<EnableIfAttr>(),
1151          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1152          OldE = Old->specific_attr_end<EnableIfAttr>();
1153        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1154     if (NewI == NewE || OldI == OldE)
1155       return true;
1156     llvm::FoldingSetNodeID NewID, OldID;
1157     NewI->getCond()->Profile(NewID, Context, true);
1158     OldI->getCond()->Profile(OldID, Context, true);
1159     if (NewID != OldID)
1160       return true;
1161   }
1162 
1163   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1164     // Don't allow overloading of destructors.  (In theory we could, but it
1165     // would be a giant change to clang.)
1166     if (isa<CXXDestructorDecl>(New))
1167       return false;
1168 
1169     CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1170                        OldTarget = IdentifyCUDATarget(Old);
1171     if (NewTarget == CFT_InvalidTarget)
1172       return false;
1173 
1174     assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1175 
1176     // Allow overloading of functions with same signature and different CUDA
1177     // target attributes.
1178     return NewTarget != OldTarget;
1179   }
1180 
1181   // The signatures match; this is not an overload.
1182   return false;
1183 }
1184 
1185 /// \brief Checks availability of the function depending on the current
1186 /// function context. Inside an unavailable function, unavailability is ignored.
1187 ///
1188 /// \returns true if \arg FD is unavailable and current context is inside
1189 /// an available function, false otherwise.
1190 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1191   if (!FD->isUnavailable())
1192     return false;
1193 
1194   // Walk up the context of the caller.
1195   Decl *C = cast<Decl>(CurContext);
1196   do {
1197     if (C->isUnavailable())
1198       return false;
1199   } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1200   return true;
1201 }
1202 
1203 /// \brief Tries a user-defined conversion from From to ToType.
1204 ///
1205 /// Produces an implicit conversion sequence for when a standard conversion
1206 /// is not an option. See TryImplicitConversion for more information.
1207 static ImplicitConversionSequence
1208 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1209                          bool SuppressUserConversions,
1210                          bool AllowExplicit,
1211                          bool InOverloadResolution,
1212                          bool CStyle,
1213                          bool AllowObjCWritebackConversion,
1214                          bool AllowObjCConversionOnExplicit) {
1215   ImplicitConversionSequence ICS;
1216 
1217   if (SuppressUserConversions) {
1218     // We're not in the case above, so there is no conversion that
1219     // we can perform.
1220     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1221     return ICS;
1222   }
1223 
1224   // Attempt user-defined conversion.
1225   OverloadCandidateSet Conversions(From->getExprLoc(),
1226                                    OverloadCandidateSet::CSK_Normal);
1227   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1228                                   Conversions, AllowExplicit,
1229                                   AllowObjCConversionOnExplicit)) {
1230   case OR_Success:
1231   case OR_Deleted:
1232     ICS.setUserDefined();
1233     // C++ [over.ics.user]p4:
1234     //   A conversion of an expression of class type to the same class
1235     //   type is given Exact Match rank, and a conversion of an
1236     //   expression of class type to a base class of that type is
1237     //   given Conversion rank, in spite of the fact that a copy
1238     //   constructor (i.e., a user-defined conversion function) is
1239     //   called for those cases.
1240     if (CXXConstructorDecl *Constructor
1241           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1242       QualType FromCanon
1243         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1244       QualType ToCanon
1245         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1246       if (Constructor->isCopyConstructor() &&
1247           (FromCanon == ToCanon ||
1248            S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
1249         // Turn this into a "standard" conversion sequence, so that it
1250         // gets ranked with standard conversion sequences.
1251         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1252         ICS.setStandard();
1253         ICS.Standard.setAsIdentityConversion();
1254         ICS.Standard.setFromType(From->getType());
1255         ICS.Standard.setAllToTypes(ToType);
1256         ICS.Standard.CopyConstructor = Constructor;
1257         ICS.Standard.FoundCopyConstructor = Found;
1258         if (ToCanon != FromCanon)
1259           ICS.Standard.Second = ICK_Derived_To_Base;
1260       }
1261     }
1262     break;
1263 
1264   case OR_Ambiguous:
1265     ICS.setAmbiguous();
1266     ICS.Ambiguous.setFromType(From->getType());
1267     ICS.Ambiguous.setToType(ToType);
1268     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1269          Cand != Conversions.end(); ++Cand)
1270       if (Cand->Viable)
1271         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1272     break;
1273 
1274     // Fall through.
1275   case OR_No_Viable_Function:
1276     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1277     break;
1278   }
1279 
1280   return ICS;
1281 }
1282 
1283 /// TryImplicitConversion - Attempt to perform an implicit conversion
1284 /// from the given expression (Expr) to the given type (ToType). This
1285 /// function returns an implicit conversion sequence that can be used
1286 /// to perform the initialization. Given
1287 ///
1288 ///   void f(float f);
1289 ///   void g(int i) { f(i); }
1290 ///
1291 /// this routine would produce an implicit conversion sequence to
1292 /// describe the initialization of f from i, which will be a standard
1293 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1294 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1295 //
1296 /// Note that this routine only determines how the conversion can be
1297 /// performed; it does not actually perform the conversion. As such,
1298 /// it will not produce any diagnostics if no conversion is available,
1299 /// but will instead return an implicit conversion sequence of kind
1300 /// "BadConversion".
1301 ///
1302 /// If @p SuppressUserConversions, then user-defined conversions are
1303 /// not permitted.
1304 /// If @p AllowExplicit, then explicit user-defined conversions are
1305 /// permitted.
1306 ///
1307 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1308 /// writeback conversion, which allows __autoreleasing id* parameters to
1309 /// be initialized with __strong id* or __weak id* arguments.
1310 static ImplicitConversionSequence
1311 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1312                       bool SuppressUserConversions,
1313                       bool AllowExplicit,
1314                       bool InOverloadResolution,
1315                       bool CStyle,
1316                       bool AllowObjCWritebackConversion,
1317                       bool AllowObjCConversionOnExplicit) {
1318   ImplicitConversionSequence ICS;
1319   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1320                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1321     ICS.setStandard();
1322     return ICS;
1323   }
1324 
1325   if (!S.getLangOpts().CPlusPlus) {
1326     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1327     return ICS;
1328   }
1329 
1330   // C++ [over.ics.user]p4:
1331   //   A conversion of an expression of class type to the same class
1332   //   type is given Exact Match rank, and a conversion of an
1333   //   expression of class type to a base class of that type is
1334   //   given Conversion rank, in spite of the fact that a copy/move
1335   //   constructor (i.e., a user-defined conversion function) is
1336   //   called for those cases.
1337   QualType FromType = From->getType();
1338   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1339       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1340        S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
1341     ICS.setStandard();
1342     ICS.Standard.setAsIdentityConversion();
1343     ICS.Standard.setFromType(FromType);
1344     ICS.Standard.setAllToTypes(ToType);
1345 
1346     // We don't actually check at this point whether there is a valid
1347     // copy/move constructor, since overloading just assumes that it
1348     // exists. When we actually perform initialization, we'll find the
1349     // appropriate constructor to copy the returned object, if needed.
1350     ICS.Standard.CopyConstructor = nullptr;
1351 
1352     // Determine whether this is considered a derived-to-base conversion.
1353     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1354       ICS.Standard.Second = ICK_Derived_To_Base;
1355 
1356     return ICS;
1357   }
1358 
1359   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1360                                   AllowExplicit, InOverloadResolution, CStyle,
1361                                   AllowObjCWritebackConversion,
1362                                   AllowObjCConversionOnExplicit);
1363 }
1364 
1365 ImplicitConversionSequence
1366 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1367                             bool SuppressUserConversions,
1368                             bool AllowExplicit,
1369                             bool InOverloadResolution,
1370                             bool CStyle,
1371                             bool AllowObjCWritebackConversion) {
1372   return ::TryImplicitConversion(*this, From, ToType,
1373                                  SuppressUserConversions, AllowExplicit,
1374                                  InOverloadResolution, CStyle,
1375                                  AllowObjCWritebackConversion,
1376                                  /*AllowObjCConversionOnExplicit=*/false);
1377 }
1378 
1379 /// PerformImplicitConversion - Perform an implicit conversion of the
1380 /// expression From to the type ToType. Returns the
1381 /// converted expression. Flavor is the kind of conversion we're
1382 /// performing, used in the error message. If @p AllowExplicit,
1383 /// explicit user-defined conversions are permitted.
1384 ExprResult
1385 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1386                                 AssignmentAction Action, bool AllowExplicit) {
1387   ImplicitConversionSequence ICS;
1388   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1389 }
1390 
1391 ExprResult
1392 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1393                                 AssignmentAction Action, bool AllowExplicit,
1394                                 ImplicitConversionSequence& ICS) {
1395   if (checkPlaceholderForOverload(*this, From))
1396     return ExprError();
1397 
1398   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1399   bool AllowObjCWritebackConversion
1400     = getLangOpts().ObjCAutoRefCount &&
1401       (Action == AA_Passing || Action == AA_Sending);
1402   if (getLangOpts().ObjC1)
1403     CheckObjCBridgeRelatedConversions(From->getLocStart(),
1404                                       ToType, From->getType(), From);
1405   ICS = ::TryImplicitConversion(*this, From, ToType,
1406                                 /*SuppressUserConversions=*/false,
1407                                 AllowExplicit,
1408                                 /*InOverloadResolution=*/false,
1409                                 /*CStyle=*/false,
1410                                 AllowObjCWritebackConversion,
1411                                 /*AllowObjCConversionOnExplicit=*/false);
1412   return PerformImplicitConversion(From, ToType, ICS, Action);
1413 }
1414 
1415 /// \brief Determine whether the conversion from FromType to ToType is a valid
1416 /// conversion that strips "noexcept" or "noreturn" off the nested function
1417 /// type.
1418 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1419                                 QualType &ResultTy) {
1420   if (Context.hasSameUnqualifiedType(FromType, ToType))
1421     return false;
1422 
1423   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1424   //                    or F(t noexcept) -> F(t)
1425   // where F adds one of the following at most once:
1426   //   - a pointer
1427   //   - a member pointer
1428   //   - a block pointer
1429   // Changes here need matching changes in FindCompositePointerType.
1430   CanQualType CanTo = Context.getCanonicalType(ToType);
1431   CanQualType CanFrom = Context.getCanonicalType(FromType);
1432   Type::TypeClass TyClass = CanTo->getTypeClass();
1433   if (TyClass != CanFrom->getTypeClass()) return false;
1434   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1435     if (TyClass == Type::Pointer) {
1436       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1437       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1438     } else if (TyClass == Type::BlockPointer) {
1439       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1440       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1441     } else if (TyClass == Type::MemberPointer) {
1442       auto ToMPT = CanTo.getAs<MemberPointerType>();
1443       auto FromMPT = CanFrom.getAs<MemberPointerType>();
1444       // A function pointer conversion cannot change the class of the function.
1445       if (ToMPT->getClass() != FromMPT->getClass())
1446         return false;
1447       CanTo = ToMPT->getPointeeType();
1448       CanFrom = FromMPT->getPointeeType();
1449     } else {
1450       return false;
1451     }
1452 
1453     TyClass = CanTo->getTypeClass();
1454     if (TyClass != CanFrom->getTypeClass()) return false;
1455     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1456       return false;
1457   }
1458 
1459   const auto *FromFn = cast<FunctionType>(CanFrom);
1460   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1461 
1462   const auto *ToFn = cast<FunctionType>(CanTo);
1463   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1464 
1465   bool Changed = false;
1466 
1467   // Drop 'noreturn' if not present in target type.
1468   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1469     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1470     Changed = true;
1471   }
1472 
1473   // Drop 'noexcept' if not present in target type.
1474   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1475     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1476     if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) {
1477       FromFn = cast<FunctionType>(
1478           Context.getFunctionType(FromFPT->getReturnType(),
1479                                   FromFPT->getParamTypes(),
1480                                   FromFPT->getExtProtoInfo().withExceptionSpec(
1481                                       FunctionProtoType::ExceptionSpecInfo()))
1482                  .getTypePtr());
1483       Changed = true;
1484     }
1485 
1486     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1487     // only if the ExtParameterInfo lists of the two function prototypes can be
1488     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1489     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1490     bool CanUseToFPT, CanUseFromFPT;
1491     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1492                                       CanUseFromFPT, NewParamInfos) &&
1493         CanUseToFPT && !CanUseFromFPT) {
1494       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1495       ExtInfo.ExtParameterInfos =
1496           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1497       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1498                                             FromFPT->getParamTypes(), ExtInfo);
1499       FromFn = QT->getAs<FunctionType>();
1500       Changed = true;
1501     }
1502   }
1503 
1504   if (!Changed)
1505     return false;
1506 
1507   assert(QualType(FromFn, 0).isCanonical());
1508   if (QualType(FromFn, 0) != CanTo) return false;
1509 
1510   ResultTy = ToType;
1511   return true;
1512 }
1513 
1514 /// \brief Determine whether the conversion from FromType to ToType is a valid
1515 /// vector conversion.
1516 ///
1517 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1518 /// conversion.
1519 static bool IsVectorConversion(Sema &S, QualType FromType,
1520                                QualType ToType, ImplicitConversionKind &ICK) {
1521   // We need at least one of these types to be a vector type to have a vector
1522   // conversion.
1523   if (!ToType->isVectorType() && !FromType->isVectorType())
1524     return false;
1525 
1526   // Identical types require no conversions.
1527   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1528     return false;
1529 
1530   // There are no conversions between extended vector types, only identity.
1531   if (ToType->isExtVectorType()) {
1532     // There are no conversions between extended vector types other than the
1533     // identity conversion.
1534     if (FromType->isExtVectorType())
1535       return false;
1536 
1537     // Vector splat from any arithmetic type to a vector.
1538     if (FromType->isArithmeticType()) {
1539       ICK = ICK_Vector_Splat;
1540       return true;
1541     }
1542   }
1543 
1544   // We can perform the conversion between vector types in the following cases:
1545   // 1)vector types are equivalent AltiVec and GCC vector types
1546   // 2)lax vector conversions are permitted and the vector types are of the
1547   //   same size
1548   if (ToType->isVectorType() && FromType->isVectorType()) {
1549     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1550         S.isLaxVectorConversion(FromType, ToType)) {
1551       ICK = ICK_Vector_Conversion;
1552       return true;
1553     }
1554   }
1555 
1556   return false;
1557 }
1558 
1559 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1560                                 bool InOverloadResolution,
1561                                 StandardConversionSequence &SCS,
1562                                 bool CStyle);
1563 
1564 /// IsStandardConversion - Determines whether there is a standard
1565 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1566 /// expression From to the type ToType. Standard conversion sequences
1567 /// only consider non-class types; for conversions that involve class
1568 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1569 /// contain the standard conversion sequence required to perform this
1570 /// conversion and this routine will return true. Otherwise, this
1571 /// routine will return false and the value of SCS is unspecified.
1572 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1573                                  bool InOverloadResolution,
1574                                  StandardConversionSequence &SCS,
1575                                  bool CStyle,
1576                                  bool AllowObjCWritebackConversion) {
1577   QualType FromType = From->getType();
1578 
1579   // Standard conversions (C++ [conv])
1580   SCS.setAsIdentityConversion();
1581   SCS.IncompatibleObjC = false;
1582   SCS.setFromType(FromType);
1583   SCS.CopyConstructor = nullptr;
1584 
1585   // There are no standard conversions for class types in C++, so
1586   // abort early. When overloading in C, however, we do permit them.
1587   if (S.getLangOpts().CPlusPlus &&
1588       (FromType->isRecordType() || ToType->isRecordType()))
1589     return false;
1590 
1591   // The first conversion can be an lvalue-to-rvalue conversion,
1592   // array-to-pointer conversion, or function-to-pointer conversion
1593   // (C++ 4p1).
1594 
1595   if (FromType == S.Context.OverloadTy) {
1596     DeclAccessPair AccessPair;
1597     if (FunctionDecl *Fn
1598           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1599                                                  AccessPair)) {
1600       // We were able to resolve the address of the overloaded function,
1601       // so we can convert to the type of that function.
1602       FromType = Fn->getType();
1603       SCS.setFromType(FromType);
1604 
1605       // we can sometimes resolve &foo<int> regardless of ToType, so check
1606       // if the type matches (identity) or we are converting to bool
1607       if (!S.Context.hasSameUnqualifiedType(
1608                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1609         QualType resultTy;
1610         // if the function type matches except for [[noreturn]], it's ok
1611         if (!S.IsFunctionConversion(FromType,
1612               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1613           // otherwise, only a boolean conversion is standard
1614           if (!ToType->isBooleanType())
1615             return false;
1616       }
1617 
1618       // Check if the "from" expression is taking the address of an overloaded
1619       // function and recompute the FromType accordingly. Take advantage of the
1620       // fact that non-static member functions *must* have such an address-of
1621       // expression.
1622       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1623       if (Method && !Method->isStatic()) {
1624         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1625                "Non-unary operator on non-static member address");
1626         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1627                == UO_AddrOf &&
1628                "Non-address-of operator on non-static member address");
1629         const Type *ClassType
1630           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1631         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1632       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1633         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1634                UO_AddrOf &&
1635                "Non-address-of operator for overloaded function expression");
1636         FromType = S.Context.getPointerType(FromType);
1637       }
1638 
1639       // Check that we've computed the proper type after overload resolution.
1640       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1641       // be calling it from within an NDEBUG block.
1642       assert(S.Context.hasSameType(
1643         FromType,
1644         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1645     } else {
1646       return false;
1647     }
1648   }
1649   // Lvalue-to-rvalue conversion (C++11 4.1):
1650   //   A glvalue (3.10) of a non-function, non-array type T can
1651   //   be converted to a prvalue.
1652   bool argIsLValue = From->isGLValue();
1653   if (argIsLValue &&
1654       !FromType->isFunctionType() && !FromType->isArrayType() &&
1655       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1656     SCS.First = ICK_Lvalue_To_Rvalue;
1657 
1658     // C11 6.3.2.1p2:
1659     //   ... if the lvalue has atomic type, the value has the non-atomic version
1660     //   of the type of the lvalue ...
1661     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1662       FromType = Atomic->getValueType();
1663 
1664     // If T is a non-class type, the type of the rvalue is the
1665     // cv-unqualified version of T. Otherwise, the type of the rvalue
1666     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1667     // just strip the qualifiers because they don't matter.
1668     FromType = FromType.getUnqualifiedType();
1669   } else if (FromType->isArrayType()) {
1670     // Array-to-pointer conversion (C++ 4.2)
1671     SCS.First = ICK_Array_To_Pointer;
1672 
1673     // An lvalue or rvalue of type "array of N T" or "array of unknown
1674     // bound of T" can be converted to an rvalue of type "pointer to
1675     // T" (C++ 4.2p1).
1676     FromType = S.Context.getArrayDecayedType(FromType);
1677 
1678     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1679       // This conversion is deprecated in C++03 (D.4)
1680       SCS.DeprecatedStringLiteralToCharPtr = true;
1681 
1682       // For the purpose of ranking in overload resolution
1683       // (13.3.3.1.1), this conversion is considered an
1684       // array-to-pointer conversion followed by a qualification
1685       // conversion (4.4). (C++ 4.2p2)
1686       SCS.Second = ICK_Identity;
1687       SCS.Third = ICK_Qualification;
1688       SCS.QualificationIncludesObjCLifetime = false;
1689       SCS.setAllToTypes(FromType);
1690       return true;
1691     }
1692   } else if (FromType->isFunctionType() && argIsLValue) {
1693     // Function-to-pointer conversion (C++ 4.3).
1694     SCS.First = ICK_Function_To_Pointer;
1695 
1696     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1697       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1698         if (!S.checkAddressOfFunctionIsAvailable(FD))
1699           return false;
1700 
1701     // An lvalue of function type T can be converted to an rvalue of
1702     // type "pointer to T." The result is a pointer to the
1703     // function. (C++ 4.3p1).
1704     FromType = S.Context.getPointerType(FromType);
1705   } else {
1706     // We don't require any conversions for the first step.
1707     SCS.First = ICK_Identity;
1708   }
1709   SCS.setToType(0, FromType);
1710 
1711   // The second conversion can be an integral promotion, floating
1712   // point promotion, integral conversion, floating point conversion,
1713   // floating-integral conversion, pointer conversion,
1714   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1715   // For overloading in C, this can also be a "compatible-type"
1716   // conversion.
1717   bool IncompatibleObjC = false;
1718   ImplicitConversionKind SecondICK = ICK_Identity;
1719   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1720     // The unqualified versions of the types are the same: there's no
1721     // conversion to do.
1722     SCS.Second = ICK_Identity;
1723   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1724     // Integral promotion (C++ 4.5).
1725     SCS.Second = ICK_Integral_Promotion;
1726     FromType = ToType.getUnqualifiedType();
1727   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1728     // Floating point promotion (C++ 4.6).
1729     SCS.Second = ICK_Floating_Promotion;
1730     FromType = ToType.getUnqualifiedType();
1731   } else if (S.IsComplexPromotion(FromType, ToType)) {
1732     // Complex promotion (Clang extension)
1733     SCS.Second = ICK_Complex_Promotion;
1734     FromType = ToType.getUnqualifiedType();
1735   } else if (ToType->isBooleanType() &&
1736              (FromType->isArithmeticType() ||
1737               FromType->isAnyPointerType() ||
1738               FromType->isBlockPointerType() ||
1739               FromType->isMemberPointerType() ||
1740               FromType->isNullPtrType())) {
1741     // Boolean conversions (C++ 4.12).
1742     SCS.Second = ICK_Boolean_Conversion;
1743     FromType = S.Context.BoolTy;
1744   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1745              ToType->isIntegralType(S.Context)) {
1746     // Integral conversions (C++ 4.7).
1747     SCS.Second = ICK_Integral_Conversion;
1748     FromType = ToType.getUnqualifiedType();
1749   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1750     // Complex conversions (C99 6.3.1.6)
1751     SCS.Second = ICK_Complex_Conversion;
1752     FromType = ToType.getUnqualifiedType();
1753   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1754              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1755     // Complex-real conversions (C99 6.3.1.7)
1756     SCS.Second = ICK_Complex_Real;
1757     FromType = ToType.getUnqualifiedType();
1758   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1759     // FIXME: disable conversions between long double and __float128 if
1760     // their representation is different until there is back end support
1761     // We of course allow this conversion if long double is really double.
1762     if (&S.Context.getFloatTypeSemantics(FromType) !=
1763         &S.Context.getFloatTypeSemantics(ToType)) {
1764       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1765                                     ToType == S.Context.LongDoubleTy) ||
1766                                    (FromType == S.Context.LongDoubleTy &&
1767                                     ToType == S.Context.Float128Ty));
1768       if (Float128AndLongDouble &&
1769           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1770            &llvm::APFloat::IEEEdouble()))
1771         return false;
1772     }
1773     // Floating point conversions (C++ 4.8).
1774     SCS.Second = ICK_Floating_Conversion;
1775     FromType = ToType.getUnqualifiedType();
1776   } else if ((FromType->isRealFloatingType() &&
1777               ToType->isIntegralType(S.Context)) ||
1778              (FromType->isIntegralOrUnscopedEnumerationType() &&
1779               ToType->isRealFloatingType())) {
1780     // Floating-integral conversions (C++ 4.9).
1781     SCS.Second = ICK_Floating_Integral;
1782     FromType = ToType.getUnqualifiedType();
1783   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1784     SCS.Second = ICK_Block_Pointer_Conversion;
1785   } else if (AllowObjCWritebackConversion &&
1786              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1787     SCS.Second = ICK_Writeback_Conversion;
1788   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1789                                    FromType, IncompatibleObjC)) {
1790     // Pointer conversions (C++ 4.10).
1791     SCS.Second = ICK_Pointer_Conversion;
1792     SCS.IncompatibleObjC = IncompatibleObjC;
1793     FromType = FromType.getUnqualifiedType();
1794   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1795                                          InOverloadResolution, FromType)) {
1796     // Pointer to member conversions (4.11).
1797     SCS.Second = ICK_Pointer_Member;
1798   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1799     SCS.Second = SecondICK;
1800     FromType = ToType.getUnqualifiedType();
1801   } else if (!S.getLangOpts().CPlusPlus &&
1802              S.Context.typesAreCompatible(ToType, FromType)) {
1803     // Compatible conversions (Clang extension for C function overloading)
1804     SCS.Second = ICK_Compatible_Conversion;
1805     FromType = ToType.getUnqualifiedType();
1806   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1807                                              InOverloadResolution,
1808                                              SCS, CStyle)) {
1809     SCS.Second = ICK_TransparentUnionConversion;
1810     FromType = ToType;
1811   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1812                                  CStyle)) {
1813     // tryAtomicConversion has updated the standard conversion sequence
1814     // appropriately.
1815     return true;
1816   } else if (ToType->isEventT() &&
1817              From->isIntegerConstantExpr(S.getASTContext()) &&
1818              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1819     SCS.Second = ICK_Zero_Event_Conversion;
1820     FromType = ToType;
1821   } else if (ToType->isQueueT() &&
1822              From->isIntegerConstantExpr(S.getASTContext()) &&
1823              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1824     SCS.Second = ICK_Zero_Queue_Conversion;
1825     FromType = ToType;
1826   } else {
1827     // No second conversion required.
1828     SCS.Second = ICK_Identity;
1829   }
1830   SCS.setToType(1, FromType);
1831 
1832   // The third conversion can be a function pointer conversion or a
1833   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1834   bool ObjCLifetimeConversion;
1835   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1836     // Function pointer conversions (removing 'noexcept') including removal of
1837     // 'noreturn' (Clang extension).
1838     SCS.Third = ICK_Function_Conversion;
1839   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1840                                          ObjCLifetimeConversion)) {
1841     SCS.Third = ICK_Qualification;
1842     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1843     FromType = ToType;
1844   } else {
1845     // No conversion required
1846     SCS.Third = ICK_Identity;
1847   }
1848 
1849   // C++ [over.best.ics]p6:
1850   //   [...] Any difference in top-level cv-qualification is
1851   //   subsumed by the initialization itself and does not constitute
1852   //   a conversion. [...]
1853   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1854   QualType CanonTo = S.Context.getCanonicalType(ToType);
1855   if (CanonFrom.getLocalUnqualifiedType()
1856                                      == CanonTo.getLocalUnqualifiedType() &&
1857       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1858     FromType = ToType;
1859     CanonFrom = CanonTo;
1860   }
1861 
1862   SCS.setToType(2, FromType);
1863 
1864   if (CanonFrom == CanonTo)
1865     return true;
1866 
1867   // If we have not converted the argument type to the parameter type,
1868   // this is a bad conversion sequence, unless we're resolving an overload in C.
1869   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1870     return false;
1871 
1872   ExprResult ER = ExprResult{From};
1873   Sema::AssignConvertType Conv =
1874       S.CheckSingleAssignmentConstraints(ToType, ER,
1875                                          /*Diagnose=*/false,
1876                                          /*DiagnoseCFAudited=*/false,
1877                                          /*ConvertRHS=*/false);
1878   ImplicitConversionKind SecondConv;
1879   switch (Conv) {
1880   case Sema::Compatible:
1881     SecondConv = ICK_C_Only_Conversion;
1882     break;
1883   // For our purposes, discarding qualifiers is just as bad as using an
1884   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1885   // qualifiers, as well.
1886   case Sema::CompatiblePointerDiscardsQualifiers:
1887   case Sema::IncompatiblePointer:
1888   case Sema::IncompatiblePointerSign:
1889     SecondConv = ICK_Incompatible_Pointer_Conversion;
1890     break;
1891   default:
1892     return false;
1893   }
1894 
1895   // First can only be an lvalue conversion, so we pretend that this was the
1896   // second conversion. First should already be valid from earlier in the
1897   // function.
1898   SCS.Second = SecondConv;
1899   SCS.setToType(1, ToType);
1900 
1901   // Third is Identity, because Second should rank us worse than any other
1902   // conversion. This could also be ICK_Qualification, but it's simpler to just
1903   // lump everything in with the second conversion, and we don't gain anything
1904   // from making this ICK_Qualification.
1905   SCS.Third = ICK_Identity;
1906   SCS.setToType(2, ToType);
1907   return true;
1908 }
1909 
1910 static bool
1911 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1912                                      QualType &ToType,
1913                                      bool InOverloadResolution,
1914                                      StandardConversionSequence &SCS,
1915                                      bool CStyle) {
1916 
1917   const RecordType *UT = ToType->getAsUnionType();
1918   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1919     return false;
1920   // The field to initialize within the transparent union.
1921   RecordDecl *UD = UT->getDecl();
1922   // It's compatible if the expression matches any of the fields.
1923   for (const auto *it : UD->fields()) {
1924     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1925                              CStyle, /*ObjCWritebackConversion=*/false)) {
1926       ToType = it->getType();
1927       return true;
1928     }
1929   }
1930   return false;
1931 }
1932 
1933 /// IsIntegralPromotion - Determines whether the conversion from the
1934 /// expression From (whose potentially-adjusted type is FromType) to
1935 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1936 /// sets PromotedType to the promoted type.
1937 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1938   const BuiltinType *To = ToType->getAs<BuiltinType>();
1939   // All integers are built-in.
1940   if (!To) {
1941     return false;
1942   }
1943 
1944   // An rvalue of type char, signed char, unsigned char, short int, or
1945   // unsigned short int can be converted to an rvalue of type int if
1946   // int can represent all the values of the source type; otherwise,
1947   // the source rvalue can be converted to an rvalue of type unsigned
1948   // int (C++ 4.5p1).
1949   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1950       !FromType->isEnumeralType()) {
1951     if (// We can promote any signed, promotable integer type to an int
1952         (FromType->isSignedIntegerType() ||
1953          // We can promote any unsigned integer type whose size is
1954          // less than int to an int.
1955          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1956       return To->getKind() == BuiltinType::Int;
1957     }
1958 
1959     return To->getKind() == BuiltinType::UInt;
1960   }
1961 
1962   // C++11 [conv.prom]p3:
1963   //   A prvalue of an unscoped enumeration type whose underlying type is not
1964   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1965   //   following types that can represent all the values of the enumeration
1966   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1967   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1968   //   long long int. If none of the types in that list can represent all the
1969   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1970   //   type can be converted to an rvalue a prvalue of the extended integer type
1971   //   with lowest integer conversion rank (4.13) greater than the rank of long
1972   //   long in which all the values of the enumeration can be represented. If
1973   //   there are two such extended types, the signed one is chosen.
1974   // C++11 [conv.prom]p4:
1975   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1976   //   can be converted to a prvalue of its underlying type. Moreover, if
1977   //   integral promotion can be applied to its underlying type, a prvalue of an
1978   //   unscoped enumeration type whose underlying type is fixed can also be
1979   //   converted to a prvalue of the promoted underlying type.
1980   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1981     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1982     // provided for a scoped enumeration.
1983     if (FromEnumType->getDecl()->isScoped())
1984       return false;
1985 
1986     // We can perform an integral promotion to the underlying type of the enum,
1987     // even if that's not the promoted type. Note that the check for promoting
1988     // the underlying type is based on the type alone, and does not consider
1989     // the bitfield-ness of the actual source expression.
1990     if (FromEnumType->getDecl()->isFixed()) {
1991       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1992       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1993              IsIntegralPromotion(nullptr, Underlying, ToType);
1994     }
1995 
1996     // We have already pre-calculated the promotion type, so this is trivial.
1997     if (ToType->isIntegerType() &&
1998         isCompleteType(From->getLocStart(), FromType))
1999       return Context.hasSameUnqualifiedType(
2000           ToType, FromEnumType->getDecl()->getPromotionType());
2001   }
2002 
2003   // C++0x [conv.prom]p2:
2004   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2005   //   to an rvalue a prvalue of the first of the following types that can
2006   //   represent all the values of its underlying type: int, unsigned int,
2007   //   long int, unsigned long int, long long int, or unsigned long long int.
2008   //   If none of the types in that list can represent all the values of its
2009   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2010   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2011   //   type.
2012   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2013       ToType->isIntegerType()) {
2014     // Determine whether the type we're converting from is signed or
2015     // unsigned.
2016     bool FromIsSigned = FromType->isSignedIntegerType();
2017     uint64_t FromSize = Context.getTypeSize(FromType);
2018 
2019     // The types we'll try to promote to, in the appropriate
2020     // order. Try each of these types.
2021     QualType PromoteTypes[6] = {
2022       Context.IntTy, Context.UnsignedIntTy,
2023       Context.LongTy, Context.UnsignedLongTy ,
2024       Context.LongLongTy, Context.UnsignedLongLongTy
2025     };
2026     for (int Idx = 0; Idx < 6; ++Idx) {
2027       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2028       if (FromSize < ToSize ||
2029           (FromSize == ToSize &&
2030            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2031         // We found the type that we can promote to. If this is the
2032         // type we wanted, we have a promotion. Otherwise, no
2033         // promotion.
2034         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2035       }
2036     }
2037   }
2038 
2039   // An rvalue for an integral bit-field (9.6) can be converted to an
2040   // rvalue of type int if int can represent all the values of the
2041   // bit-field; otherwise, it can be converted to unsigned int if
2042   // unsigned int can represent all the values of the bit-field. If
2043   // the bit-field is larger yet, no integral promotion applies to
2044   // it. If the bit-field has an enumerated type, it is treated as any
2045   // other value of that type for promotion purposes (C++ 4.5p3).
2046   // FIXME: We should delay checking of bit-fields until we actually perform the
2047   // conversion.
2048   if (From) {
2049     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2050       llvm::APSInt BitWidth;
2051       if (FromType->isIntegralType(Context) &&
2052           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2053         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2054         ToSize = Context.getTypeSize(ToType);
2055 
2056         // Are we promoting to an int from a bitfield that fits in an int?
2057         if (BitWidth < ToSize ||
2058             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2059           return To->getKind() == BuiltinType::Int;
2060         }
2061 
2062         // Are we promoting to an unsigned int from an unsigned bitfield
2063         // that fits into an unsigned int?
2064         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2065           return To->getKind() == BuiltinType::UInt;
2066         }
2067 
2068         return false;
2069       }
2070     }
2071   }
2072 
2073   // An rvalue of type bool can be converted to an rvalue of type int,
2074   // with false becoming zero and true becoming one (C++ 4.5p4).
2075   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2076     return true;
2077   }
2078 
2079   return false;
2080 }
2081 
2082 /// IsFloatingPointPromotion - Determines whether the conversion from
2083 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2084 /// returns true and sets PromotedType to the promoted type.
2085 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2086   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2087     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2088       /// An rvalue of type float can be converted to an rvalue of type
2089       /// double. (C++ 4.6p1).
2090       if (FromBuiltin->getKind() == BuiltinType::Float &&
2091           ToBuiltin->getKind() == BuiltinType::Double)
2092         return true;
2093 
2094       // C99 6.3.1.5p1:
2095       //   When a float is promoted to double or long double, or a
2096       //   double is promoted to long double [...].
2097       if (!getLangOpts().CPlusPlus &&
2098           (FromBuiltin->getKind() == BuiltinType::Float ||
2099            FromBuiltin->getKind() == BuiltinType::Double) &&
2100           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2101            ToBuiltin->getKind() == BuiltinType::Float128))
2102         return true;
2103 
2104       // Half can be promoted to float.
2105       if (!getLangOpts().NativeHalfType &&
2106            FromBuiltin->getKind() == BuiltinType::Half &&
2107           ToBuiltin->getKind() == BuiltinType::Float)
2108         return true;
2109     }
2110 
2111   return false;
2112 }
2113 
2114 /// \brief Determine if a conversion is a complex promotion.
2115 ///
2116 /// A complex promotion is defined as a complex -> complex conversion
2117 /// where the conversion between the underlying real types is a
2118 /// floating-point or integral promotion.
2119 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2120   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2121   if (!FromComplex)
2122     return false;
2123 
2124   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2125   if (!ToComplex)
2126     return false;
2127 
2128   return IsFloatingPointPromotion(FromComplex->getElementType(),
2129                                   ToComplex->getElementType()) ||
2130     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2131                         ToComplex->getElementType());
2132 }
2133 
2134 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2135 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2136 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2137 /// if non-empty, will be a pointer to ToType that may or may not have
2138 /// the right set of qualifiers on its pointee.
2139 ///
2140 static QualType
2141 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2142                                    QualType ToPointee, QualType ToType,
2143                                    ASTContext &Context,
2144                                    bool StripObjCLifetime = false) {
2145   assert((FromPtr->getTypeClass() == Type::Pointer ||
2146           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2147          "Invalid similarly-qualified pointer type");
2148 
2149   /// Conversions to 'id' subsume cv-qualifier conversions.
2150   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2151     return ToType.getUnqualifiedType();
2152 
2153   QualType CanonFromPointee
2154     = Context.getCanonicalType(FromPtr->getPointeeType());
2155   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2156   Qualifiers Quals = CanonFromPointee.getQualifiers();
2157 
2158   if (StripObjCLifetime)
2159     Quals.removeObjCLifetime();
2160 
2161   // Exact qualifier match -> return the pointer type we're converting to.
2162   if (CanonToPointee.getLocalQualifiers() == Quals) {
2163     // ToType is exactly what we need. Return it.
2164     if (!ToType.isNull())
2165       return ToType.getUnqualifiedType();
2166 
2167     // Build a pointer to ToPointee. It has the right qualifiers
2168     // already.
2169     if (isa<ObjCObjectPointerType>(ToType))
2170       return Context.getObjCObjectPointerType(ToPointee);
2171     return Context.getPointerType(ToPointee);
2172   }
2173 
2174   // Just build a canonical type that has the right qualifiers.
2175   QualType QualifiedCanonToPointee
2176     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2177 
2178   if (isa<ObjCObjectPointerType>(ToType))
2179     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2180   return Context.getPointerType(QualifiedCanonToPointee);
2181 }
2182 
2183 static bool isNullPointerConstantForConversion(Expr *Expr,
2184                                                bool InOverloadResolution,
2185                                                ASTContext &Context) {
2186   // Handle value-dependent integral null pointer constants correctly.
2187   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2188   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2189       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2190     return !InOverloadResolution;
2191 
2192   return Expr->isNullPointerConstant(Context,
2193                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2194                                         : Expr::NPC_ValueDependentIsNull);
2195 }
2196 
2197 /// IsPointerConversion - Determines whether the conversion of the
2198 /// expression From, which has the (possibly adjusted) type FromType,
2199 /// can be converted to the type ToType via a pointer conversion (C++
2200 /// 4.10). If so, returns true and places the converted type (that
2201 /// might differ from ToType in its cv-qualifiers at some level) into
2202 /// ConvertedType.
2203 ///
2204 /// This routine also supports conversions to and from block pointers
2205 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2206 /// pointers to interfaces. FIXME: Once we've determined the
2207 /// appropriate overloading rules for Objective-C, we may want to
2208 /// split the Objective-C checks into a different routine; however,
2209 /// GCC seems to consider all of these conversions to be pointer
2210 /// conversions, so for now they live here. IncompatibleObjC will be
2211 /// set if the conversion is an allowed Objective-C conversion that
2212 /// should result in a warning.
2213 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2214                                bool InOverloadResolution,
2215                                QualType& ConvertedType,
2216                                bool &IncompatibleObjC) {
2217   IncompatibleObjC = false;
2218   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2219                               IncompatibleObjC))
2220     return true;
2221 
2222   // Conversion from a null pointer constant to any Objective-C pointer type.
2223   if (ToType->isObjCObjectPointerType() &&
2224       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2225     ConvertedType = ToType;
2226     return true;
2227   }
2228 
2229   // Blocks: Block pointers can be converted to void*.
2230   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2231       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2232     ConvertedType = ToType;
2233     return true;
2234   }
2235   // Blocks: A null pointer constant can be converted to a block
2236   // pointer type.
2237   if (ToType->isBlockPointerType() &&
2238       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2239     ConvertedType = ToType;
2240     return true;
2241   }
2242 
2243   // If the left-hand-side is nullptr_t, the right side can be a null
2244   // pointer constant.
2245   if (ToType->isNullPtrType() &&
2246       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2247     ConvertedType = ToType;
2248     return true;
2249   }
2250 
2251   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2252   if (!ToTypePtr)
2253     return false;
2254 
2255   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2256   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2257     ConvertedType = ToType;
2258     return true;
2259   }
2260 
2261   // Beyond this point, both types need to be pointers
2262   // , including objective-c pointers.
2263   QualType ToPointeeType = ToTypePtr->getPointeeType();
2264   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2265       !getLangOpts().ObjCAutoRefCount) {
2266     ConvertedType = BuildSimilarlyQualifiedPointerType(
2267                                       FromType->getAs<ObjCObjectPointerType>(),
2268                                                        ToPointeeType,
2269                                                        ToType, Context);
2270     return true;
2271   }
2272   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2273   if (!FromTypePtr)
2274     return false;
2275 
2276   QualType FromPointeeType = FromTypePtr->getPointeeType();
2277 
2278   // If the unqualified pointee types are the same, this can't be a
2279   // pointer conversion, so don't do all of the work below.
2280   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2281     return false;
2282 
2283   // An rvalue of type "pointer to cv T," where T is an object type,
2284   // can be converted to an rvalue of type "pointer to cv void" (C++
2285   // 4.10p2).
2286   if (FromPointeeType->isIncompleteOrObjectType() &&
2287       ToPointeeType->isVoidType()) {
2288     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2289                                                        ToPointeeType,
2290                                                        ToType, Context,
2291                                                    /*StripObjCLifetime=*/true);
2292     return true;
2293   }
2294 
2295   // MSVC allows implicit function to void* type conversion.
2296   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2297       ToPointeeType->isVoidType()) {
2298     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2299                                                        ToPointeeType,
2300                                                        ToType, Context);
2301     return true;
2302   }
2303 
2304   // When we're overloading in C, we allow a special kind of pointer
2305   // conversion for compatible-but-not-identical pointee types.
2306   if (!getLangOpts().CPlusPlus &&
2307       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2308     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2309                                                        ToPointeeType,
2310                                                        ToType, Context);
2311     return true;
2312   }
2313 
2314   // C++ [conv.ptr]p3:
2315   //
2316   //   An rvalue of type "pointer to cv D," where D is a class type,
2317   //   can be converted to an rvalue of type "pointer to cv B," where
2318   //   B is a base class (clause 10) of D. If B is an inaccessible
2319   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2320   //   necessitates this conversion is ill-formed. The result of the
2321   //   conversion is a pointer to the base class sub-object of the
2322   //   derived class object. The null pointer value is converted to
2323   //   the null pointer value of the destination type.
2324   //
2325   // Note that we do not check for ambiguity or inaccessibility
2326   // here. That is handled by CheckPointerConversion.
2327   if (getLangOpts().CPlusPlus &&
2328       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2329       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2330       IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2331     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2332                                                        ToPointeeType,
2333                                                        ToType, Context);
2334     return true;
2335   }
2336 
2337   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2338       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2339     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2340                                                        ToPointeeType,
2341                                                        ToType, Context);
2342     return true;
2343   }
2344 
2345   return false;
2346 }
2347 
2348 /// \brief Adopt the given qualifiers for the given type.
2349 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2350   Qualifiers TQs = T.getQualifiers();
2351 
2352   // Check whether qualifiers already match.
2353   if (TQs == Qs)
2354     return T;
2355 
2356   if (Qs.compatiblyIncludes(TQs))
2357     return Context.getQualifiedType(T, Qs);
2358 
2359   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2360 }
2361 
2362 /// isObjCPointerConversion - Determines whether this is an
2363 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2364 /// with the same arguments and return values.
2365 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2366                                    QualType& ConvertedType,
2367                                    bool &IncompatibleObjC) {
2368   if (!getLangOpts().ObjC1)
2369     return false;
2370 
2371   // The set of qualifiers on the type we're converting from.
2372   Qualifiers FromQualifiers = FromType.getQualifiers();
2373 
2374   // First, we handle all conversions on ObjC object pointer types.
2375   const ObjCObjectPointerType* ToObjCPtr =
2376     ToType->getAs<ObjCObjectPointerType>();
2377   const ObjCObjectPointerType *FromObjCPtr =
2378     FromType->getAs<ObjCObjectPointerType>();
2379 
2380   if (ToObjCPtr && FromObjCPtr) {
2381     // If the pointee types are the same (ignoring qualifications),
2382     // then this is not a pointer conversion.
2383     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2384                                        FromObjCPtr->getPointeeType()))
2385       return false;
2386 
2387     // Conversion between Objective-C pointers.
2388     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2389       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2390       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2391       if (getLangOpts().CPlusPlus && LHS && RHS &&
2392           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2393                                                 FromObjCPtr->getPointeeType()))
2394         return false;
2395       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2396                                                    ToObjCPtr->getPointeeType(),
2397                                                          ToType, Context);
2398       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2399       return true;
2400     }
2401 
2402     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2403       // Okay: this is some kind of implicit downcast of Objective-C
2404       // interfaces, which is permitted. However, we're going to
2405       // complain about it.
2406       IncompatibleObjC = true;
2407       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2408                                                    ToObjCPtr->getPointeeType(),
2409                                                          ToType, Context);
2410       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2411       return true;
2412     }
2413   }
2414   // Beyond this point, both types need to be C pointers or block pointers.
2415   QualType ToPointeeType;
2416   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2417     ToPointeeType = ToCPtr->getPointeeType();
2418   else if (const BlockPointerType *ToBlockPtr =
2419             ToType->getAs<BlockPointerType>()) {
2420     // Objective C++: We're able to convert from a pointer to any object
2421     // to a block pointer type.
2422     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2423       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2424       return true;
2425     }
2426     ToPointeeType = ToBlockPtr->getPointeeType();
2427   }
2428   else if (FromType->getAs<BlockPointerType>() &&
2429            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2430     // Objective C++: We're able to convert from a block pointer type to a
2431     // pointer to any object.
2432     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2433     return true;
2434   }
2435   else
2436     return false;
2437 
2438   QualType FromPointeeType;
2439   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2440     FromPointeeType = FromCPtr->getPointeeType();
2441   else if (const BlockPointerType *FromBlockPtr =
2442            FromType->getAs<BlockPointerType>())
2443     FromPointeeType = FromBlockPtr->getPointeeType();
2444   else
2445     return false;
2446 
2447   // If we have pointers to pointers, recursively check whether this
2448   // is an Objective-C conversion.
2449   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2450       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2451                               IncompatibleObjC)) {
2452     // We always complain about this conversion.
2453     IncompatibleObjC = true;
2454     ConvertedType = Context.getPointerType(ConvertedType);
2455     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2456     return true;
2457   }
2458   // Allow conversion of pointee being objective-c pointer to another one;
2459   // as in I* to id.
2460   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2461       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2462       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2463                               IncompatibleObjC)) {
2464 
2465     ConvertedType = Context.getPointerType(ConvertedType);
2466     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2467     return true;
2468   }
2469 
2470   // If we have pointers to functions or blocks, check whether the only
2471   // differences in the argument and result types are in Objective-C
2472   // pointer conversions. If so, we permit the conversion (but
2473   // complain about it).
2474   const FunctionProtoType *FromFunctionType
2475     = FromPointeeType->getAs<FunctionProtoType>();
2476   const FunctionProtoType *ToFunctionType
2477     = ToPointeeType->getAs<FunctionProtoType>();
2478   if (FromFunctionType && ToFunctionType) {
2479     // If the function types are exactly the same, this isn't an
2480     // Objective-C pointer conversion.
2481     if (Context.getCanonicalType(FromPointeeType)
2482           == Context.getCanonicalType(ToPointeeType))
2483       return false;
2484 
2485     // Perform the quick checks that will tell us whether these
2486     // function types are obviously different.
2487     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2488         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2489         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2490       return false;
2491 
2492     bool HasObjCConversion = false;
2493     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2494         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2495       // Okay, the types match exactly. Nothing to do.
2496     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2497                                        ToFunctionType->getReturnType(),
2498                                        ConvertedType, IncompatibleObjC)) {
2499       // Okay, we have an Objective-C pointer conversion.
2500       HasObjCConversion = true;
2501     } else {
2502       // Function types are too different. Abort.
2503       return false;
2504     }
2505 
2506     // Check argument types.
2507     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2508          ArgIdx != NumArgs; ++ArgIdx) {
2509       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2510       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2511       if (Context.getCanonicalType(FromArgType)
2512             == Context.getCanonicalType(ToArgType)) {
2513         // Okay, the types match exactly. Nothing to do.
2514       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2515                                          ConvertedType, IncompatibleObjC)) {
2516         // Okay, we have an Objective-C pointer conversion.
2517         HasObjCConversion = true;
2518       } else {
2519         // Argument types are too different. Abort.
2520         return false;
2521       }
2522     }
2523 
2524     if (HasObjCConversion) {
2525       // We had an Objective-C conversion. Allow this pointer
2526       // conversion, but complain about it.
2527       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2528       IncompatibleObjC = true;
2529       return true;
2530     }
2531   }
2532 
2533   return false;
2534 }
2535 
2536 /// \brief Determine whether this is an Objective-C writeback conversion,
2537 /// used for parameter passing when performing automatic reference counting.
2538 ///
2539 /// \param FromType The type we're converting form.
2540 ///
2541 /// \param ToType The type we're converting to.
2542 ///
2543 /// \param ConvertedType The type that will be produced after applying
2544 /// this conversion.
2545 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2546                                      QualType &ConvertedType) {
2547   if (!getLangOpts().ObjCAutoRefCount ||
2548       Context.hasSameUnqualifiedType(FromType, ToType))
2549     return false;
2550 
2551   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2552   QualType ToPointee;
2553   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2554     ToPointee = ToPointer->getPointeeType();
2555   else
2556     return false;
2557 
2558   Qualifiers ToQuals = ToPointee.getQualifiers();
2559   if (!ToPointee->isObjCLifetimeType() ||
2560       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2561       !ToQuals.withoutObjCLifetime().empty())
2562     return false;
2563 
2564   // Argument must be a pointer to __strong to __weak.
2565   QualType FromPointee;
2566   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2567     FromPointee = FromPointer->getPointeeType();
2568   else
2569     return false;
2570 
2571   Qualifiers FromQuals = FromPointee.getQualifiers();
2572   if (!FromPointee->isObjCLifetimeType() ||
2573       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2574        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2575     return false;
2576 
2577   // Make sure that we have compatible qualifiers.
2578   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2579   if (!ToQuals.compatiblyIncludes(FromQuals))
2580     return false;
2581 
2582   // Remove qualifiers from the pointee type we're converting from; they
2583   // aren't used in the compatibility check belong, and we'll be adding back
2584   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2585   FromPointee = FromPointee.getUnqualifiedType();
2586 
2587   // The unqualified form of the pointee types must be compatible.
2588   ToPointee = ToPointee.getUnqualifiedType();
2589   bool IncompatibleObjC;
2590   if (Context.typesAreCompatible(FromPointee, ToPointee))
2591     FromPointee = ToPointee;
2592   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2593                                     IncompatibleObjC))
2594     return false;
2595 
2596   /// \brief Construct the type we're converting to, which is a pointer to
2597   /// __autoreleasing pointee.
2598   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2599   ConvertedType = Context.getPointerType(FromPointee);
2600   return true;
2601 }
2602 
2603 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2604                                     QualType& ConvertedType) {
2605   QualType ToPointeeType;
2606   if (const BlockPointerType *ToBlockPtr =
2607         ToType->getAs<BlockPointerType>())
2608     ToPointeeType = ToBlockPtr->getPointeeType();
2609   else
2610     return false;
2611 
2612   QualType FromPointeeType;
2613   if (const BlockPointerType *FromBlockPtr =
2614       FromType->getAs<BlockPointerType>())
2615     FromPointeeType = FromBlockPtr->getPointeeType();
2616   else
2617     return false;
2618   // We have pointer to blocks, check whether the only
2619   // differences in the argument and result types are in Objective-C
2620   // pointer conversions. If so, we permit the conversion.
2621 
2622   const FunctionProtoType *FromFunctionType
2623     = FromPointeeType->getAs<FunctionProtoType>();
2624   const FunctionProtoType *ToFunctionType
2625     = ToPointeeType->getAs<FunctionProtoType>();
2626 
2627   if (!FromFunctionType || !ToFunctionType)
2628     return false;
2629 
2630   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2631     return true;
2632 
2633   // Perform the quick checks that will tell us whether these
2634   // function types are obviously different.
2635   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2636       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2637     return false;
2638 
2639   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2640   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2641   if (FromEInfo != ToEInfo)
2642     return false;
2643 
2644   bool IncompatibleObjC = false;
2645   if (Context.hasSameType(FromFunctionType->getReturnType(),
2646                           ToFunctionType->getReturnType())) {
2647     // Okay, the types match exactly. Nothing to do.
2648   } else {
2649     QualType RHS = FromFunctionType->getReturnType();
2650     QualType LHS = ToFunctionType->getReturnType();
2651     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2652         !RHS.hasQualifiers() && LHS.hasQualifiers())
2653        LHS = LHS.getUnqualifiedType();
2654 
2655      if (Context.hasSameType(RHS,LHS)) {
2656        // OK exact match.
2657      } else if (isObjCPointerConversion(RHS, LHS,
2658                                         ConvertedType, IncompatibleObjC)) {
2659      if (IncompatibleObjC)
2660        return false;
2661      // Okay, we have an Objective-C pointer conversion.
2662      }
2663      else
2664        return false;
2665    }
2666 
2667    // Check argument types.
2668    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2669         ArgIdx != NumArgs; ++ArgIdx) {
2670      IncompatibleObjC = false;
2671      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2672      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2673      if (Context.hasSameType(FromArgType, ToArgType)) {
2674        // Okay, the types match exactly. Nothing to do.
2675      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2676                                         ConvertedType, IncompatibleObjC)) {
2677        if (IncompatibleObjC)
2678          return false;
2679        // Okay, we have an Objective-C pointer conversion.
2680      } else
2681        // Argument types are too different. Abort.
2682        return false;
2683    }
2684 
2685    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2686    bool CanUseToFPT, CanUseFromFPT;
2687    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2688                                       CanUseToFPT, CanUseFromFPT,
2689                                       NewParamInfos))
2690      return false;
2691 
2692    ConvertedType = ToType;
2693    return true;
2694 }
2695 
2696 enum {
2697   ft_default,
2698   ft_different_class,
2699   ft_parameter_arity,
2700   ft_parameter_mismatch,
2701   ft_return_type,
2702   ft_qualifer_mismatch,
2703   ft_noexcept
2704 };
2705 
2706 /// Attempts to get the FunctionProtoType from a Type. Handles
2707 /// MemberFunctionPointers properly.
2708 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2709   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2710     return FPT;
2711 
2712   if (auto *MPT = FromType->getAs<MemberPointerType>())
2713     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2714 
2715   return nullptr;
2716 }
2717 
2718 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2719 /// function types.  Catches different number of parameter, mismatch in
2720 /// parameter types, and different return types.
2721 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2722                                       QualType FromType, QualType ToType) {
2723   // If either type is not valid, include no extra info.
2724   if (FromType.isNull() || ToType.isNull()) {
2725     PDiag << ft_default;
2726     return;
2727   }
2728 
2729   // Get the function type from the pointers.
2730   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2731     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2732                             *ToMember = ToType->getAs<MemberPointerType>();
2733     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2734       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2735             << QualType(FromMember->getClass(), 0);
2736       return;
2737     }
2738     FromType = FromMember->getPointeeType();
2739     ToType = ToMember->getPointeeType();
2740   }
2741 
2742   if (FromType->isPointerType())
2743     FromType = FromType->getPointeeType();
2744   if (ToType->isPointerType())
2745     ToType = ToType->getPointeeType();
2746 
2747   // Remove references.
2748   FromType = FromType.getNonReferenceType();
2749   ToType = ToType.getNonReferenceType();
2750 
2751   // Don't print extra info for non-specialized template functions.
2752   if (FromType->isInstantiationDependentType() &&
2753       !FromType->getAs<TemplateSpecializationType>()) {
2754     PDiag << ft_default;
2755     return;
2756   }
2757 
2758   // No extra info for same types.
2759   if (Context.hasSameType(FromType, ToType)) {
2760     PDiag << ft_default;
2761     return;
2762   }
2763 
2764   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2765                           *ToFunction = tryGetFunctionProtoType(ToType);
2766 
2767   // Both types need to be function types.
2768   if (!FromFunction || !ToFunction) {
2769     PDiag << ft_default;
2770     return;
2771   }
2772 
2773   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2774     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2775           << FromFunction->getNumParams();
2776     return;
2777   }
2778 
2779   // Handle different parameter types.
2780   unsigned ArgPos;
2781   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2782     PDiag << ft_parameter_mismatch << ArgPos + 1
2783           << ToFunction->getParamType(ArgPos)
2784           << FromFunction->getParamType(ArgPos);
2785     return;
2786   }
2787 
2788   // Handle different return type.
2789   if (!Context.hasSameType(FromFunction->getReturnType(),
2790                            ToFunction->getReturnType())) {
2791     PDiag << ft_return_type << ToFunction->getReturnType()
2792           << FromFunction->getReturnType();
2793     return;
2794   }
2795 
2796   unsigned FromQuals = FromFunction->getTypeQuals(),
2797            ToQuals = ToFunction->getTypeQuals();
2798   if (FromQuals != ToQuals) {
2799     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2800     return;
2801   }
2802 
2803   // Handle exception specification differences on canonical type (in C++17
2804   // onwards).
2805   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2806           ->isNothrow(Context) !=
2807       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2808           ->isNothrow(Context)) {
2809     PDiag << ft_noexcept;
2810     return;
2811   }
2812 
2813   // Unable to find a difference, so add no extra info.
2814   PDiag << ft_default;
2815 }
2816 
2817 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2818 /// for equality of their argument types. Caller has already checked that
2819 /// they have same number of arguments.  If the parameters are different,
2820 /// ArgPos will have the parameter index of the first different parameter.
2821 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2822                                       const FunctionProtoType *NewType,
2823                                       unsigned *ArgPos) {
2824   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2825                                               N = NewType->param_type_begin(),
2826                                               E = OldType->param_type_end();
2827        O && (O != E); ++O, ++N) {
2828     if (!Context.hasSameType(O->getUnqualifiedType(),
2829                              N->getUnqualifiedType())) {
2830       if (ArgPos)
2831         *ArgPos = O - OldType->param_type_begin();
2832       return false;
2833     }
2834   }
2835   return true;
2836 }
2837 
2838 /// CheckPointerConversion - Check the pointer conversion from the
2839 /// expression From to the type ToType. This routine checks for
2840 /// ambiguous or inaccessible derived-to-base pointer
2841 /// conversions for which IsPointerConversion has already returned
2842 /// true. It returns true and produces a diagnostic if there was an
2843 /// error, or returns false otherwise.
2844 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2845                                   CastKind &Kind,
2846                                   CXXCastPath& BasePath,
2847                                   bool IgnoreBaseAccess,
2848                                   bool Diagnose) {
2849   QualType FromType = From->getType();
2850   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2851 
2852   Kind = CK_BitCast;
2853 
2854   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2855       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2856           Expr::NPCK_ZeroExpression) {
2857     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2858       DiagRuntimeBehavior(From->getExprLoc(), From,
2859                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2860                             << ToType << From->getSourceRange());
2861     else if (!isUnevaluatedContext())
2862       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2863         << ToType << From->getSourceRange();
2864   }
2865   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2866     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2867       QualType FromPointeeType = FromPtrType->getPointeeType(),
2868                ToPointeeType   = ToPtrType->getPointeeType();
2869 
2870       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2871           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2872         // We must have a derived-to-base conversion. Check an
2873         // ambiguous or inaccessible conversion.
2874         unsigned InaccessibleID = 0;
2875         unsigned AmbigiousID = 0;
2876         if (Diagnose) {
2877           InaccessibleID = diag::err_upcast_to_inaccessible_base;
2878           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2879         }
2880         if (CheckDerivedToBaseConversion(
2881                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2882                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2883                 &BasePath, IgnoreBaseAccess))
2884           return true;
2885 
2886         // The conversion was successful.
2887         Kind = CK_DerivedToBase;
2888       }
2889 
2890       if (Diagnose && !IsCStyleOrFunctionalCast &&
2891           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2892         assert(getLangOpts().MSVCCompat &&
2893                "this should only be possible with MSVCCompat!");
2894         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2895             << From->getSourceRange();
2896       }
2897     }
2898   } else if (const ObjCObjectPointerType *ToPtrType =
2899                ToType->getAs<ObjCObjectPointerType>()) {
2900     if (const ObjCObjectPointerType *FromPtrType =
2901           FromType->getAs<ObjCObjectPointerType>()) {
2902       // Objective-C++ conversions are always okay.
2903       // FIXME: We should have a different class of conversions for the
2904       // Objective-C++ implicit conversions.
2905       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2906         return false;
2907     } else if (FromType->isBlockPointerType()) {
2908       Kind = CK_BlockPointerToObjCPointerCast;
2909     } else {
2910       Kind = CK_CPointerToObjCPointerCast;
2911     }
2912   } else if (ToType->isBlockPointerType()) {
2913     if (!FromType->isBlockPointerType())
2914       Kind = CK_AnyPointerToBlockPointerCast;
2915   }
2916 
2917   // We shouldn't fall into this case unless it's valid for other
2918   // reasons.
2919   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2920     Kind = CK_NullToPointer;
2921 
2922   return false;
2923 }
2924 
2925 /// IsMemberPointerConversion - Determines whether the conversion of the
2926 /// expression From, which has the (possibly adjusted) type FromType, can be
2927 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2928 /// If so, returns true and places the converted type (that might differ from
2929 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2930 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2931                                      QualType ToType,
2932                                      bool InOverloadResolution,
2933                                      QualType &ConvertedType) {
2934   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2935   if (!ToTypePtr)
2936     return false;
2937 
2938   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2939   if (From->isNullPointerConstant(Context,
2940                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2941                                         : Expr::NPC_ValueDependentIsNull)) {
2942     ConvertedType = ToType;
2943     return true;
2944   }
2945 
2946   // Otherwise, both types have to be member pointers.
2947   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2948   if (!FromTypePtr)
2949     return false;
2950 
2951   // A pointer to member of B can be converted to a pointer to member of D,
2952   // where D is derived from B (C++ 4.11p2).
2953   QualType FromClass(FromTypePtr->getClass(), 0);
2954   QualType ToClass(ToTypePtr->getClass(), 0);
2955 
2956   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2957       IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2958     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2959                                                  ToClass.getTypePtr());
2960     return true;
2961   }
2962 
2963   return false;
2964 }
2965 
2966 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2967 /// expression From to the type ToType. This routine checks for ambiguous or
2968 /// virtual or inaccessible base-to-derived member pointer conversions
2969 /// for which IsMemberPointerConversion has already returned true. It returns
2970 /// true and produces a diagnostic if there was an error, or returns false
2971 /// otherwise.
2972 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2973                                         CastKind &Kind,
2974                                         CXXCastPath &BasePath,
2975                                         bool IgnoreBaseAccess) {
2976   QualType FromType = From->getType();
2977   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2978   if (!FromPtrType) {
2979     // This must be a null pointer to member pointer conversion
2980     assert(From->isNullPointerConstant(Context,
2981                                        Expr::NPC_ValueDependentIsNull) &&
2982            "Expr must be null pointer constant!");
2983     Kind = CK_NullToMemberPointer;
2984     return false;
2985   }
2986 
2987   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2988   assert(ToPtrType && "No member pointer cast has a target type "
2989                       "that is not a member pointer.");
2990 
2991   QualType FromClass = QualType(FromPtrType->getClass(), 0);
2992   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2993 
2994   // FIXME: What about dependent types?
2995   assert(FromClass->isRecordType() && "Pointer into non-class.");
2996   assert(ToClass->isRecordType() && "Pointer into non-class.");
2997 
2998   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2999                      /*DetectVirtual=*/true);
3000   bool DerivationOkay =
3001       IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
3002   assert(DerivationOkay &&
3003          "Should not have been called if derivation isn't OK.");
3004   (void)DerivationOkay;
3005 
3006   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3007                                   getUnqualifiedType())) {
3008     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3009     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3010       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3011     return true;
3012   }
3013 
3014   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3015     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3016       << FromClass << ToClass << QualType(VBase, 0)
3017       << From->getSourceRange();
3018     return true;
3019   }
3020 
3021   if (!IgnoreBaseAccess)
3022     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3023                          Paths.front(),
3024                          diag::err_downcast_from_inaccessible_base);
3025 
3026   // Must be a base to derived member conversion.
3027   BuildBasePathArray(Paths, BasePath);
3028   Kind = CK_BaseToDerivedMemberPointer;
3029   return false;
3030 }
3031 
3032 /// Determine whether the lifetime conversion between the two given
3033 /// qualifiers sets is nontrivial.
3034 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3035                                                Qualifiers ToQuals) {
3036   // Converting anything to const __unsafe_unretained is trivial.
3037   if (ToQuals.hasConst() &&
3038       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3039     return false;
3040 
3041   return true;
3042 }
3043 
3044 /// IsQualificationConversion - Determines whether the conversion from
3045 /// an rvalue of type FromType to ToType is a qualification conversion
3046 /// (C++ 4.4).
3047 ///
3048 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3049 /// when the qualification conversion involves a change in the Objective-C
3050 /// object lifetime.
3051 bool
3052 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3053                                 bool CStyle, bool &ObjCLifetimeConversion) {
3054   FromType = Context.getCanonicalType(FromType);
3055   ToType = Context.getCanonicalType(ToType);
3056   ObjCLifetimeConversion = false;
3057 
3058   // If FromType and ToType are the same type, this is not a
3059   // qualification conversion.
3060   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3061     return false;
3062 
3063   // (C++ 4.4p4):
3064   //   A conversion can add cv-qualifiers at levels other than the first
3065   //   in multi-level pointers, subject to the following rules: [...]
3066   bool PreviousToQualsIncludeConst = true;
3067   bool UnwrappedAnyPointer = false;
3068   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
3069     // Within each iteration of the loop, we check the qualifiers to
3070     // determine if this still looks like a qualification
3071     // conversion. Then, if all is well, we unwrap one more level of
3072     // pointers or pointers-to-members and do it all again
3073     // until there are no more pointers or pointers-to-members left to
3074     // unwrap.
3075     UnwrappedAnyPointer = true;
3076 
3077     Qualifiers FromQuals = FromType.getQualifiers();
3078     Qualifiers ToQuals = ToType.getQualifiers();
3079 
3080     // Ignore __unaligned qualifier if this type is void.
3081     if (ToType.getUnqualifiedType()->isVoidType())
3082       FromQuals.removeUnaligned();
3083 
3084     // Objective-C ARC:
3085     //   Check Objective-C lifetime conversions.
3086     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3087         UnwrappedAnyPointer) {
3088       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3089         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3090           ObjCLifetimeConversion = true;
3091         FromQuals.removeObjCLifetime();
3092         ToQuals.removeObjCLifetime();
3093       } else {
3094         // Qualification conversions cannot cast between different
3095         // Objective-C lifetime qualifiers.
3096         return false;
3097       }
3098     }
3099 
3100     // Allow addition/removal of GC attributes but not changing GC attributes.
3101     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3102         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3103       FromQuals.removeObjCGCAttr();
3104       ToQuals.removeObjCGCAttr();
3105     }
3106 
3107     //   -- for every j > 0, if const is in cv 1,j then const is in cv
3108     //      2,j, and similarly for volatile.
3109     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3110       return false;
3111 
3112     //   -- if the cv 1,j and cv 2,j are different, then const is in
3113     //      every cv for 0 < k < j.
3114     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3115         && !PreviousToQualsIncludeConst)
3116       return false;
3117 
3118     // Keep track of whether all prior cv-qualifiers in the "to" type
3119     // include const.
3120     PreviousToQualsIncludeConst
3121       = PreviousToQualsIncludeConst && ToQuals.hasConst();
3122   }
3123 
3124   // We are left with FromType and ToType being the pointee types
3125   // after unwrapping the original FromType and ToType the same number
3126   // of types. If we unwrapped any pointers, and if FromType and
3127   // ToType have the same unqualified type (since we checked
3128   // qualifiers above), then this is a qualification conversion.
3129   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3130 }
3131 
3132 /// \brief - Determine whether this is a conversion from a scalar type to an
3133 /// atomic type.
3134 ///
3135 /// If successful, updates \c SCS's second and third steps in the conversion
3136 /// sequence to finish the conversion.
3137 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3138                                 bool InOverloadResolution,
3139                                 StandardConversionSequence &SCS,
3140                                 bool CStyle) {
3141   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3142   if (!ToAtomic)
3143     return false;
3144 
3145   StandardConversionSequence InnerSCS;
3146   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3147                             InOverloadResolution, InnerSCS,
3148                             CStyle, /*AllowObjCWritebackConversion=*/false))
3149     return false;
3150 
3151   SCS.Second = InnerSCS.Second;
3152   SCS.setToType(1, InnerSCS.getToType(1));
3153   SCS.Third = InnerSCS.Third;
3154   SCS.QualificationIncludesObjCLifetime
3155     = InnerSCS.QualificationIncludesObjCLifetime;
3156   SCS.setToType(2, InnerSCS.getToType(2));
3157   return true;
3158 }
3159 
3160 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3161                                               CXXConstructorDecl *Constructor,
3162                                               QualType Type) {
3163   const FunctionProtoType *CtorType =
3164       Constructor->getType()->getAs<FunctionProtoType>();
3165   if (CtorType->getNumParams() > 0) {
3166     QualType FirstArg = CtorType->getParamType(0);
3167     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3168       return true;
3169   }
3170   return false;
3171 }
3172 
3173 static OverloadingResult
3174 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3175                                        CXXRecordDecl *To,
3176                                        UserDefinedConversionSequence &User,
3177                                        OverloadCandidateSet &CandidateSet,
3178                                        bool AllowExplicit) {
3179   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3180   for (auto *D : S.LookupConstructors(To)) {
3181     auto Info = getConstructorInfo(D);
3182     if (!Info)
3183       continue;
3184 
3185     bool Usable = !Info.Constructor->isInvalidDecl() &&
3186                   S.isInitListConstructor(Info.Constructor) &&
3187                   (AllowExplicit || !Info.Constructor->isExplicit());
3188     if (Usable) {
3189       // If the first argument is (a reference to) the target type,
3190       // suppress conversions.
3191       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3192           S.Context, Info.Constructor, ToType);
3193       if (Info.ConstructorTmpl)
3194         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3195                                        /*ExplicitArgs*/ nullptr, From,
3196                                        CandidateSet, SuppressUserConversions);
3197       else
3198         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3199                                CandidateSet, SuppressUserConversions);
3200     }
3201   }
3202 
3203   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3204 
3205   OverloadCandidateSet::iterator Best;
3206   switch (auto Result =
3207             CandidateSet.BestViableFunction(S, From->getLocStart(),
3208                                             Best)) {
3209   case OR_Deleted:
3210   case OR_Success: {
3211     // Record the standard conversion we used and the conversion function.
3212     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3213     QualType ThisType = Constructor->getThisType(S.Context);
3214     // Initializer lists don't have conversions as such.
3215     User.Before.setAsIdentityConversion();
3216     User.HadMultipleCandidates = HadMultipleCandidates;
3217     User.ConversionFunction = Constructor;
3218     User.FoundConversionFunction = Best->FoundDecl;
3219     User.After.setAsIdentityConversion();
3220     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3221     User.After.setAllToTypes(ToType);
3222     return Result;
3223   }
3224 
3225   case OR_No_Viable_Function:
3226     return OR_No_Viable_Function;
3227   case OR_Ambiguous:
3228     return OR_Ambiguous;
3229   }
3230 
3231   llvm_unreachable("Invalid OverloadResult!");
3232 }
3233 
3234 /// Determines whether there is a user-defined conversion sequence
3235 /// (C++ [over.ics.user]) that converts expression From to the type
3236 /// ToType. If such a conversion exists, User will contain the
3237 /// user-defined conversion sequence that performs such a conversion
3238 /// and this routine will return true. Otherwise, this routine returns
3239 /// false and User is unspecified.
3240 ///
3241 /// \param AllowExplicit  true if the conversion should consider C++0x
3242 /// "explicit" conversion functions as well as non-explicit conversion
3243 /// functions (C++0x [class.conv.fct]p2).
3244 ///
3245 /// \param AllowObjCConversionOnExplicit true if the conversion should
3246 /// allow an extra Objective-C pointer conversion on uses of explicit
3247 /// constructors. Requires \c AllowExplicit to also be set.
3248 static OverloadingResult
3249 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3250                         UserDefinedConversionSequence &User,
3251                         OverloadCandidateSet &CandidateSet,
3252                         bool AllowExplicit,
3253                         bool AllowObjCConversionOnExplicit) {
3254   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3255   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3256 
3257   // Whether we will only visit constructors.
3258   bool ConstructorsOnly = false;
3259 
3260   // If the type we are conversion to is a class type, enumerate its
3261   // constructors.
3262   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3263     // C++ [over.match.ctor]p1:
3264     //   When objects of class type are direct-initialized (8.5), or
3265     //   copy-initialized from an expression of the same or a
3266     //   derived class type (8.5), overload resolution selects the
3267     //   constructor. [...] For copy-initialization, the candidate
3268     //   functions are all the converting constructors (12.3.1) of
3269     //   that class. The argument list is the expression-list within
3270     //   the parentheses of the initializer.
3271     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3272         (From->getType()->getAs<RecordType>() &&
3273          S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3274       ConstructorsOnly = true;
3275 
3276     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3277       // We're not going to find any constructors.
3278     } else if (CXXRecordDecl *ToRecordDecl
3279                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3280 
3281       Expr **Args = &From;
3282       unsigned NumArgs = 1;
3283       bool ListInitializing = false;
3284       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3285         // But first, see if there is an init-list-constructor that will work.
3286         OverloadingResult Result = IsInitializerListConstructorConversion(
3287             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3288         if (Result != OR_No_Viable_Function)
3289           return Result;
3290         // Never mind.
3291         CandidateSet.clear(
3292             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3293 
3294         // If we're list-initializing, we pass the individual elements as
3295         // arguments, not the entire list.
3296         Args = InitList->getInits();
3297         NumArgs = InitList->getNumInits();
3298         ListInitializing = true;
3299       }
3300 
3301       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3302         auto Info = getConstructorInfo(D);
3303         if (!Info)
3304           continue;
3305 
3306         bool Usable = !Info.Constructor->isInvalidDecl();
3307         if (ListInitializing)
3308           Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3309         else
3310           Usable = Usable &&
3311                    Info.Constructor->isConvertingConstructor(AllowExplicit);
3312         if (Usable) {
3313           bool SuppressUserConversions = !ConstructorsOnly;
3314           if (SuppressUserConversions && ListInitializing) {
3315             SuppressUserConversions = false;
3316             if (NumArgs == 1) {
3317               // If the first argument is (a reference to) the target type,
3318               // suppress conversions.
3319               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3320                   S.Context, Info.Constructor, ToType);
3321             }
3322           }
3323           if (Info.ConstructorTmpl)
3324             S.AddTemplateOverloadCandidate(
3325                 Info.ConstructorTmpl, Info.FoundDecl,
3326                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3327                 CandidateSet, SuppressUserConversions);
3328           else
3329             // Allow one user-defined conversion when user specifies a
3330             // From->ToType conversion via an static cast (c-style, etc).
3331             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3332                                    llvm::makeArrayRef(Args, NumArgs),
3333                                    CandidateSet, SuppressUserConversions);
3334         }
3335       }
3336     }
3337   }
3338 
3339   // Enumerate conversion functions, if we're allowed to.
3340   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3341   } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3342     // No conversion functions from incomplete types.
3343   } else if (const RecordType *FromRecordType
3344                                    = From->getType()->getAs<RecordType>()) {
3345     if (CXXRecordDecl *FromRecordDecl
3346          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3347       // Add all of the conversion functions as candidates.
3348       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3349       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3350         DeclAccessPair FoundDecl = I.getPair();
3351         NamedDecl *D = FoundDecl.getDecl();
3352         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3353         if (isa<UsingShadowDecl>(D))
3354           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3355 
3356         CXXConversionDecl *Conv;
3357         FunctionTemplateDecl *ConvTemplate;
3358         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3359           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3360         else
3361           Conv = cast<CXXConversionDecl>(D);
3362 
3363         if (AllowExplicit || !Conv->isExplicit()) {
3364           if (ConvTemplate)
3365             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3366                                              ActingContext, From, ToType,
3367                                              CandidateSet,
3368                                              AllowObjCConversionOnExplicit);
3369           else
3370             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3371                                      From, ToType, CandidateSet,
3372                                      AllowObjCConversionOnExplicit);
3373         }
3374       }
3375     }
3376   }
3377 
3378   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3379 
3380   OverloadCandidateSet::iterator Best;
3381   switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3382                                                         Best)) {
3383   case OR_Success:
3384   case OR_Deleted:
3385     // Record the standard conversion we used and the conversion function.
3386     if (CXXConstructorDecl *Constructor
3387           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3388       // C++ [over.ics.user]p1:
3389       //   If the user-defined conversion is specified by a
3390       //   constructor (12.3.1), the initial standard conversion
3391       //   sequence converts the source type to the type required by
3392       //   the argument of the constructor.
3393       //
3394       QualType ThisType = Constructor->getThisType(S.Context);
3395       if (isa<InitListExpr>(From)) {
3396         // Initializer lists don't have conversions as such.
3397         User.Before.setAsIdentityConversion();
3398       } else {
3399         if (Best->Conversions[0].isEllipsis())
3400           User.EllipsisConversion = true;
3401         else {
3402           User.Before = Best->Conversions[0].Standard;
3403           User.EllipsisConversion = false;
3404         }
3405       }
3406       User.HadMultipleCandidates = HadMultipleCandidates;
3407       User.ConversionFunction = Constructor;
3408       User.FoundConversionFunction = Best->FoundDecl;
3409       User.After.setAsIdentityConversion();
3410       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3411       User.After.setAllToTypes(ToType);
3412       return Result;
3413     }
3414     if (CXXConversionDecl *Conversion
3415                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3416       // C++ [over.ics.user]p1:
3417       //
3418       //   [...] If the user-defined conversion is specified by a
3419       //   conversion function (12.3.2), the initial standard
3420       //   conversion sequence converts the source type to the
3421       //   implicit object parameter of the conversion function.
3422       User.Before = Best->Conversions[0].Standard;
3423       User.HadMultipleCandidates = HadMultipleCandidates;
3424       User.ConversionFunction = Conversion;
3425       User.FoundConversionFunction = Best->FoundDecl;
3426       User.EllipsisConversion = false;
3427 
3428       // C++ [over.ics.user]p2:
3429       //   The second standard conversion sequence converts the
3430       //   result of the user-defined conversion to the target type
3431       //   for the sequence. Since an implicit conversion sequence
3432       //   is an initialization, the special rules for
3433       //   initialization by user-defined conversion apply when
3434       //   selecting the best user-defined conversion for a
3435       //   user-defined conversion sequence (see 13.3.3 and
3436       //   13.3.3.1).
3437       User.After = Best->FinalConversion;
3438       return Result;
3439     }
3440     llvm_unreachable("Not a constructor or conversion function?");
3441 
3442   case OR_No_Viable_Function:
3443     return OR_No_Viable_Function;
3444 
3445   case OR_Ambiguous:
3446     return OR_Ambiguous;
3447   }
3448 
3449   llvm_unreachable("Invalid OverloadResult!");
3450 }
3451 
3452 bool
3453 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3454   ImplicitConversionSequence ICS;
3455   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3456                                     OverloadCandidateSet::CSK_Normal);
3457   OverloadingResult OvResult =
3458     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3459                             CandidateSet, false, false);
3460   if (OvResult == OR_Ambiguous)
3461     Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3462         << From->getType() << ToType << From->getSourceRange();
3463   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3464     if (!RequireCompleteType(From->getLocStart(), ToType,
3465                              diag::err_typecheck_nonviable_condition_incomplete,
3466                              From->getType(), From->getSourceRange()))
3467       Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3468           << false << From->getType() << From->getSourceRange() << ToType;
3469   } else
3470     return false;
3471   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3472   return true;
3473 }
3474 
3475 /// \brief Compare the user-defined conversion functions or constructors
3476 /// of two user-defined conversion sequences to determine whether any ordering
3477 /// is possible.
3478 static ImplicitConversionSequence::CompareKind
3479 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3480                            FunctionDecl *Function2) {
3481   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3482     return ImplicitConversionSequence::Indistinguishable;
3483 
3484   // Objective-C++:
3485   //   If both conversion functions are implicitly-declared conversions from
3486   //   a lambda closure type to a function pointer and a block pointer,
3487   //   respectively, always prefer the conversion to a function pointer,
3488   //   because the function pointer is more lightweight and is more likely
3489   //   to keep code working.
3490   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3491   if (!Conv1)
3492     return ImplicitConversionSequence::Indistinguishable;
3493 
3494   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3495   if (!Conv2)
3496     return ImplicitConversionSequence::Indistinguishable;
3497 
3498   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3499     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3500     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3501     if (Block1 != Block2)
3502       return Block1 ? ImplicitConversionSequence::Worse
3503                     : ImplicitConversionSequence::Better;
3504   }
3505 
3506   return ImplicitConversionSequence::Indistinguishable;
3507 }
3508 
3509 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3510     const ImplicitConversionSequence &ICS) {
3511   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3512          (ICS.isUserDefined() &&
3513           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3514 }
3515 
3516 /// CompareImplicitConversionSequences - Compare two implicit
3517 /// conversion sequences to determine whether one is better than the
3518 /// other or if they are indistinguishable (C++ 13.3.3.2).
3519 static ImplicitConversionSequence::CompareKind
3520 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3521                                    const ImplicitConversionSequence& ICS1,
3522                                    const ImplicitConversionSequence& ICS2)
3523 {
3524   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3525   // conversion sequences (as defined in 13.3.3.1)
3526   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3527   //      conversion sequence than a user-defined conversion sequence or
3528   //      an ellipsis conversion sequence, and
3529   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3530   //      conversion sequence than an ellipsis conversion sequence
3531   //      (13.3.3.1.3).
3532   //
3533   // C++0x [over.best.ics]p10:
3534   //   For the purpose of ranking implicit conversion sequences as
3535   //   described in 13.3.3.2, the ambiguous conversion sequence is
3536   //   treated as a user-defined sequence that is indistinguishable
3537   //   from any other user-defined conversion sequence.
3538 
3539   // String literal to 'char *' conversion has been deprecated in C++03. It has
3540   // been removed from C++11. We still accept this conversion, if it happens at
3541   // the best viable function. Otherwise, this conversion is considered worse
3542   // than ellipsis conversion. Consider this as an extension; this is not in the
3543   // standard. For example:
3544   //
3545   // int &f(...);    // #1
3546   // void f(char*);  // #2
3547   // void g() { int &r = f("foo"); }
3548   //
3549   // In C++03, we pick #2 as the best viable function.
3550   // In C++11, we pick #1 as the best viable function, because ellipsis
3551   // conversion is better than string-literal to char* conversion (since there
3552   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3553   // convert arguments, #2 would be the best viable function in C++11.
3554   // If the best viable function has this conversion, a warning will be issued
3555   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3556 
3557   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3558       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3559       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3560     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3561                ? ImplicitConversionSequence::Worse
3562                : ImplicitConversionSequence::Better;
3563 
3564   if (ICS1.getKindRank() < ICS2.getKindRank())
3565     return ImplicitConversionSequence::Better;
3566   if (ICS2.getKindRank() < ICS1.getKindRank())
3567     return ImplicitConversionSequence::Worse;
3568 
3569   // The following checks require both conversion sequences to be of
3570   // the same kind.
3571   if (ICS1.getKind() != ICS2.getKind())
3572     return ImplicitConversionSequence::Indistinguishable;
3573 
3574   ImplicitConversionSequence::CompareKind Result =
3575       ImplicitConversionSequence::Indistinguishable;
3576 
3577   // Two implicit conversion sequences of the same form are
3578   // indistinguishable conversion sequences unless one of the
3579   // following rules apply: (C++ 13.3.3.2p3):
3580 
3581   // List-initialization sequence L1 is a better conversion sequence than
3582   // list-initialization sequence L2 if:
3583   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3584   //   if not that,
3585   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3586   //   and N1 is smaller than N2.,
3587   // even if one of the other rules in this paragraph would otherwise apply.
3588   if (!ICS1.isBad()) {
3589     if (ICS1.isStdInitializerListElement() &&
3590         !ICS2.isStdInitializerListElement())
3591       return ImplicitConversionSequence::Better;
3592     if (!ICS1.isStdInitializerListElement() &&
3593         ICS2.isStdInitializerListElement())
3594       return ImplicitConversionSequence::Worse;
3595   }
3596 
3597   if (ICS1.isStandard())
3598     // Standard conversion sequence S1 is a better conversion sequence than
3599     // standard conversion sequence S2 if [...]
3600     Result = CompareStandardConversionSequences(S, Loc,
3601                                                 ICS1.Standard, ICS2.Standard);
3602   else if (ICS1.isUserDefined()) {
3603     // User-defined conversion sequence U1 is a better conversion
3604     // sequence than another user-defined conversion sequence U2 if
3605     // they contain the same user-defined conversion function or
3606     // constructor and if the second standard conversion sequence of
3607     // U1 is better than the second standard conversion sequence of
3608     // U2 (C++ 13.3.3.2p3).
3609     if (ICS1.UserDefined.ConversionFunction ==
3610           ICS2.UserDefined.ConversionFunction)
3611       Result = CompareStandardConversionSequences(S, Loc,
3612                                                   ICS1.UserDefined.After,
3613                                                   ICS2.UserDefined.After);
3614     else
3615       Result = compareConversionFunctions(S,
3616                                           ICS1.UserDefined.ConversionFunction,
3617                                           ICS2.UserDefined.ConversionFunction);
3618   }
3619 
3620   return Result;
3621 }
3622 
3623 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3624   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3625     Qualifiers Quals;
3626     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3627     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3628   }
3629 
3630   return Context.hasSameUnqualifiedType(T1, T2);
3631 }
3632 
3633 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3634 // determine if one is a proper subset of the other.
3635 static ImplicitConversionSequence::CompareKind
3636 compareStandardConversionSubsets(ASTContext &Context,
3637                                  const StandardConversionSequence& SCS1,
3638                                  const StandardConversionSequence& SCS2) {
3639   ImplicitConversionSequence::CompareKind Result
3640     = ImplicitConversionSequence::Indistinguishable;
3641 
3642   // the identity conversion sequence is considered to be a subsequence of
3643   // any non-identity conversion sequence
3644   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3645     return ImplicitConversionSequence::Better;
3646   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3647     return ImplicitConversionSequence::Worse;
3648 
3649   if (SCS1.Second != SCS2.Second) {
3650     if (SCS1.Second == ICK_Identity)
3651       Result = ImplicitConversionSequence::Better;
3652     else if (SCS2.Second == ICK_Identity)
3653       Result = ImplicitConversionSequence::Worse;
3654     else
3655       return ImplicitConversionSequence::Indistinguishable;
3656   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3657     return ImplicitConversionSequence::Indistinguishable;
3658 
3659   if (SCS1.Third == SCS2.Third) {
3660     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3661                              : ImplicitConversionSequence::Indistinguishable;
3662   }
3663 
3664   if (SCS1.Third == ICK_Identity)
3665     return Result == ImplicitConversionSequence::Worse
3666              ? ImplicitConversionSequence::Indistinguishable
3667              : ImplicitConversionSequence::Better;
3668 
3669   if (SCS2.Third == ICK_Identity)
3670     return Result == ImplicitConversionSequence::Better
3671              ? ImplicitConversionSequence::Indistinguishable
3672              : ImplicitConversionSequence::Worse;
3673 
3674   return ImplicitConversionSequence::Indistinguishable;
3675 }
3676 
3677 /// \brief Determine whether one of the given reference bindings is better
3678 /// than the other based on what kind of bindings they are.
3679 static bool
3680 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3681                              const StandardConversionSequence &SCS2) {
3682   // C++0x [over.ics.rank]p3b4:
3683   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3684   //      implicit object parameter of a non-static member function declared
3685   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3686   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3687   //      lvalue reference to a function lvalue and S2 binds an rvalue
3688   //      reference*.
3689   //
3690   // FIXME: Rvalue references. We're going rogue with the above edits,
3691   // because the semantics in the current C++0x working paper (N3225 at the
3692   // time of this writing) break the standard definition of std::forward
3693   // and std::reference_wrapper when dealing with references to functions.
3694   // Proposed wording changes submitted to CWG for consideration.
3695   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3696       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3697     return false;
3698 
3699   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3700           SCS2.IsLvalueReference) ||
3701          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3702           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3703 }
3704 
3705 /// CompareStandardConversionSequences - Compare two standard
3706 /// conversion sequences to determine whether one is better than the
3707 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3708 static ImplicitConversionSequence::CompareKind
3709 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3710                                    const StandardConversionSequence& SCS1,
3711                                    const StandardConversionSequence& SCS2)
3712 {
3713   // Standard conversion sequence S1 is a better conversion sequence
3714   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3715 
3716   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3717   //     sequences in the canonical form defined by 13.3.3.1.1,
3718   //     excluding any Lvalue Transformation; the identity conversion
3719   //     sequence is considered to be a subsequence of any
3720   //     non-identity conversion sequence) or, if not that,
3721   if (ImplicitConversionSequence::CompareKind CK
3722         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3723     return CK;
3724 
3725   //  -- the rank of S1 is better than the rank of S2 (by the rules
3726   //     defined below), or, if not that,
3727   ImplicitConversionRank Rank1 = SCS1.getRank();
3728   ImplicitConversionRank Rank2 = SCS2.getRank();
3729   if (Rank1 < Rank2)
3730     return ImplicitConversionSequence::Better;
3731   else if (Rank2 < Rank1)
3732     return ImplicitConversionSequence::Worse;
3733 
3734   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3735   // are indistinguishable unless one of the following rules
3736   // applies:
3737 
3738   //   A conversion that is not a conversion of a pointer, or
3739   //   pointer to member, to bool is better than another conversion
3740   //   that is such a conversion.
3741   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3742     return SCS2.isPointerConversionToBool()
3743              ? ImplicitConversionSequence::Better
3744              : ImplicitConversionSequence::Worse;
3745 
3746   // C++ [over.ics.rank]p4b2:
3747   //
3748   //   If class B is derived directly or indirectly from class A,
3749   //   conversion of B* to A* is better than conversion of B* to
3750   //   void*, and conversion of A* to void* is better than conversion
3751   //   of B* to void*.
3752   bool SCS1ConvertsToVoid
3753     = SCS1.isPointerConversionToVoidPointer(S.Context);
3754   bool SCS2ConvertsToVoid
3755     = SCS2.isPointerConversionToVoidPointer(S.Context);
3756   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3757     // Exactly one of the conversion sequences is a conversion to
3758     // a void pointer; it's the worse conversion.
3759     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3760                               : ImplicitConversionSequence::Worse;
3761   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3762     // Neither conversion sequence converts to a void pointer; compare
3763     // their derived-to-base conversions.
3764     if (ImplicitConversionSequence::CompareKind DerivedCK
3765           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3766       return DerivedCK;
3767   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3768              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3769     // Both conversion sequences are conversions to void
3770     // pointers. Compare the source types to determine if there's an
3771     // inheritance relationship in their sources.
3772     QualType FromType1 = SCS1.getFromType();
3773     QualType FromType2 = SCS2.getFromType();
3774 
3775     // Adjust the types we're converting from via the array-to-pointer
3776     // conversion, if we need to.
3777     if (SCS1.First == ICK_Array_To_Pointer)
3778       FromType1 = S.Context.getArrayDecayedType(FromType1);
3779     if (SCS2.First == ICK_Array_To_Pointer)
3780       FromType2 = S.Context.getArrayDecayedType(FromType2);
3781 
3782     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3783     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3784 
3785     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3786       return ImplicitConversionSequence::Better;
3787     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3788       return ImplicitConversionSequence::Worse;
3789 
3790     // Objective-C++: If one interface is more specific than the
3791     // other, it is the better one.
3792     const ObjCObjectPointerType* FromObjCPtr1
3793       = FromType1->getAs<ObjCObjectPointerType>();
3794     const ObjCObjectPointerType* FromObjCPtr2
3795       = FromType2->getAs<ObjCObjectPointerType>();
3796     if (FromObjCPtr1 && FromObjCPtr2) {
3797       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3798                                                           FromObjCPtr2);
3799       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3800                                                            FromObjCPtr1);
3801       if (AssignLeft != AssignRight) {
3802         return AssignLeft? ImplicitConversionSequence::Better
3803                          : ImplicitConversionSequence::Worse;
3804       }
3805     }
3806   }
3807 
3808   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3809   // bullet 3).
3810   if (ImplicitConversionSequence::CompareKind QualCK
3811         = CompareQualificationConversions(S, SCS1, SCS2))
3812     return QualCK;
3813 
3814   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3815     // Check for a better reference binding based on the kind of bindings.
3816     if (isBetterReferenceBindingKind(SCS1, SCS2))
3817       return ImplicitConversionSequence::Better;
3818     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3819       return ImplicitConversionSequence::Worse;
3820 
3821     // C++ [over.ics.rank]p3b4:
3822     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3823     //      which the references refer are the same type except for
3824     //      top-level cv-qualifiers, and the type to which the reference
3825     //      initialized by S2 refers is more cv-qualified than the type
3826     //      to which the reference initialized by S1 refers.
3827     QualType T1 = SCS1.getToType(2);
3828     QualType T2 = SCS2.getToType(2);
3829     T1 = S.Context.getCanonicalType(T1);
3830     T2 = S.Context.getCanonicalType(T2);
3831     Qualifiers T1Quals, T2Quals;
3832     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3833     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3834     if (UnqualT1 == UnqualT2) {
3835       // Objective-C++ ARC: If the references refer to objects with different
3836       // lifetimes, prefer bindings that don't change lifetime.
3837       if (SCS1.ObjCLifetimeConversionBinding !=
3838                                           SCS2.ObjCLifetimeConversionBinding) {
3839         return SCS1.ObjCLifetimeConversionBinding
3840                                            ? ImplicitConversionSequence::Worse
3841                                            : ImplicitConversionSequence::Better;
3842       }
3843 
3844       // If the type is an array type, promote the element qualifiers to the
3845       // type for comparison.
3846       if (isa<ArrayType>(T1) && T1Quals)
3847         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3848       if (isa<ArrayType>(T2) && T2Quals)
3849         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3850       if (T2.isMoreQualifiedThan(T1))
3851         return ImplicitConversionSequence::Better;
3852       else if (T1.isMoreQualifiedThan(T2))
3853         return ImplicitConversionSequence::Worse;
3854     }
3855   }
3856 
3857   // In Microsoft mode, prefer an integral conversion to a
3858   // floating-to-integral conversion if the integral conversion
3859   // is between types of the same size.
3860   // For example:
3861   // void f(float);
3862   // void f(int);
3863   // int main {
3864   //    long a;
3865   //    f(a);
3866   // }
3867   // Here, MSVC will call f(int) instead of generating a compile error
3868   // as clang will do in standard mode.
3869   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3870       SCS2.Second == ICK_Floating_Integral &&
3871       S.Context.getTypeSize(SCS1.getFromType()) ==
3872           S.Context.getTypeSize(SCS1.getToType(2)))
3873     return ImplicitConversionSequence::Better;
3874 
3875   return ImplicitConversionSequence::Indistinguishable;
3876 }
3877 
3878 /// CompareQualificationConversions - Compares two standard conversion
3879 /// sequences to determine whether they can be ranked based on their
3880 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3881 static ImplicitConversionSequence::CompareKind
3882 CompareQualificationConversions(Sema &S,
3883                                 const StandardConversionSequence& SCS1,
3884                                 const StandardConversionSequence& SCS2) {
3885   // C++ 13.3.3.2p3:
3886   //  -- S1 and S2 differ only in their qualification conversion and
3887   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3888   //     cv-qualification signature of type T1 is a proper subset of
3889   //     the cv-qualification signature of type T2, and S1 is not the
3890   //     deprecated string literal array-to-pointer conversion (4.2).
3891   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3892       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3893     return ImplicitConversionSequence::Indistinguishable;
3894 
3895   // FIXME: the example in the standard doesn't use a qualification
3896   // conversion (!)
3897   QualType T1 = SCS1.getToType(2);
3898   QualType T2 = SCS2.getToType(2);
3899   T1 = S.Context.getCanonicalType(T1);
3900   T2 = S.Context.getCanonicalType(T2);
3901   Qualifiers T1Quals, T2Quals;
3902   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3903   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3904 
3905   // If the types are the same, we won't learn anything by unwrapped
3906   // them.
3907   if (UnqualT1 == UnqualT2)
3908     return ImplicitConversionSequence::Indistinguishable;
3909 
3910   // If the type is an array type, promote the element qualifiers to the type
3911   // for comparison.
3912   if (isa<ArrayType>(T1) && T1Quals)
3913     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3914   if (isa<ArrayType>(T2) && T2Quals)
3915     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3916 
3917   ImplicitConversionSequence::CompareKind Result
3918     = ImplicitConversionSequence::Indistinguishable;
3919 
3920   // Objective-C++ ARC:
3921   //   Prefer qualification conversions not involving a change in lifetime
3922   //   to qualification conversions that do not change lifetime.
3923   if (SCS1.QualificationIncludesObjCLifetime !=
3924                                       SCS2.QualificationIncludesObjCLifetime) {
3925     Result = SCS1.QualificationIncludesObjCLifetime
3926                ? ImplicitConversionSequence::Worse
3927                : ImplicitConversionSequence::Better;
3928   }
3929 
3930   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3931     // Within each iteration of the loop, we check the qualifiers to
3932     // determine if this still looks like a qualification
3933     // conversion. Then, if all is well, we unwrap one more level of
3934     // pointers or pointers-to-members and do it all again
3935     // until there are no more pointers or pointers-to-members left
3936     // to unwrap. This essentially mimics what
3937     // IsQualificationConversion does, but here we're checking for a
3938     // strict subset of qualifiers.
3939     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3940       // The qualifiers are the same, so this doesn't tell us anything
3941       // about how the sequences rank.
3942       ;
3943     else if (T2.isMoreQualifiedThan(T1)) {
3944       // T1 has fewer qualifiers, so it could be the better sequence.
3945       if (Result == ImplicitConversionSequence::Worse)
3946         // Neither has qualifiers that are a subset of the other's
3947         // qualifiers.
3948         return ImplicitConversionSequence::Indistinguishable;
3949 
3950       Result = ImplicitConversionSequence::Better;
3951     } else if (T1.isMoreQualifiedThan(T2)) {
3952       // T2 has fewer qualifiers, so it could be the better sequence.
3953       if (Result == ImplicitConversionSequence::Better)
3954         // Neither has qualifiers that are a subset of the other's
3955         // qualifiers.
3956         return ImplicitConversionSequence::Indistinguishable;
3957 
3958       Result = ImplicitConversionSequence::Worse;
3959     } else {
3960       // Qualifiers are disjoint.
3961       return ImplicitConversionSequence::Indistinguishable;
3962     }
3963 
3964     // If the types after this point are equivalent, we're done.
3965     if (S.Context.hasSameUnqualifiedType(T1, T2))
3966       break;
3967   }
3968 
3969   // Check that the winning standard conversion sequence isn't using
3970   // the deprecated string literal array to pointer conversion.
3971   switch (Result) {
3972   case ImplicitConversionSequence::Better:
3973     if (SCS1.DeprecatedStringLiteralToCharPtr)
3974       Result = ImplicitConversionSequence::Indistinguishable;
3975     break;
3976 
3977   case ImplicitConversionSequence::Indistinguishable:
3978     break;
3979 
3980   case ImplicitConversionSequence::Worse:
3981     if (SCS2.DeprecatedStringLiteralToCharPtr)
3982       Result = ImplicitConversionSequence::Indistinguishable;
3983     break;
3984   }
3985 
3986   return Result;
3987 }
3988 
3989 /// CompareDerivedToBaseConversions - Compares two standard conversion
3990 /// sequences to determine whether they can be ranked based on their
3991 /// various kinds of derived-to-base conversions (C++
3992 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
3993 /// conversions between Objective-C interface types.
3994 static ImplicitConversionSequence::CompareKind
3995 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
3996                                 const StandardConversionSequence& SCS1,
3997                                 const StandardConversionSequence& SCS2) {
3998   QualType FromType1 = SCS1.getFromType();
3999   QualType ToType1 = SCS1.getToType(1);
4000   QualType FromType2 = SCS2.getFromType();
4001   QualType ToType2 = SCS2.getToType(1);
4002 
4003   // Adjust the types we're converting from via the array-to-pointer
4004   // conversion, if we need to.
4005   if (SCS1.First == ICK_Array_To_Pointer)
4006     FromType1 = S.Context.getArrayDecayedType(FromType1);
4007   if (SCS2.First == ICK_Array_To_Pointer)
4008     FromType2 = S.Context.getArrayDecayedType(FromType2);
4009 
4010   // Canonicalize all of the types.
4011   FromType1 = S.Context.getCanonicalType(FromType1);
4012   ToType1 = S.Context.getCanonicalType(ToType1);
4013   FromType2 = S.Context.getCanonicalType(FromType2);
4014   ToType2 = S.Context.getCanonicalType(ToType2);
4015 
4016   // C++ [over.ics.rank]p4b3:
4017   //
4018   //   If class B is derived directly or indirectly from class A and
4019   //   class C is derived directly or indirectly from B,
4020   //
4021   // Compare based on pointer conversions.
4022   if (SCS1.Second == ICK_Pointer_Conversion &&
4023       SCS2.Second == ICK_Pointer_Conversion &&
4024       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4025       FromType1->isPointerType() && FromType2->isPointerType() &&
4026       ToType1->isPointerType() && ToType2->isPointerType()) {
4027     QualType FromPointee1
4028       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4029     QualType ToPointee1
4030       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4031     QualType FromPointee2
4032       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4033     QualType ToPointee2
4034       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4035 
4036     //   -- conversion of C* to B* is better than conversion of C* to A*,
4037     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4038       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4039         return ImplicitConversionSequence::Better;
4040       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4041         return ImplicitConversionSequence::Worse;
4042     }
4043 
4044     //   -- conversion of B* to A* is better than conversion of C* to A*,
4045     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4046       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4047         return ImplicitConversionSequence::Better;
4048       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4049         return ImplicitConversionSequence::Worse;
4050     }
4051   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4052              SCS2.Second == ICK_Pointer_Conversion) {
4053     const ObjCObjectPointerType *FromPtr1
4054       = FromType1->getAs<ObjCObjectPointerType>();
4055     const ObjCObjectPointerType *FromPtr2
4056       = FromType2->getAs<ObjCObjectPointerType>();
4057     const ObjCObjectPointerType *ToPtr1
4058       = ToType1->getAs<ObjCObjectPointerType>();
4059     const ObjCObjectPointerType *ToPtr2
4060       = ToType2->getAs<ObjCObjectPointerType>();
4061 
4062     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4063       // Apply the same conversion ranking rules for Objective-C pointer types
4064       // that we do for C++ pointers to class types. However, we employ the
4065       // Objective-C pseudo-subtyping relationship used for assignment of
4066       // Objective-C pointer types.
4067       bool FromAssignLeft
4068         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4069       bool FromAssignRight
4070         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4071       bool ToAssignLeft
4072         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4073       bool ToAssignRight
4074         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4075 
4076       // A conversion to an a non-id object pointer type or qualified 'id'
4077       // type is better than a conversion to 'id'.
4078       if (ToPtr1->isObjCIdType() &&
4079           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4080         return ImplicitConversionSequence::Worse;
4081       if (ToPtr2->isObjCIdType() &&
4082           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4083         return ImplicitConversionSequence::Better;
4084 
4085       // A conversion to a non-id object pointer type is better than a
4086       // conversion to a qualified 'id' type
4087       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4088         return ImplicitConversionSequence::Worse;
4089       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4090         return ImplicitConversionSequence::Better;
4091 
4092       // A conversion to an a non-Class object pointer type or qualified 'Class'
4093       // type is better than a conversion to 'Class'.
4094       if (ToPtr1->isObjCClassType() &&
4095           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4096         return ImplicitConversionSequence::Worse;
4097       if (ToPtr2->isObjCClassType() &&
4098           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4099         return ImplicitConversionSequence::Better;
4100 
4101       // A conversion to a non-Class object pointer type is better than a
4102       // conversion to a qualified 'Class' type.
4103       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4104         return ImplicitConversionSequence::Worse;
4105       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4106         return ImplicitConversionSequence::Better;
4107 
4108       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4109       if (S.Context.hasSameType(FromType1, FromType2) &&
4110           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4111           (ToAssignLeft != ToAssignRight)) {
4112         if (FromPtr1->isSpecialized()) {
4113           // "conversion of B<A> * to B * is better than conversion of B * to
4114           // C *.
4115           bool IsFirstSame =
4116               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4117           bool IsSecondSame =
4118               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4119           if (IsFirstSame) {
4120             if (!IsSecondSame)
4121               return ImplicitConversionSequence::Better;
4122           } else if (IsSecondSame)
4123             return ImplicitConversionSequence::Worse;
4124         }
4125         return ToAssignLeft? ImplicitConversionSequence::Worse
4126                            : ImplicitConversionSequence::Better;
4127       }
4128 
4129       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4130       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4131           (FromAssignLeft != FromAssignRight))
4132         return FromAssignLeft? ImplicitConversionSequence::Better
4133         : ImplicitConversionSequence::Worse;
4134     }
4135   }
4136 
4137   // Ranking of member-pointer types.
4138   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4139       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4140       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4141     const MemberPointerType * FromMemPointer1 =
4142                                         FromType1->getAs<MemberPointerType>();
4143     const MemberPointerType * ToMemPointer1 =
4144                                           ToType1->getAs<MemberPointerType>();
4145     const MemberPointerType * FromMemPointer2 =
4146                                           FromType2->getAs<MemberPointerType>();
4147     const MemberPointerType * ToMemPointer2 =
4148                                           ToType2->getAs<MemberPointerType>();
4149     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4150     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4151     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4152     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4153     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4154     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4155     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4156     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4157     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4158     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4159       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4160         return ImplicitConversionSequence::Worse;
4161       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4162         return ImplicitConversionSequence::Better;
4163     }
4164     // conversion of B::* to C::* is better than conversion of A::* to C::*
4165     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4166       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4167         return ImplicitConversionSequence::Better;
4168       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4169         return ImplicitConversionSequence::Worse;
4170     }
4171   }
4172 
4173   if (SCS1.Second == ICK_Derived_To_Base) {
4174     //   -- conversion of C to B is better than conversion of C to A,
4175     //   -- binding of an expression of type C to a reference of type
4176     //      B& is better than binding an expression of type C to a
4177     //      reference of type A&,
4178     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4179         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4180       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4181         return ImplicitConversionSequence::Better;
4182       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4183         return ImplicitConversionSequence::Worse;
4184     }
4185 
4186     //   -- conversion of B to A is better than conversion of C to A.
4187     //   -- binding of an expression of type B to a reference of type
4188     //      A& is better than binding an expression of type C to a
4189     //      reference of type A&,
4190     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4191         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4192       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4193         return ImplicitConversionSequence::Better;
4194       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4195         return ImplicitConversionSequence::Worse;
4196     }
4197   }
4198 
4199   return ImplicitConversionSequence::Indistinguishable;
4200 }
4201 
4202 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
4203 /// C++ class.
4204 static bool isTypeValid(QualType T) {
4205   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4206     return !Record->isInvalidDecl();
4207 
4208   return true;
4209 }
4210 
4211 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4212 /// determine whether they are reference-related,
4213 /// reference-compatible, reference-compatible with added
4214 /// qualification, or incompatible, for use in C++ initialization by
4215 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4216 /// type, and the first type (T1) is the pointee type of the reference
4217 /// type being initialized.
4218 Sema::ReferenceCompareResult
4219 Sema::CompareReferenceRelationship(SourceLocation Loc,
4220                                    QualType OrigT1, QualType OrigT2,
4221                                    bool &DerivedToBase,
4222                                    bool &ObjCConversion,
4223                                    bool &ObjCLifetimeConversion) {
4224   assert(!OrigT1->isReferenceType() &&
4225     "T1 must be the pointee type of the reference type");
4226   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4227 
4228   QualType T1 = Context.getCanonicalType(OrigT1);
4229   QualType T2 = Context.getCanonicalType(OrigT2);
4230   Qualifiers T1Quals, T2Quals;
4231   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4232   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4233 
4234   // C++ [dcl.init.ref]p4:
4235   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4236   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4237   //   T1 is a base class of T2.
4238   DerivedToBase = false;
4239   ObjCConversion = false;
4240   ObjCLifetimeConversion = false;
4241   QualType ConvertedT2;
4242   if (UnqualT1 == UnqualT2) {
4243     // Nothing to do.
4244   } else if (isCompleteType(Loc, OrigT2) &&
4245              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4246              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4247     DerivedToBase = true;
4248   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4249            UnqualT2->isObjCObjectOrInterfaceType() &&
4250            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4251     ObjCConversion = true;
4252   else if (UnqualT2->isFunctionType() &&
4253            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4254     // C++1z [dcl.init.ref]p4:
4255     //   cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4256     //   function" and T1 is "function"
4257     //
4258     // We extend this to also apply to 'noreturn', so allow any function
4259     // conversion between function types.
4260     return Ref_Compatible;
4261   else
4262     return Ref_Incompatible;
4263 
4264   // At this point, we know that T1 and T2 are reference-related (at
4265   // least).
4266 
4267   // If the type is an array type, promote the element qualifiers to the type
4268   // for comparison.
4269   if (isa<ArrayType>(T1) && T1Quals)
4270     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4271   if (isa<ArrayType>(T2) && T2Quals)
4272     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4273 
4274   // C++ [dcl.init.ref]p4:
4275   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4276   //   reference-related to T2 and cv1 is the same cv-qualification
4277   //   as, or greater cv-qualification than, cv2. For purposes of
4278   //   overload resolution, cases for which cv1 is greater
4279   //   cv-qualification than cv2 are identified as
4280   //   reference-compatible with added qualification (see 13.3.3.2).
4281   //
4282   // Note that we also require equivalence of Objective-C GC and address-space
4283   // qualifiers when performing these computations, so that e.g., an int in
4284   // address space 1 is not reference-compatible with an int in address
4285   // space 2.
4286   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4287       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4288     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4289       ObjCLifetimeConversion = true;
4290 
4291     T1Quals.removeObjCLifetime();
4292     T2Quals.removeObjCLifetime();
4293   }
4294 
4295   // MS compiler ignores __unaligned qualifier for references; do the same.
4296   T1Quals.removeUnaligned();
4297   T2Quals.removeUnaligned();
4298 
4299   if (T1Quals.compatiblyIncludes(T2Quals))
4300     return Ref_Compatible;
4301   else
4302     return Ref_Related;
4303 }
4304 
4305 /// \brief Look for a user-defined conversion to a value reference-compatible
4306 ///        with DeclType. Return true if something definite is found.
4307 static bool
4308 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4309                          QualType DeclType, SourceLocation DeclLoc,
4310                          Expr *Init, QualType T2, bool AllowRvalues,
4311                          bool AllowExplicit) {
4312   assert(T2->isRecordType() && "Can only find conversions of record types.");
4313   CXXRecordDecl *T2RecordDecl
4314     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4315 
4316   OverloadCandidateSet CandidateSet(
4317       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4318   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4319   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4320     NamedDecl *D = *I;
4321     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4322     if (isa<UsingShadowDecl>(D))
4323       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4324 
4325     FunctionTemplateDecl *ConvTemplate
4326       = dyn_cast<FunctionTemplateDecl>(D);
4327     CXXConversionDecl *Conv;
4328     if (ConvTemplate)
4329       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4330     else
4331       Conv = cast<CXXConversionDecl>(D);
4332 
4333     // If this is an explicit conversion, and we're not allowed to consider
4334     // explicit conversions, skip it.
4335     if (!AllowExplicit && Conv->isExplicit())
4336       continue;
4337 
4338     if (AllowRvalues) {
4339       bool DerivedToBase = false;
4340       bool ObjCConversion = false;
4341       bool ObjCLifetimeConversion = false;
4342 
4343       // If we are initializing an rvalue reference, don't permit conversion
4344       // functions that return lvalues.
4345       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4346         const ReferenceType *RefType
4347           = Conv->getConversionType()->getAs<LValueReferenceType>();
4348         if (RefType && !RefType->getPointeeType()->isFunctionType())
4349           continue;
4350       }
4351 
4352       if (!ConvTemplate &&
4353           S.CompareReferenceRelationship(
4354             DeclLoc,
4355             Conv->getConversionType().getNonReferenceType()
4356               .getUnqualifiedType(),
4357             DeclType.getNonReferenceType().getUnqualifiedType(),
4358             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4359           Sema::Ref_Incompatible)
4360         continue;
4361     } else {
4362       // If the conversion function doesn't return a reference type,
4363       // it can't be considered for this conversion. An rvalue reference
4364       // is only acceptable if its referencee is a function type.
4365 
4366       const ReferenceType *RefType =
4367         Conv->getConversionType()->getAs<ReferenceType>();
4368       if (!RefType ||
4369           (!RefType->isLValueReferenceType() &&
4370            !RefType->getPointeeType()->isFunctionType()))
4371         continue;
4372     }
4373 
4374     if (ConvTemplate)
4375       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4376                                        Init, DeclType, CandidateSet,
4377                                        /*AllowObjCConversionOnExplicit=*/false);
4378     else
4379       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4380                                DeclType, CandidateSet,
4381                                /*AllowObjCConversionOnExplicit=*/false);
4382   }
4383 
4384   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4385 
4386   OverloadCandidateSet::iterator Best;
4387   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4388   case OR_Success:
4389     // C++ [over.ics.ref]p1:
4390     //
4391     //   [...] If the parameter binds directly to the result of
4392     //   applying a conversion function to the argument
4393     //   expression, the implicit conversion sequence is a
4394     //   user-defined conversion sequence (13.3.3.1.2), with the
4395     //   second standard conversion sequence either an identity
4396     //   conversion or, if the conversion function returns an
4397     //   entity of a type that is a derived class of the parameter
4398     //   type, a derived-to-base Conversion.
4399     if (!Best->FinalConversion.DirectBinding)
4400       return false;
4401 
4402     ICS.setUserDefined();
4403     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4404     ICS.UserDefined.After = Best->FinalConversion;
4405     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4406     ICS.UserDefined.ConversionFunction = Best->Function;
4407     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4408     ICS.UserDefined.EllipsisConversion = false;
4409     assert(ICS.UserDefined.After.ReferenceBinding &&
4410            ICS.UserDefined.After.DirectBinding &&
4411            "Expected a direct reference binding!");
4412     return true;
4413 
4414   case OR_Ambiguous:
4415     ICS.setAmbiguous();
4416     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4417          Cand != CandidateSet.end(); ++Cand)
4418       if (Cand->Viable)
4419         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4420     return true;
4421 
4422   case OR_No_Viable_Function:
4423   case OR_Deleted:
4424     // There was no suitable conversion, or we found a deleted
4425     // conversion; continue with other checks.
4426     return false;
4427   }
4428 
4429   llvm_unreachable("Invalid OverloadResult!");
4430 }
4431 
4432 /// \brief Compute an implicit conversion sequence for reference
4433 /// initialization.
4434 static ImplicitConversionSequence
4435 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4436                  SourceLocation DeclLoc,
4437                  bool SuppressUserConversions,
4438                  bool AllowExplicit) {
4439   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4440 
4441   // Most paths end in a failed conversion.
4442   ImplicitConversionSequence ICS;
4443   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4444 
4445   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4446   QualType T2 = Init->getType();
4447 
4448   // If the initializer is the address of an overloaded function, try
4449   // to resolve the overloaded function. If all goes well, T2 is the
4450   // type of the resulting function.
4451   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4452     DeclAccessPair Found;
4453     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4454                                                                 false, Found))
4455       T2 = Fn->getType();
4456   }
4457 
4458   // Compute some basic properties of the types and the initializer.
4459   bool isRValRef = DeclType->isRValueReferenceType();
4460   bool DerivedToBase = false;
4461   bool ObjCConversion = false;
4462   bool ObjCLifetimeConversion = false;
4463   Expr::Classification InitCategory = Init->Classify(S.Context);
4464   Sema::ReferenceCompareResult RefRelationship
4465     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4466                                      ObjCConversion, ObjCLifetimeConversion);
4467 
4468 
4469   // C++0x [dcl.init.ref]p5:
4470   //   A reference to type "cv1 T1" is initialized by an expression
4471   //   of type "cv2 T2" as follows:
4472 
4473   //     -- If reference is an lvalue reference and the initializer expression
4474   if (!isRValRef) {
4475     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4476     //        reference-compatible with "cv2 T2," or
4477     //
4478     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4479     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4480       // C++ [over.ics.ref]p1:
4481       //   When a parameter of reference type binds directly (8.5.3)
4482       //   to an argument expression, the implicit conversion sequence
4483       //   is the identity conversion, unless the argument expression
4484       //   has a type that is a derived class of the parameter type,
4485       //   in which case the implicit conversion sequence is a
4486       //   derived-to-base Conversion (13.3.3.1).
4487       ICS.setStandard();
4488       ICS.Standard.First = ICK_Identity;
4489       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4490                          : ObjCConversion? ICK_Compatible_Conversion
4491                          : ICK_Identity;
4492       ICS.Standard.Third = ICK_Identity;
4493       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4494       ICS.Standard.setToType(0, T2);
4495       ICS.Standard.setToType(1, T1);
4496       ICS.Standard.setToType(2, T1);
4497       ICS.Standard.ReferenceBinding = true;
4498       ICS.Standard.DirectBinding = true;
4499       ICS.Standard.IsLvalueReference = !isRValRef;
4500       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4501       ICS.Standard.BindsToRvalue = false;
4502       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4503       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4504       ICS.Standard.CopyConstructor = nullptr;
4505       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4506 
4507       // Nothing more to do: the inaccessibility/ambiguity check for
4508       // derived-to-base conversions is suppressed when we're
4509       // computing the implicit conversion sequence (C++
4510       // [over.best.ics]p2).
4511       return ICS;
4512     }
4513 
4514     //       -- has a class type (i.e., T2 is a class type), where T1 is
4515     //          not reference-related to T2, and can be implicitly
4516     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4517     //          is reference-compatible with "cv3 T3" 92) (this
4518     //          conversion is selected by enumerating the applicable
4519     //          conversion functions (13.3.1.6) and choosing the best
4520     //          one through overload resolution (13.3)),
4521     if (!SuppressUserConversions && T2->isRecordType() &&
4522         S.isCompleteType(DeclLoc, T2) &&
4523         RefRelationship == Sema::Ref_Incompatible) {
4524       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4525                                    Init, T2, /*AllowRvalues=*/false,
4526                                    AllowExplicit))
4527         return ICS;
4528     }
4529   }
4530 
4531   //     -- Otherwise, the reference shall be an lvalue reference to a
4532   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4533   //        shall be an rvalue reference.
4534   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4535     return ICS;
4536 
4537   //       -- If the initializer expression
4538   //
4539   //            -- is an xvalue, class prvalue, array prvalue or function
4540   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4541   if (RefRelationship == Sema::Ref_Compatible &&
4542       (InitCategory.isXValue() ||
4543        (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4544        (InitCategory.isLValue() && T2->isFunctionType()))) {
4545     ICS.setStandard();
4546     ICS.Standard.First = ICK_Identity;
4547     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4548                       : ObjCConversion? ICK_Compatible_Conversion
4549                       : ICK_Identity;
4550     ICS.Standard.Third = ICK_Identity;
4551     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4552     ICS.Standard.setToType(0, T2);
4553     ICS.Standard.setToType(1, T1);
4554     ICS.Standard.setToType(2, T1);
4555     ICS.Standard.ReferenceBinding = true;
4556     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4557     // binding unless we're binding to a class prvalue.
4558     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4559     // allow the use of rvalue references in C++98/03 for the benefit of
4560     // standard library implementors; therefore, we need the xvalue check here.
4561     ICS.Standard.DirectBinding =
4562       S.getLangOpts().CPlusPlus11 ||
4563       !(InitCategory.isPRValue() || T2->isRecordType());
4564     ICS.Standard.IsLvalueReference = !isRValRef;
4565     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4566     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4567     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4568     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4569     ICS.Standard.CopyConstructor = nullptr;
4570     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4571     return ICS;
4572   }
4573 
4574   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4575   //               reference-related to T2, and can be implicitly converted to
4576   //               an xvalue, class prvalue, or function lvalue of type
4577   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4578   //               "cv3 T3",
4579   //
4580   //          then the reference is bound to the value of the initializer
4581   //          expression in the first case and to the result of the conversion
4582   //          in the second case (or, in either case, to an appropriate base
4583   //          class subobject).
4584   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4585       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4586       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4587                                Init, T2, /*AllowRvalues=*/true,
4588                                AllowExplicit)) {
4589     // In the second case, if the reference is an rvalue reference
4590     // and the second standard conversion sequence of the
4591     // user-defined conversion sequence includes an lvalue-to-rvalue
4592     // conversion, the program is ill-formed.
4593     if (ICS.isUserDefined() && isRValRef &&
4594         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4595       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4596 
4597     return ICS;
4598   }
4599 
4600   // A temporary of function type cannot be created; don't even try.
4601   if (T1->isFunctionType())
4602     return ICS;
4603 
4604   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4605   //          initialized from the initializer expression using the
4606   //          rules for a non-reference copy initialization (8.5). The
4607   //          reference is then bound to the temporary. If T1 is
4608   //          reference-related to T2, cv1 must be the same
4609   //          cv-qualification as, or greater cv-qualification than,
4610   //          cv2; otherwise, the program is ill-formed.
4611   if (RefRelationship == Sema::Ref_Related) {
4612     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4613     // we would be reference-compatible or reference-compatible with
4614     // added qualification. But that wasn't the case, so the reference
4615     // initialization fails.
4616     //
4617     // Note that we only want to check address spaces and cvr-qualifiers here.
4618     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4619     Qualifiers T1Quals = T1.getQualifiers();
4620     Qualifiers T2Quals = T2.getQualifiers();
4621     T1Quals.removeObjCGCAttr();
4622     T1Quals.removeObjCLifetime();
4623     T2Quals.removeObjCGCAttr();
4624     T2Quals.removeObjCLifetime();
4625     // MS compiler ignores __unaligned qualifier for references; do the same.
4626     T1Quals.removeUnaligned();
4627     T2Quals.removeUnaligned();
4628     if (!T1Quals.compatiblyIncludes(T2Quals))
4629       return ICS;
4630   }
4631 
4632   // If at least one of the types is a class type, the types are not
4633   // related, and we aren't allowed any user conversions, the
4634   // reference binding fails. This case is important for breaking
4635   // recursion, since TryImplicitConversion below will attempt to
4636   // create a temporary through the use of a copy constructor.
4637   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4638       (T1->isRecordType() || T2->isRecordType()))
4639     return ICS;
4640 
4641   // If T1 is reference-related to T2 and the reference is an rvalue
4642   // reference, the initializer expression shall not be an lvalue.
4643   if (RefRelationship >= Sema::Ref_Related &&
4644       isRValRef && Init->Classify(S.Context).isLValue())
4645     return ICS;
4646 
4647   // C++ [over.ics.ref]p2:
4648   //   When a parameter of reference type is not bound directly to
4649   //   an argument expression, the conversion sequence is the one
4650   //   required to convert the argument expression to the
4651   //   underlying type of the reference according to
4652   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4653   //   to copy-initializing a temporary of the underlying type with
4654   //   the argument expression. Any difference in top-level
4655   //   cv-qualification is subsumed by the initialization itself
4656   //   and does not constitute a conversion.
4657   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4658                               /*AllowExplicit=*/false,
4659                               /*InOverloadResolution=*/false,
4660                               /*CStyle=*/false,
4661                               /*AllowObjCWritebackConversion=*/false,
4662                               /*AllowObjCConversionOnExplicit=*/false);
4663 
4664   // Of course, that's still a reference binding.
4665   if (ICS.isStandard()) {
4666     ICS.Standard.ReferenceBinding = true;
4667     ICS.Standard.IsLvalueReference = !isRValRef;
4668     ICS.Standard.BindsToFunctionLvalue = false;
4669     ICS.Standard.BindsToRvalue = true;
4670     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4671     ICS.Standard.ObjCLifetimeConversionBinding = false;
4672   } else if (ICS.isUserDefined()) {
4673     const ReferenceType *LValRefType =
4674         ICS.UserDefined.ConversionFunction->getReturnType()
4675             ->getAs<LValueReferenceType>();
4676 
4677     // C++ [over.ics.ref]p3:
4678     //   Except for an implicit object parameter, for which see 13.3.1, a
4679     //   standard conversion sequence cannot be formed if it requires [...]
4680     //   binding an rvalue reference to an lvalue other than a function
4681     //   lvalue.
4682     // Note that the function case is not possible here.
4683     if (DeclType->isRValueReferenceType() && LValRefType) {
4684       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4685       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4686       // reference to an rvalue!
4687       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4688       return ICS;
4689     }
4690 
4691     ICS.UserDefined.After.ReferenceBinding = true;
4692     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4693     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4694     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4695     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4696     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4697   }
4698 
4699   return ICS;
4700 }
4701 
4702 static ImplicitConversionSequence
4703 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4704                       bool SuppressUserConversions,
4705                       bool InOverloadResolution,
4706                       bool AllowObjCWritebackConversion,
4707                       bool AllowExplicit = false);
4708 
4709 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4710 /// initializer list From.
4711 static ImplicitConversionSequence
4712 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4713                   bool SuppressUserConversions,
4714                   bool InOverloadResolution,
4715                   bool AllowObjCWritebackConversion) {
4716   // C++11 [over.ics.list]p1:
4717   //   When an argument is an initializer list, it is not an expression and
4718   //   special rules apply for converting it to a parameter type.
4719 
4720   ImplicitConversionSequence Result;
4721   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4722 
4723   // We need a complete type for what follows. Incomplete types can never be
4724   // initialized from init lists.
4725   if (!S.isCompleteType(From->getLocStart(), ToType))
4726     return Result;
4727 
4728   // Per DR1467:
4729   //   If the parameter type is a class X and the initializer list has a single
4730   //   element of type cv U, where U is X or a class derived from X, the
4731   //   implicit conversion sequence is the one required to convert the element
4732   //   to the parameter type.
4733   //
4734   //   Otherwise, if the parameter type is a character array [... ]
4735   //   and the initializer list has a single element that is an
4736   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4737   //   implicit conversion sequence is the identity conversion.
4738   if (From->getNumInits() == 1) {
4739     if (ToType->isRecordType()) {
4740       QualType InitType = From->getInit(0)->getType();
4741       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4742           S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4743         return TryCopyInitialization(S, From->getInit(0), ToType,
4744                                      SuppressUserConversions,
4745                                      InOverloadResolution,
4746                                      AllowObjCWritebackConversion);
4747     }
4748     // FIXME: Check the other conditions here: array of character type,
4749     // initializer is a string literal.
4750     if (ToType->isArrayType()) {
4751       InitializedEntity Entity =
4752         InitializedEntity::InitializeParameter(S.Context, ToType,
4753                                                /*Consumed=*/false);
4754       if (S.CanPerformCopyInitialization(Entity, From)) {
4755         Result.setStandard();
4756         Result.Standard.setAsIdentityConversion();
4757         Result.Standard.setFromType(ToType);
4758         Result.Standard.setAllToTypes(ToType);
4759         return Result;
4760       }
4761     }
4762   }
4763 
4764   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4765   // C++11 [over.ics.list]p2:
4766   //   If the parameter type is std::initializer_list<X> or "array of X" and
4767   //   all the elements can be implicitly converted to X, the implicit
4768   //   conversion sequence is the worst conversion necessary to convert an
4769   //   element of the list to X.
4770   //
4771   // C++14 [over.ics.list]p3:
4772   //   Otherwise, if the parameter type is "array of N X", if the initializer
4773   //   list has exactly N elements or if it has fewer than N elements and X is
4774   //   default-constructible, and if all the elements of the initializer list
4775   //   can be implicitly converted to X, the implicit conversion sequence is
4776   //   the worst conversion necessary to convert an element of the list to X.
4777   //
4778   // FIXME: We're missing a lot of these checks.
4779   bool toStdInitializerList = false;
4780   QualType X;
4781   if (ToType->isArrayType())
4782     X = S.Context.getAsArrayType(ToType)->getElementType();
4783   else
4784     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4785   if (!X.isNull()) {
4786     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4787       Expr *Init = From->getInit(i);
4788       ImplicitConversionSequence ICS =
4789           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4790                                 InOverloadResolution,
4791                                 AllowObjCWritebackConversion);
4792       // If a single element isn't convertible, fail.
4793       if (ICS.isBad()) {
4794         Result = ICS;
4795         break;
4796       }
4797       // Otherwise, look for the worst conversion.
4798       if (Result.isBad() ||
4799           CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4800                                              Result) ==
4801               ImplicitConversionSequence::Worse)
4802         Result = ICS;
4803     }
4804 
4805     // For an empty list, we won't have computed any conversion sequence.
4806     // Introduce the identity conversion sequence.
4807     if (From->getNumInits() == 0) {
4808       Result.setStandard();
4809       Result.Standard.setAsIdentityConversion();
4810       Result.Standard.setFromType(ToType);
4811       Result.Standard.setAllToTypes(ToType);
4812     }
4813 
4814     Result.setStdInitializerListElement(toStdInitializerList);
4815     return Result;
4816   }
4817 
4818   // C++14 [over.ics.list]p4:
4819   // C++11 [over.ics.list]p3:
4820   //   Otherwise, if the parameter is a non-aggregate class X and overload
4821   //   resolution chooses a single best constructor [...] the implicit
4822   //   conversion sequence is a user-defined conversion sequence. If multiple
4823   //   constructors are viable but none is better than the others, the
4824   //   implicit conversion sequence is a user-defined conversion sequence.
4825   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4826     // This function can deal with initializer lists.
4827     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4828                                     /*AllowExplicit=*/false,
4829                                     InOverloadResolution, /*CStyle=*/false,
4830                                     AllowObjCWritebackConversion,
4831                                     /*AllowObjCConversionOnExplicit=*/false);
4832   }
4833 
4834   // C++14 [over.ics.list]p5:
4835   // C++11 [over.ics.list]p4:
4836   //   Otherwise, if the parameter has an aggregate type which can be
4837   //   initialized from the initializer list [...] the implicit conversion
4838   //   sequence is a user-defined conversion sequence.
4839   if (ToType->isAggregateType()) {
4840     // Type is an aggregate, argument is an init list. At this point it comes
4841     // down to checking whether the initialization works.
4842     // FIXME: Find out whether this parameter is consumed or not.
4843     // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4844     // need to call into the initialization code here; overload resolution
4845     // should not be doing that.
4846     InitializedEntity Entity =
4847         InitializedEntity::InitializeParameter(S.Context, ToType,
4848                                                /*Consumed=*/false);
4849     if (S.CanPerformCopyInitialization(Entity, From)) {
4850       Result.setUserDefined();
4851       Result.UserDefined.Before.setAsIdentityConversion();
4852       // Initializer lists don't have a type.
4853       Result.UserDefined.Before.setFromType(QualType());
4854       Result.UserDefined.Before.setAllToTypes(QualType());
4855 
4856       Result.UserDefined.After.setAsIdentityConversion();
4857       Result.UserDefined.After.setFromType(ToType);
4858       Result.UserDefined.After.setAllToTypes(ToType);
4859       Result.UserDefined.ConversionFunction = nullptr;
4860     }
4861     return Result;
4862   }
4863 
4864   // C++14 [over.ics.list]p6:
4865   // C++11 [over.ics.list]p5:
4866   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4867   if (ToType->isReferenceType()) {
4868     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4869     // mention initializer lists in any way. So we go by what list-
4870     // initialization would do and try to extrapolate from that.
4871 
4872     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4873 
4874     // If the initializer list has a single element that is reference-related
4875     // to the parameter type, we initialize the reference from that.
4876     if (From->getNumInits() == 1) {
4877       Expr *Init = From->getInit(0);
4878 
4879       QualType T2 = Init->getType();
4880 
4881       // If the initializer is the address of an overloaded function, try
4882       // to resolve the overloaded function. If all goes well, T2 is the
4883       // type of the resulting function.
4884       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4885         DeclAccessPair Found;
4886         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4887                                    Init, ToType, false, Found))
4888           T2 = Fn->getType();
4889       }
4890 
4891       // Compute some basic properties of the types and the initializer.
4892       bool dummy1 = false;
4893       bool dummy2 = false;
4894       bool dummy3 = false;
4895       Sema::ReferenceCompareResult RefRelationship
4896         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4897                                          dummy2, dummy3);
4898 
4899       if (RefRelationship >= Sema::Ref_Related) {
4900         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4901                                 SuppressUserConversions,
4902                                 /*AllowExplicit=*/false);
4903       }
4904     }
4905 
4906     // Otherwise, we bind the reference to a temporary created from the
4907     // initializer list.
4908     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4909                                InOverloadResolution,
4910                                AllowObjCWritebackConversion);
4911     if (Result.isFailure())
4912       return Result;
4913     assert(!Result.isEllipsis() &&
4914            "Sub-initialization cannot result in ellipsis conversion.");
4915 
4916     // Can we even bind to a temporary?
4917     if (ToType->isRValueReferenceType() ||
4918         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4919       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4920                                             Result.UserDefined.After;
4921       SCS.ReferenceBinding = true;
4922       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4923       SCS.BindsToRvalue = true;
4924       SCS.BindsToFunctionLvalue = false;
4925       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4926       SCS.ObjCLifetimeConversionBinding = false;
4927     } else
4928       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4929                     From, ToType);
4930     return Result;
4931   }
4932 
4933   // C++14 [over.ics.list]p7:
4934   // C++11 [over.ics.list]p6:
4935   //   Otherwise, if the parameter type is not a class:
4936   if (!ToType->isRecordType()) {
4937     //    - if the initializer list has one element that is not itself an
4938     //      initializer list, the implicit conversion sequence is the one
4939     //      required to convert the element to the parameter type.
4940     unsigned NumInits = From->getNumInits();
4941     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4942       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4943                                      SuppressUserConversions,
4944                                      InOverloadResolution,
4945                                      AllowObjCWritebackConversion);
4946     //    - if the initializer list has no elements, the implicit conversion
4947     //      sequence is the identity conversion.
4948     else if (NumInits == 0) {
4949       Result.setStandard();
4950       Result.Standard.setAsIdentityConversion();
4951       Result.Standard.setFromType(ToType);
4952       Result.Standard.setAllToTypes(ToType);
4953     }
4954     return Result;
4955   }
4956 
4957   // C++14 [over.ics.list]p8:
4958   // C++11 [over.ics.list]p7:
4959   //   In all cases other than those enumerated above, no conversion is possible
4960   return Result;
4961 }
4962 
4963 /// TryCopyInitialization - Try to copy-initialize a value of type
4964 /// ToType from the expression From. Return the implicit conversion
4965 /// sequence required to pass this argument, which may be a bad
4966 /// conversion sequence (meaning that the argument cannot be passed to
4967 /// a parameter of this type). If @p SuppressUserConversions, then we
4968 /// do not permit any user-defined conversion sequences.
4969 static ImplicitConversionSequence
4970 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4971                       bool SuppressUserConversions,
4972                       bool InOverloadResolution,
4973                       bool AllowObjCWritebackConversion,
4974                       bool AllowExplicit) {
4975   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4976     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4977                              InOverloadResolution,AllowObjCWritebackConversion);
4978 
4979   if (ToType->isReferenceType())
4980     return TryReferenceInit(S, From, ToType,
4981                             /*FIXME:*/From->getLocStart(),
4982                             SuppressUserConversions,
4983                             AllowExplicit);
4984 
4985   return TryImplicitConversion(S, From, ToType,
4986                                SuppressUserConversions,
4987                                /*AllowExplicit=*/false,
4988                                InOverloadResolution,
4989                                /*CStyle=*/false,
4990                                AllowObjCWritebackConversion,
4991                                /*AllowObjCConversionOnExplicit=*/false);
4992 }
4993 
4994 static bool TryCopyInitialization(const CanQualType FromQTy,
4995                                   const CanQualType ToQTy,
4996                                   Sema &S,
4997                                   SourceLocation Loc,
4998                                   ExprValueKind FromVK) {
4999   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5000   ImplicitConversionSequence ICS =
5001     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5002 
5003   return !ICS.isBad();
5004 }
5005 
5006 /// TryObjectArgumentInitialization - Try to initialize the object
5007 /// parameter of the given member function (@c Method) from the
5008 /// expression @p From.
5009 static ImplicitConversionSequence
5010 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5011                                 Expr::Classification FromClassification,
5012                                 CXXMethodDecl *Method,
5013                                 CXXRecordDecl *ActingContext) {
5014   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5015   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5016   //                 const volatile object.
5017   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
5018     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
5019   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
5020 
5021   // Set up the conversion sequence as a "bad" conversion, to allow us
5022   // to exit early.
5023   ImplicitConversionSequence ICS;
5024 
5025   // We need to have an object of class type.
5026   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5027     FromType = PT->getPointeeType();
5028 
5029     // When we had a pointer, it's implicitly dereferenced, so we
5030     // better have an lvalue.
5031     assert(FromClassification.isLValue());
5032   }
5033 
5034   assert(FromType->isRecordType());
5035 
5036   // C++0x [over.match.funcs]p4:
5037   //   For non-static member functions, the type of the implicit object
5038   //   parameter is
5039   //
5040   //     - "lvalue reference to cv X" for functions declared without a
5041   //        ref-qualifier or with the & ref-qualifier
5042   //     - "rvalue reference to cv X" for functions declared with the &&
5043   //        ref-qualifier
5044   //
5045   // where X is the class of which the function is a member and cv is the
5046   // cv-qualification on the member function declaration.
5047   //
5048   // However, when finding an implicit conversion sequence for the argument, we
5049   // are not allowed to perform user-defined conversions
5050   // (C++ [over.match.funcs]p5). We perform a simplified version of
5051   // reference binding here, that allows class rvalues to bind to
5052   // non-constant references.
5053 
5054   // First check the qualifiers.
5055   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5056   if (ImplicitParamType.getCVRQualifiers()
5057                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5058       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5059     ICS.setBad(BadConversionSequence::bad_qualifiers,
5060                FromType, ImplicitParamType);
5061     return ICS;
5062   }
5063 
5064   // Check that we have either the same type or a derived type. It
5065   // affects the conversion rank.
5066   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5067   ImplicitConversionKind SecondKind;
5068   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5069     SecondKind = ICK_Identity;
5070   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5071     SecondKind = ICK_Derived_To_Base;
5072   else {
5073     ICS.setBad(BadConversionSequence::unrelated_class,
5074                FromType, ImplicitParamType);
5075     return ICS;
5076   }
5077 
5078   // Check the ref-qualifier.
5079   switch (Method->getRefQualifier()) {
5080   case RQ_None:
5081     // Do nothing; we don't care about lvalueness or rvalueness.
5082     break;
5083 
5084   case RQ_LValue:
5085     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5086       // non-const lvalue reference cannot bind to an rvalue
5087       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5088                  ImplicitParamType);
5089       return ICS;
5090     }
5091     break;
5092 
5093   case RQ_RValue:
5094     if (!FromClassification.isRValue()) {
5095       // rvalue reference cannot bind to an lvalue
5096       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5097                  ImplicitParamType);
5098       return ICS;
5099     }
5100     break;
5101   }
5102 
5103   // Success. Mark this as a reference binding.
5104   ICS.setStandard();
5105   ICS.Standard.setAsIdentityConversion();
5106   ICS.Standard.Second = SecondKind;
5107   ICS.Standard.setFromType(FromType);
5108   ICS.Standard.setAllToTypes(ImplicitParamType);
5109   ICS.Standard.ReferenceBinding = true;
5110   ICS.Standard.DirectBinding = true;
5111   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5112   ICS.Standard.BindsToFunctionLvalue = false;
5113   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5114   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5115     = (Method->getRefQualifier() == RQ_None);
5116   return ICS;
5117 }
5118 
5119 /// PerformObjectArgumentInitialization - Perform initialization of
5120 /// the implicit object parameter for the given Method with the given
5121 /// expression.
5122 ExprResult
5123 Sema::PerformObjectArgumentInitialization(Expr *From,
5124                                           NestedNameSpecifier *Qualifier,
5125                                           NamedDecl *FoundDecl,
5126                                           CXXMethodDecl *Method) {
5127   QualType FromRecordType, DestType;
5128   QualType ImplicitParamRecordType  =
5129     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
5130 
5131   Expr::Classification FromClassification;
5132   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5133     FromRecordType = PT->getPointeeType();
5134     DestType = Method->getThisType(Context);
5135     FromClassification = Expr::Classification::makeSimpleLValue();
5136   } else {
5137     FromRecordType = From->getType();
5138     DestType = ImplicitParamRecordType;
5139     FromClassification = From->Classify(Context);
5140   }
5141 
5142   // Note that we always use the true parent context when performing
5143   // the actual argument initialization.
5144   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5145       *this, From->getLocStart(), From->getType(), FromClassification, Method,
5146       Method->getParent());
5147   if (ICS.isBad()) {
5148     if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
5149       Qualifiers FromQs = FromRecordType.getQualifiers();
5150       Qualifiers ToQs = DestType.getQualifiers();
5151       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5152       if (CVR) {
5153         Diag(From->getLocStart(),
5154              diag::err_member_function_call_bad_cvr)
5155           << Method->getDeclName() << FromRecordType << (CVR - 1)
5156           << From->getSourceRange();
5157         Diag(Method->getLocation(), diag::note_previous_decl)
5158           << Method->getDeclName();
5159         return ExprError();
5160       }
5161     }
5162 
5163     return Diag(From->getLocStart(),
5164                 diag::err_implicit_object_parameter_init)
5165        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5166   }
5167 
5168   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5169     ExprResult FromRes =
5170       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5171     if (FromRes.isInvalid())
5172       return ExprError();
5173     From = FromRes.get();
5174   }
5175 
5176   if (!Context.hasSameType(From->getType(), DestType))
5177     From = ImpCastExprToType(From, DestType, CK_NoOp,
5178                              From->getValueKind()).get();
5179   return From;
5180 }
5181 
5182 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5183 /// expression From to bool (C++0x [conv]p3).
5184 static ImplicitConversionSequence
5185 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5186   return TryImplicitConversion(S, From, S.Context.BoolTy,
5187                                /*SuppressUserConversions=*/false,
5188                                /*AllowExplicit=*/true,
5189                                /*InOverloadResolution=*/false,
5190                                /*CStyle=*/false,
5191                                /*AllowObjCWritebackConversion=*/false,
5192                                /*AllowObjCConversionOnExplicit=*/false);
5193 }
5194 
5195 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5196 /// of the expression From to bool (C++0x [conv]p3).
5197 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5198   if (checkPlaceholderForOverload(*this, From))
5199     return ExprError();
5200 
5201   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5202   if (!ICS.isBad())
5203     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5204 
5205   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5206     return Diag(From->getLocStart(),
5207                 diag::err_typecheck_bool_condition)
5208                   << From->getType() << From->getSourceRange();
5209   return ExprError();
5210 }
5211 
5212 /// Check that the specified conversion is permitted in a converted constant
5213 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5214 /// is acceptable.
5215 static bool CheckConvertedConstantConversions(Sema &S,
5216                                               StandardConversionSequence &SCS) {
5217   // Since we know that the target type is an integral or unscoped enumeration
5218   // type, most conversion kinds are impossible. All possible First and Third
5219   // conversions are fine.
5220   switch (SCS.Second) {
5221   case ICK_Identity:
5222   case ICK_Function_Conversion:
5223   case ICK_Integral_Promotion:
5224   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5225   case ICK_Zero_Queue_Conversion:
5226     return true;
5227 
5228   case ICK_Boolean_Conversion:
5229     // Conversion from an integral or unscoped enumeration type to bool is
5230     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5231     // conversion, so we allow it in a converted constant expression.
5232     //
5233     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5234     // a lot of popular code. We should at least add a warning for this
5235     // (non-conforming) extension.
5236     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5237            SCS.getToType(2)->isBooleanType();
5238 
5239   case ICK_Pointer_Conversion:
5240   case ICK_Pointer_Member:
5241     // C++1z: null pointer conversions and null member pointer conversions are
5242     // only permitted if the source type is std::nullptr_t.
5243     return SCS.getFromType()->isNullPtrType();
5244 
5245   case ICK_Floating_Promotion:
5246   case ICK_Complex_Promotion:
5247   case ICK_Floating_Conversion:
5248   case ICK_Complex_Conversion:
5249   case ICK_Floating_Integral:
5250   case ICK_Compatible_Conversion:
5251   case ICK_Derived_To_Base:
5252   case ICK_Vector_Conversion:
5253   case ICK_Vector_Splat:
5254   case ICK_Complex_Real:
5255   case ICK_Block_Pointer_Conversion:
5256   case ICK_TransparentUnionConversion:
5257   case ICK_Writeback_Conversion:
5258   case ICK_Zero_Event_Conversion:
5259   case ICK_C_Only_Conversion:
5260   case ICK_Incompatible_Pointer_Conversion:
5261     return false;
5262 
5263   case ICK_Lvalue_To_Rvalue:
5264   case ICK_Array_To_Pointer:
5265   case ICK_Function_To_Pointer:
5266     llvm_unreachable("found a first conversion kind in Second");
5267 
5268   case ICK_Qualification:
5269     llvm_unreachable("found a third conversion kind in Second");
5270 
5271   case ICK_Num_Conversion_Kinds:
5272     break;
5273   }
5274 
5275   llvm_unreachable("unknown conversion kind");
5276 }
5277 
5278 /// CheckConvertedConstantExpression - Check that the expression From is a
5279 /// converted constant expression of type T, perform the conversion and produce
5280 /// the converted expression, per C++11 [expr.const]p3.
5281 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5282                                                    QualType T, APValue &Value,
5283                                                    Sema::CCEKind CCE,
5284                                                    bool RequireInt) {
5285   assert(S.getLangOpts().CPlusPlus11 &&
5286          "converted constant expression outside C++11");
5287 
5288   if (checkPlaceholderForOverload(S, From))
5289     return ExprError();
5290 
5291   // C++1z [expr.const]p3:
5292   //  A converted constant expression of type T is an expression,
5293   //  implicitly converted to type T, where the converted
5294   //  expression is a constant expression and the implicit conversion
5295   //  sequence contains only [... list of conversions ...].
5296   // C++1z [stmt.if]p2:
5297   //  If the if statement is of the form if constexpr, the value of the
5298   //  condition shall be a contextually converted constant expression of type
5299   //  bool.
5300   ImplicitConversionSequence ICS =
5301       CCE == Sema::CCEK_ConstexprIf
5302           ? TryContextuallyConvertToBool(S, From)
5303           : TryCopyInitialization(S, From, T,
5304                                   /*SuppressUserConversions=*/false,
5305                                   /*InOverloadResolution=*/false,
5306                                   /*AllowObjcWritebackConversion=*/false,
5307                                   /*AllowExplicit=*/false);
5308   StandardConversionSequence *SCS = nullptr;
5309   switch (ICS.getKind()) {
5310   case ImplicitConversionSequence::StandardConversion:
5311     SCS = &ICS.Standard;
5312     break;
5313   case ImplicitConversionSequence::UserDefinedConversion:
5314     // We are converting to a non-class type, so the Before sequence
5315     // must be trivial.
5316     SCS = &ICS.UserDefined.After;
5317     break;
5318   case ImplicitConversionSequence::AmbiguousConversion:
5319   case ImplicitConversionSequence::BadConversion:
5320     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5321       return S.Diag(From->getLocStart(),
5322                     diag::err_typecheck_converted_constant_expression)
5323                 << From->getType() << From->getSourceRange() << T;
5324     return ExprError();
5325 
5326   case ImplicitConversionSequence::EllipsisConversion:
5327     llvm_unreachable("ellipsis conversion in converted constant expression");
5328   }
5329 
5330   // Check that we would only use permitted conversions.
5331   if (!CheckConvertedConstantConversions(S, *SCS)) {
5332     return S.Diag(From->getLocStart(),
5333                   diag::err_typecheck_converted_constant_expression_disallowed)
5334              << From->getType() << From->getSourceRange() << T;
5335   }
5336   // [...] and where the reference binding (if any) binds directly.
5337   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5338     return S.Diag(From->getLocStart(),
5339                   diag::err_typecheck_converted_constant_expression_indirect)
5340              << From->getType() << From->getSourceRange() << T;
5341   }
5342 
5343   ExprResult Result =
5344       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5345   if (Result.isInvalid())
5346     return Result;
5347 
5348   // Check for a narrowing implicit conversion.
5349   APValue PreNarrowingValue;
5350   QualType PreNarrowingType;
5351   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5352                                 PreNarrowingType)) {
5353   case NK_Dependent_Narrowing:
5354     // Implicit conversion to a narrower type, but the expression is
5355     // value-dependent so we can't tell whether it's actually narrowing.
5356   case NK_Variable_Narrowing:
5357     // Implicit conversion to a narrower type, and the value is not a constant
5358     // expression. We'll diagnose this in a moment.
5359   case NK_Not_Narrowing:
5360     break;
5361 
5362   case NK_Constant_Narrowing:
5363     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5364       << CCE << /*Constant*/1
5365       << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5366     break;
5367 
5368   case NK_Type_Narrowing:
5369     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5370       << CCE << /*Constant*/0 << From->getType() << T;
5371     break;
5372   }
5373 
5374   if (Result.get()->isValueDependent()) {
5375     Value = APValue();
5376     return Result;
5377   }
5378 
5379   // Check the expression is a constant expression.
5380   SmallVector<PartialDiagnosticAt, 8> Notes;
5381   Expr::EvalResult Eval;
5382   Eval.Diag = &Notes;
5383 
5384   if ((T->isReferenceType()
5385            ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5386            : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5387       (RequireInt && !Eval.Val.isInt())) {
5388     // The expression can't be folded, so we can't keep it at this position in
5389     // the AST.
5390     Result = ExprError();
5391   } else {
5392     Value = Eval.Val;
5393 
5394     if (Notes.empty()) {
5395       // It's a constant expression.
5396       return Result;
5397     }
5398   }
5399 
5400   // It's not a constant expression. Produce an appropriate diagnostic.
5401   if (Notes.size() == 1 &&
5402       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5403     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5404   else {
5405     S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5406       << CCE << From->getSourceRange();
5407     for (unsigned I = 0; I < Notes.size(); ++I)
5408       S.Diag(Notes[I].first, Notes[I].second);
5409   }
5410   return ExprError();
5411 }
5412 
5413 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5414                                                   APValue &Value, CCEKind CCE) {
5415   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5416 }
5417 
5418 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5419                                                   llvm::APSInt &Value,
5420                                                   CCEKind CCE) {
5421   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5422 
5423   APValue V;
5424   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5425   if (!R.isInvalid() && !R.get()->isValueDependent())
5426     Value = V.getInt();
5427   return R;
5428 }
5429 
5430 
5431 /// dropPointerConversions - If the given standard conversion sequence
5432 /// involves any pointer conversions, remove them.  This may change
5433 /// the result type of the conversion sequence.
5434 static void dropPointerConversion(StandardConversionSequence &SCS) {
5435   if (SCS.Second == ICK_Pointer_Conversion) {
5436     SCS.Second = ICK_Identity;
5437     SCS.Third = ICK_Identity;
5438     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5439   }
5440 }
5441 
5442 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5443 /// convert the expression From to an Objective-C pointer type.
5444 static ImplicitConversionSequence
5445 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5446   // Do an implicit conversion to 'id'.
5447   QualType Ty = S.Context.getObjCIdType();
5448   ImplicitConversionSequence ICS
5449     = TryImplicitConversion(S, From, Ty,
5450                             // FIXME: Are these flags correct?
5451                             /*SuppressUserConversions=*/false,
5452                             /*AllowExplicit=*/true,
5453                             /*InOverloadResolution=*/false,
5454                             /*CStyle=*/false,
5455                             /*AllowObjCWritebackConversion=*/false,
5456                             /*AllowObjCConversionOnExplicit=*/true);
5457 
5458   // Strip off any final conversions to 'id'.
5459   switch (ICS.getKind()) {
5460   case ImplicitConversionSequence::BadConversion:
5461   case ImplicitConversionSequence::AmbiguousConversion:
5462   case ImplicitConversionSequence::EllipsisConversion:
5463     break;
5464 
5465   case ImplicitConversionSequence::UserDefinedConversion:
5466     dropPointerConversion(ICS.UserDefined.After);
5467     break;
5468 
5469   case ImplicitConversionSequence::StandardConversion:
5470     dropPointerConversion(ICS.Standard);
5471     break;
5472   }
5473 
5474   return ICS;
5475 }
5476 
5477 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5478 /// conversion of the expression From to an Objective-C pointer type.
5479 /// Returns a valid but null ExprResult if no conversion sequence exists.
5480 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5481   if (checkPlaceholderForOverload(*this, From))
5482     return ExprError();
5483 
5484   QualType Ty = Context.getObjCIdType();
5485   ImplicitConversionSequence ICS =
5486     TryContextuallyConvertToObjCPointer(*this, From);
5487   if (!ICS.isBad())
5488     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5489   return ExprResult();
5490 }
5491 
5492 /// Determine whether the provided type is an integral type, or an enumeration
5493 /// type of a permitted flavor.
5494 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5495   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5496                                  : T->isIntegralOrUnscopedEnumerationType();
5497 }
5498 
5499 static ExprResult
5500 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5501                             Sema::ContextualImplicitConverter &Converter,
5502                             QualType T, UnresolvedSetImpl &ViableConversions) {
5503 
5504   if (Converter.Suppress)
5505     return ExprError();
5506 
5507   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5508   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5509     CXXConversionDecl *Conv =
5510         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5511     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5512     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5513   }
5514   return From;
5515 }
5516 
5517 static bool
5518 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5519                            Sema::ContextualImplicitConverter &Converter,
5520                            QualType T, bool HadMultipleCandidates,
5521                            UnresolvedSetImpl &ExplicitConversions) {
5522   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5523     DeclAccessPair Found = ExplicitConversions[0];
5524     CXXConversionDecl *Conversion =
5525         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5526 
5527     // The user probably meant to invoke the given explicit
5528     // conversion; use it.
5529     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5530     std::string TypeStr;
5531     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5532 
5533     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5534         << FixItHint::CreateInsertion(From->getLocStart(),
5535                                       "static_cast<" + TypeStr + ">(")
5536         << FixItHint::CreateInsertion(
5537                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5538     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5539 
5540     // If we aren't in a SFINAE context, build a call to the
5541     // explicit conversion function.
5542     if (SemaRef.isSFINAEContext())
5543       return true;
5544 
5545     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5546     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5547                                                        HadMultipleCandidates);
5548     if (Result.isInvalid())
5549       return true;
5550     // Record usage of conversion in an implicit cast.
5551     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5552                                     CK_UserDefinedConversion, Result.get(),
5553                                     nullptr, Result.get()->getValueKind());
5554   }
5555   return false;
5556 }
5557 
5558 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5559                              Sema::ContextualImplicitConverter &Converter,
5560                              QualType T, bool HadMultipleCandidates,
5561                              DeclAccessPair &Found) {
5562   CXXConversionDecl *Conversion =
5563       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5564   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5565 
5566   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5567   if (!Converter.SuppressConversion) {
5568     if (SemaRef.isSFINAEContext())
5569       return true;
5570 
5571     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5572         << From->getSourceRange();
5573   }
5574 
5575   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5576                                                      HadMultipleCandidates);
5577   if (Result.isInvalid())
5578     return true;
5579   // Record usage of conversion in an implicit cast.
5580   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5581                                   CK_UserDefinedConversion, Result.get(),
5582                                   nullptr, Result.get()->getValueKind());
5583   return false;
5584 }
5585 
5586 static ExprResult finishContextualImplicitConversion(
5587     Sema &SemaRef, SourceLocation Loc, Expr *From,
5588     Sema::ContextualImplicitConverter &Converter) {
5589   if (!Converter.match(From->getType()) && !Converter.Suppress)
5590     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5591         << From->getSourceRange();
5592 
5593   return SemaRef.DefaultLvalueConversion(From);
5594 }
5595 
5596 static void
5597 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5598                                   UnresolvedSetImpl &ViableConversions,
5599                                   OverloadCandidateSet &CandidateSet) {
5600   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5601     DeclAccessPair FoundDecl = ViableConversions[I];
5602     NamedDecl *D = FoundDecl.getDecl();
5603     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5604     if (isa<UsingShadowDecl>(D))
5605       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5606 
5607     CXXConversionDecl *Conv;
5608     FunctionTemplateDecl *ConvTemplate;
5609     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5610       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5611     else
5612       Conv = cast<CXXConversionDecl>(D);
5613 
5614     if (ConvTemplate)
5615       SemaRef.AddTemplateConversionCandidate(
5616         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5617         /*AllowObjCConversionOnExplicit=*/false);
5618     else
5619       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5620                                      ToType, CandidateSet,
5621                                      /*AllowObjCConversionOnExplicit=*/false);
5622   }
5623 }
5624 
5625 /// \brief Attempt to convert the given expression to a type which is accepted
5626 /// by the given converter.
5627 ///
5628 /// This routine will attempt to convert an expression of class type to a
5629 /// type accepted by the specified converter. In C++11 and before, the class
5630 /// must have a single non-explicit conversion function converting to a matching
5631 /// type. In C++1y, there can be multiple such conversion functions, but only
5632 /// one target type.
5633 ///
5634 /// \param Loc The source location of the construct that requires the
5635 /// conversion.
5636 ///
5637 /// \param From The expression we're converting from.
5638 ///
5639 /// \param Converter Used to control and diagnose the conversion process.
5640 ///
5641 /// \returns The expression, converted to an integral or enumeration type if
5642 /// successful.
5643 ExprResult Sema::PerformContextualImplicitConversion(
5644     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5645   // We can't perform any more checking for type-dependent expressions.
5646   if (From->isTypeDependent())
5647     return From;
5648 
5649   // Process placeholders immediately.
5650   if (From->hasPlaceholderType()) {
5651     ExprResult result = CheckPlaceholderExpr(From);
5652     if (result.isInvalid())
5653       return result;
5654     From = result.get();
5655   }
5656 
5657   // If the expression already has a matching type, we're golden.
5658   QualType T = From->getType();
5659   if (Converter.match(T))
5660     return DefaultLvalueConversion(From);
5661 
5662   // FIXME: Check for missing '()' if T is a function type?
5663 
5664   // We can only perform contextual implicit conversions on objects of class
5665   // type.
5666   const RecordType *RecordTy = T->getAs<RecordType>();
5667   if (!RecordTy || !getLangOpts().CPlusPlus) {
5668     if (!Converter.Suppress)
5669       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5670     return From;
5671   }
5672 
5673   // We must have a complete class type.
5674   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5675     ContextualImplicitConverter &Converter;
5676     Expr *From;
5677 
5678     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5679         : Converter(Converter), From(From) {}
5680 
5681     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5682       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5683     }
5684   } IncompleteDiagnoser(Converter, From);
5685 
5686   if (Converter.Suppress ? !isCompleteType(Loc, T)
5687                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5688     return From;
5689 
5690   // Look for a conversion to an integral or enumeration type.
5691   UnresolvedSet<4>
5692       ViableConversions; // These are *potentially* viable in C++1y.
5693   UnresolvedSet<4> ExplicitConversions;
5694   const auto &Conversions =
5695       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5696 
5697   bool HadMultipleCandidates =
5698       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5699 
5700   // To check that there is only one target type, in C++1y:
5701   QualType ToType;
5702   bool HasUniqueTargetType = true;
5703 
5704   // Collect explicit or viable (potentially in C++1y) conversions.
5705   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5706     NamedDecl *D = (*I)->getUnderlyingDecl();
5707     CXXConversionDecl *Conversion;
5708     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5709     if (ConvTemplate) {
5710       if (getLangOpts().CPlusPlus14)
5711         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5712       else
5713         continue; // C++11 does not consider conversion operator templates(?).
5714     } else
5715       Conversion = cast<CXXConversionDecl>(D);
5716 
5717     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5718            "Conversion operator templates are considered potentially "
5719            "viable in C++1y");
5720 
5721     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5722     if (Converter.match(CurToType) || ConvTemplate) {
5723 
5724       if (Conversion->isExplicit()) {
5725         // FIXME: For C++1y, do we need this restriction?
5726         // cf. diagnoseNoViableConversion()
5727         if (!ConvTemplate)
5728           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5729       } else {
5730         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5731           if (ToType.isNull())
5732             ToType = CurToType.getUnqualifiedType();
5733           else if (HasUniqueTargetType &&
5734                    (CurToType.getUnqualifiedType() != ToType))
5735             HasUniqueTargetType = false;
5736         }
5737         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5738       }
5739     }
5740   }
5741 
5742   if (getLangOpts().CPlusPlus14) {
5743     // C++1y [conv]p6:
5744     // ... An expression e of class type E appearing in such a context
5745     // is said to be contextually implicitly converted to a specified
5746     // type T and is well-formed if and only if e can be implicitly
5747     // converted to a type T that is determined as follows: E is searched
5748     // for conversion functions whose return type is cv T or reference to
5749     // cv T such that T is allowed by the context. There shall be
5750     // exactly one such T.
5751 
5752     // If no unique T is found:
5753     if (ToType.isNull()) {
5754       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5755                                      HadMultipleCandidates,
5756                                      ExplicitConversions))
5757         return ExprError();
5758       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5759     }
5760 
5761     // If more than one unique Ts are found:
5762     if (!HasUniqueTargetType)
5763       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5764                                          ViableConversions);
5765 
5766     // If one unique T is found:
5767     // First, build a candidate set from the previously recorded
5768     // potentially viable conversions.
5769     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5770     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5771                                       CandidateSet);
5772 
5773     // Then, perform overload resolution over the candidate set.
5774     OverloadCandidateSet::iterator Best;
5775     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5776     case OR_Success: {
5777       // Apply this conversion.
5778       DeclAccessPair Found =
5779           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5780       if (recordConversion(*this, Loc, From, Converter, T,
5781                            HadMultipleCandidates, Found))
5782         return ExprError();
5783       break;
5784     }
5785     case OR_Ambiguous:
5786       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5787                                          ViableConversions);
5788     case OR_No_Viable_Function:
5789       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5790                                      HadMultipleCandidates,
5791                                      ExplicitConversions))
5792         return ExprError();
5793     // fall through 'OR_Deleted' case.
5794     case OR_Deleted:
5795       // We'll complain below about a non-integral condition type.
5796       break;
5797     }
5798   } else {
5799     switch (ViableConversions.size()) {
5800     case 0: {
5801       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5802                                      HadMultipleCandidates,
5803                                      ExplicitConversions))
5804         return ExprError();
5805 
5806       // We'll complain below about a non-integral condition type.
5807       break;
5808     }
5809     case 1: {
5810       // Apply this conversion.
5811       DeclAccessPair Found = ViableConversions[0];
5812       if (recordConversion(*this, Loc, From, Converter, T,
5813                            HadMultipleCandidates, Found))
5814         return ExprError();
5815       break;
5816     }
5817     default:
5818       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5819                                          ViableConversions);
5820     }
5821   }
5822 
5823   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5824 }
5825 
5826 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5827 /// an acceptable non-member overloaded operator for a call whose
5828 /// arguments have types T1 (and, if non-empty, T2). This routine
5829 /// implements the check in C++ [over.match.oper]p3b2 concerning
5830 /// enumeration types.
5831 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5832                                                    FunctionDecl *Fn,
5833                                                    ArrayRef<Expr *> Args) {
5834   QualType T1 = Args[0]->getType();
5835   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5836 
5837   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5838     return true;
5839 
5840   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5841     return true;
5842 
5843   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5844   if (Proto->getNumParams() < 1)
5845     return false;
5846 
5847   if (T1->isEnumeralType()) {
5848     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5849     if (Context.hasSameUnqualifiedType(T1, ArgType))
5850       return true;
5851   }
5852 
5853   if (Proto->getNumParams() < 2)
5854     return false;
5855 
5856   if (!T2.isNull() && T2->isEnumeralType()) {
5857     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5858     if (Context.hasSameUnqualifiedType(T2, ArgType))
5859       return true;
5860   }
5861 
5862   return false;
5863 }
5864 
5865 /// AddOverloadCandidate - Adds the given function to the set of
5866 /// candidate functions, using the given function call arguments.  If
5867 /// @p SuppressUserConversions, then don't allow user-defined
5868 /// conversions via constructors or conversion operators.
5869 ///
5870 /// \param PartialOverloading true if we are performing "partial" overloading
5871 /// based on an incomplete set of function arguments. This feature is used by
5872 /// code completion.
5873 void
5874 Sema::AddOverloadCandidate(FunctionDecl *Function,
5875                            DeclAccessPair FoundDecl,
5876                            ArrayRef<Expr *> Args,
5877                            OverloadCandidateSet &CandidateSet,
5878                            bool SuppressUserConversions,
5879                            bool PartialOverloading,
5880                            bool AllowExplicit,
5881                            ConversionSequenceList EarlyConversions) {
5882   const FunctionProtoType *Proto
5883     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5884   assert(Proto && "Functions without a prototype cannot be overloaded");
5885   assert(!Function->getDescribedFunctionTemplate() &&
5886          "Use AddTemplateOverloadCandidate for function templates");
5887 
5888   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5889     if (!isa<CXXConstructorDecl>(Method)) {
5890       // If we get here, it's because we're calling a member function
5891       // that is named without a member access expression (e.g.,
5892       // "this->f") that was either written explicitly or created
5893       // implicitly. This can happen with a qualified call to a member
5894       // function, e.g., X::f(). We use an empty type for the implied
5895       // object argument (C++ [over.call.func]p3), and the acting context
5896       // is irrelevant.
5897       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
5898                          Expr::Classification::makeSimpleLValue(), Args,
5899                          CandidateSet, SuppressUserConversions,
5900                          PartialOverloading, EarlyConversions);
5901       return;
5902     }
5903     // We treat a constructor like a non-member function, since its object
5904     // argument doesn't participate in overload resolution.
5905   }
5906 
5907   if (!CandidateSet.isNewCandidate(Function))
5908     return;
5909 
5910   // C++ [over.match.oper]p3:
5911   //   if no operand has a class type, only those non-member functions in the
5912   //   lookup set that have a first parameter of type T1 or "reference to
5913   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5914   //   is a right operand) a second parameter of type T2 or "reference to
5915   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5916   //   candidate functions.
5917   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5918       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5919     return;
5920 
5921   // C++11 [class.copy]p11: [DR1402]
5922   //   A defaulted move constructor that is defined as deleted is ignored by
5923   //   overload resolution.
5924   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5925   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5926       Constructor->isMoveConstructor())
5927     return;
5928 
5929   // Overload resolution is always an unevaluated context.
5930   EnterExpressionEvaluationContext Unevaluated(
5931       *this, Sema::ExpressionEvaluationContext::Unevaluated);
5932 
5933   // Add this candidate
5934   OverloadCandidate &Candidate =
5935       CandidateSet.addCandidate(Args.size(), EarlyConversions);
5936   Candidate.FoundDecl = FoundDecl;
5937   Candidate.Function = Function;
5938   Candidate.Viable = true;
5939   Candidate.IsSurrogate = false;
5940   Candidate.IgnoreObjectArgument = false;
5941   Candidate.ExplicitCallArguments = Args.size();
5942 
5943   if (Constructor) {
5944     // C++ [class.copy]p3:
5945     //   A member function template is never instantiated to perform the copy
5946     //   of a class object to an object of its class type.
5947     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5948     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
5949         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5950          IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5951                        ClassType))) {
5952       Candidate.Viable = false;
5953       Candidate.FailureKind = ovl_fail_illegal_constructor;
5954       return;
5955     }
5956 
5957     // C++ [over.match.funcs]p8: (proposed DR resolution)
5958     //   A constructor inherited from class type C that has a first parameter
5959     //   of type "reference to P" (including such a constructor instantiated
5960     //   from a template) is excluded from the set of candidate functions when
5961     //   constructing an object of type cv D if the argument list has exactly
5962     //   one argument and D is reference-related to P and P is reference-related
5963     //   to C.
5964     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
5965     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
5966         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
5967       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
5968       QualType C = Context.getRecordType(Constructor->getParent());
5969       QualType D = Context.getRecordType(Shadow->getParent());
5970       SourceLocation Loc = Args.front()->getExprLoc();
5971       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
5972           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
5973         Candidate.Viable = false;
5974         Candidate.FailureKind = ovl_fail_inhctor_slice;
5975         return;
5976       }
5977     }
5978   }
5979 
5980   unsigned NumParams = Proto->getNumParams();
5981 
5982   // (C++ 13.3.2p2): A candidate function having fewer than m
5983   // parameters is viable only if it has an ellipsis in its parameter
5984   // list (8.3.5).
5985   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
5986       !Proto->isVariadic()) {
5987     Candidate.Viable = false;
5988     Candidate.FailureKind = ovl_fail_too_many_arguments;
5989     return;
5990   }
5991 
5992   // (C++ 13.3.2p2): A candidate function having more than m parameters
5993   // is viable only if the (m+1)st parameter has a default argument
5994   // (8.3.6). For the purposes of overload resolution, the
5995   // parameter list is truncated on the right, so that there are
5996   // exactly m parameters.
5997   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5998   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5999     // Not enough arguments.
6000     Candidate.Viable = false;
6001     Candidate.FailureKind = ovl_fail_too_few_arguments;
6002     return;
6003   }
6004 
6005   // (CUDA B.1): Check for invalid calls between targets.
6006   if (getLangOpts().CUDA)
6007     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6008       // Skip the check for callers that are implicit members, because in this
6009       // case we may not yet know what the member's target is; the target is
6010       // inferred for the member automatically, based on the bases and fields of
6011       // the class.
6012       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6013         Candidate.Viable = false;
6014         Candidate.FailureKind = ovl_fail_bad_target;
6015         return;
6016       }
6017 
6018   // Determine the implicit conversion sequences for each of the
6019   // arguments.
6020   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6021     if (Candidate.Conversions[ArgIdx].isInitialized()) {
6022       // We already formed a conversion sequence for this parameter during
6023       // template argument deduction.
6024     } else if (ArgIdx < NumParams) {
6025       // (C++ 13.3.2p3): for F to be a viable function, there shall
6026       // exist for each argument an implicit conversion sequence
6027       // (13.3.3.1) that converts that argument to the corresponding
6028       // parameter of F.
6029       QualType ParamType = Proto->getParamType(ArgIdx);
6030       Candidate.Conversions[ArgIdx]
6031         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6032                                 SuppressUserConversions,
6033                                 /*InOverloadResolution=*/true,
6034                                 /*AllowObjCWritebackConversion=*/
6035                                   getLangOpts().ObjCAutoRefCount,
6036                                 AllowExplicit);
6037       if (Candidate.Conversions[ArgIdx].isBad()) {
6038         Candidate.Viable = false;
6039         Candidate.FailureKind = ovl_fail_bad_conversion;
6040         return;
6041       }
6042     } else {
6043       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6044       // argument for which there is no corresponding parameter is
6045       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6046       Candidate.Conversions[ArgIdx].setEllipsis();
6047     }
6048   }
6049 
6050   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6051     Candidate.Viable = false;
6052     Candidate.FailureKind = ovl_fail_enable_if;
6053     Candidate.DeductionFailure.Data = FailedAttr;
6054     return;
6055   }
6056 
6057   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6058     Candidate.Viable = false;
6059     Candidate.FailureKind = ovl_fail_ext_disabled;
6060     return;
6061   }
6062 }
6063 
6064 ObjCMethodDecl *
6065 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6066                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6067   if (Methods.size() <= 1)
6068     return nullptr;
6069 
6070   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6071     bool Match = true;
6072     ObjCMethodDecl *Method = Methods[b];
6073     unsigned NumNamedArgs = Sel.getNumArgs();
6074     // Method might have more arguments than selector indicates. This is due
6075     // to addition of c-style arguments in method.
6076     if (Method->param_size() > NumNamedArgs)
6077       NumNamedArgs = Method->param_size();
6078     if (Args.size() < NumNamedArgs)
6079       continue;
6080 
6081     for (unsigned i = 0; i < NumNamedArgs; i++) {
6082       // We can't do any type-checking on a type-dependent argument.
6083       if (Args[i]->isTypeDependent()) {
6084         Match = false;
6085         break;
6086       }
6087 
6088       ParmVarDecl *param = Method->parameters()[i];
6089       Expr *argExpr = Args[i];
6090       assert(argExpr && "SelectBestMethod(): missing expression");
6091 
6092       // Strip the unbridged-cast placeholder expression off unless it's
6093       // a consumed argument.
6094       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6095           !param->hasAttr<CFConsumedAttr>())
6096         argExpr = stripARCUnbridgedCast(argExpr);
6097 
6098       // If the parameter is __unknown_anytype, move on to the next method.
6099       if (param->getType() == Context.UnknownAnyTy) {
6100         Match = false;
6101         break;
6102       }
6103 
6104       ImplicitConversionSequence ConversionState
6105         = TryCopyInitialization(*this, argExpr, param->getType(),
6106                                 /*SuppressUserConversions*/false,
6107                                 /*InOverloadResolution=*/true,
6108                                 /*AllowObjCWritebackConversion=*/
6109                                 getLangOpts().ObjCAutoRefCount,
6110                                 /*AllowExplicit*/false);
6111       // This function looks for a reasonably-exact match, so we consider
6112       // incompatible pointer conversions to be a failure here.
6113       if (ConversionState.isBad() ||
6114           (ConversionState.isStandard() &&
6115            ConversionState.Standard.Second ==
6116                ICK_Incompatible_Pointer_Conversion)) {
6117         Match = false;
6118         break;
6119       }
6120     }
6121     // Promote additional arguments to variadic methods.
6122     if (Match && Method->isVariadic()) {
6123       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6124         if (Args[i]->isTypeDependent()) {
6125           Match = false;
6126           break;
6127         }
6128         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6129                                                           nullptr);
6130         if (Arg.isInvalid()) {
6131           Match = false;
6132           break;
6133         }
6134       }
6135     } else {
6136       // Check for extra arguments to non-variadic methods.
6137       if (Args.size() != NumNamedArgs)
6138         Match = false;
6139       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6140         // Special case when selectors have no argument. In this case, select
6141         // one with the most general result type of 'id'.
6142         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6143           QualType ReturnT = Methods[b]->getReturnType();
6144           if (ReturnT->isObjCIdType())
6145             return Methods[b];
6146         }
6147       }
6148     }
6149 
6150     if (Match)
6151       return Method;
6152   }
6153   return nullptr;
6154 }
6155 
6156 // specific_attr_iterator iterates over enable_if attributes in reverse, and
6157 // enable_if is order-sensitive. As a result, we need to reverse things
6158 // sometimes. Size of 4 elements is arbitrary.
6159 static SmallVector<EnableIfAttr *, 4>
6160 getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6161   SmallVector<EnableIfAttr *, 4> Result;
6162   if (!Function->hasAttrs())
6163     return Result;
6164 
6165   const auto &FuncAttrs = Function->getAttrs();
6166   for (Attr *Attr : FuncAttrs)
6167     if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6168       Result.push_back(EnableIf);
6169 
6170   std::reverse(Result.begin(), Result.end());
6171   return Result;
6172 }
6173 
6174 static bool
6175 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6176                                  ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6177                                  bool MissingImplicitThis, Expr *&ConvertedThis,
6178                                  SmallVectorImpl<Expr *> &ConvertedArgs) {
6179   if (ThisArg) {
6180     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6181     assert(!isa<CXXConstructorDecl>(Method) &&
6182            "Shouldn't have `this` for ctors!");
6183     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6184     ExprResult R = S.PerformObjectArgumentInitialization(
6185         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6186     if (R.isInvalid())
6187       return false;
6188     ConvertedThis = R.get();
6189   } else {
6190     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6191       (void)MD;
6192       assert((MissingImplicitThis || MD->isStatic() ||
6193               isa<CXXConstructorDecl>(MD)) &&
6194              "Expected `this` for non-ctor instance methods");
6195     }
6196     ConvertedThis = nullptr;
6197   }
6198 
6199   // Ignore any variadic arguments. Converting them is pointless, since the
6200   // user can't refer to them in the function condition.
6201   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6202 
6203   // Convert the arguments.
6204   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6205     ExprResult R;
6206     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6207                                         S.Context, Function->getParamDecl(I)),
6208                                     SourceLocation(), Args[I]);
6209 
6210     if (R.isInvalid())
6211       return false;
6212 
6213     ConvertedArgs.push_back(R.get());
6214   }
6215 
6216   if (Trap.hasErrorOccurred())
6217     return false;
6218 
6219   // Push default arguments if needed.
6220   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6221     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6222       ParmVarDecl *P = Function->getParamDecl(i);
6223       ExprResult R = S.PerformCopyInitialization(
6224           InitializedEntity::InitializeParameter(S.Context,
6225                                                  Function->getParamDecl(i)),
6226           SourceLocation(),
6227           P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6228                                            : P->getDefaultArg());
6229       if (R.isInvalid())
6230         return false;
6231       ConvertedArgs.push_back(R.get());
6232     }
6233 
6234     if (Trap.hasErrorOccurred())
6235       return false;
6236   }
6237   return true;
6238 }
6239 
6240 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6241                                   bool MissingImplicitThis) {
6242   SmallVector<EnableIfAttr *, 4> EnableIfAttrs =
6243       getOrderedEnableIfAttrs(Function);
6244   if (EnableIfAttrs.empty())
6245     return nullptr;
6246 
6247   SFINAETrap Trap(*this);
6248   SmallVector<Expr *, 16> ConvertedArgs;
6249   // FIXME: We should look into making enable_if late-parsed.
6250   Expr *DiscardedThis;
6251   if (!convertArgsForAvailabilityChecks(
6252           *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6253           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6254     return EnableIfAttrs[0];
6255 
6256   for (auto *EIA : EnableIfAttrs) {
6257     APValue Result;
6258     // FIXME: This doesn't consider value-dependent cases, because doing so is
6259     // very difficult. Ideally, we should handle them more gracefully.
6260     if (!EIA->getCond()->EvaluateWithSubstitution(
6261             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6262       return EIA;
6263 
6264     if (!Result.isInt() || !Result.getInt().getBoolValue())
6265       return EIA;
6266   }
6267   return nullptr;
6268 }
6269 
6270 template <typename CheckFn>
6271 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6272                                         bool ArgDependent, SourceLocation Loc,
6273                                         CheckFn &&IsSuccessful) {
6274   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6275   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6276     if (ArgDependent == DIA->getArgDependent())
6277       Attrs.push_back(DIA);
6278   }
6279 
6280   // Common case: No diagnose_if attributes, so we can quit early.
6281   if (Attrs.empty())
6282     return false;
6283 
6284   auto WarningBegin = std::stable_partition(
6285       Attrs.begin(), Attrs.end(),
6286       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6287 
6288   // Note that diagnose_if attributes are late-parsed, so they appear in the
6289   // correct order (unlike enable_if attributes).
6290   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6291                                IsSuccessful);
6292   if (ErrAttr != WarningBegin) {
6293     const DiagnoseIfAttr *DIA = *ErrAttr;
6294     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6295     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6296         << DIA->getParent() << DIA->getCond()->getSourceRange();
6297     return true;
6298   }
6299 
6300   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6301     if (IsSuccessful(DIA)) {
6302       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6303       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6304           << DIA->getParent() << DIA->getCond()->getSourceRange();
6305     }
6306 
6307   return false;
6308 }
6309 
6310 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6311                                                const Expr *ThisArg,
6312                                                ArrayRef<const Expr *> Args,
6313                                                SourceLocation Loc) {
6314   return diagnoseDiagnoseIfAttrsWith(
6315       *this, Function, /*ArgDependent=*/true, Loc,
6316       [&](const DiagnoseIfAttr *DIA) {
6317         APValue Result;
6318         // It's sane to use the same Args for any redecl of this function, since
6319         // EvaluateWithSubstitution only cares about the position of each
6320         // argument in the arg list, not the ParmVarDecl* it maps to.
6321         if (!DIA->getCond()->EvaluateWithSubstitution(
6322                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6323           return false;
6324         return Result.isInt() && Result.getInt().getBoolValue();
6325       });
6326 }
6327 
6328 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6329                                                  SourceLocation Loc) {
6330   return diagnoseDiagnoseIfAttrsWith(
6331       *this, ND, /*ArgDependent=*/false, Loc,
6332       [&](const DiagnoseIfAttr *DIA) {
6333         bool Result;
6334         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6335                Result;
6336       });
6337 }
6338 
6339 /// \brief Add all of the function declarations in the given function set to
6340 /// the overload candidate set.
6341 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6342                                  ArrayRef<Expr *> Args,
6343                                  OverloadCandidateSet& CandidateSet,
6344                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6345                                  bool SuppressUserConversions,
6346                                  bool PartialOverloading,
6347                                  bool FirstArgumentIsBase) {
6348   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6349     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6350     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6351       ArrayRef<Expr *> FunctionArgs = Args;
6352       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6353         QualType ObjectType;
6354         Expr::Classification ObjectClassification;
6355         if (Args.size() > 0) {
6356           if (Expr *E = Args[0]) {
6357             // Use the explit base to restrict the lookup:
6358             ObjectType = E->getType();
6359             ObjectClassification = E->Classify(Context);
6360           } // .. else there is an implit base.
6361           FunctionArgs = Args.slice(1);
6362         }
6363         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6364                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6365                            ObjectClassification, FunctionArgs, CandidateSet,
6366                            SuppressUserConversions, PartialOverloading);
6367       } else {
6368         // Slice the first argument (which is the base) when we access
6369         // static method as non-static
6370         if (Args.size() > 0 && (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6371                                              !isa<CXXConstructorDecl>(FD)))) {
6372           assert(cast<CXXMethodDecl>(FD)->isStatic());
6373           FunctionArgs = Args.slice(1);
6374         }
6375         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6376                              SuppressUserConversions, PartialOverloading);
6377       }
6378     } else {
6379       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
6380       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6381           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) {
6382         QualType ObjectType;
6383         Expr::Classification ObjectClassification;
6384         if (Expr *E = Args[0]) {
6385           // Use the explit base to restrict the lookup:
6386           ObjectType = E->getType();
6387           ObjectClassification = E->Classify(Context);
6388         } // .. else there is an implit base.
6389         AddMethodTemplateCandidate(
6390             FunTmpl, F.getPair(),
6391             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6392             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6393             Args.slice(1), CandidateSet, SuppressUserConversions,
6394             PartialOverloading);
6395       } else {
6396         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6397                                      ExplicitTemplateArgs, Args,
6398                                      CandidateSet, SuppressUserConversions,
6399                                      PartialOverloading);
6400       }
6401     }
6402   }
6403 }
6404 
6405 /// AddMethodCandidate - Adds a named decl (which is some kind of
6406 /// method) as a method candidate to the given overload set.
6407 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6408                               QualType ObjectType,
6409                               Expr::Classification ObjectClassification,
6410                               ArrayRef<Expr *> Args,
6411                               OverloadCandidateSet& CandidateSet,
6412                               bool SuppressUserConversions) {
6413   NamedDecl *Decl = FoundDecl.getDecl();
6414   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6415 
6416   if (isa<UsingShadowDecl>(Decl))
6417     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6418 
6419   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6420     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6421            "Expected a member function template");
6422     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6423                                /*ExplicitArgs*/ nullptr, ObjectType,
6424                                ObjectClassification, Args, CandidateSet,
6425                                SuppressUserConversions);
6426   } else {
6427     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6428                        ObjectType, ObjectClassification, Args, CandidateSet,
6429                        SuppressUserConversions);
6430   }
6431 }
6432 
6433 /// AddMethodCandidate - Adds the given C++ member function to the set
6434 /// of candidate functions, using the given function call arguments
6435 /// and the object argument (@c Object). For example, in a call
6436 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6437 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6438 /// allow user-defined conversions via constructors or conversion
6439 /// operators.
6440 void
6441 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6442                          CXXRecordDecl *ActingContext, QualType ObjectType,
6443                          Expr::Classification ObjectClassification,
6444                          ArrayRef<Expr *> Args,
6445                          OverloadCandidateSet &CandidateSet,
6446                          bool SuppressUserConversions,
6447                          bool PartialOverloading,
6448                          ConversionSequenceList EarlyConversions) {
6449   const FunctionProtoType *Proto
6450     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6451   assert(Proto && "Methods without a prototype cannot be overloaded");
6452   assert(!isa<CXXConstructorDecl>(Method) &&
6453          "Use AddOverloadCandidate for constructors");
6454 
6455   if (!CandidateSet.isNewCandidate(Method))
6456     return;
6457 
6458   // C++11 [class.copy]p23: [DR1402]
6459   //   A defaulted move assignment operator that is defined as deleted is
6460   //   ignored by overload resolution.
6461   if (Method->isDefaulted() && Method->isDeleted() &&
6462       Method->isMoveAssignmentOperator())
6463     return;
6464 
6465   // Overload resolution is always an unevaluated context.
6466   EnterExpressionEvaluationContext Unevaluated(
6467       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6468 
6469   // Add this candidate
6470   OverloadCandidate &Candidate =
6471       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6472   Candidate.FoundDecl = FoundDecl;
6473   Candidate.Function = Method;
6474   Candidate.IsSurrogate = false;
6475   Candidate.IgnoreObjectArgument = false;
6476   Candidate.ExplicitCallArguments = Args.size();
6477 
6478   unsigned NumParams = Proto->getNumParams();
6479 
6480   // (C++ 13.3.2p2): A candidate function having fewer than m
6481   // parameters is viable only if it has an ellipsis in its parameter
6482   // list (8.3.5).
6483   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6484       !Proto->isVariadic()) {
6485     Candidate.Viable = false;
6486     Candidate.FailureKind = ovl_fail_too_many_arguments;
6487     return;
6488   }
6489 
6490   // (C++ 13.3.2p2): A candidate function having more than m parameters
6491   // is viable only if the (m+1)st parameter has a default argument
6492   // (8.3.6). For the purposes of overload resolution, the
6493   // parameter list is truncated on the right, so that there are
6494   // exactly m parameters.
6495   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6496   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6497     // Not enough arguments.
6498     Candidate.Viable = false;
6499     Candidate.FailureKind = ovl_fail_too_few_arguments;
6500     return;
6501   }
6502 
6503   Candidate.Viable = true;
6504 
6505   if (Method->isStatic() || ObjectType.isNull())
6506     // The implicit object argument is ignored.
6507     Candidate.IgnoreObjectArgument = true;
6508   else {
6509     // Determine the implicit conversion sequence for the object
6510     // parameter.
6511     Candidate.Conversions[0] = TryObjectArgumentInitialization(
6512         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6513         Method, ActingContext);
6514     if (Candidate.Conversions[0].isBad()) {
6515       Candidate.Viable = false;
6516       Candidate.FailureKind = ovl_fail_bad_conversion;
6517       return;
6518     }
6519   }
6520 
6521   // (CUDA B.1): Check for invalid calls between targets.
6522   if (getLangOpts().CUDA)
6523     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6524       if (!IsAllowedCUDACall(Caller, Method)) {
6525         Candidate.Viable = false;
6526         Candidate.FailureKind = ovl_fail_bad_target;
6527         return;
6528       }
6529 
6530   // Determine the implicit conversion sequences for each of the
6531   // arguments.
6532   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6533     if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6534       // We already formed a conversion sequence for this parameter during
6535       // template argument deduction.
6536     } else if (ArgIdx < NumParams) {
6537       // (C++ 13.3.2p3): for F to be a viable function, there shall
6538       // exist for each argument an implicit conversion sequence
6539       // (13.3.3.1) that converts that argument to the corresponding
6540       // parameter of F.
6541       QualType ParamType = Proto->getParamType(ArgIdx);
6542       Candidate.Conversions[ArgIdx + 1]
6543         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6544                                 SuppressUserConversions,
6545                                 /*InOverloadResolution=*/true,
6546                                 /*AllowObjCWritebackConversion=*/
6547                                   getLangOpts().ObjCAutoRefCount);
6548       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6549         Candidate.Viable = false;
6550         Candidate.FailureKind = ovl_fail_bad_conversion;
6551         return;
6552       }
6553     } else {
6554       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6555       // argument for which there is no corresponding parameter is
6556       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6557       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6558     }
6559   }
6560 
6561   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6562     Candidate.Viable = false;
6563     Candidate.FailureKind = ovl_fail_enable_if;
6564     Candidate.DeductionFailure.Data = FailedAttr;
6565     return;
6566   }
6567 }
6568 
6569 /// \brief Add a C++ member function template as a candidate to the candidate
6570 /// set, using template argument deduction to produce an appropriate member
6571 /// function template specialization.
6572 void
6573 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6574                                  DeclAccessPair FoundDecl,
6575                                  CXXRecordDecl *ActingContext,
6576                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6577                                  QualType ObjectType,
6578                                  Expr::Classification ObjectClassification,
6579                                  ArrayRef<Expr *> Args,
6580                                  OverloadCandidateSet& CandidateSet,
6581                                  bool SuppressUserConversions,
6582                                  bool PartialOverloading) {
6583   if (!CandidateSet.isNewCandidate(MethodTmpl))
6584     return;
6585 
6586   // C++ [over.match.funcs]p7:
6587   //   In each case where a candidate is a function template, candidate
6588   //   function template specializations are generated using template argument
6589   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6590   //   candidate functions in the usual way.113) A given name can refer to one
6591   //   or more function templates and also to a set of overloaded non-template
6592   //   functions. In such a case, the candidate functions generated from each
6593   //   function template are combined with the set of non-template candidate
6594   //   functions.
6595   TemplateDeductionInfo Info(CandidateSet.getLocation());
6596   FunctionDecl *Specialization = nullptr;
6597   ConversionSequenceList Conversions;
6598   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6599           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6600           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6601             return CheckNonDependentConversions(
6602                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6603                 SuppressUserConversions, ActingContext, ObjectType,
6604                 ObjectClassification);
6605           })) {
6606     OverloadCandidate &Candidate =
6607         CandidateSet.addCandidate(Conversions.size(), Conversions);
6608     Candidate.FoundDecl = FoundDecl;
6609     Candidate.Function = MethodTmpl->getTemplatedDecl();
6610     Candidate.Viable = false;
6611     Candidate.IsSurrogate = false;
6612     Candidate.IgnoreObjectArgument =
6613         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6614         ObjectType.isNull();
6615     Candidate.ExplicitCallArguments = Args.size();
6616     if (Result == TDK_NonDependentConversionFailure)
6617       Candidate.FailureKind = ovl_fail_bad_conversion;
6618     else {
6619       Candidate.FailureKind = ovl_fail_bad_deduction;
6620       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6621                                                             Info);
6622     }
6623     return;
6624   }
6625 
6626   // Add the function template specialization produced by template argument
6627   // deduction as a candidate.
6628   assert(Specialization && "Missing member function template specialization?");
6629   assert(isa<CXXMethodDecl>(Specialization) &&
6630          "Specialization is not a member function?");
6631   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6632                      ActingContext, ObjectType, ObjectClassification, Args,
6633                      CandidateSet, SuppressUserConversions, PartialOverloading,
6634                      Conversions);
6635 }
6636 
6637 /// \brief Add a C++ function template specialization as a candidate
6638 /// in the candidate set, using template argument deduction to produce
6639 /// an appropriate function template specialization.
6640 void
6641 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6642                                    DeclAccessPair FoundDecl,
6643                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6644                                    ArrayRef<Expr *> Args,
6645                                    OverloadCandidateSet& CandidateSet,
6646                                    bool SuppressUserConversions,
6647                                    bool PartialOverloading) {
6648   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6649     return;
6650 
6651   // C++ [over.match.funcs]p7:
6652   //   In each case where a candidate is a function template, candidate
6653   //   function template specializations are generated using template argument
6654   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6655   //   candidate functions in the usual way.113) A given name can refer to one
6656   //   or more function templates and also to a set of overloaded non-template
6657   //   functions. In such a case, the candidate functions generated from each
6658   //   function template are combined with the set of non-template candidate
6659   //   functions.
6660   TemplateDeductionInfo Info(CandidateSet.getLocation());
6661   FunctionDecl *Specialization = nullptr;
6662   ConversionSequenceList Conversions;
6663   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6664           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6665           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6666             return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6667                                                 Args, CandidateSet, Conversions,
6668                                                 SuppressUserConversions);
6669           })) {
6670     OverloadCandidate &Candidate =
6671         CandidateSet.addCandidate(Conversions.size(), Conversions);
6672     Candidate.FoundDecl = FoundDecl;
6673     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6674     Candidate.Viable = false;
6675     Candidate.IsSurrogate = false;
6676     // Ignore the object argument if there is one, since we don't have an object
6677     // type.
6678     Candidate.IgnoreObjectArgument =
6679         isa<CXXMethodDecl>(Candidate.Function) &&
6680         !isa<CXXConstructorDecl>(Candidate.Function);
6681     Candidate.ExplicitCallArguments = Args.size();
6682     if (Result == TDK_NonDependentConversionFailure)
6683       Candidate.FailureKind = ovl_fail_bad_conversion;
6684     else {
6685       Candidate.FailureKind = ovl_fail_bad_deduction;
6686       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6687                                                             Info);
6688     }
6689     return;
6690   }
6691 
6692   // Add the function template specialization produced by template argument
6693   // deduction as a candidate.
6694   assert(Specialization && "Missing function template specialization?");
6695   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6696                        SuppressUserConversions, PartialOverloading,
6697                        /*AllowExplicit*/false, Conversions);
6698 }
6699 
6700 /// Check that implicit conversion sequences can be formed for each argument
6701 /// whose corresponding parameter has a non-dependent type, per DR1391's
6702 /// [temp.deduct.call]p10.
6703 bool Sema::CheckNonDependentConversions(
6704     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6705     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6706     ConversionSequenceList &Conversions, bool SuppressUserConversions,
6707     CXXRecordDecl *ActingContext, QualType ObjectType,
6708     Expr::Classification ObjectClassification) {
6709   // FIXME: The cases in which we allow explicit conversions for constructor
6710   // arguments never consider calling a constructor template. It's not clear
6711   // that is correct.
6712   const bool AllowExplicit = false;
6713 
6714   auto *FD = FunctionTemplate->getTemplatedDecl();
6715   auto *Method = dyn_cast<CXXMethodDecl>(FD);
6716   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6717   unsigned ThisConversions = HasThisConversion ? 1 : 0;
6718 
6719   Conversions =
6720       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6721 
6722   // Overload resolution is always an unevaluated context.
6723   EnterExpressionEvaluationContext Unevaluated(
6724       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6725 
6726   // For a method call, check the 'this' conversion here too. DR1391 doesn't
6727   // require that, but this check should never result in a hard error, and
6728   // overload resolution is permitted to sidestep instantiations.
6729   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6730       !ObjectType.isNull()) {
6731     Conversions[0] = TryObjectArgumentInitialization(
6732         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6733         Method, ActingContext);
6734     if (Conversions[0].isBad())
6735       return true;
6736   }
6737 
6738   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6739        ++I) {
6740     QualType ParamType = ParamTypes[I];
6741     if (!ParamType->isDependentType()) {
6742       Conversions[ThisConversions + I]
6743         = TryCopyInitialization(*this, Args[I], ParamType,
6744                                 SuppressUserConversions,
6745                                 /*InOverloadResolution=*/true,
6746                                 /*AllowObjCWritebackConversion=*/
6747                                   getLangOpts().ObjCAutoRefCount,
6748                                 AllowExplicit);
6749       if (Conversions[ThisConversions + I].isBad())
6750         return true;
6751     }
6752   }
6753 
6754   return false;
6755 }
6756 
6757 /// Determine whether this is an allowable conversion from the result
6758 /// of an explicit conversion operator to the expected type, per C++
6759 /// [over.match.conv]p1 and [over.match.ref]p1.
6760 ///
6761 /// \param ConvType The return type of the conversion function.
6762 ///
6763 /// \param ToType The type we are converting to.
6764 ///
6765 /// \param AllowObjCPointerConversion Allow a conversion from one
6766 /// Objective-C pointer to another.
6767 ///
6768 /// \returns true if the conversion is allowable, false otherwise.
6769 static bool isAllowableExplicitConversion(Sema &S,
6770                                           QualType ConvType, QualType ToType,
6771                                           bool AllowObjCPointerConversion) {
6772   QualType ToNonRefType = ToType.getNonReferenceType();
6773 
6774   // Easy case: the types are the same.
6775   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6776     return true;
6777 
6778   // Allow qualification conversions.
6779   bool ObjCLifetimeConversion;
6780   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6781                                   ObjCLifetimeConversion))
6782     return true;
6783 
6784   // If we're not allowed to consider Objective-C pointer conversions,
6785   // we're done.
6786   if (!AllowObjCPointerConversion)
6787     return false;
6788 
6789   // Is this an Objective-C pointer conversion?
6790   bool IncompatibleObjC = false;
6791   QualType ConvertedType;
6792   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6793                                    IncompatibleObjC);
6794 }
6795 
6796 /// AddConversionCandidate - Add a C++ conversion function as a
6797 /// candidate in the candidate set (C++ [over.match.conv],
6798 /// C++ [over.match.copy]). From is the expression we're converting from,
6799 /// and ToType is the type that we're eventually trying to convert to
6800 /// (which may or may not be the same type as the type that the
6801 /// conversion function produces).
6802 void
6803 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6804                              DeclAccessPair FoundDecl,
6805                              CXXRecordDecl *ActingContext,
6806                              Expr *From, QualType ToType,
6807                              OverloadCandidateSet& CandidateSet,
6808                              bool AllowObjCConversionOnExplicit,
6809                              bool AllowResultConversion) {
6810   assert(!Conversion->getDescribedFunctionTemplate() &&
6811          "Conversion function templates use AddTemplateConversionCandidate");
6812   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6813   if (!CandidateSet.isNewCandidate(Conversion))
6814     return;
6815 
6816   // If the conversion function has an undeduced return type, trigger its
6817   // deduction now.
6818   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6819     if (DeduceReturnType(Conversion, From->getExprLoc()))
6820       return;
6821     ConvType = Conversion->getConversionType().getNonReferenceType();
6822   }
6823 
6824   // If we don't allow any conversion of the result type, ignore conversion
6825   // functions that don't convert to exactly (possibly cv-qualified) T.
6826   if (!AllowResultConversion &&
6827       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
6828     return;
6829 
6830   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6831   // operator is only a candidate if its return type is the target type or
6832   // can be converted to the target type with a qualification conversion.
6833   if (Conversion->isExplicit() &&
6834       !isAllowableExplicitConversion(*this, ConvType, ToType,
6835                                      AllowObjCConversionOnExplicit))
6836     return;
6837 
6838   // Overload resolution is always an unevaluated context.
6839   EnterExpressionEvaluationContext Unevaluated(
6840       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6841 
6842   // Add this candidate
6843   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6844   Candidate.FoundDecl = FoundDecl;
6845   Candidate.Function = Conversion;
6846   Candidate.IsSurrogate = false;
6847   Candidate.IgnoreObjectArgument = false;
6848   Candidate.FinalConversion.setAsIdentityConversion();
6849   Candidate.FinalConversion.setFromType(ConvType);
6850   Candidate.FinalConversion.setAllToTypes(ToType);
6851   Candidate.Viable = true;
6852   Candidate.ExplicitCallArguments = 1;
6853 
6854   // C++ [over.match.funcs]p4:
6855   //   For conversion functions, the function is considered to be a member of
6856   //   the class of the implicit implied object argument for the purpose of
6857   //   defining the type of the implicit object parameter.
6858   //
6859   // Determine the implicit conversion sequence for the implicit
6860   // object parameter.
6861   QualType ImplicitParamType = From->getType();
6862   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6863     ImplicitParamType = FromPtrType->getPointeeType();
6864   CXXRecordDecl *ConversionContext
6865     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6866 
6867   Candidate.Conversions[0] = TryObjectArgumentInitialization(
6868       *this, CandidateSet.getLocation(), From->getType(),
6869       From->Classify(Context), Conversion, ConversionContext);
6870 
6871   if (Candidate.Conversions[0].isBad()) {
6872     Candidate.Viable = false;
6873     Candidate.FailureKind = ovl_fail_bad_conversion;
6874     return;
6875   }
6876 
6877   // We won't go through a user-defined type conversion function to convert a
6878   // derived to base as such conversions are given Conversion Rank. They only
6879   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6880   QualType FromCanon
6881     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6882   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6883   if (FromCanon == ToCanon ||
6884       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6885     Candidate.Viable = false;
6886     Candidate.FailureKind = ovl_fail_trivial_conversion;
6887     return;
6888   }
6889 
6890   // To determine what the conversion from the result of calling the
6891   // conversion function to the type we're eventually trying to
6892   // convert to (ToType), we need to synthesize a call to the
6893   // conversion function and attempt copy initialization from it. This
6894   // makes sure that we get the right semantics with respect to
6895   // lvalues/rvalues and the type. Fortunately, we can allocate this
6896   // call on the stack and we don't need its arguments to be
6897   // well-formed.
6898   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6899                             VK_LValue, From->getLocStart());
6900   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6901                                 Context.getPointerType(Conversion->getType()),
6902                                 CK_FunctionToPointerDecay,
6903                                 &ConversionRef, VK_RValue);
6904 
6905   QualType ConversionType = Conversion->getConversionType();
6906   if (!isCompleteType(From->getLocStart(), ConversionType)) {
6907     Candidate.Viable = false;
6908     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6909     return;
6910   }
6911 
6912   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6913 
6914   // Note that it is safe to allocate CallExpr on the stack here because
6915   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6916   // allocator).
6917   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6918   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6919                 From->getLocStart());
6920   ImplicitConversionSequence ICS =
6921     TryCopyInitialization(*this, &Call, ToType,
6922                           /*SuppressUserConversions=*/true,
6923                           /*InOverloadResolution=*/false,
6924                           /*AllowObjCWritebackConversion=*/false);
6925 
6926   switch (ICS.getKind()) {
6927   case ImplicitConversionSequence::StandardConversion:
6928     Candidate.FinalConversion = ICS.Standard;
6929 
6930     // C++ [over.ics.user]p3:
6931     //   If the user-defined conversion is specified by a specialization of a
6932     //   conversion function template, the second standard conversion sequence
6933     //   shall have exact match rank.
6934     if (Conversion->getPrimaryTemplate() &&
6935         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6936       Candidate.Viable = false;
6937       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6938       return;
6939     }
6940 
6941     // C++0x [dcl.init.ref]p5:
6942     //    In the second case, if the reference is an rvalue reference and
6943     //    the second standard conversion sequence of the user-defined
6944     //    conversion sequence includes an lvalue-to-rvalue conversion, the
6945     //    program is ill-formed.
6946     if (ToType->isRValueReferenceType() &&
6947         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6948       Candidate.Viable = false;
6949       Candidate.FailureKind = ovl_fail_bad_final_conversion;
6950       return;
6951     }
6952     break;
6953 
6954   case ImplicitConversionSequence::BadConversion:
6955     Candidate.Viable = false;
6956     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6957     return;
6958 
6959   default:
6960     llvm_unreachable(
6961            "Can only end up with a standard conversion sequence or failure");
6962   }
6963 
6964   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6965     Candidate.Viable = false;
6966     Candidate.FailureKind = ovl_fail_enable_if;
6967     Candidate.DeductionFailure.Data = FailedAttr;
6968     return;
6969   }
6970 }
6971 
6972 /// \brief Adds a conversion function template specialization
6973 /// candidate to the overload set, using template argument deduction
6974 /// to deduce the template arguments of the conversion function
6975 /// template from the type that we are converting to (C++
6976 /// [temp.deduct.conv]).
6977 void
6978 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6979                                      DeclAccessPair FoundDecl,
6980                                      CXXRecordDecl *ActingDC,
6981                                      Expr *From, QualType ToType,
6982                                      OverloadCandidateSet &CandidateSet,
6983                                      bool AllowObjCConversionOnExplicit,
6984                                      bool AllowResultConversion) {
6985   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6986          "Only conversion function templates permitted here");
6987 
6988   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6989     return;
6990 
6991   TemplateDeductionInfo Info(CandidateSet.getLocation());
6992   CXXConversionDecl *Specialization = nullptr;
6993   if (TemplateDeductionResult Result
6994         = DeduceTemplateArguments(FunctionTemplate, ToType,
6995                                   Specialization, Info)) {
6996     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6997     Candidate.FoundDecl = FoundDecl;
6998     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6999     Candidate.Viable = false;
7000     Candidate.FailureKind = ovl_fail_bad_deduction;
7001     Candidate.IsSurrogate = false;
7002     Candidate.IgnoreObjectArgument = false;
7003     Candidate.ExplicitCallArguments = 1;
7004     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7005                                                           Info);
7006     return;
7007   }
7008 
7009   // Add the conversion function template specialization produced by
7010   // template argument deduction as a candidate.
7011   assert(Specialization && "Missing function template specialization?");
7012   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7013                          CandidateSet, AllowObjCConversionOnExplicit,
7014                          AllowResultConversion);
7015 }
7016 
7017 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7018 /// converts the given @c Object to a function pointer via the
7019 /// conversion function @c Conversion, and then attempts to call it
7020 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7021 /// the type of function that we'll eventually be calling.
7022 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7023                                  DeclAccessPair FoundDecl,
7024                                  CXXRecordDecl *ActingContext,
7025                                  const FunctionProtoType *Proto,
7026                                  Expr *Object,
7027                                  ArrayRef<Expr *> Args,
7028                                  OverloadCandidateSet& CandidateSet) {
7029   if (!CandidateSet.isNewCandidate(Conversion))
7030     return;
7031 
7032   // Overload resolution is always an unevaluated context.
7033   EnterExpressionEvaluationContext Unevaluated(
7034       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7035 
7036   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7037   Candidate.FoundDecl = FoundDecl;
7038   Candidate.Function = nullptr;
7039   Candidate.Surrogate = Conversion;
7040   Candidate.Viable = true;
7041   Candidate.IsSurrogate = true;
7042   Candidate.IgnoreObjectArgument = false;
7043   Candidate.ExplicitCallArguments = Args.size();
7044 
7045   // Determine the implicit conversion sequence for the implicit
7046   // object parameter.
7047   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7048       *this, CandidateSet.getLocation(), Object->getType(),
7049       Object->Classify(Context), Conversion, ActingContext);
7050   if (ObjectInit.isBad()) {
7051     Candidate.Viable = false;
7052     Candidate.FailureKind = ovl_fail_bad_conversion;
7053     Candidate.Conversions[0] = ObjectInit;
7054     return;
7055   }
7056 
7057   // The first conversion is actually a user-defined conversion whose
7058   // first conversion is ObjectInit's standard conversion (which is
7059   // effectively a reference binding). Record it as such.
7060   Candidate.Conversions[0].setUserDefined();
7061   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7062   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7063   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7064   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7065   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7066   Candidate.Conversions[0].UserDefined.After
7067     = Candidate.Conversions[0].UserDefined.Before;
7068   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7069 
7070   // Find the
7071   unsigned NumParams = Proto->getNumParams();
7072 
7073   // (C++ 13.3.2p2): A candidate function having fewer than m
7074   // parameters is viable only if it has an ellipsis in its parameter
7075   // list (8.3.5).
7076   if (Args.size() > NumParams && !Proto->isVariadic()) {
7077     Candidate.Viable = false;
7078     Candidate.FailureKind = ovl_fail_too_many_arguments;
7079     return;
7080   }
7081 
7082   // Function types don't have any default arguments, so just check if
7083   // we have enough arguments.
7084   if (Args.size() < NumParams) {
7085     // Not enough arguments.
7086     Candidate.Viable = false;
7087     Candidate.FailureKind = ovl_fail_too_few_arguments;
7088     return;
7089   }
7090 
7091   // Determine the implicit conversion sequences for each of the
7092   // arguments.
7093   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7094     if (ArgIdx < NumParams) {
7095       // (C++ 13.3.2p3): for F to be a viable function, there shall
7096       // exist for each argument an implicit conversion sequence
7097       // (13.3.3.1) that converts that argument to the corresponding
7098       // parameter of F.
7099       QualType ParamType = Proto->getParamType(ArgIdx);
7100       Candidate.Conversions[ArgIdx + 1]
7101         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7102                                 /*SuppressUserConversions=*/false,
7103                                 /*InOverloadResolution=*/false,
7104                                 /*AllowObjCWritebackConversion=*/
7105                                   getLangOpts().ObjCAutoRefCount);
7106       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7107         Candidate.Viable = false;
7108         Candidate.FailureKind = ovl_fail_bad_conversion;
7109         return;
7110       }
7111     } else {
7112       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7113       // argument for which there is no corresponding parameter is
7114       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7115       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7116     }
7117   }
7118 
7119   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7120     Candidate.Viable = false;
7121     Candidate.FailureKind = ovl_fail_enable_if;
7122     Candidate.DeductionFailure.Data = FailedAttr;
7123     return;
7124   }
7125 }
7126 
7127 /// \brief Add overload candidates for overloaded operators that are
7128 /// member functions.
7129 ///
7130 /// Add the overloaded operator candidates that are member functions
7131 /// for the operator Op that was used in an operator expression such
7132 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7133 /// CandidateSet will store the added overload candidates. (C++
7134 /// [over.match.oper]).
7135 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7136                                        SourceLocation OpLoc,
7137                                        ArrayRef<Expr *> Args,
7138                                        OverloadCandidateSet& CandidateSet,
7139                                        SourceRange OpRange) {
7140   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7141 
7142   // C++ [over.match.oper]p3:
7143   //   For a unary operator @ with an operand of a type whose
7144   //   cv-unqualified version is T1, and for a binary operator @ with
7145   //   a left operand of a type whose cv-unqualified version is T1 and
7146   //   a right operand of a type whose cv-unqualified version is T2,
7147   //   three sets of candidate functions, designated member
7148   //   candidates, non-member candidates and built-in candidates, are
7149   //   constructed as follows:
7150   QualType T1 = Args[0]->getType();
7151 
7152   //     -- If T1 is a complete class type or a class currently being
7153   //        defined, the set of member candidates is the result of the
7154   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7155   //        the set of member candidates is empty.
7156   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7157     // Complete the type if it can be completed.
7158     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7159       return;
7160     // If the type is neither complete nor being defined, bail out now.
7161     if (!T1Rec->getDecl()->getDefinition())
7162       return;
7163 
7164     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7165     LookupQualifiedName(Operators, T1Rec->getDecl());
7166     Operators.suppressDiagnostics();
7167 
7168     for (LookupResult::iterator Oper = Operators.begin(),
7169                              OperEnd = Operators.end();
7170          Oper != OperEnd;
7171          ++Oper)
7172       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7173                          Args[0]->Classify(Context), Args.slice(1),
7174                          CandidateSet, /*SuppressUserConversions=*/false);
7175   }
7176 }
7177 
7178 /// AddBuiltinCandidate - Add a candidate for a built-in
7179 /// operator. ResultTy and ParamTys are the result and parameter types
7180 /// of the built-in candidate, respectively. Args and NumArgs are the
7181 /// arguments being passed to the candidate. IsAssignmentOperator
7182 /// should be true when this built-in candidate is an assignment
7183 /// operator. NumContextualBoolArguments is the number of arguments
7184 /// (at the beginning of the argument list) that will be contextually
7185 /// converted to bool.
7186 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7187                                OverloadCandidateSet& CandidateSet,
7188                                bool IsAssignmentOperator,
7189                                unsigned NumContextualBoolArguments) {
7190   // Overload resolution is always an unevaluated context.
7191   EnterExpressionEvaluationContext Unevaluated(
7192       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7193 
7194   // Add this candidate
7195   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7196   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7197   Candidate.Function = nullptr;
7198   Candidate.IsSurrogate = false;
7199   Candidate.IgnoreObjectArgument = false;
7200   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7201 
7202   // Determine the implicit conversion sequences for each of the
7203   // arguments.
7204   Candidate.Viable = true;
7205   Candidate.ExplicitCallArguments = Args.size();
7206   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7207     // C++ [over.match.oper]p4:
7208     //   For the built-in assignment operators, conversions of the
7209     //   left operand are restricted as follows:
7210     //     -- no temporaries are introduced to hold the left operand, and
7211     //     -- no user-defined conversions are applied to the left
7212     //        operand to achieve a type match with the left-most
7213     //        parameter of a built-in candidate.
7214     //
7215     // We block these conversions by turning off user-defined
7216     // conversions, since that is the only way that initialization of
7217     // a reference to a non-class type can occur from something that
7218     // is not of the same type.
7219     if (ArgIdx < NumContextualBoolArguments) {
7220       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7221              "Contextual conversion to bool requires bool type");
7222       Candidate.Conversions[ArgIdx]
7223         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7224     } else {
7225       Candidate.Conversions[ArgIdx]
7226         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7227                                 ArgIdx == 0 && IsAssignmentOperator,
7228                                 /*InOverloadResolution=*/false,
7229                                 /*AllowObjCWritebackConversion=*/
7230                                   getLangOpts().ObjCAutoRefCount);
7231     }
7232     if (Candidate.Conversions[ArgIdx].isBad()) {
7233       Candidate.Viable = false;
7234       Candidate.FailureKind = ovl_fail_bad_conversion;
7235       break;
7236     }
7237   }
7238 }
7239 
7240 namespace {
7241 
7242 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7243 /// candidate operator functions for built-in operators (C++
7244 /// [over.built]). The types are separated into pointer types and
7245 /// enumeration types.
7246 class BuiltinCandidateTypeSet  {
7247   /// TypeSet - A set of types.
7248   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7249                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7250 
7251   /// PointerTypes - The set of pointer types that will be used in the
7252   /// built-in candidates.
7253   TypeSet PointerTypes;
7254 
7255   /// MemberPointerTypes - The set of member pointer types that will be
7256   /// used in the built-in candidates.
7257   TypeSet MemberPointerTypes;
7258 
7259   /// EnumerationTypes - The set of enumeration types that will be
7260   /// used in the built-in candidates.
7261   TypeSet EnumerationTypes;
7262 
7263   /// \brief The set of vector types that will be used in the built-in
7264   /// candidates.
7265   TypeSet VectorTypes;
7266 
7267   /// \brief A flag indicating non-record types are viable candidates
7268   bool HasNonRecordTypes;
7269 
7270   /// \brief A flag indicating whether either arithmetic or enumeration types
7271   /// were present in the candidate set.
7272   bool HasArithmeticOrEnumeralTypes;
7273 
7274   /// \brief A flag indicating whether the nullptr type was present in the
7275   /// candidate set.
7276   bool HasNullPtrType;
7277 
7278   /// Sema - The semantic analysis instance where we are building the
7279   /// candidate type set.
7280   Sema &SemaRef;
7281 
7282   /// Context - The AST context in which we will build the type sets.
7283   ASTContext &Context;
7284 
7285   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7286                                                const Qualifiers &VisibleQuals);
7287   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7288 
7289 public:
7290   /// iterator - Iterates through the types that are part of the set.
7291   typedef TypeSet::iterator iterator;
7292 
7293   BuiltinCandidateTypeSet(Sema &SemaRef)
7294     : HasNonRecordTypes(false),
7295       HasArithmeticOrEnumeralTypes(false),
7296       HasNullPtrType(false),
7297       SemaRef(SemaRef),
7298       Context(SemaRef.Context) { }
7299 
7300   void AddTypesConvertedFrom(QualType Ty,
7301                              SourceLocation Loc,
7302                              bool AllowUserConversions,
7303                              bool AllowExplicitConversions,
7304                              const Qualifiers &VisibleTypeConversionsQuals);
7305 
7306   /// pointer_begin - First pointer type found;
7307   iterator pointer_begin() { return PointerTypes.begin(); }
7308 
7309   /// pointer_end - Past the last pointer type found;
7310   iterator pointer_end() { return PointerTypes.end(); }
7311 
7312   /// member_pointer_begin - First member pointer type found;
7313   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7314 
7315   /// member_pointer_end - Past the last member pointer type found;
7316   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7317 
7318   /// enumeration_begin - First enumeration type found;
7319   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7320 
7321   /// enumeration_end - Past the last enumeration type found;
7322   iterator enumeration_end() { return EnumerationTypes.end(); }
7323 
7324   iterator vector_begin() { return VectorTypes.begin(); }
7325   iterator vector_end() { return VectorTypes.end(); }
7326 
7327   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7328   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7329   bool hasNullPtrType() const { return HasNullPtrType; }
7330 };
7331 
7332 } // end anonymous namespace
7333 
7334 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7335 /// the set of pointer types along with any more-qualified variants of
7336 /// that type. For example, if @p Ty is "int const *", this routine
7337 /// will add "int const *", "int const volatile *", "int const
7338 /// restrict *", and "int const volatile restrict *" to the set of
7339 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7340 /// false otherwise.
7341 ///
7342 /// FIXME: what to do about extended qualifiers?
7343 bool
7344 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7345                                              const Qualifiers &VisibleQuals) {
7346 
7347   // Insert this type.
7348   if (!PointerTypes.insert(Ty))
7349     return false;
7350 
7351   QualType PointeeTy;
7352   const PointerType *PointerTy = Ty->getAs<PointerType>();
7353   bool buildObjCPtr = false;
7354   if (!PointerTy) {
7355     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7356     PointeeTy = PTy->getPointeeType();
7357     buildObjCPtr = true;
7358   } else {
7359     PointeeTy = PointerTy->getPointeeType();
7360   }
7361 
7362   // Don't add qualified variants of arrays. For one, they're not allowed
7363   // (the qualifier would sink to the element type), and for another, the
7364   // only overload situation where it matters is subscript or pointer +- int,
7365   // and those shouldn't have qualifier variants anyway.
7366   if (PointeeTy->isArrayType())
7367     return true;
7368 
7369   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7370   bool hasVolatile = VisibleQuals.hasVolatile();
7371   bool hasRestrict = VisibleQuals.hasRestrict();
7372 
7373   // Iterate through all strict supersets of BaseCVR.
7374   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7375     if ((CVR | BaseCVR) != CVR) continue;
7376     // Skip over volatile if no volatile found anywhere in the types.
7377     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7378 
7379     // Skip over restrict if no restrict found anywhere in the types, or if
7380     // the type cannot be restrict-qualified.
7381     if ((CVR & Qualifiers::Restrict) &&
7382         (!hasRestrict ||
7383          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7384       continue;
7385 
7386     // Build qualified pointee type.
7387     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7388 
7389     // Build qualified pointer type.
7390     QualType QPointerTy;
7391     if (!buildObjCPtr)
7392       QPointerTy = Context.getPointerType(QPointeeTy);
7393     else
7394       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7395 
7396     // Insert qualified pointer type.
7397     PointerTypes.insert(QPointerTy);
7398   }
7399 
7400   return true;
7401 }
7402 
7403 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7404 /// to the set of pointer types along with any more-qualified variants of
7405 /// that type. For example, if @p Ty is "int const *", this routine
7406 /// will add "int const *", "int const volatile *", "int const
7407 /// restrict *", and "int const volatile restrict *" to the set of
7408 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7409 /// false otherwise.
7410 ///
7411 /// FIXME: what to do about extended qualifiers?
7412 bool
7413 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7414     QualType Ty) {
7415   // Insert this type.
7416   if (!MemberPointerTypes.insert(Ty))
7417     return false;
7418 
7419   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7420   assert(PointerTy && "type was not a member pointer type!");
7421 
7422   QualType PointeeTy = PointerTy->getPointeeType();
7423   // Don't add qualified variants of arrays. For one, they're not allowed
7424   // (the qualifier would sink to the element type), and for another, the
7425   // only overload situation where it matters is subscript or pointer +- int,
7426   // and those shouldn't have qualifier variants anyway.
7427   if (PointeeTy->isArrayType())
7428     return true;
7429   const Type *ClassTy = PointerTy->getClass();
7430 
7431   // Iterate through all strict supersets of the pointee type's CVR
7432   // qualifiers.
7433   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7434   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7435     if ((CVR | BaseCVR) != CVR) continue;
7436 
7437     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7438     MemberPointerTypes.insert(
7439       Context.getMemberPointerType(QPointeeTy, ClassTy));
7440   }
7441 
7442   return true;
7443 }
7444 
7445 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7446 /// Ty can be implicit converted to the given set of @p Types. We're
7447 /// primarily interested in pointer types and enumeration types. We also
7448 /// take member pointer types, for the conditional operator.
7449 /// AllowUserConversions is true if we should look at the conversion
7450 /// functions of a class type, and AllowExplicitConversions if we
7451 /// should also include the explicit conversion functions of a class
7452 /// type.
7453 void
7454 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7455                                                SourceLocation Loc,
7456                                                bool AllowUserConversions,
7457                                                bool AllowExplicitConversions,
7458                                                const Qualifiers &VisibleQuals) {
7459   // Only deal with canonical types.
7460   Ty = Context.getCanonicalType(Ty);
7461 
7462   // Look through reference types; they aren't part of the type of an
7463   // expression for the purposes of conversions.
7464   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7465     Ty = RefTy->getPointeeType();
7466 
7467   // If we're dealing with an array type, decay to the pointer.
7468   if (Ty->isArrayType())
7469     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7470 
7471   // Otherwise, we don't care about qualifiers on the type.
7472   Ty = Ty.getLocalUnqualifiedType();
7473 
7474   // Flag if we ever add a non-record type.
7475   const RecordType *TyRec = Ty->getAs<RecordType>();
7476   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7477 
7478   // Flag if we encounter an arithmetic type.
7479   HasArithmeticOrEnumeralTypes =
7480     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7481 
7482   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7483     PointerTypes.insert(Ty);
7484   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7485     // Insert our type, and its more-qualified variants, into the set
7486     // of types.
7487     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7488       return;
7489   } else if (Ty->isMemberPointerType()) {
7490     // Member pointers are far easier, since the pointee can't be converted.
7491     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7492       return;
7493   } else if (Ty->isEnumeralType()) {
7494     HasArithmeticOrEnumeralTypes = true;
7495     EnumerationTypes.insert(Ty);
7496   } else if (Ty->isVectorType()) {
7497     // We treat vector types as arithmetic types in many contexts as an
7498     // extension.
7499     HasArithmeticOrEnumeralTypes = true;
7500     VectorTypes.insert(Ty);
7501   } else if (Ty->isNullPtrType()) {
7502     HasNullPtrType = true;
7503   } else if (AllowUserConversions && TyRec) {
7504     // No conversion functions in incomplete types.
7505     if (!SemaRef.isCompleteType(Loc, Ty))
7506       return;
7507 
7508     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7509     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7510       if (isa<UsingShadowDecl>(D))
7511         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7512 
7513       // Skip conversion function templates; they don't tell us anything
7514       // about which builtin types we can convert to.
7515       if (isa<FunctionTemplateDecl>(D))
7516         continue;
7517 
7518       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7519       if (AllowExplicitConversions || !Conv->isExplicit()) {
7520         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7521                               VisibleQuals);
7522       }
7523     }
7524   }
7525 }
7526 
7527 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7528 /// the volatile- and non-volatile-qualified assignment operators for the
7529 /// given type to the candidate set.
7530 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7531                                                    QualType T,
7532                                                    ArrayRef<Expr *> Args,
7533                                     OverloadCandidateSet &CandidateSet) {
7534   QualType ParamTypes[2];
7535 
7536   // T& operator=(T&, T)
7537   ParamTypes[0] = S.Context.getLValueReferenceType(T);
7538   ParamTypes[1] = T;
7539   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7540                         /*IsAssignmentOperator=*/true);
7541 
7542   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7543     // volatile T& operator=(volatile T&, T)
7544     ParamTypes[0]
7545       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7546     ParamTypes[1] = T;
7547     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7548                           /*IsAssignmentOperator=*/true);
7549   }
7550 }
7551 
7552 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7553 /// if any, found in visible type conversion functions found in ArgExpr's type.
7554 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7555     Qualifiers VRQuals;
7556     const RecordType *TyRec;
7557     if (const MemberPointerType *RHSMPType =
7558         ArgExpr->getType()->getAs<MemberPointerType>())
7559       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7560     else
7561       TyRec = ArgExpr->getType()->getAs<RecordType>();
7562     if (!TyRec) {
7563       // Just to be safe, assume the worst case.
7564       VRQuals.addVolatile();
7565       VRQuals.addRestrict();
7566       return VRQuals;
7567     }
7568 
7569     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7570     if (!ClassDecl->hasDefinition())
7571       return VRQuals;
7572 
7573     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7574       if (isa<UsingShadowDecl>(D))
7575         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7576       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7577         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7578         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7579           CanTy = ResTypeRef->getPointeeType();
7580         // Need to go down the pointer/mempointer chain and add qualifiers
7581         // as see them.
7582         bool done = false;
7583         while (!done) {
7584           if (CanTy.isRestrictQualified())
7585             VRQuals.addRestrict();
7586           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7587             CanTy = ResTypePtr->getPointeeType();
7588           else if (const MemberPointerType *ResTypeMPtr =
7589                 CanTy->getAs<MemberPointerType>())
7590             CanTy = ResTypeMPtr->getPointeeType();
7591           else
7592             done = true;
7593           if (CanTy.isVolatileQualified())
7594             VRQuals.addVolatile();
7595           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7596             return VRQuals;
7597         }
7598       }
7599     }
7600     return VRQuals;
7601 }
7602 
7603 namespace {
7604 
7605 /// \brief Helper class to manage the addition of builtin operator overload
7606 /// candidates. It provides shared state and utility methods used throughout
7607 /// the process, as well as a helper method to add each group of builtin
7608 /// operator overloads from the standard to a candidate set.
7609 class BuiltinOperatorOverloadBuilder {
7610   // Common instance state available to all overload candidate addition methods.
7611   Sema &S;
7612   ArrayRef<Expr *> Args;
7613   Qualifiers VisibleTypeConversionsQuals;
7614   bool HasArithmeticOrEnumeralCandidateType;
7615   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7616   OverloadCandidateSet &CandidateSet;
7617 
7618   static constexpr int ArithmeticTypesCap = 24;
7619   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
7620 
7621   // Define some indices used to iterate over the arithemetic types in
7622   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
7623   // types are that preserved by promotion (C++ [over.built]p2).
7624   unsigned FirstIntegralType,
7625            LastIntegralType;
7626   unsigned FirstPromotedIntegralType,
7627            LastPromotedIntegralType;
7628   unsigned FirstPromotedArithmeticType,
7629            LastPromotedArithmeticType;
7630   unsigned NumArithmeticTypes;
7631 
7632   void InitArithmeticTypes() {
7633     // Start of promoted types.
7634     FirstPromotedArithmeticType = 0;
7635     ArithmeticTypes.push_back(S.Context.FloatTy);
7636     ArithmeticTypes.push_back(S.Context.DoubleTy);
7637     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7638     if (S.Context.getTargetInfo().hasFloat128Type())
7639       ArithmeticTypes.push_back(S.Context.Float128Ty);
7640 
7641     // Start of integral types.
7642     FirstIntegralType = ArithmeticTypes.size();
7643     FirstPromotedIntegralType = ArithmeticTypes.size();
7644     ArithmeticTypes.push_back(S.Context.IntTy);
7645     ArithmeticTypes.push_back(S.Context.LongTy);
7646     ArithmeticTypes.push_back(S.Context.LongLongTy);
7647     if (S.Context.getTargetInfo().hasInt128Type())
7648       ArithmeticTypes.push_back(S.Context.Int128Ty);
7649     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7650     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7651     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7652     if (S.Context.getTargetInfo().hasInt128Type())
7653       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7654     LastPromotedIntegralType = ArithmeticTypes.size();
7655     LastPromotedArithmeticType = ArithmeticTypes.size();
7656     // End of promoted types.
7657 
7658     ArithmeticTypes.push_back(S.Context.BoolTy);
7659     ArithmeticTypes.push_back(S.Context.CharTy);
7660     ArithmeticTypes.push_back(S.Context.WCharTy);
7661     ArithmeticTypes.push_back(S.Context.Char16Ty);
7662     ArithmeticTypes.push_back(S.Context.Char32Ty);
7663     ArithmeticTypes.push_back(S.Context.SignedCharTy);
7664     ArithmeticTypes.push_back(S.Context.ShortTy);
7665     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7666     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7667     LastIntegralType = ArithmeticTypes.size();
7668     NumArithmeticTypes = ArithmeticTypes.size();
7669     // End of integral types.
7670     // FIXME: What about complex? What about half?
7671 
7672     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
7673            "Enough inline storage for all arithmetic types.");
7674   }
7675 
7676   /// \brief Helper method to factor out the common pattern of adding overloads
7677   /// for '++' and '--' builtin operators.
7678   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7679                                            bool HasVolatile,
7680                                            bool HasRestrict) {
7681     QualType ParamTypes[2] = {
7682       S.Context.getLValueReferenceType(CandidateTy),
7683       S.Context.IntTy
7684     };
7685 
7686     // Non-volatile version.
7687     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7688 
7689     // Use a heuristic to reduce number of builtin candidates in the set:
7690     // add volatile version only if there are conversions to a volatile type.
7691     if (HasVolatile) {
7692       ParamTypes[0] =
7693         S.Context.getLValueReferenceType(
7694           S.Context.getVolatileType(CandidateTy));
7695       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7696     }
7697 
7698     // Add restrict version only if there are conversions to a restrict type
7699     // and our candidate type is a non-restrict-qualified pointer.
7700     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7701         !CandidateTy.isRestrictQualified()) {
7702       ParamTypes[0]
7703         = S.Context.getLValueReferenceType(
7704             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7705       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7706 
7707       if (HasVolatile) {
7708         ParamTypes[0]
7709           = S.Context.getLValueReferenceType(
7710               S.Context.getCVRQualifiedType(CandidateTy,
7711                                             (Qualifiers::Volatile |
7712                                              Qualifiers::Restrict)));
7713         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7714       }
7715     }
7716 
7717   }
7718 
7719 public:
7720   BuiltinOperatorOverloadBuilder(
7721     Sema &S, ArrayRef<Expr *> Args,
7722     Qualifiers VisibleTypeConversionsQuals,
7723     bool HasArithmeticOrEnumeralCandidateType,
7724     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7725     OverloadCandidateSet &CandidateSet)
7726     : S(S), Args(Args),
7727       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7728       HasArithmeticOrEnumeralCandidateType(
7729         HasArithmeticOrEnumeralCandidateType),
7730       CandidateTypes(CandidateTypes),
7731       CandidateSet(CandidateSet) {
7732 
7733     InitArithmeticTypes();
7734   }
7735 
7736   // C++ [over.built]p3:
7737   //
7738   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
7739   //   is either volatile or empty, there exist candidate operator
7740   //   functions of the form
7741   //
7742   //       VQ T&      operator++(VQ T&);
7743   //       T          operator++(VQ T&, int);
7744   //
7745   // C++ [over.built]p4:
7746   //
7747   //   For every pair (T, VQ), where T is an arithmetic type other
7748   //   than bool, and VQ is either volatile or empty, there exist
7749   //   candidate operator functions of the form
7750   //
7751   //       VQ T&      operator--(VQ T&);
7752   //       T          operator--(VQ T&, int);
7753   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7754     if (!HasArithmeticOrEnumeralCandidateType)
7755       return;
7756 
7757     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7758          Arith < NumArithmeticTypes; ++Arith) {
7759       addPlusPlusMinusMinusStyleOverloads(
7760         ArithmeticTypes[Arith],
7761         VisibleTypeConversionsQuals.hasVolatile(),
7762         VisibleTypeConversionsQuals.hasRestrict());
7763     }
7764   }
7765 
7766   // C++ [over.built]p5:
7767   //
7768   //   For every pair (T, VQ), where T is a cv-qualified or
7769   //   cv-unqualified object type, and VQ is either volatile or
7770   //   empty, there exist candidate operator functions of the form
7771   //
7772   //       T*VQ&      operator++(T*VQ&);
7773   //       T*VQ&      operator--(T*VQ&);
7774   //       T*         operator++(T*VQ&, int);
7775   //       T*         operator--(T*VQ&, int);
7776   void addPlusPlusMinusMinusPointerOverloads() {
7777     for (BuiltinCandidateTypeSet::iterator
7778               Ptr = CandidateTypes[0].pointer_begin(),
7779            PtrEnd = CandidateTypes[0].pointer_end();
7780          Ptr != PtrEnd; ++Ptr) {
7781       // Skip pointer types that aren't pointers to object types.
7782       if (!(*Ptr)->getPointeeType()->isObjectType())
7783         continue;
7784 
7785       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7786         (!(*Ptr).isVolatileQualified() &&
7787          VisibleTypeConversionsQuals.hasVolatile()),
7788         (!(*Ptr).isRestrictQualified() &&
7789          VisibleTypeConversionsQuals.hasRestrict()));
7790     }
7791   }
7792 
7793   // C++ [over.built]p6:
7794   //   For every cv-qualified or cv-unqualified object type T, there
7795   //   exist candidate operator functions of the form
7796   //
7797   //       T&         operator*(T*);
7798   //
7799   // C++ [over.built]p7:
7800   //   For every function type T that does not have cv-qualifiers or a
7801   //   ref-qualifier, there exist candidate operator functions of the form
7802   //       T&         operator*(T*);
7803   void addUnaryStarPointerOverloads() {
7804     for (BuiltinCandidateTypeSet::iterator
7805               Ptr = CandidateTypes[0].pointer_begin(),
7806            PtrEnd = CandidateTypes[0].pointer_end();
7807          Ptr != PtrEnd; ++Ptr) {
7808       QualType ParamTy = *Ptr;
7809       QualType PointeeTy = ParamTy->getPointeeType();
7810       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7811         continue;
7812 
7813       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7814         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7815           continue;
7816 
7817       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7818     }
7819   }
7820 
7821   // C++ [over.built]p9:
7822   //  For every promoted arithmetic type T, there exist candidate
7823   //  operator functions of the form
7824   //
7825   //       T         operator+(T);
7826   //       T         operator-(T);
7827   void addUnaryPlusOrMinusArithmeticOverloads() {
7828     if (!HasArithmeticOrEnumeralCandidateType)
7829       return;
7830 
7831     for (unsigned Arith = FirstPromotedArithmeticType;
7832          Arith < LastPromotedArithmeticType; ++Arith) {
7833       QualType ArithTy = ArithmeticTypes[Arith];
7834       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
7835     }
7836 
7837     // Extension: We also add these operators for vector types.
7838     for (BuiltinCandidateTypeSet::iterator
7839               Vec = CandidateTypes[0].vector_begin(),
7840            VecEnd = CandidateTypes[0].vector_end();
7841          Vec != VecEnd; ++Vec) {
7842       QualType VecTy = *Vec;
7843       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7844     }
7845   }
7846 
7847   // C++ [over.built]p8:
7848   //   For every type T, there exist candidate operator functions of
7849   //   the form
7850   //
7851   //       T*         operator+(T*);
7852   void addUnaryPlusPointerOverloads() {
7853     for (BuiltinCandidateTypeSet::iterator
7854               Ptr = CandidateTypes[0].pointer_begin(),
7855            PtrEnd = CandidateTypes[0].pointer_end();
7856          Ptr != PtrEnd; ++Ptr) {
7857       QualType ParamTy = *Ptr;
7858       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7859     }
7860   }
7861 
7862   // C++ [over.built]p10:
7863   //   For every promoted integral type T, there exist candidate
7864   //   operator functions of the form
7865   //
7866   //        T         operator~(T);
7867   void addUnaryTildePromotedIntegralOverloads() {
7868     if (!HasArithmeticOrEnumeralCandidateType)
7869       return;
7870 
7871     for (unsigned Int = FirstPromotedIntegralType;
7872          Int < LastPromotedIntegralType; ++Int) {
7873       QualType IntTy = ArithmeticTypes[Int];
7874       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
7875     }
7876 
7877     // Extension: We also add this operator for vector types.
7878     for (BuiltinCandidateTypeSet::iterator
7879               Vec = CandidateTypes[0].vector_begin(),
7880            VecEnd = CandidateTypes[0].vector_end();
7881          Vec != VecEnd; ++Vec) {
7882       QualType VecTy = *Vec;
7883       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7884     }
7885   }
7886 
7887   // C++ [over.match.oper]p16:
7888   //   For every pointer to member type T or type std::nullptr_t, there
7889   //   exist candidate operator functions of the form
7890   //
7891   //        bool operator==(T,T);
7892   //        bool operator!=(T,T);
7893   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
7894     /// Set of (canonical) types that we've already handled.
7895     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7896 
7897     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7898       for (BuiltinCandidateTypeSet::iterator
7899                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7900              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7901            MemPtr != MemPtrEnd;
7902            ++MemPtr) {
7903         // Don't add the same builtin candidate twice.
7904         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7905           continue;
7906 
7907         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7908         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7909       }
7910 
7911       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7912         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7913         if (AddedTypes.insert(NullPtrTy).second) {
7914           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7915           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7916         }
7917       }
7918     }
7919   }
7920 
7921   // C++ [over.built]p15:
7922   //
7923   //   For every T, where T is an enumeration type or a pointer type,
7924   //   there exist candidate operator functions of the form
7925   //
7926   //        bool       operator<(T, T);
7927   //        bool       operator>(T, T);
7928   //        bool       operator<=(T, T);
7929   //        bool       operator>=(T, T);
7930   //        bool       operator==(T, T);
7931   //        bool       operator!=(T, T);
7932   void addRelationalPointerOrEnumeralOverloads() {
7933     // C++ [over.match.oper]p3:
7934     //   [...]the built-in candidates include all of the candidate operator
7935     //   functions defined in 13.6 that, compared to the given operator, [...]
7936     //   do not have the same parameter-type-list as any non-template non-member
7937     //   candidate.
7938     //
7939     // Note that in practice, this only affects enumeration types because there
7940     // aren't any built-in candidates of record type, and a user-defined operator
7941     // must have an operand of record or enumeration type. Also, the only other
7942     // overloaded operator with enumeration arguments, operator=,
7943     // cannot be overloaded for enumeration types, so this is the only place
7944     // where we must suppress candidates like this.
7945     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7946       UserDefinedBinaryOperators;
7947 
7948     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7949       if (CandidateTypes[ArgIdx].enumeration_begin() !=
7950           CandidateTypes[ArgIdx].enumeration_end()) {
7951         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7952                                          CEnd = CandidateSet.end();
7953              C != CEnd; ++C) {
7954           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7955             continue;
7956 
7957           if (C->Function->isFunctionTemplateSpecialization())
7958             continue;
7959 
7960           QualType FirstParamType =
7961             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7962           QualType SecondParamType =
7963             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7964 
7965           // Skip if either parameter isn't of enumeral type.
7966           if (!FirstParamType->isEnumeralType() ||
7967               !SecondParamType->isEnumeralType())
7968             continue;
7969 
7970           // Add this operator to the set of known user-defined operators.
7971           UserDefinedBinaryOperators.insert(
7972             std::make_pair(S.Context.getCanonicalType(FirstParamType),
7973                            S.Context.getCanonicalType(SecondParamType)));
7974         }
7975       }
7976     }
7977 
7978     /// Set of (canonical) types that we've already handled.
7979     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7980 
7981     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7982       for (BuiltinCandidateTypeSet::iterator
7983                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7984              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7985            Ptr != PtrEnd; ++Ptr) {
7986         // Don't add the same builtin candidate twice.
7987         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7988           continue;
7989 
7990         QualType ParamTypes[2] = { *Ptr, *Ptr };
7991         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7992       }
7993       for (BuiltinCandidateTypeSet::iterator
7994                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7995              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7996            Enum != EnumEnd; ++Enum) {
7997         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7998 
7999         // Don't add the same builtin candidate twice, or if a user defined
8000         // candidate exists.
8001         if (!AddedTypes.insert(CanonType).second ||
8002             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8003                                                             CanonType)))
8004           continue;
8005 
8006         QualType ParamTypes[2] = { *Enum, *Enum };
8007         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8008       }
8009     }
8010   }
8011 
8012   // C++ [over.built]p13:
8013   //
8014   //   For every cv-qualified or cv-unqualified object type T
8015   //   there exist candidate operator functions of the form
8016   //
8017   //      T*         operator+(T*, ptrdiff_t);
8018   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8019   //      T*         operator-(T*, ptrdiff_t);
8020   //      T*         operator+(ptrdiff_t, T*);
8021   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8022   //
8023   // C++ [over.built]p14:
8024   //
8025   //   For every T, where T is a pointer to object type, there
8026   //   exist candidate operator functions of the form
8027   //
8028   //      ptrdiff_t  operator-(T, T);
8029   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8030     /// Set of (canonical) types that we've already handled.
8031     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8032 
8033     for (int Arg = 0; Arg < 2; ++Arg) {
8034       QualType AsymmetricParamTypes[2] = {
8035         S.Context.getPointerDiffType(),
8036         S.Context.getPointerDiffType(),
8037       };
8038       for (BuiltinCandidateTypeSet::iterator
8039                 Ptr = CandidateTypes[Arg].pointer_begin(),
8040              PtrEnd = CandidateTypes[Arg].pointer_end();
8041            Ptr != PtrEnd; ++Ptr) {
8042         QualType PointeeTy = (*Ptr)->getPointeeType();
8043         if (!PointeeTy->isObjectType())
8044           continue;
8045 
8046         AsymmetricParamTypes[Arg] = *Ptr;
8047         if (Arg == 0 || Op == OO_Plus) {
8048           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8049           // T* operator+(ptrdiff_t, T*);
8050           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8051         }
8052         if (Op == OO_Minus) {
8053           // ptrdiff_t operator-(T, T);
8054           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8055             continue;
8056 
8057           QualType ParamTypes[2] = { *Ptr, *Ptr };
8058           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8059         }
8060       }
8061     }
8062   }
8063 
8064   // C++ [over.built]p12:
8065   //
8066   //   For every pair of promoted arithmetic types L and R, there
8067   //   exist candidate operator functions of the form
8068   //
8069   //        LR         operator*(L, R);
8070   //        LR         operator/(L, R);
8071   //        LR         operator+(L, R);
8072   //        LR         operator-(L, R);
8073   //        bool       operator<(L, R);
8074   //        bool       operator>(L, R);
8075   //        bool       operator<=(L, R);
8076   //        bool       operator>=(L, R);
8077   //        bool       operator==(L, R);
8078   //        bool       operator!=(L, R);
8079   //
8080   //   where LR is the result of the usual arithmetic conversions
8081   //   between types L and R.
8082   //
8083   // C++ [over.built]p24:
8084   //
8085   //   For every pair of promoted arithmetic types L and R, there exist
8086   //   candidate operator functions of the form
8087   //
8088   //        LR       operator?(bool, L, R);
8089   //
8090   //   where LR is the result of the usual arithmetic conversions
8091   //   between types L and R.
8092   // Our candidates ignore the first parameter.
8093   void addGenericBinaryArithmeticOverloads() {
8094     if (!HasArithmeticOrEnumeralCandidateType)
8095       return;
8096 
8097     for (unsigned Left = FirstPromotedArithmeticType;
8098          Left < LastPromotedArithmeticType; ++Left) {
8099       for (unsigned Right = FirstPromotedArithmeticType;
8100            Right < LastPromotedArithmeticType; ++Right) {
8101         QualType LandR[2] = { ArithmeticTypes[Left],
8102                               ArithmeticTypes[Right] };
8103         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8104       }
8105     }
8106 
8107     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8108     // conditional operator for vector types.
8109     for (BuiltinCandidateTypeSet::iterator
8110               Vec1 = CandidateTypes[0].vector_begin(),
8111            Vec1End = CandidateTypes[0].vector_end();
8112          Vec1 != Vec1End; ++Vec1) {
8113       for (BuiltinCandidateTypeSet::iterator
8114                 Vec2 = CandidateTypes[1].vector_begin(),
8115              Vec2End = CandidateTypes[1].vector_end();
8116            Vec2 != Vec2End; ++Vec2) {
8117         QualType LandR[2] = { *Vec1, *Vec2 };
8118         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8119       }
8120     }
8121   }
8122 
8123   // C++ [over.built]p17:
8124   //
8125   //   For every pair of promoted integral types L and R, there
8126   //   exist candidate operator functions of the form
8127   //
8128   //      LR         operator%(L, R);
8129   //      LR         operator&(L, R);
8130   //      LR         operator^(L, R);
8131   //      LR         operator|(L, R);
8132   //      L          operator<<(L, R);
8133   //      L          operator>>(L, R);
8134   //
8135   //   where LR is the result of the usual arithmetic conversions
8136   //   between types L and R.
8137   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8138     if (!HasArithmeticOrEnumeralCandidateType)
8139       return;
8140 
8141     for (unsigned Left = FirstPromotedIntegralType;
8142          Left < LastPromotedIntegralType; ++Left) {
8143       for (unsigned Right = FirstPromotedIntegralType;
8144            Right < LastPromotedIntegralType; ++Right) {
8145         QualType LandR[2] = { ArithmeticTypes[Left],
8146                               ArithmeticTypes[Right] };
8147         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8148       }
8149     }
8150   }
8151 
8152   // C++ [over.built]p20:
8153   //
8154   //   For every pair (T, VQ), where T is an enumeration or
8155   //   pointer to member type and VQ is either volatile or
8156   //   empty, there exist candidate operator functions of the form
8157   //
8158   //        VQ T&      operator=(VQ T&, T);
8159   void addAssignmentMemberPointerOrEnumeralOverloads() {
8160     /// Set of (canonical) types that we've already handled.
8161     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8162 
8163     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8164       for (BuiltinCandidateTypeSet::iterator
8165                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8166              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8167            Enum != EnumEnd; ++Enum) {
8168         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8169           continue;
8170 
8171         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8172       }
8173 
8174       for (BuiltinCandidateTypeSet::iterator
8175                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8176              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8177            MemPtr != MemPtrEnd; ++MemPtr) {
8178         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8179           continue;
8180 
8181         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8182       }
8183     }
8184   }
8185 
8186   // C++ [over.built]p19:
8187   //
8188   //   For every pair (T, VQ), where T is any type and VQ is either
8189   //   volatile or empty, there exist candidate operator functions
8190   //   of the form
8191   //
8192   //        T*VQ&      operator=(T*VQ&, T*);
8193   //
8194   // C++ [over.built]p21:
8195   //
8196   //   For every pair (T, VQ), where T is a cv-qualified or
8197   //   cv-unqualified object type and VQ is either volatile or
8198   //   empty, there exist candidate operator functions of the form
8199   //
8200   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8201   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8202   void addAssignmentPointerOverloads(bool isEqualOp) {
8203     /// Set of (canonical) types that we've already handled.
8204     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8205 
8206     for (BuiltinCandidateTypeSet::iterator
8207               Ptr = CandidateTypes[0].pointer_begin(),
8208            PtrEnd = CandidateTypes[0].pointer_end();
8209          Ptr != PtrEnd; ++Ptr) {
8210       // If this is operator=, keep track of the builtin candidates we added.
8211       if (isEqualOp)
8212         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8213       else if (!(*Ptr)->getPointeeType()->isObjectType())
8214         continue;
8215 
8216       // non-volatile version
8217       QualType ParamTypes[2] = {
8218         S.Context.getLValueReferenceType(*Ptr),
8219         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8220       };
8221       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8222                             /*IsAssigmentOperator=*/ isEqualOp);
8223 
8224       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8225                           VisibleTypeConversionsQuals.hasVolatile();
8226       if (NeedVolatile) {
8227         // volatile version
8228         ParamTypes[0] =
8229           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8230         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8231                               /*IsAssigmentOperator=*/isEqualOp);
8232       }
8233 
8234       if (!(*Ptr).isRestrictQualified() &&
8235           VisibleTypeConversionsQuals.hasRestrict()) {
8236         // restrict version
8237         ParamTypes[0]
8238           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8239         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8240                               /*IsAssigmentOperator=*/isEqualOp);
8241 
8242         if (NeedVolatile) {
8243           // volatile restrict version
8244           ParamTypes[0]
8245             = S.Context.getLValueReferenceType(
8246                 S.Context.getCVRQualifiedType(*Ptr,
8247                                               (Qualifiers::Volatile |
8248                                                Qualifiers::Restrict)));
8249           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8250                                 /*IsAssigmentOperator=*/isEqualOp);
8251         }
8252       }
8253     }
8254 
8255     if (isEqualOp) {
8256       for (BuiltinCandidateTypeSet::iterator
8257                 Ptr = CandidateTypes[1].pointer_begin(),
8258              PtrEnd = CandidateTypes[1].pointer_end();
8259            Ptr != PtrEnd; ++Ptr) {
8260         // Make sure we don't add the same candidate twice.
8261         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8262           continue;
8263 
8264         QualType ParamTypes[2] = {
8265           S.Context.getLValueReferenceType(*Ptr),
8266           *Ptr,
8267         };
8268 
8269         // non-volatile version
8270         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8271                               /*IsAssigmentOperator=*/true);
8272 
8273         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8274                            VisibleTypeConversionsQuals.hasVolatile();
8275         if (NeedVolatile) {
8276           // volatile version
8277           ParamTypes[0] =
8278             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8279           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8280                                 /*IsAssigmentOperator=*/true);
8281         }
8282 
8283         if (!(*Ptr).isRestrictQualified() &&
8284             VisibleTypeConversionsQuals.hasRestrict()) {
8285           // restrict version
8286           ParamTypes[0]
8287             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8288           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8289                                 /*IsAssigmentOperator=*/true);
8290 
8291           if (NeedVolatile) {
8292             // volatile restrict version
8293             ParamTypes[0]
8294               = S.Context.getLValueReferenceType(
8295                   S.Context.getCVRQualifiedType(*Ptr,
8296                                                 (Qualifiers::Volatile |
8297                                                  Qualifiers::Restrict)));
8298             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8299                                   /*IsAssigmentOperator=*/true);
8300           }
8301         }
8302       }
8303     }
8304   }
8305 
8306   // C++ [over.built]p18:
8307   //
8308   //   For every triple (L, VQ, R), where L is an arithmetic type,
8309   //   VQ is either volatile or empty, and R is a promoted
8310   //   arithmetic type, there exist candidate operator functions of
8311   //   the form
8312   //
8313   //        VQ L&      operator=(VQ L&, R);
8314   //        VQ L&      operator*=(VQ L&, R);
8315   //        VQ L&      operator/=(VQ L&, R);
8316   //        VQ L&      operator+=(VQ L&, R);
8317   //        VQ L&      operator-=(VQ L&, R);
8318   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8319     if (!HasArithmeticOrEnumeralCandidateType)
8320       return;
8321 
8322     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8323       for (unsigned Right = FirstPromotedArithmeticType;
8324            Right < LastPromotedArithmeticType; ++Right) {
8325         QualType ParamTypes[2];
8326         ParamTypes[1] = ArithmeticTypes[Right];
8327 
8328         // Add this built-in operator as a candidate (VQ is empty).
8329         ParamTypes[0] =
8330           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8331         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8332                               /*IsAssigmentOperator=*/isEqualOp);
8333 
8334         // Add this built-in operator as a candidate (VQ is 'volatile').
8335         if (VisibleTypeConversionsQuals.hasVolatile()) {
8336           ParamTypes[0] =
8337             S.Context.getVolatileType(ArithmeticTypes[Left]);
8338           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8339           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8340                                 /*IsAssigmentOperator=*/isEqualOp);
8341         }
8342       }
8343     }
8344 
8345     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8346     for (BuiltinCandidateTypeSet::iterator
8347               Vec1 = CandidateTypes[0].vector_begin(),
8348            Vec1End = CandidateTypes[0].vector_end();
8349          Vec1 != Vec1End; ++Vec1) {
8350       for (BuiltinCandidateTypeSet::iterator
8351                 Vec2 = CandidateTypes[1].vector_begin(),
8352              Vec2End = CandidateTypes[1].vector_end();
8353            Vec2 != Vec2End; ++Vec2) {
8354         QualType ParamTypes[2];
8355         ParamTypes[1] = *Vec2;
8356         // Add this built-in operator as a candidate (VQ is empty).
8357         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8358         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8359                               /*IsAssigmentOperator=*/isEqualOp);
8360 
8361         // Add this built-in operator as a candidate (VQ is 'volatile').
8362         if (VisibleTypeConversionsQuals.hasVolatile()) {
8363           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8364           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8365           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8366                                 /*IsAssigmentOperator=*/isEqualOp);
8367         }
8368       }
8369     }
8370   }
8371 
8372   // C++ [over.built]p22:
8373   //
8374   //   For every triple (L, VQ, R), where L is an integral type, VQ
8375   //   is either volatile or empty, and R is a promoted integral
8376   //   type, there exist candidate operator functions of the form
8377   //
8378   //        VQ L&       operator%=(VQ L&, R);
8379   //        VQ L&       operator<<=(VQ L&, R);
8380   //        VQ L&       operator>>=(VQ L&, R);
8381   //        VQ L&       operator&=(VQ L&, R);
8382   //        VQ L&       operator^=(VQ L&, R);
8383   //        VQ L&       operator|=(VQ L&, R);
8384   void addAssignmentIntegralOverloads() {
8385     if (!HasArithmeticOrEnumeralCandidateType)
8386       return;
8387 
8388     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8389       for (unsigned Right = FirstPromotedIntegralType;
8390            Right < LastPromotedIntegralType; ++Right) {
8391         QualType ParamTypes[2];
8392         ParamTypes[1] = ArithmeticTypes[Right];
8393 
8394         // Add this built-in operator as a candidate (VQ is empty).
8395         ParamTypes[0] =
8396           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8397         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8398         if (VisibleTypeConversionsQuals.hasVolatile()) {
8399           // Add this built-in operator as a candidate (VQ is 'volatile').
8400           ParamTypes[0] = ArithmeticTypes[Left];
8401           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8402           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8403           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8404         }
8405       }
8406     }
8407   }
8408 
8409   // C++ [over.operator]p23:
8410   //
8411   //   There also exist candidate operator functions of the form
8412   //
8413   //        bool        operator!(bool);
8414   //        bool        operator&&(bool, bool);
8415   //        bool        operator||(bool, bool);
8416   void addExclaimOverload() {
8417     QualType ParamTy = S.Context.BoolTy;
8418     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8419                           /*IsAssignmentOperator=*/false,
8420                           /*NumContextualBoolArguments=*/1);
8421   }
8422   void addAmpAmpOrPipePipeOverload() {
8423     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8424     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8425                           /*IsAssignmentOperator=*/false,
8426                           /*NumContextualBoolArguments=*/2);
8427   }
8428 
8429   // C++ [over.built]p13:
8430   //
8431   //   For every cv-qualified or cv-unqualified object type T there
8432   //   exist candidate operator functions of the form
8433   //
8434   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8435   //        T&         operator[](T*, ptrdiff_t);
8436   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8437   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8438   //        T&         operator[](ptrdiff_t, T*);
8439   void addSubscriptOverloads() {
8440     for (BuiltinCandidateTypeSet::iterator
8441               Ptr = CandidateTypes[0].pointer_begin(),
8442            PtrEnd = CandidateTypes[0].pointer_end();
8443          Ptr != PtrEnd; ++Ptr) {
8444       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8445       QualType PointeeType = (*Ptr)->getPointeeType();
8446       if (!PointeeType->isObjectType())
8447         continue;
8448 
8449       // T& operator[](T*, ptrdiff_t)
8450       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8451     }
8452 
8453     for (BuiltinCandidateTypeSet::iterator
8454               Ptr = CandidateTypes[1].pointer_begin(),
8455            PtrEnd = CandidateTypes[1].pointer_end();
8456          Ptr != PtrEnd; ++Ptr) {
8457       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8458       QualType PointeeType = (*Ptr)->getPointeeType();
8459       if (!PointeeType->isObjectType())
8460         continue;
8461 
8462       // T& operator[](ptrdiff_t, T*)
8463       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8464     }
8465   }
8466 
8467   // C++ [over.built]p11:
8468   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8469   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8470   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8471   //    there exist candidate operator functions of the form
8472   //
8473   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8474   //
8475   //    where CV12 is the union of CV1 and CV2.
8476   void addArrowStarOverloads() {
8477     for (BuiltinCandidateTypeSet::iterator
8478              Ptr = CandidateTypes[0].pointer_begin(),
8479            PtrEnd = CandidateTypes[0].pointer_end();
8480          Ptr != PtrEnd; ++Ptr) {
8481       QualType C1Ty = (*Ptr);
8482       QualType C1;
8483       QualifierCollector Q1;
8484       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8485       if (!isa<RecordType>(C1))
8486         continue;
8487       // heuristic to reduce number of builtin candidates in the set.
8488       // Add volatile/restrict version only if there are conversions to a
8489       // volatile/restrict type.
8490       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8491         continue;
8492       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8493         continue;
8494       for (BuiltinCandidateTypeSet::iterator
8495                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8496              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8497            MemPtr != MemPtrEnd; ++MemPtr) {
8498         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8499         QualType C2 = QualType(mptr->getClass(), 0);
8500         C2 = C2.getUnqualifiedType();
8501         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8502           break;
8503         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8504         // build CV12 T&
8505         QualType T = mptr->getPointeeType();
8506         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8507             T.isVolatileQualified())
8508           continue;
8509         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8510             T.isRestrictQualified())
8511           continue;
8512         T = Q1.apply(S.Context, T);
8513         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8514       }
8515     }
8516   }
8517 
8518   // Note that we don't consider the first argument, since it has been
8519   // contextually converted to bool long ago. The candidates below are
8520   // therefore added as binary.
8521   //
8522   // C++ [over.built]p25:
8523   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8524   //   enumeration type, there exist candidate operator functions of the form
8525   //
8526   //        T        operator?(bool, T, T);
8527   //
8528   void addConditionalOperatorOverloads() {
8529     /// Set of (canonical) types that we've already handled.
8530     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8531 
8532     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8533       for (BuiltinCandidateTypeSet::iterator
8534                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8535              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8536            Ptr != PtrEnd; ++Ptr) {
8537         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8538           continue;
8539 
8540         QualType ParamTypes[2] = { *Ptr, *Ptr };
8541         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8542       }
8543 
8544       for (BuiltinCandidateTypeSet::iterator
8545                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8546              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8547            MemPtr != MemPtrEnd; ++MemPtr) {
8548         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8549           continue;
8550 
8551         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8552         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8553       }
8554 
8555       if (S.getLangOpts().CPlusPlus11) {
8556         for (BuiltinCandidateTypeSet::iterator
8557                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8558                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8559              Enum != EnumEnd; ++Enum) {
8560           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8561             continue;
8562 
8563           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8564             continue;
8565 
8566           QualType ParamTypes[2] = { *Enum, *Enum };
8567           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8568         }
8569       }
8570     }
8571   }
8572 };
8573 
8574 } // end anonymous namespace
8575 
8576 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8577 /// operator overloads to the candidate set (C++ [over.built]), based
8578 /// on the operator @p Op and the arguments given. For example, if the
8579 /// operator is a binary '+', this routine might add "int
8580 /// operator+(int, int)" to cover integer addition.
8581 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8582                                         SourceLocation OpLoc,
8583                                         ArrayRef<Expr *> Args,
8584                                         OverloadCandidateSet &CandidateSet) {
8585   // Find all of the types that the arguments can convert to, but only
8586   // if the operator we're looking at has built-in operator candidates
8587   // that make use of these types. Also record whether we encounter non-record
8588   // candidate types or either arithmetic or enumeral candidate types.
8589   Qualifiers VisibleTypeConversionsQuals;
8590   VisibleTypeConversionsQuals.addConst();
8591   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8592     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8593 
8594   bool HasNonRecordCandidateType = false;
8595   bool HasArithmeticOrEnumeralCandidateType = false;
8596   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8597   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8598     CandidateTypes.emplace_back(*this);
8599     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8600                                                  OpLoc,
8601                                                  true,
8602                                                  (Op == OO_Exclaim ||
8603                                                   Op == OO_AmpAmp ||
8604                                                   Op == OO_PipePipe),
8605                                                  VisibleTypeConversionsQuals);
8606     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8607         CandidateTypes[ArgIdx].hasNonRecordTypes();
8608     HasArithmeticOrEnumeralCandidateType =
8609         HasArithmeticOrEnumeralCandidateType ||
8610         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8611   }
8612 
8613   // Exit early when no non-record types have been added to the candidate set
8614   // for any of the arguments to the operator.
8615   //
8616   // We can't exit early for !, ||, or &&, since there we have always have
8617   // 'bool' overloads.
8618   if (!HasNonRecordCandidateType &&
8619       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8620     return;
8621 
8622   // Setup an object to manage the common state for building overloads.
8623   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8624                                            VisibleTypeConversionsQuals,
8625                                            HasArithmeticOrEnumeralCandidateType,
8626                                            CandidateTypes, CandidateSet);
8627 
8628   // Dispatch over the operation to add in only those overloads which apply.
8629   switch (Op) {
8630   case OO_None:
8631   case NUM_OVERLOADED_OPERATORS:
8632     llvm_unreachable("Expected an overloaded operator");
8633 
8634   case OO_New:
8635   case OO_Delete:
8636   case OO_Array_New:
8637   case OO_Array_Delete:
8638   case OO_Call:
8639     llvm_unreachable(
8640                     "Special operators don't use AddBuiltinOperatorCandidates");
8641 
8642   case OO_Comma:
8643   case OO_Arrow:
8644   case OO_Coawait:
8645     // C++ [over.match.oper]p3:
8646     //   -- For the operator ',', the unary operator '&', the
8647     //      operator '->', or the operator 'co_await', the
8648     //      built-in candidates set is empty.
8649     break;
8650 
8651   case OO_Plus: // '+' is either unary or binary
8652     if (Args.size() == 1)
8653       OpBuilder.addUnaryPlusPointerOverloads();
8654     // Fall through.
8655 
8656   case OO_Minus: // '-' is either unary or binary
8657     if (Args.size() == 1) {
8658       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8659     } else {
8660       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8661       OpBuilder.addGenericBinaryArithmeticOverloads();
8662     }
8663     break;
8664 
8665   case OO_Star: // '*' is either unary or binary
8666     if (Args.size() == 1)
8667       OpBuilder.addUnaryStarPointerOverloads();
8668     else
8669       OpBuilder.addGenericBinaryArithmeticOverloads();
8670     break;
8671 
8672   case OO_Slash:
8673     OpBuilder.addGenericBinaryArithmeticOverloads();
8674     break;
8675 
8676   case OO_PlusPlus:
8677   case OO_MinusMinus:
8678     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8679     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8680     break;
8681 
8682   case OO_EqualEqual:
8683   case OO_ExclaimEqual:
8684     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8685     // Fall through.
8686 
8687   case OO_Less:
8688   case OO_Greater:
8689   case OO_LessEqual:
8690   case OO_GreaterEqual:
8691     OpBuilder.addRelationalPointerOrEnumeralOverloads();
8692     OpBuilder.addGenericBinaryArithmeticOverloads();
8693     break;
8694 
8695   case OO_Percent:
8696   case OO_Caret:
8697   case OO_Pipe:
8698   case OO_LessLess:
8699   case OO_GreaterGreater:
8700     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8701     break;
8702 
8703   case OO_Amp: // '&' is either unary or binary
8704     if (Args.size() == 1)
8705       // C++ [over.match.oper]p3:
8706       //   -- For the operator ',', the unary operator '&', or the
8707       //      operator '->', the built-in candidates set is empty.
8708       break;
8709 
8710     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8711     break;
8712 
8713   case OO_Tilde:
8714     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8715     break;
8716 
8717   case OO_Equal:
8718     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8719     // Fall through.
8720 
8721   case OO_PlusEqual:
8722   case OO_MinusEqual:
8723     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8724     // Fall through.
8725 
8726   case OO_StarEqual:
8727   case OO_SlashEqual:
8728     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8729     break;
8730 
8731   case OO_PercentEqual:
8732   case OO_LessLessEqual:
8733   case OO_GreaterGreaterEqual:
8734   case OO_AmpEqual:
8735   case OO_CaretEqual:
8736   case OO_PipeEqual:
8737     OpBuilder.addAssignmentIntegralOverloads();
8738     break;
8739 
8740   case OO_Exclaim:
8741     OpBuilder.addExclaimOverload();
8742     break;
8743 
8744   case OO_AmpAmp:
8745   case OO_PipePipe:
8746     OpBuilder.addAmpAmpOrPipePipeOverload();
8747     break;
8748 
8749   case OO_Subscript:
8750     OpBuilder.addSubscriptOverloads();
8751     break;
8752 
8753   case OO_ArrowStar:
8754     OpBuilder.addArrowStarOverloads();
8755     break;
8756 
8757   case OO_Conditional:
8758     OpBuilder.addConditionalOperatorOverloads();
8759     OpBuilder.addGenericBinaryArithmeticOverloads();
8760     break;
8761   }
8762 }
8763 
8764 /// \brief Add function candidates found via argument-dependent lookup
8765 /// to the set of overloading candidates.
8766 ///
8767 /// This routine performs argument-dependent name lookup based on the
8768 /// given function name (which may also be an operator name) and adds
8769 /// all of the overload candidates found by ADL to the overload
8770 /// candidate set (C++ [basic.lookup.argdep]).
8771 void
8772 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8773                                            SourceLocation Loc,
8774                                            ArrayRef<Expr *> Args,
8775                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8776                                            OverloadCandidateSet& CandidateSet,
8777                                            bool PartialOverloading) {
8778   ADLResult Fns;
8779 
8780   // FIXME: This approach for uniquing ADL results (and removing
8781   // redundant candidates from the set) relies on pointer-equality,
8782   // which means we need to key off the canonical decl.  However,
8783   // always going back to the canonical decl might not get us the
8784   // right set of default arguments.  What default arguments are
8785   // we supposed to consider on ADL candidates, anyway?
8786 
8787   // FIXME: Pass in the explicit template arguments?
8788   ArgumentDependentLookup(Name, Loc, Args, Fns);
8789 
8790   // Erase all of the candidates we already knew about.
8791   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8792                                    CandEnd = CandidateSet.end();
8793        Cand != CandEnd; ++Cand)
8794     if (Cand->Function) {
8795       Fns.erase(Cand->Function);
8796       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8797         Fns.erase(FunTmpl);
8798     }
8799 
8800   // For each of the ADL candidates we found, add it to the overload
8801   // set.
8802   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8803     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8804     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8805       if (ExplicitTemplateArgs)
8806         continue;
8807 
8808       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8809                            PartialOverloading);
8810     } else
8811       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8812                                    FoundDecl, ExplicitTemplateArgs,
8813                                    Args, CandidateSet, PartialOverloading);
8814   }
8815 }
8816 
8817 namespace {
8818 enum class Comparison { Equal, Better, Worse };
8819 }
8820 
8821 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8822 /// overload resolution.
8823 ///
8824 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8825 /// Cand1's first N enable_if attributes have precisely the same conditions as
8826 /// Cand2's first N enable_if attributes (where N = the number of enable_if
8827 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8828 ///
8829 /// Note that you can have a pair of candidates such that Cand1's enable_if
8830 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8831 /// worse than Cand1's.
8832 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8833                                        const FunctionDecl *Cand2) {
8834   // Common case: One (or both) decls don't have enable_if attrs.
8835   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8836   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8837   if (!Cand1Attr || !Cand2Attr) {
8838     if (Cand1Attr == Cand2Attr)
8839       return Comparison::Equal;
8840     return Cand1Attr ? Comparison::Better : Comparison::Worse;
8841   }
8842 
8843   // FIXME: The next several lines are just
8844   // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8845   // instead of reverse order which is how they're stored in the AST.
8846   auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8847   auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8848 
8849   // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8850   // has fewer enable_if attributes than Cand2.
8851   if (Cand1Attrs.size() < Cand2Attrs.size())
8852     return Comparison::Worse;
8853 
8854   auto Cand1I = Cand1Attrs.begin();
8855   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8856   for (auto &Cand2A : Cand2Attrs) {
8857     Cand1ID.clear();
8858     Cand2ID.clear();
8859 
8860     auto &Cand1A = *Cand1I++;
8861     Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8862     Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8863     if (Cand1ID != Cand2ID)
8864       return Comparison::Worse;
8865   }
8866 
8867   return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
8868 }
8869 
8870 /// isBetterOverloadCandidate - Determines whether the first overload
8871 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8872 bool clang::isBetterOverloadCandidate(
8873     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
8874     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
8875   // Define viable functions to be better candidates than non-viable
8876   // functions.
8877   if (!Cand2.Viable)
8878     return Cand1.Viable;
8879   else if (!Cand1.Viable)
8880     return false;
8881 
8882   // C++ [over.match.best]p1:
8883   //
8884   //   -- if F is a static member function, ICS1(F) is defined such
8885   //      that ICS1(F) is neither better nor worse than ICS1(G) for
8886   //      any function G, and, symmetrically, ICS1(G) is neither
8887   //      better nor worse than ICS1(F).
8888   unsigned StartArg = 0;
8889   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8890     StartArg = 1;
8891 
8892   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8893     // We don't allow incompatible pointer conversions in C++.
8894     if (!S.getLangOpts().CPlusPlus)
8895       return ICS.isStandard() &&
8896              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8897 
8898     // The only ill-formed conversion we allow in C++ is the string literal to
8899     // char* conversion, which is only considered ill-formed after C++11.
8900     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8901            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8902   };
8903 
8904   // Define functions that don't require ill-formed conversions for a given
8905   // argument to be better candidates than functions that do.
8906   unsigned NumArgs = Cand1.Conversions.size();
8907   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
8908   bool HasBetterConversion = false;
8909   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8910     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8911     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8912     if (Cand1Bad != Cand2Bad) {
8913       if (Cand1Bad)
8914         return false;
8915       HasBetterConversion = true;
8916     }
8917   }
8918 
8919   if (HasBetterConversion)
8920     return true;
8921 
8922   // C++ [over.match.best]p1:
8923   //   A viable function F1 is defined to be a better function than another
8924   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
8925   //   conversion sequence than ICSi(F2), and then...
8926   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8927     switch (CompareImplicitConversionSequences(S, Loc,
8928                                                Cand1.Conversions[ArgIdx],
8929                                                Cand2.Conversions[ArgIdx])) {
8930     case ImplicitConversionSequence::Better:
8931       // Cand1 has a better conversion sequence.
8932       HasBetterConversion = true;
8933       break;
8934 
8935     case ImplicitConversionSequence::Worse:
8936       // Cand1 can't be better than Cand2.
8937       return false;
8938 
8939     case ImplicitConversionSequence::Indistinguishable:
8940       // Do nothing.
8941       break;
8942     }
8943   }
8944 
8945   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
8946   //       ICSj(F2), or, if not that,
8947   if (HasBetterConversion)
8948     return true;
8949 
8950   //   -- the context is an initialization by user-defined conversion
8951   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
8952   //      from the return type of F1 to the destination type (i.e.,
8953   //      the type of the entity being initialized) is a better
8954   //      conversion sequence than the standard conversion sequence
8955   //      from the return type of F2 to the destination type.
8956   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
8957       Cand1.Function && Cand2.Function &&
8958       isa<CXXConversionDecl>(Cand1.Function) &&
8959       isa<CXXConversionDecl>(Cand2.Function)) {
8960     // First check whether we prefer one of the conversion functions over the
8961     // other. This only distinguishes the results in non-standard, extension
8962     // cases such as the conversion from a lambda closure type to a function
8963     // pointer or block.
8964     ImplicitConversionSequence::CompareKind Result =
8965         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8966     if (Result == ImplicitConversionSequence::Indistinguishable)
8967       Result = CompareStandardConversionSequences(S, Loc,
8968                                                   Cand1.FinalConversion,
8969                                                   Cand2.FinalConversion);
8970 
8971     if (Result != ImplicitConversionSequence::Indistinguishable)
8972       return Result == ImplicitConversionSequence::Better;
8973 
8974     // FIXME: Compare kind of reference binding if conversion functions
8975     // convert to a reference type used in direct reference binding, per
8976     // C++14 [over.match.best]p1 section 2 bullet 3.
8977   }
8978 
8979   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
8980   // as combined with the resolution to CWG issue 243.
8981   //
8982   // When the context is initialization by constructor ([over.match.ctor] or
8983   // either phase of [over.match.list]), a constructor is preferred over
8984   // a conversion function.
8985   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
8986       Cand1.Function && Cand2.Function &&
8987       isa<CXXConstructorDecl>(Cand1.Function) !=
8988           isa<CXXConstructorDecl>(Cand2.Function))
8989     return isa<CXXConstructorDecl>(Cand1.Function);
8990 
8991   //    -- F1 is a non-template function and F2 is a function template
8992   //       specialization, or, if not that,
8993   bool Cand1IsSpecialization = Cand1.Function &&
8994                                Cand1.Function->getPrimaryTemplate();
8995   bool Cand2IsSpecialization = Cand2.Function &&
8996                                Cand2.Function->getPrimaryTemplate();
8997   if (Cand1IsSpecialization != Cand2IsSpecialization)
8998     return Cand2IsSpecialization;
8999 
9000   //   -- F1 and F2 are function template specializations, and the function
9001   //      template for F1 is more specialized than the template for F2
9002   //      according to the partial ordering rules described in 14.5.5.2, or,
9003   //      if not that,
9004   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9005     if (FunctionTemplateDecl *BetterTemplate
9006           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9007                                          Cand2.Function->getPrimaryTemplate(),
9008                                          Loc,
9009                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9010                                                              : TPOC_Call,
9011                                          Cand1.ExplicitCallArguments,
9012                                          Cand2.ExplicitCallArguments))
9013       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9014   }
9015 
9016   // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9017   // A derived-class constructor beats an (inherited) base class constructor.
9018   bool Cand1IsInherited =
9019       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9020   bool Cand2IsInherited =
9021       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9022   if (Cand1IsInherited != Cand2IsInherited)
9023     return Cand2IsInherited;
9024   else if (Cand1IsInherited) {
9025     assert(Cand2IsInherited);
9026     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9027     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9028     if (Cand1Class->isDerivedFrom(Cand2Class))
9029       return true;
9030     if (Cand2Class->isDerivedFrom(Cand1Class))
9031       return false;
9032     // Inherited from sibling base classes: still ambiguous.
9033   }
9034 
9035   // Check C++17 tie-breakers for deduction guides.
9036   {
9037     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9038     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9039     if (Guide1 && Guide2) {
9040       //  -- F1 is generated from a deduction-guide and F2 is not
9041       if (Guide1->isImplicit() != Guide2->isImplicit())
9042         return Guide2->isImplicit();
9043 
9044       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9045       if (Guide1->isCopyDeductionCandidate())
9046         return true;
9047     }
9048   }
9049 
9050   // Check for enable_if value-based overload resolution.
9051   if (Cand1.Function && Cand2.Function) {
9052     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9053     if (Cmp != Comparison::Equal)
9054       return Cmp == Comparison::Better;
9055   }
9056 
9057   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9058     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9059     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9060            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9061   }
9062 
9063   bool HasPS1 = Cand1.Function != nullptr &&
9064                 functionHasPassObjectSizeParams(Cand1.Function);
9065   bool HasPS2 = Cand2.Function != nullptr &&
9066                 functionHasPassObjectSizeParams(Cand2.Function);
9067   return HasPS1 != HasPS2 && HasPS1;
9068 }
9069 
9070 /// Determine whether two declarations are "equivalent" for the purposes of
9071 /// name lookup and overload resolution. This applies when the same internal/no
9072 /// linkage entity is defined by two modules (probably by textually including
9073 /// the same header). In such a case, we don't consider the declarations to
9074 /// declare the same entity, but we also don't want lookups with both
9075 /// declarations visible to be ambiguous in some cases (this happens when using
9076 /// a modularized libstdc++).
9077 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9078                                                   const NamedDecl *B) {
9079   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9080   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9081   if (!VA || !VB)
9082     return false;
9083 
9084   // The declarations must be declaring the same name as an internal linkage
9085   // entity in different modules.
9086   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9087           VB->getDeclContext()->getRedeclContext()) ||
9088       getOwningModule(const_cast<ValueDecl *>(VA)) ==
9089           getOwningModule(const_cast<ValueDecl *>(VB)) ||
9090       VA->isExternallyVisible() || VB->isExternallyVisible())
9091     return false;
9092 
9093   // Check that the declarations appear to be equivalent.
9094   //
9095   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9096   // For constants and functions, we should check the initializer or body is
9097   // the same. For non-constant variables, we shouldn't allow it at all.
9098   if (Context.hasSameType(VA->getType(), VB->getType()))
9099     return true;
9100 
9101   // Enum constants within unnamed enumerations will have different types, but
9102   // may still be similar enough to be interchangeable for our purposes.
9103   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9104     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9105       // Only handle anonymous enums. If the enumerations were named and
9106       // equivalent, they would have been merged to the same type.
9107       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9108       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9109       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9110           !Context.hasSameType(EnumA->getIntegerType(),
9111                                EnumB->getIntegerType()))
9112         return false;
9113       // Allow this only if the value is the same for both enumerators.
9114       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9115     }
9116   }
9117 
9118   // Nothing else is sufficiently similar.
9119   return false;
9120 }
9121 
9122 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9123     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9124   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9125 
9126   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9127   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9128       << !M << (M ? M->getFullModuleName() : "");
9129 
9130   for (auto *E : Equiv) {
9131     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9132     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9133         << !M << (M ? M->getFullModuleName() : "");
9134   }
9135 }
9136 
9137 /// \brief Computes the best viable function (C++ 13.3.3)
9138 /// within an overload candidate set.
9139 ///
9140 /// \param Loc The location of the function name (or operator symbol) for
9141 /// which overload resolution occurs.
9142 ///
9143 /// \param Best If overload resolution was successful or found a deleted
9144 /// function, \p Best points to the candidate function found.
9145 ///
9146 /// \returns The result of overload resolution.
9147 OverloadingResult
9148 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9149                                          iterator &Best) {
9150   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9151   std::transform(begin(), end(), std::back_inserter(Candidates),
9152                  [](OverloadCandidate &Cand) { return &Cand; });
9153 
9154   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9155   // are accepted by both clang and NVCC. However, during a particular
9156   // compilation mode only one call variant is viable. We need to
9157   // exclude non-viable overload candidates from consideration based
9158   // only on their host/device attributes. Specifically, if one
9159   // candidate call is WrongSide and the other is SameSide, we ignore
9160   // the WrongSide candidate.
9161   if (S.getLangOpts().CUDA) {
9162     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9163     bool ContainsSameSideCandidate =
9164         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9165           return Cand->Function &&
9166                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9167                      Sema::CFP_SameSide;
9168         });
9169     if (ContainsSameSideCandidate) {
9170       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9171         return Cand->Function &&
9172                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9173                    Sema::CFP_WrongSide;
9174       };
9175       llvm::erase_if(Candidates, IsWrongSideCandidate);
9176     }
9177   }
9178 
9179   // Find the best viable function.
9180   Best = end();
9181   for (auto *Cand : Candidates)
9182     if (Cand->Viable)
9183       if (Best == end() ||
9184           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9185         Best = Cand;
9186 
9187   // If we didn't find any viable functions, abort.
9188   if (Best == end())
9189     return OR_No_Viable_Function;
9190 
9191   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9192 
9193   // Make sure that this function is better than every other viable
9194   // function. If not, we have an ambiguity.
9195   for (auto *Cand : Candidates) {
9196     if (Cand->Viable && Cand != Best &&
9197         !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
9198       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9199                                                    Cand->Function)) {
9200         EquivalentCands.push_back(Cand->Function);
9201         continue;
9202       }
9203 
9204       Best = end();
9205       return OR_Ambiguous;
9206     }
9207   }
9208 
9209   // Best is the best viable function.
9210   if (Best->Function &&
9211       (Best->Function->isDeleted() ||
9212        S.isFunctionConsideredUnavailable(Best->Function)))
9213     return OR_Deleted;
9214 
9215   if (!EquivalentCands.empty())
9216     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9217                                                     EquivalentCands);
9218 
9219   return OR_Success;
9220 }
9221 
9222 namespace {
9223 
9224 enum OverloadCandidateKind {
9225   oc_function,
9226   oc_method,
9227   oc_constructor,
9228   oc_function_template,
9229   oc_method_template,
9230   oc_constructor_template,
9231   oc_implicit_default_constructor,
9232   oc_implicit_copy_constructor,
9233   oc_implicit_move_constructor,
9234   oc_implicit_copy_assignment,
9235   oc_implicit_move_assignment,
9236   oc_inherited_constructor,
9237   oc_inherited_constructor_template
9238 };
9239 
9240 static OverloadCandidateKind
9241 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9242                           std::string &Description) {
9243   bool isTemplate = false;
9244 
9245   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9246     isTemplate = true;
9247     Description = S.getTemplateArgumentBindingsText(
9248       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9249   }
9250 
9251   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9252     if (!Ctor->isImplicit()) {
9253       if (isa<ConstructorUsingShadowDecl>(Found))
9254         return isTemplate ? oc_inherited_constructor_template
9255                           : oc_inherited_constructor;
9256       else
9257         return isTemplate ? oc_constructor_template : oc_constructor;
9258     }
9259 
9260     if (Ctor->isDefaultConstructor())
9261       return oc_implicit_default_constructor;
9262 
9263     if (Ctor->isMoveConstructor())
9264       return oc_implicit_move_constructor;
9265 
9266     assert(Ctor->isCopyConstructor() &&
9267            "unexpected sort of implicit constructor");
9268     return oc_implicit_copy_constructor;
9269   }
9270 
9271   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9272     // This actually gets spelled 'candidate function' for now, but
9273     // it doesn't hurt to split it out.
9274     if (!Meth->isImplicit())
9275       return isTemplate ? oc_method_template : oc_method;
9276 
9277     if (Meth->isMoveAssignmentOperator())
9278       return oc_implicit_move_assignment;
9279 
9280     if (Meth->isCopyAssignmentOperator())
9281       return oc_implicit_copy_assignment;
9282 
9283     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9284     return oc_method;
9285   }
9286 
9287   return isTemplate ? oc_function_template : oc_function;
9288 }
9289 
9290 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9291   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9292   // set.
9293   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9294     S.Diag(FoundDecl->getLocation(),
9295            diag::note_ovl_candidate_inherited_constructor)
9296       << Shadow->getNominatedBaseClass();
9297 }
9298 
9299 } // end anonymous namespace
9300 
9301 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9302                                     const FunctionDecl *FD) {
9303   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9304     bool AlwaysTrue;
9305     if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9306       return false;
9307     if (!AlwaysTrue)
9308       return false;
9309   }
9310   return true;
9311 }
9312 
9313 /// \brief Returns true if we can take the address of the function.
9314 ///
9315 /// \param Complain - If true, we'll emit a diagnostic
9316 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9317 ///   we in overload resolution?
9318 /// \param Loc - The location of the statement we're complaining about. Ignored
9319 ///   if we're not complaining, or if we're in overload resolution.
9320 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9321                                               bool Complain,
9322                                               bool InOverloadResolution,
9323                                               SourceLocation Loc) {
9324   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9325     if (Complain) {
9326       if (InOverloadResolution)
9327         S.Diag(FD->getLocStart(),
9328                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9329       else
9330         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9331     }
9332     return false;
9333   }
9334 
9335   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9336     return P->hasAttr<PassObjectSizeAttr>();
9337   });
9338   if (I == FD->param_end())
9339     return true;
9340 
9341   if (Complain) {
9342     // Add one to ParamNo because it's user-facing
9343     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9344     if (InOverloadResolution)
9345       S.Diag(FD->getLocation(),
9346              diag::note_ovl_candidate_has_pass_object_size_params)
9347           << ParamNo;
9348     else
9349       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9350           << FD << ParamNo;
9351   }
9352   return false;
9353 }
9354 
9355 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9356                                                const FunctionDecl *FD) {
9357   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9358                                            /*InOverloadResolution=*/true,
9359                                            /*Loc=*/SourceLocation());
9360 }
9361 
9362 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9363                                              bool Complain,
9364                                              SourceLocation Loc) {
9365   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9366                                              /*InOverloadResolution=*/false,
9367                                              Loc);
9368 }
9369 
9370 // Notes the location of an overload candidate.
9371 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9372                                  QualType DestType, bool TakingAddress) {
9373   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9374     return;
9375 
9376   std::string FnDesc;
9377   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9378   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9379                              << (unsigned) K << Fn << FnDesc;
9380 
9381   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9382   Diag(Fn->getLocation(), PD);
9383   MaybeEmitInheritedConstructorNote(*this, Found);
9384 }
9385 
9386 // Notes the location of all overload candidates designated through
9387 // OverloadedExpr
9388 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9389                                      bool TakingAddress) {
9390   assert(OverloadedExpr->getType() == Context.OverloadTy);
9391 
9392   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9393   OverloadExpr *OvlExpr = Ovl.Expression;
9394 
9395   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9396                             IEnd = OvlExpr->decls_end();
9397        I != IEnd; ++I) {
9398     if (FunctionTemplateDecl *FunTmpl =
9399                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9400       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9401                             TakingAddress);
9402     } else if (FunctionDecl *Fun
9403                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9404       NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9405     }
9406   }
9407 }
9408 
9409 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9410 /// "lead" diagnostic; it will be given two arguments, the source and
9411 /// target types of the conversion.
9412 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9413                                  Sema &S,
9414                                  SourceLocation CaretLoc,
9415                                  const PartialDiagnostic &PDiag) const {
9416   S.Diag(CaretLoc, PDiag)
9417     << Ambiguous.getFromType() << Ambiguous.getToType();
9418   // FIXME: The note limiting machinery is borrowed from
9419   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9420   // refactoring here.
9421   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9422   unsigned CandsShown = 0;
9423   AmbiguousConversionSequence::const_iterator I, E;
9424   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9425     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9426       break;
9427     ++CandsShown;
9428     S.NoteOverloadCandidate(I->first, I->second);
9429   }
9430   if (I != E)
9431     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9432 }
9433 
9434 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9435                                   unsigned I, bool TakingCandidateAddress) {
9436   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9437   assert(Conv.isBad());
9438   assert(Cand->Function && "for now, candidate must be a function");
9439   FunctionDecl *Fn = Cand->Function;
9440 
9441   // There's a conversion slot for the object argument if this is a
9442   // non-constructor method.  Note that 'I' corresponds the
9443   // conversion-slot index.
9444   bool isObjectArgument = false;
9445   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9446     if (I == 0)
9447       isObjectArgument = true;
9448     else
9449       I--;
9450   }
9451 
9452   std::string FnDesc;
9453   OverloadCandidateKind FnKind =
9454       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9455 
9456   Expr *FromExpr = Conv.Bad.FromExpr;
9457   QualType FromTy = Conv.Bad.getFromType();
9458   QualType ToTy = Conv.Bad.getToType();
9459 
9460   if (FromTy == S.Context.OverloadTy) {
9461     assert(FromExpr && "overload set argument came from implicit argument?");
9462     Expr *E = FromExpr->IgnoreParens();
9463     if (isa<UnaryOperator>(E))
9464       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9465     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9466 
9467     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9468       << (unsigned) FnKind << FnDesc
9469       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9470       << ToTy << Name << I+1;
9471     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9472     return;
9473   }
9474 
9475   // Do some hand-waving analysis to see if the non-viability is due
9476   // to a qualifier mismatch.
9477   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9478   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9479   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9480     CToTy = RT->getPointeeType();
9481   else {
9482     // TODO: detect and diagnose the full richness of const mismatches.
9483     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9484       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9485         CFromTy = FromPT->getPointeeType();
9486         CToTy = ToPT->getPointeeType();
9487       }
9488   }
9489 
9490   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9491       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9492     Qualifiers FromQs = CFromTy.getQualifiers();
9493     Qualifiers ToQs = CToTy.getQualifiers();
9494 
9495     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9496       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9497         << (unsigned) FnKind << FnDesc
9498         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9499         << FromTy
9500         << FromQs.getAddressSpaceAttributePrintValue()
9501         << ToQs.getAddressSpaceAttributePrintValue()
9502         << (unsigned) isObjectArgument << I+1;
9503       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9504       return;
9505     }
9506 
9507     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9508       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9509         << (unsigned) FnKind << FnDesc
9510         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9511         << FromTy
9512         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9513         << (unsigned) isObjectArgument << I+1;
9514       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9515       return;
9516     }
9517 
9518     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9519       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9520       << (unsigned) FnKind << FnDesc
9521       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9522       << FromTy
9523       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9524       << (unsigned) isObjectArgument << I+1;
9525       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9526       return;
9527     }
9528 
9529     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9530       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9531         << (unsigned) FnKind << FnDesc
9532         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9533         << FromTy << FromQs.hasUnaligned() << I+1;
9534       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9535       return;
9536     }
9537 
9538     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9539     assert(CVR && "unexpected qualifiers mismatch");
9540 
9541     if (isObjectArgument) {
9542       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9543         << (unsigned) FnKind << FnDesc
9544         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9545         << FromTy << (CVR - 1);
9546     } else {
9547       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9548         << (unsigned) FnKind << FnDesc
9549         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9550         << FromTy << (CVR - 1) << I+1;
9551     }
9552     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9553     return;
9554   }
9555 
9556   // Special diagnostic for failure to convert an initializer list, since
9557   // telling the user that it has type void is not useful.
9558   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9559     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9560       << (unsigned) FnKind << FnDesc
9561       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9562       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9563     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9564     return;
9565   }
9566 
9567   // Diagnose references or pointers to incomplete types differently,
9568   // since it's far from impossible that the incompleteness triggered
9569   // the failure.
9570   QualType TempFromTy = FromTy.getNonReferenceType();
9571   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9572     TempFromTy = PTy->getPointeeType();
9573   if (TempFromTy->isIncompleteType()) {
9574     // Emit the generic diagnostic and, optionally, add the hints to it.
9575     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9576       << (unsigned) FnKind << FnDesc
9577       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9578       << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9579       << (unsigned) (Cand->Fix.Kind);
9580 
9581     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9582     return;
9583   }
9584 
9585   // Diagnose base -> derived pointer conversions.
9586   unsigned BaseToDerivedConversion = 0;
9587   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9588     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9589       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9590                                                FromPtrTy->getPointeeType()) &&
9591           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9592           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9593           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9594                           FromPtrTy->getPointeeType()))
9595         BaseToDerivedConversion = 1;
9596     }
9597   } else if (const ObjCObjectPointerType *FromPtrTy
9598                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9599     if (const ObjCObjectPointerType *ToPtrTy
9600                                         = ToTy->getAs<ObjCObjectPointerType>())
9601       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9602         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9603           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9604                                                 FromPtrTy->getPointeeType()) &&
9605               FromIface->isSuperClassOf(ToIface))
9606             BaseToDerivedConversion = 2;
9607   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9608     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9609         !FromTy->isIncompleteType() &&
9610         !ToRefTy->getPointeeType()->isIncompleteType() &&
9611         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9612       BaseToDerivedConversion = 3;
9613     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9614                ToTy.getNonReferenceType().getCanonicalType() ==
9615                FromTy.getNonReferenceType().getCanonicalType()) {
9616       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9617         << (unsigned) FnKind << FnDesc
9618         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9619         << (unsigned) isObjectArgument << I + 1;
9620       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9621       return;
9622     }
9623   }
9624 
9625   if (BaseToDerivedConversion) {
9626     S.Diag(Fn->getLocation(),
9627            diag::note_ovl_candidate_bad_base_to_derived_conv)
9628       << (unsigned) FnKind << FnDesc
9629       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9630       << (BaseToDerivedConversion - 1)
9631       << FromTy << ToTy << I+1;
9632     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9633     return;
9634   }
9635 
9636   if (isa<ObjCObjectPointerType>(CFromTy) &&
9637       isa<PointerType>(CToTy)) {
9638       Qualifiers FromQs = CFromTy.getQualifiers();
9639       Qualifiers ToQs = CToTy.getQualifiers();
9640       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9641         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9642         << (unsigned) FnKind << FnDesc
9643         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9644         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9645         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9646         return;
9647       }
9648   }
9649 
9650   if (TakingCandidateAddress &&
9651       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9652     return;
9653 
9654   // Emit the generic diagnostic and, optionally, add the hints to it.
9655   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9656   FDiag << (unsigned) FnKind << FnDesc
9657     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9658     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9659     << (unsigned) (Cand->Fix.Kind);
9660 
9661   // If we can fix the conversion, suggest the FixIts.
9662   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9663        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9664     FDiag << *HI;
9665   S.Diag(Fn->getLocation(), FDiag);
9666 
9667   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9668 }
9669 
9670 /// Additional arity mismatch diagnosis specific to a function overload
9671 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9672 /// over a candidate in any candidate set.
9673 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9674                                unsigned NumArgs) {
9675   FunctionDecl *Fn = Cand->Function;
9676   unsigned MinParams = Fn->getMinRequiredArguments();
9677 
9678   // With invalid overloaded operators, it's possible that we think we
9679   // have an arity mismatch when in fact it looks like we have the
9680   // right number of arguments, because only overloaded operators have
9681   // the weird behavior of overloading member and non-member functions.
9682   // Just don't report anything.
9683   if (Fn->isInvalidDecl() &&
9684       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9685     return true;
9686 
9687   if (NumArgs < MinParams) {
9688     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9689            (Cand->FailureKind == ovl_fail_bad_deduction &&
9690             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9691   } else {
9692     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9693            (Cand->FailureKind == ovl_fail_bad_deduction &&
9694             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9695   }
9696 
9697   return false;
9698 }
9699 
9700 /// General arity mismatch diagnosis over a candidate in a candidate set.
9701 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9702                                   unsigned NumFormalArgs) {
9703   assert(isa<FunctionDecl>(D) &&
9704       "The templated declaration should at least be a function"
9705       " when diagnosing bad template argument deduction due to too many"
9706       " or too few arguments");
9707 
9708   FunctionDecl *Fn = cast<FunctionDecl>(D);
9709 
9710   // TODO: treat calls to a missing default constructor as a special case
9711   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9712   unsigned MinParams = Fn->getMinRequiredArguments();
9713 
9714   // at least / at most / exactly
9715   unsigned mode, modeCount;
9716   if (NumFormalArgs < MinParams) {
9717     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9718         FnTy->isTemplateVariadic())
9719       mode = 0; // "at least"
9720     else
9721       mode = 2; // "exactly"
9722     modeCount = MinParams;
9723   } else {
9724     if (MinParams != FnTy->getNumParams())
9725       mode = 1; // "at most"
9726     else
9727       mode = 2; // "exactly"
9728     modeCount = FnTy->getNumParams();
9729   }
9730 
9731   std::string Description;
9732   OverloadCandidateKind FnKind =
9733       ClassifyOverloadCandidate(S, Found, Fn, Description);
9734 
9735   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9736     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9737       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9738       << mode << Fn->getParamDecl(0) << NumFormalArgs;
9739   else
9740     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9741       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9742       << mode << modeCount << NumFormalArgs;
9743   MaybeEmitInheritedConstructorNote(S, Found);
9744 }
9745 
9746 /// Arity mismatch diagnosis specific to a function overload candidate.
9747 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9748                                   unsigned NumFormalArgs) {
9749   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9750     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9751 }
9752 
9753 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9754   if (TemplateDecl *TD = Templated->getDescribedTemplate())
9755     return TD;
9756   llvm_unreachable("Unsupported: Getting the described template declaration"
9757                    " for bad deduction diagnosis");
9758 }
9759 
9760 /// Diagnose a failed template-argument deduction.
9761 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9762                                  DeductionFailureInfo &DeductionFailure,
9763                                  unsigned NumArgs,
9764                                  bool TakingCandidateAddress) {
9765   TemplateParameter Param = DeductionFailure.getTemplateParameter();
9766   NamedDecl *ParamD;
9767   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9768   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9769   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9770   switch (DeductionFailure.Result) {
9771   case Sema::TDK_Success:
9772     llvm_unreachable("TDK_success while diagnosing bad deduction");
9773 
9774   case Sema::TDK_Incomplete: {
9775     assert(ParamD && "no parameter found for incomplete deduction result");
9776     S.Diag(Templated->getLocation(),
9777            diag::note_ovl_candidate_incomplete_deduction)
9778         << ParamD->getDeclName();
9779     MaybeEmitInheritedConstructorNote(S, Found);
9780     return;
9781   }
9782 
9783   case Sema::TDK_Underqualified: {
9784     assert(ParamD && "no parameter found for bad qualifiers deduction result");
9785     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9786 
9787     QualType Param = DeductionFailure.getFirstArg()->getAsType();
9788 
9789     // Param will have been canonicalized, but it should just be a
9790     // qualified version of ParamD, so move the qualifiers to that.
9791     QualifierCollector Qs;
9792     Qs.strip(Param);
9793     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9794     assert(S.Context.hasSameType(Param, NonCanonParam));
9795 
9796     // Arg has also been canonicalized, but there's nothing we can do
9797     // about that.  It also doesn't matter as much, because it won't
9798     // have any template parameters in it (because deduction isn't
9799     // done on dependent types).
9800     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9801 
9802     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9803         << ParamD->getDeclName() << Arg << NonCanonParam;
9804     MaybeEmitInheritedConstructorNote(S, Found);
9805     return;
9806   }
9807 
9808   case Sema::TDK_Inconsistent: {
9809     assert(ParamD && "no parameter found for inconsistent deduction result");
9810     int which = 0;
9811     if (isa<TemplateTypeParmDecl>(ParamD))
9812       which = 0;
9813     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9814       // Deduction might have failed because we deduced arguments of two
9815       // different types for a non-type template parameter.
9816       // FIXME: Use a different TDK value for this.
9817       QualType T1 =
9818           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
9819       QualType T2 =
9820           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
9821       if (!S.Context.hasSameType(T1, T2)) {
9822         S.Diag(Templated->getLocation(),
9823                diag::note_ovl_candidate_inconsistent_deduction_types)
9824           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
9825           << *DeductionFailure.getSecondArg() << T2;
9826         MaybeEmitInheritedConstructorNote(S, Found);
9827         return;
9828       }
9829 
9830       which = 1;
9831     } else {
9832       which = 2;
9833     }
9834 
9835     S.Diag(Templated->getLocation(),
9836            diag::note_ovl_candidate_inconsistent_deduction)
9837         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9838         << *DeductionFailure.getSecondArg();
9839     MaybeEmitInheritedConstructorNote(S, Found);
9840     return;
9841   }
9842 
9843   case Sema::TDK_InvalidExplicitArguments:
9844     assert(ParamD && "no parameter found for invalid explicit arguments");
9845     if (ParamD->getDeclName())
9846       S.Diag(Templated->getLocation(),
9847              diag::note_ovl_candidate_explicit_arg_mismatch_named)
9848           << ParamD->getDeclName();
9849     else {
9850       int index = 0;
9851       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9852         index = TTP->getIndex();
9853       else if (NonTypeTemplateParmDecl *NTTP
9854                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9855         index = NTTP->getIndex();
9856       else
9857         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9858       S.Diag(Templated->getLocation(),
9859              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9860           << (index + 1);
9861     }
9862     MaybeEmitInheritedConstructorNote(S, Found);
9863     return;
9864 
9865   case Sema::TDK_TooManyArguments:
9866   case Sema::TDK_TooFewArguments:
9867     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
9868     return;
9869 
9870   case Sema::TDK_InstantiationDepth:
9871     S.Diag(Templated->getLocation(),
9872            diag::note_ovl_candidate_instantiation_depth);
9873     MaybeEmitInheritedConstructorNote(S, Found);
9874     return;
9875 
9876   case Sema::TDK_SubstitutionFailure: {
9877     // Format the template argument list into the argument string.
9878     SmallString<128> TemplateArgString;
9879     if (TemplateArgumentList *Args =
9880             DeductionFailure.getTemplateArgumentList()) {
9881       TemplateArgString = " ";
9882       TemplateArgString += S.getTemplateArgumentBindingsText(
9883           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9884     }
9885 
9886     // If this candidate was disabled by enable_if, say so.
9887     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9888     if (PDiag && PDiag->second.getDiagID() ==
9889           diag::err_typename_nested_not_found_enable_if) {
9890       // FIXME: Use the source range of the condition, and the fully-qualified
9891       //        name of the enable_if template. These are both present in PDiag.
9892       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9893         << "'enable_if'" << TemplateArgString;
9894       return;
9895     }
9896 
9897     // We found a specific requirement that disabled the enable_if.
9898     if (PDiag && PDiag->second.getDiagID() ==
9899         diag::err_typename_nested_not_found_requirement) {
9900       S.Diag(Templated->getLocation(),
9901              diag::note_ovl_candidate_disabled_by_requirement)
9902         << PDiag->second.getStringArg(0) << TemplateArgString;
9903       return;
9904     }
9905 
9906     // Format the SFINAE diagnostic into the argument string.
9907     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9908     //        formatted message in another diagnostic.
9909     SmallString<128> SFINAEArgString;
9910     SourceRange R;
9911     if (PDiag) {
9912       SFINAEArgString = ": ";
9913       R = SourceRange(PDiag->first, PDiag->first);
9914       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9915     }
9916 
9917     S.Diag(Templated->getLocation(),
9918            diag::note_ovl_candidate_substitution_failure)
9919         << TemplateArgString << SFINAEArgString << R;
9920     MaybeEmitInheritedConstructorNote(S, Found);
9921     return;
9922   }
9923 
9924   case Sema::TDK_DeducedMismatch:
9925   case Sema::TDK_DeducedMismatchNested: {
9926     // Format the template argument list into the argument string.
9927     SmallString<128> TemplateArgString;
9928     if (TemplateArgumentList *Args =
9929             DeductionFailure.getTemplateArgumentList()) {
9930       TemplateArgString = " ";
9931       TemplateArgString += S.getTemplateArgumentBindingsText(
9932           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9933     }
9934 
9935     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9936         << (*DeductionFailure.getCallArgIndex() + 1)
9937         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9938         << TemplateArgString
9939         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
9940     break;
9941   }
9942 
9943   case Sema::TDK_NonDeducedMismatch: {
9944     // FIXME: Provide a source location to indicate what we couldn't match.
9945     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9946     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
9947     if (FirstTA.getKind() == TemplateArgument::Template &&
9948         SecondTA.getKind() == TemplateArgument::Template) {
9949       TemplateName FirstTN = FirstTA.getAsTemplate();
9950       TemplateName SecondTN = SecondTA.getAsTemplate();
9951       if (FirstTN.getKind() == TemplateName::Template &&
9952           SecondTN.getKind() == TemplateName::Template) {
9953         if (FirstTN.getAsTemplateDecl()->getName() ==
9954             SecondTN.getAsTemplateDecl()->getName()) {
9955           // FIXME: This fixes a bad diagnostic where both templates are named
9956           // the same.  This particular case is a bit difficult since:
9957           // 1) It is passed as a string to the diagnostic printer.
9958           // 2) The diagnostic printer only attempts to find a better
9959           //    name for types, not decls.
9960           // Ideally, this should folded into the diagnostic printer.
9961           S.Diag(Templated->getLocation(),
9962                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9963               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9964           return;
9965         }
9966       }
9967     }
9968 
9969     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9970         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9971       return;
9972 
9973     // FIXME: For generic lambda parameters, check if the function is a lambda
9974     // call operator, and if so, emit a prettier and more informative
9975     // diagnostic that mentions 'auto' and lambda in addition to
9976     // (or instead of?) the canonical template type parameters.
9977     S.Diag(Templated->getLocation(),
9978            diag::note_ovl_candidate_non_deduced_mismatch)
9979         << FirstTA << SecondTA;
9980     return;
9981   }
9982   // TODO: diagnose these individually, then kill off
9983   // note_ovl_candidate_bad_deduction, which is uselessly vague.
9984   case Sema::TDK_MiscellaneousDeductionFailure:
9985     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9986     MaybeEmitInheritedConstructorNote(S, Found);
9987     return;
9988   case Sema::TDK_CUDATargetMismatch:
9989     S.Diag(Templated->getLocation(),
9990            diag::note_cuda_ovl_candidate_target_mismatch);
9991     return;
9992   }
9993 }
9994 
9995 /// Diagnose a failed template-argument deduction, for function calls.
9996 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9997                                  unsigned NumArgs,
9998                                  bool TakingCandidateAddress) {
9999   unsigned TDK = Cand->DeductionFailure.Result;
10000   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10001     if (CheckArityMismatch(S, Cand, NumArgs))
10002       return;
10003   }
10004   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10005                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10006 }
10007 
10008 /// CUDA: diagnose an invalid call across targets.
10009 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10010   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10011   FunctionDecl *Callee = Cand->Function;
10012 
10013   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10014                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10015 
10016   std::string FnDesc;
10017   OverloadCandidateKind FnKind =
10018       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
10019 
10020   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10021       << (unsigned)FnKind << CalleeTarget << CallerTarget;
10022 
10023   // This could be an implicit constructor for which we could not infer the
10024   // target due to a collsion. Diagnose that case.
10025   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10026   if (Meth != nullptr && Meth->isImplicit()) {
10027     CXXRecordDecl *ParentClass = Meth->getParent();
10028     Sema::CXXSpecialMember CSM;
10029 
10030     switch (FnKind) {
10031     default:
10032       return;
10033     case oc_implicit_default_constructor:
10034       CSM = Sema::CXXDefaultConstructor;
10035       break;
10036     case oc_implicit_copy_constructor:
10037       CSM = Sema::CXXCopyConstructor;
10038       break;
10039     case oc_implicit_move_constructor:
10040       CSM = Sema::CXXMoveConstructor;
10041       break;
10042     case oc_implicit_copy_assignment:
10043       CSM = Sema::CXXCopyAssignment;
10044       break;
10045     case oc_implicit_move_assignment:
10046       CSM = Sema::CXXMoveAssignment;
10047       break;
10048     };
10049 
10050     bool ConstRHS = false;
10051     if (Meth->getNumParams()) {
10052       if (const ReferenceType *RT =
10053               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10054         ConstRHS = RT->getPointeeType().isConstQualified();
10055       }
10056     }
10057 
10058     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10059                                               /* ConstRHS */ ConstRHS,
10060                                               /* Diagnose */ true);
10061   }
10062 }
10063 
10064 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10065   FunctionDecl *Callee = Cand->Function;
10066   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10067 
10068   S.Diag(Callee->getLocation(),
10069          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10070       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10071 }
10072 
10073 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10074   FunctionDecl *Callee = Cand->Function;
10075 
10076   S.Diag(Callee->getLocation(),
10077          diag::note_ovl_candidate_disabled_by_extension);
10078 }
10079 
10080 /// Generates a 'note' diagnostic for an overload candidate.  We've
10081 /// already generated a primary error at the call site.
10082 ///
10083 /// It really does need to be a single diagnostic with its caret
10084 /// pointed at the candidate declaration.  Yes, this creates some
10085 /// major challenges of technical writing.  Yes, this makes pointing
10086 /// out problems with specific arguments quite awkward.  It's still
10087 /// better than generating twenty screens of text for every failed
10088 /// overload.
10089 ///
10090 /// It would be great to be able to express per-candidate problems
10091 /// more richly for those diagnostic clients that cared, but we'd
10092 /// still have to be just as careful with the default diagnostics.
10093 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10094                                   unsigned NumArgs,
10095                                   bool TakingCandidateAddress) {
10096   FunctionDecl *Fn = Cand->Function;
10097 
10098   // Note deleted candidates, but only if they're viable.
10099   if (Cand->Viable) {
10100     if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10101       std::string FnDesc;
10102       OverloadCandidateKind FnKind =
10103         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
10104 
10105       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10106         << FnKind << FnDesc
10107         << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10108       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10109       return;
10110     }
10111 
10112     // We don't really have anything else to say about viable candidates.
10113     S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10114     return;
10115   }
10116 
10117   switch (Cand->FailureKind) {
10118   case ovl_fail_too_many_arguments:
10119   case ovl_fail_too_few_arguments:
10120     return DiagnoseArityMismatch(S, Cand, NumArgs);
10121 
10122   case ovl_fail_bad_deduction:
10123     return DiagnoseBadDeduction(S, Cand, NumArgs,
10124                                 TakingCandidateAddress);
10125 
10126   case ovl_fail_illegal_constructor: {
10127     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10128       << (Fn->getPrimaryTemplate() ? 1 : 0);
10129     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10130     return;
10131   }
10132 
10133   case ovl_fail_trivial_conversion:
10134   case ovl_fail_bad_final_conversion:
10135   case ovl_fail_final_conversion_not_exact:
10136     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10137 
10138   case ovl_fail_bad_conversion: {
10139     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10140     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10141       if (Cand->Conversions[I].isBad())
10142         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10143 
10144     // FIXME: this currently happens when we're called from SemaInit
10145     // when user-conversion overload fails.  Figure out how to handle
10146     // those conditions and diagnose them well.
10147     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10148   }
10149 
10150   case ovl_fail_bad_target:
10151     return DiagnoseBadTarget(S, Cand);
10152 
10153   case ovl_fail_enable_if:
10154     return DiagnoseFailedEnableIfAttr(S, Cand);
10155 
10156   case ovl_fail_ext_disabled:
10157     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10158 
10159   case ovl_fail_inhctor_slice:
10160     // It's generally not interesting to note copy/move constructors here.
10161     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10162       return;
10163     S.Diag(Fn->getLocation(),
10164            diag::note_ovl_candidate_inherited_constructor_slice)
10165       << (Fn->getPrimaryTemplate() ? 1 : 0)
10166       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10167     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10168     return;
10169 
10170   case ovl_fail_addr_not_available: {
10171     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10172     (void)Available;
10173     assert(!Available);
10174     break;
10175   }
10176   }
10177 }
10178 
10179 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10180   // Desugar the type of the surrogate down to a function type,
10181   // retaining as many typedefs as possible while still showing
10182   // the function type (and, therefore, its parameter types).
10183   QualType FnType = Cand->Surrogate->getConversionType();
10184   bool isLValueReference = false;
10185   bool isRValueReference = false;
10186   bool isPointer = false;
10187   if (const LValueReferenceType *FnTypeRef =
10188         FnType->getAs<LValueReferenceType>()) {
10189     FnType = FnTypeRef->getPointeeType();
10190     isLValueReference = true;
10191   } else if (const RValueReferenceType *FnTypeRef =
10192                FnType->getAs<RValueReferenceType>()) {
10193     FnType = FnTypeRef->getPointeeType();
10194     isRValueReference = true;
10195   }
10196   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10197     FnType = FnTypePtr->getPointeeType();
10198     isPointer = true;
10199   }
10200   // Desugar down to a function type.
10201   FnType = QualType(FnType->getAs<FunctionType>(), 0);
10202   // Reconstruct the pointer/reference as appropriate.
10203   if (isPointer) FnType = S.Context.getPointerType(FnType);
10204   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10205   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10206 
10207   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10208     << FnType;
10209 }
10210 
10211 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10212                                          SourceLocation OpLoc,
10213                                          OverloadCandidate *Cand) {
10214   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10215   std::string TypeStr("operator");
10216   TypeStr += Opc;
10217   TypeStr += "(";
10218   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
10219   if (Cand->Conversions.size() == 1) {
10220     TypeStr += ")";
10221     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10222   } else {
10223     TypeStr += ", ";
10224     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
10225     TypeStr += ")";
10226     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10227   }
10228 }
10229 
10230 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10231                                          OverloadCandidate *Cand) {
10232   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10233     if (ICS.isBad()) break; // all meaningless after first invalid
10234     if (!ICS.isAmbiguous()) continue;
10235 
10236     ICS.DiagnoseAmbiguousConversion(
10237         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10238   }
10239 }
10240 
10241 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10242   if (Cand->Function)
10243     return Cand->Function->getLocation();
10244   if (Cand->IsSurrogate)
10245     return Cand->Surrogate->getLocation();
10246   return SourceLocation();
10247 }
10248 
10249 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10250   switch ((Sema::TemplateDeductionResult)DFI.Result) {
10251   case Sema::TDK_Success:
10252   case Sema::TDK_NonDependentConversionFailure:
10253     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10254 
10255   case Sema::TDK_Invalid:
10256   case Sema::TDK_Incomplete:
10257     return 1;
10258 
10259   case Sema::TDK_Underqualified:
10260   case Sema::TDK_Inconsistent:
10261     return 2;
10262 
10263   case Sema::TDK_SubstitutionFailure:
10264   case Sema::TDK_DeducedMismatch:
10265   case Sema::TDK_DeducedMismatchNested:
10266   case Sema::TDK_NonDeducedMismatch:
10267   case Sema::TDK_MiscellaneousDeductionFailure:
10268   case Sema::TDK_CUDATargetMismatch:
10269     return 3;
10270 
10271   case Sema::TDK_InstantiationDepth:
10272     return 4;
10273 
10274   case Sema::TDK_InvalidExplicitArguments:
10275     return 5;
10276 
10277   case Sema::TDK_TooManyArguments:
10278   case Sema::TDK_TooFewArguments:
10279     return 6;
10280   }
10281   llvm_unreachable("Unhandled deduction result");
10282 }
10283 
10284 namespace {
10285 struct CompareOverloadCandidatesForDisplay {
10286   Sema &S;
10287   SourceLocation Loc;
10288   size_t NumArgs;
10289   OverloadCandidateSet::CandidateSetKind CSK;
10290 
10291   CompareOverloadCandidatesForDisplay(
10292       Sema &S, SourceLocation Loc, size_t NArgs,
10293       OverloadCandidateSet::CandidateSetKind CSK)
10294       : S(S), NumArgs(NArgs), CSK(CSK) {}
10295 
10296   bool operator()(const OverloadCandidate *L,
10297                   const OverloadCandidate *R) {
10298     // Fast-path this check.
10299     if (L == R) return false;
10300 
10301     // Order first by viability.
10302     if (L->Viable) {
10303       if (!R->Viable) return true;
10304 
10305       // TODO: introduce a tri-valued comparison for overload
10306       // candidates.  Would be more worthwhile if we had a sort
10307       // that could exploit it.
10308       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10309         return true;
10310       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10311         return false;
10312     } else if (R->Viable)
10313       return false;
10314 
10315     assert(L->Viable == R->Viable);
10316 
10317     // Criteria by which we can sort non-viable candidates:
10318     if (!L->Viable) {
10319       // 1. Arity mismatches come after other candidates.
10320       if (L->FailureKind == ovl_fail_too_many_arguments ||
10321           L->FailureKind == ovl_fail_too_few_arguments) {
10322         if (R->FailureKind == ovl_fail_too_many_arguments ||
10323             R->FailureKind == ovl_fail_too_few_arguments) {
10324           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10325           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10326           if (LDist == RDist) {
10327             if (L->FailureKind == R->FailureKind)
10328               // Sort non-surrogates before surrogates.
10329               return !L->IsSurrogate && R->IsSurrogate;
10330             // Sort candidates requiring fewer parameters than there were
10331             // arguments given after candidates requiring more parameters
10332             // than there were arguments given.
10333             return L->FailureKind == ovl_fail_too_many_arguments;
10334           }
10335           return LDist < RDist;
10336         }
10337         return false;
10338       }
10339       if (R->FailureKind == ovl_fail_too_many_arguments ||
10340           R->FailureKind == ovl_fail_too_few_arguments)
10341         return true;
10342 
10343       // 2. Bad conversions come first and are ordered by the number
10344       // of bad conversions and quality of good conversions.
10345       if (L->FailureKind == ovl_fail_bad_conversion) {
10346         if (R->FailureKind != ovl_fail_bad_conversion)
10347           return true;
10348 
10349         // The conversion that can be fixed with a smaller number of changes,
10350         // comes first.
10351         unsigned numLFixes = L->Fix.NumConversionsFixed;
10352         unsigned numRFixes = R->Fix.NumConversionsFixed;
10353         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10354         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10355         if (numLFixes != numRFixes) {
10356           return numLFixes < numRFixes;
10357         }
10358 
10359         // If there's any ordering between the defined conversions...
10360         // FIXME: this might not be transitive.
10361         assert(L->Conversions.size() == R->Conversions.size());
10362 
10363         int leftBetter = 0;
10364         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10365         for (unsigned E = L->Conversions.size(); I != E; ++I) {
10366           switch (CompareImplicitConversionSequences(S, Loc,
10367                                                      L->Conversions[I],
10368                                                      R->Conversions[I])) {
10369           case ImplicitConversionSequence::Better:
10370             leftBetter++;
10371             break;
10372 
10373           case ImplicitConversionSequence::Worse:
10374             leftBetter--;
10375             break;
10376 
10377           case ImplicitConversionSequence::Indistinguishable:
10378             break;
10379           }
10380         }
10381         if (leftBetter > 0) return true;
10382         if (leftBetter < 0) return false;
10383 
10384       } else if (R->FailureKind == ovl_fail_bad_conversion)
10385         return false;
10386 
10387       if (L->FailureKind == ovl_fail_bad_deduction) {
10388         if (R->FailureKind != ovl_fail_bad_deduction)
10389           return true;
10390 
10391         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10392           return RankDeductionFailure(L->DeductionFailure)
10393                < RankDeductionFailure(R->DeductionFailure);
10394       } else if (R->FailureKind == ovl_fail_bad_deduction)
10395         return false;
10396 
10397       // TODO: others?
10398     }
10399 
10400     // Sort everything else by location.
10401     SourceLocation LLoc = GetLocationForCandidate(L);
10402     SourceLocation RLoc = GetLocationForCandidate(R);
10403 
10404     // Put candidates without locations (e.g. builtins) at the end.
10405     if (LLoc.isInvalid()) return false;
10406     if (RLoc.isInvalid()) return true;
10407 
10408     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10409   }
10410 };
10411 }
10412 
10413 /// CompleteNonViableCandidate - Normally, overload resolution only
10414 /// computes up to the first bad conversion. Produces the FixIt set if
10415 /// possible.
10416 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10417                                        ArrayRef<Expr *> Args) {
10418   assert(!Cand->Viable);
10419 
10420   // Don't do anything on failures other than bad conversion.
10421   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10422 
10423   // We only want the FixIts if all the arguments can be corrected.
10424   bool Unfixable = false;
10425   // Use a implicit copy initialization to check conversion fixes.
10426   Cand->Fix.setConversionChecker(TryCopyInitialization);
10427 
10428   // Attempt to fix the bad conversion.
10429   unsigned ConvCount = Cand->Conversions.size();
10430   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10431        ++ConvIdx) {
10432     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10433     if (Cand->Conversions[ConvIdx].isInitialized() &&
10434         Cand->Conversions[ConvIdx].isBad()) {
10435       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10436       break;
10437     }
10438   }
10439 
10440   // FIXME: this should probably be preserved from the overload
10441   // operation somehow.
10442   bool SuppressUserConversions = false;
10443 
10444   unsigned ConvIdx = 0;
10445   ArrayRef<QualType> ParamTypes;
10446 
10447   if (Cand->IsSurrogate) {
10448     QualType ConvType
10449       = Cand->Surrogate->getConversionType().getNonReferenceType();
10450     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10451       ConvType = ConvPtrType->getPointeeType();
10452     ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10453     // Conversion 0 is 'this', which doesn't have a corresponding argument.
10454     ConvIdx = 1;
10455   } else if (Cand->Function) {
10456     ParamTypes =
10457         Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
10458     if (isa<CXXMethodDecl>(Cand->Function) &&
10459         !isa<CXXConstructorDecl>(Cand->Function)) {
10460       // Conversion 0 is 'this', which doesn't have a corresponding argument.
10461       ConvIdx = 1;
10462     }
10463   } else {
10464     // Builtin operator.
10465     assert(ConvCount <= 3);
10466     ParamTypes = Cand->BuiltinParamTypes;
10467   }
10468 
10469   // Fill in the rest of the conversions.
10470   for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10471     if (Cand->Conversions[ConvIdx].isInitialized()) {
10472       // We've already checked this conversion.
10473     } else if (ArgIdx < ParamTypes.size()) {
10474       if (ParamTypes[ArgIdx]->isDependentType())
10475         Cand->Conversions[ConvIdx].setAsIdentityConversion(
10476             Args[ArgIdx]->getType());
10477       else {
10478         Cand->Conversions[ConvIdx] =
10479             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10480                                   SuppressUserConversions,
10481                                   /*InOverloadResolution=*/true,
10482                                   /*AllowObjCWritebackConversion=*/
10483                                   S.getLangOpts().ObjCAutoRefCount);
10484         // Store the FixIt in the candidate if it exists.
10485         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10486           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10487       }
10488     } else
10489       Cand->Conversions[ConvIdx].setEllipsis();
10490   }
10491 }
10492 
10493 /// PrintOverloadCandidates - When overload resolution fails, prints
10494 /// diagnostic messages containing the candidates in the candidate
10495 /// set.
10496 void OverloadCandidateSet::NoteCandidates(
10497     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10498     StringRef Opc, SourceLocation OpLoc,
10499     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10500   // Sort the candidates by viability and position.  Sorting directly would
10501   // be prohibitive, so we make a set of pointers and sort those.
10502   SmallVector<OverloadCandidate*, 32> Cands;
10503   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10504   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10505     if (!Filter(*Cand))
10506       continue;
10507     if (Cand->Viable)
10508       Cands.push_back(Cand);
10509     else if (OCD == OCD_AllCandidates) {
10510       CompleteNonViableCandidate(S, Cand, Args);
10511       if (Cand->Function || Cand->IsSurrogate)
10512         Cands.push_back(Cand);
10513       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10514       // want to list every possible builtin candidate.
10515     }
10516   }
10517 
10518   std::stable_sort(Cands.begin(), Cands.end(),
10519             CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
10520 
10521   bool ReportedAmbiguousConversions = false;
10522 
10523   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10524   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10525   unsigned CandsShown = 0;
10526   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10527     OverloadCandidate *Cand = *I;
10528 
10529     // Set an arbitrary limit on the number of candidate functions we'll spam
10530     // the user with.  FIXME: This limit should depend on details of the
10531     // candidate list.
10532     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10533       break;
10534     }
10535     ++CandsShown;
10536 
10537     if (Cand->Function)
10538       NoteFunctionCandidate(S, Cand, Args.size(),
10539                             /*TakingCandidateAddress=*/false);
10540     else if (Cand->IsSurrogate)
10541       NoteSurrogateCandidate(S, Cand);
10542     else {
10543       assert(Cand->Viable &&
10544              "Non-viable built-in candidates are not added to Cands.");
10545       // Generally we only see ambiguities including viable builtin
10546       // operators if overload resolution got screwed up by an
10547       // ambiguous user-defined conversion.
10548       //
10549       // FIXME: It's quite possible for different conversions to see
10550       // different ambiguities, though.
10551       if (!ReportedAmbiguousConversions) {
10552         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10553         ReportedAmbiguousConversions = true;
10554       }
10555 
10556       // If this is a viable builtin, print it.
10557       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10558     }
10559   }
10560 
10561   if (I != E)
10562     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10563 }
10564 
10565 static SourceLocation
10566 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10567   return Cand->Specialization ? Cand->Specialization->getLocation()
10568                               : SourceLocation();
10569 }
10570 
10571 namespace {
10572 struct CompareTemplateSpecCandidatesForDisplay {
10573   Sema &S;
10574   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10575 
10576   bool operator()(const TemplateSpecCandidate *L,
10577                   const TemplateSpecCandidate *R) {
10578     // Fast-path this check.
10579     if (L == R)
10580       return false;
10581 
10582     // Assuming that both candidates are not matches...
10583 
10584     // Sort by the ranking of deduction failures.
10585     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10586       return RankDeductionFailure(L->DeductionFailure) <
10587              RankDeductionFailure(R->DeductionFailure);
10588 
10589     // Sort everything else by location.
10590     SourceLocation LLoc = GetLocationForCandidate(L);
10591     SourceLocation RLoc = GetLocationForCandidate(R);
10592 
10593     // Put candidates without locations (e.g. builtins) at the end.
10594     if (LLoc.isInvalid())
10595       return false;
10596     if (RLoc.isInvalid())
10597       return true;
10598 
10599     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10600   }
10601 };
10602 }
10603 
10604 /// Diagnose a template argument deduction failure.
10605 /// We are treating these failures as overload failures due to bad
10606 /// deductions.
10607 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10608                                                  bool ForTakingAddress) {
10609   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10610                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10611 }
10612 
10613 void TemplateSpecCandidateSet::destroyCandidates() {
10614   for (iterator i = begin(), e = end(); i != e; ++i) {
10615     i->DeductionFailure.Destroy();
10616   }
10617 }
10618 
10619 void TemplateSpecCandidateSet::clear() {
10620   destroyCandidates();
10621   Candidates.clear();
10622 }
10623 
10624 /// NoteCandidates - When no template specialization match is found, prints
10625 /// diagnostic messages containing the non-matching specializations that form
10626 /// the candidate set.
10627 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10628 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10629 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10630   // Sort the candidates by position (assuming no candidate is a match).
10631   // Sorting directly would be prohibitive, so we make a set of pointers
10632   // and sort those.
10633   SmallVector<TemplateSpecCandidate *, 32> Cands;
10634   Cands.reserve(size());
10635   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10636     if (Cand->Specialization)
10637       Cands.push_back(Cand);
10638     // Otherwise, this is a non-matching builtin candidate.  We do not,
10639     // in general, want to list every possible builtin candidate.
10640   }
10641 
10642   std::sort(Cands.begin(), Cands.end(),
10643             CompareTemplateSpecCandidatesForDisplay(S));
10644 
10645   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10646   // for generalization purposes (?).
10647   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10648 
10649   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10650   unsigned CandsShown = 0;
10651   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10652     TemplateSpecCandidate *Cand = *I;
10653 
10654     // Set an arbitrary limit on the number of candidates we'll spam
10655     // the user with.  FIXME: This limit should depend on details of the
10656     // candidate list.
10657     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10658       break;
10659     ++CandsShown;
10660 
10661     assert(Cand->Specialization &&
10662            "Non-matching built-in candidates are not added to Cands.");
10663     Cand->NoteDeductionFailure(S, ForTakingAddress);
10664   }
10665 
10666   if (I != E)
10667     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10668 }
10669 
10670 // [PossiblyAFunctionType]  -->   [Return]
10671 // NonFunctionType --> NonFunctionType
10672 // R (A) --> R(A)
10673 // R (*)(A) --> R (A)
10674 // R (&)(A) --> R (A)
10675 // R (S::*)(A) --> R (A)
10676 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10677   QualType Ret = PossiblyAFunctionType;
10678   if (const PointerType *ToTypePtr =
10679     PossiblyAFunctionType->getAs<PointerType>())
10680     Ret = ToTypePtr->getPointeeType();
10681   else if (const ReferenceType *ToTypeRef =
10682     PossiblyAFunctionType->getAs<ReferenceType>())
10683     Ret = ToTypeRef->getPointeeType();
10684   else if (const MemberPointerType *MemTypePtr =
10685     PossiblyAFunctionType->getAs<MemberPointerType>())
10686     Ret = MemTypePtr->getPointeeType();
10687   Ret =
10688     Context.getCanonicalType(Ret).getUnqualifiedType();
10689   return Ret;
10690 }
10691 
10692 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10693                                  bool Complain = true) {
10694   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10695       S.DeduceReturnType(FD, Loc, Complain))
10696     return true;
10697 
10698   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10699   if (S.getLangOpts().CPlusPlus1z &&
10700       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10701       !S.ResolveExceptionSpec(Loc, FPT))
10702     return true;
10703 
10704   return false;
10705 }
10706 
10707 namespace {
10708 // A helper class to help with address of function resolution
10709 // - allows us to avoid passing around all those ugly parameters
10710 class AddressOfFunctionResolver {
10711   Sema& S;
10712   Expr* SourceExpr;
10713   const QualType& TargetType;
10714   QualType TargetFunctionType; // Extracted function type from target type
10715 
10716   bool Complain;
10717   //DeclAccessPair& ResultFunctionAccessPair;
10718   ASTContext& Context;
10719 
10720   bool TargetTypeIsNonStaticMemberFunction;
10721   bool FoundNonTemplateFunction;
10722   bool StaticMemberFunctionFromBoundPointer;
10723   bool HasComplained;
10724 
10725   OverloadExpr::FindResult OvlExprInfo;
10726   OverloadExpr *OvlExpr;
10727   TemplateArgumentListInfo OvlExplicitTemplateArgs;
10728   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10729   TemplateSpecCandidateSet FailedCandidates;
10730 
10731 public:
10732   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10733                             const QualType &TargetType, bool Complain)
10734       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10735         Complain(Complain), Context(S.getASTContext()),
10736         TargetTypeIsNonStaticMemberFunction(
10737             !!TargetType->getAs<MemberPointerType>()),
10738         FoundNonTemplateFunction(false),
10739         StaticMemberFunctionFromBoundPointer(false),
10740         HasComplained(false),
10741         OvlExprInfo(OverloadExpr::find(SourceExpr)),
10742         OvlExpr(OvlExprInfo.Expression),
10743         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10744     ExtractUnqualifiedFunctionTypeFromTargetType();
10745 
10746     if (TargetFunctionType->isFunctionType()) {
10747       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10748         if (!UME->isImplicitAccess() &&
10749             !S.ResolveSingleFunctionTemplateSpecialization(UME))
10750           StaticMemberFunctionFromBoundPointer = true;
10751     } else if (OvlExpr->hasExplicitTemplateArgs()) {
10752       DeclAccessPair dap;
10753       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10754               OvlExpr, false, &dap)) {
10755         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10756           if (!Method->isStatic()) {
10757             // If the target type is a non-function type and the function found
10758             // is a non-static member function, pretend as if that was the
10759             // target, it's the only possible type to end up with.
10760             TargetTypeIsNonStaticMemberFunction = true;
10761 
10762             // And skip adding the function if its not in the proper form.
10763             // We'll diagnose this due to an empty set of functions.
10764             if (!OvlExprInfo.HasFormOfMemberPointer)
10765               return;
10766           }
10767 
10768         Matches.push_back(std::make_pair(dap, Fn));
10769       }
10770       return;
10771     }
10772 
10773     if (OvlExpr->hasExplicitTemplateArgs())
10774       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10775 
10776     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10777       // C++ [over.over]p4:
10778       //   If more than one function is selected, [...]
10779       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10780         if (FoundNonTemplateFunction)
10781           EliminateAllTemplateMatches();
10782         else
10783           EliminateAllExceptMostSpecializedTemplate();
10784       }
10785     }
10786 
10787     if (S.getLangOpts().CUDA && Matches.size() > 1)
10788       EliminateSuboptimalCudaMatches();
10789   }
10790 
10791   bool hasComplained() const { return HasComplained; }
10792 
10793 private:
10794   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10795     QualType Discard;
10796     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10797            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
10798   }
10799 
10800   /// \return true if A is considered a better overload candidate for the
10801   /// desired type than B.
10802   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10803     // If A doesn't have exactly the correct type, we don't want to classify it
10804     // as "better" than anything else. This way, the user is required to
10805     // disambiguate for us if there are multiple candidates and no exact match.
10806     return candidateHasExactlyCorrectType(A) &&
10807            (!candidateHasExactlyCorrectType(B) ||
10808             compareEnableIfAttrs(S, A, B) == Comparison::Better);
10809   }
10810 
10811   /// \return true if we were able to eliminate all but one overload candidate,
10812   /// false otherwise.
10813   bool eliminiateSuboptimalOverloadCandidates() {
10814     // Same algorithm as overload resolution -- one pass to pick the "best",
10815     // another pass to be sure that nothing is better than the best.
10816     auto Best = Matches.begin();
10817     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10818       if (isBetterCandidate(I->second, Best->second))
10819         Best = I;
10820 
10821     const FunctionDecl *BestFn = Best->second;
10822     auto IsBestOrInferiorToBest = [this, BestFn](
10823         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10824       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10825     };
10826 
10827     // Note: We explicitly leave Matches unmodified if there isn't a clear best
10828     // option, so we can potentially give the user a better error
10829     if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10830       return false;
10831     Matches[0] = *Best;
10832     Matches.resize(1);
10833     return true;
10834   }
10835 
10836   bool isTargetTypeAFunction() const {
10837     return TargetFunctionType->isFunctionType();
10838   }
10839 
10840   // [ToType]     [Return]
10841 
10842   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10843   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10844   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10845   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10846     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10847   }
10848 
10849   // return true if any matching specializations were found
10850   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10851                                    const DeclAccessPair& CurAccessFunPair) {
10852     if (CXXMethodDecl *Method
10853               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10854       // Skip non-static function templates when converting to pointer, and
10855       // static when converting to member pointer.
10856       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10857         return false;
10858     }
10859     else if (TargetTypeIsNonStaticMemberFunction)
10860       return false;
10861 
10862     // C++ [over.over]p2:
10863     //   If the name is a function template, template argument deduction is
10864     //   done (14.8.2.2), and if the argument deduction succeeds, the
10865     //   resulting template argument list is used to generate a single
10866     //   function template specialization, which is added to the set of
10867     //   overloaded functions considered.
10868     FunctionDecl *Specialization = nullptr;
10869     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10870     if (Sema::TemplateDeductionResult Result
10871           = S.DeduceTemplateArguments(FunctionTemplate,
10872                                       &OvlExplicitTemplateArgs,
10873                                       TargetFunctionType, Specialization,
10874                                       Info, /*IsAddressOfFunction*/true)) {
10875       // Make a note of the failed deduction for diagnostics.
10876       FailedCandidates.addCandidate()
10877           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
10878                MakeDeductionFailureInfo(Context, Result, Info));
10879       return false;
10880     }
10881 
10882     // Template argument deduction ensures that we have an exact match or
10883     // compatible pointer-to-function arguments that would be adjusted by ICS.
10884     // This function template specicalization works.
10885     assert(S.isSameOrCompatibleFunctionType(
10886               Context.getCanonicalType(Specialization->getType()),
10887               Context.getCanonicalType(TargetFunctionType)));
10888 
10889     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
10890       return false;
10891 
10892     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10893     return true;
10894   }
10895 
10896   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10897                                       const DeclAccessPair& CurAccessFunPair) {
10898     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10899       // Skip non-static functions when converting to pointer, and static
10900       // when converting to member pointer.
10901       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10902         return false;
10903     }
10904     else if (TargetTypeIsNonStaticMemberFunction)
10905       return false;
10906 
10907     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
10908       if (S.getLangOpts().CUDA)
10909         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
10910           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
10911             return false;
10912 
10913       // If any candidate has a placeholder return type, trigger its deduction
10914       // now.
10915       if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
10916                                Complain)) {
10917         HasComplained |= Complain;
10918         return false;
10919       }
10920 
10921       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
10922         return false;
10923 
10924       // If we're in C, we need to support types that aren't exactly identical.
10925       if (!S.getLangOpts().CPlusPlus ||
10926           candidateHasExactlyCorrectType(FunDecl)) {
10927         Matches.push_back(std::make_pair(
10928             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
10929         FoundNonTemplateFunction = true;
10930         return true;
10931       }
10932     }
10933 
10934     return false;
10935   }
10936 
10937   bool FindAllFunctionsThatMatchTargetTypeExactly() {
10938     bool Ret = false;
10939 
10940     // If the overload expression doesn't have the form of a pointer to
10941     // member, don't try to convert it to a pointer-to-member type.
10942     if (IsInvalidFormOfPointerToMemberFunction())
10943       return false;
10944 
10945     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10946                                E = OvlExpr->decls_end();
10947          I != E; ++I) {
10948       // Look through any using declarations to find the underlying function.
10949       NamedDecl *Fn = (*I)->getUnderlyingDecl();
10950 
10951       // C++ [over.over]p3:
10952       //   Non-member functions and static member functions match
10953       //   targets of type "pointer-to-function" or "reference-to-function."
10954       //   Nonstatic member functions match targets of
10955       //   type "pointer-to-member-function."
10956       // Note that according to DR 247, the containing class does not matter.
10957       if (FunctionTemplateDecl *FunctionTemplate
10958                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
10959         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10960           Ret = true;
10961       }
10962       // If we have explicit template arguments supplied, skip non-templates.
10963       else if (!OvlExpr->hasExplicitTemplateArgs() &&
10964                AddMatchingNonTemplateFunction(Fn, I.getPair()))
10965         Ret = true;
10966     }
10967     assert(Ret || Matches.empty());
10968     return Ret;
10969   }
10970 
10971   void EliminateAllExceptMostSpecializedTemplate() {
10972     //   [...] and any given function template specialization F1 is
10973     //   eliminated if the set contains a second function template
10974     //   specialization whose function template is more specialized
10975     //   than the function template of F1 according to the partial
10976     //   ordering rules of 14.5.5.2.
10977 
10978     // The algorithm specified above is quadratic. We instead use a
10979     // two-pass algorithm (similar to the one used to identify the
10980     // best viable function in an overload set) that identifies the
10981     // best function template (if it exists).
10982 
10983     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10984     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10985       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
10986 
10987     // TODO: It looks like FailedCandidates does not serve much purpose
10988     // here, since the no_viable diagnostic has index 0.
10989     UnresolvedSetIterator Result = S.getMostSpecialized(
10990         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
10991         SourceExpr->getLocStart(), S.PDiag(),
10992         S.PDiag(diag::err_addr_ovl_ambiguous)
10993           << Matches[0].second->getDeclName(),
10994         S.PDiag(diag::note_ovl_candidate)
10995           << (unsigned)oc_function_template,
10996         Complain, TargetFunctionType);
10997 
10998     if (Result != MatchesCopy.end()) {
10999       // Make it the first and only element
11000       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11001       Matches[0].second = cast<FunctionDecl>(*Result);
11002       Matches.resize(1);
11003     } else
11004       HasComplained |= Complain;
11005   }
11006 
11007   void EliminateAllTemplateMatches() {
11008     //   [...] any function template specializations in the set are
11009     //   eliminated if the set also contains a non-template function, [...]
11010     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11011       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11012         ++I;
11013       else {
11014         Matches[I] = Matches[--N];
11015         Matches.resize(N);
11016       }
11017     }
11018   }
11019 
11020   void EliminateSuboptimalCudaMatches() {
11021     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11022   }
11023 
11024 public:
11025   void ComplainNoMatchesFound() const {
11026     assert(Matches.empty());
11027     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
11028         << OvlExpr->getName() << TargetFunctionType
11029         << OvlExpr->getSourceRange();
11030     if (FailedCandidates.empty())
11031       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11032                                   /*TakingAddress=*/true);
11033     else {
11034       // We have some deduction failure messages. Use them to diagnose
11035       // the function templates, and diagnose the non-template candidates
11036       // normally.
11037       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11038                                  IEnd = OvlExpr->decls_end();
11039            I != IEnd; ++I)
11040         if (FunctionDecl *Fun =
11041                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11042           if (!functionHasPassObjectSizeParams(Fun))
11043             S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
11044                                     /*TakingAddress=*/true);
11045       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
11046     }
11047   }
11048 
11049   bool IsInvalidFormOfPointerToMemberFunction() const {
11050     return TargetTypeIsNonStaticMemberFunction &&
11051       !OvlExprInfo.HasFormOfMemberPointer;
11052   }
11053 
11054   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11055       // TODO: Should we condition this on whether any functions might
11056       // have matched, or is it more appropriate to do that in callers?
11057       // TODO: a fixit wouldn't hurt.
11058       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11059         << TargetType << OvlExpr->getSourceRange();
11060   }
11061 
11062   bool IsStaticMemberFunctionFromBoundPointer() const {
11063     return StaticMemberFunctionFromBoundPointer;
11064   }
11065 
11066   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11067     S.Diag(OvlExpr->getLocStart(),
11068            diag::err_invalid_form_pointer_member_function)
11069       << OvlExpr->getSourceRange();
11070   }
11071 
11072   void ComplainOfInvalidConversion() const {
11073     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
11074       << OvlExpr->getName() << TargetType;
11075   }
11076 
11077   void ComplainMultipleMatchesFound() const {
11078     assert(Matches.size() > 1);
11079     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
11080       << OvlExpr->getName()
11081       << OvlExpr->getSourceRange();
11082     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11083                                 /*TakingAddress=*/true);
11084   }
11085 
11086   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11087 
11088   int getNumMatches() const { return Matches.size(); }
11089 
11090   FunctionDecl* getMatchingFunctionDecl() const {
11091     if (Matches.size() != 1) return nullptr;
11092     return Matches[0].second;
11093   }
11094 
11095   const DeclAccessPair* getMatchingFunctionAccessPair() const {
11096     if (Matches.size() != 1) return nullptr;
11097     return &Matches[0].first;
11098   }
11099 };
11100 }
11101 
11102 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11103 /// an overloaded function (C++ [over.over]), where @p From is an
11104 /// expression with overloaded function type and @p ToType is the type
11105 /// we're trying to resolve to. For example:
11106 ///
11107 /// @code
11108 /// int f(double);
11109 /// int f(int);
11110 ///
11111 /// int (*pfd)(double) = f; // selects f(double)
11112 /// @endcode
11113 ///
11114 /// This routine returns the resulting FunctionDecl if it could be
11115 /// resolved, and NULL otherwise. When @p Complain is true, this
11116 /// routine will emit diagnostics if there is an error.
11117 FunctionDecl *
11118 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11119                                          QualType TargetType,
11120                                          bool Complain,
11121                                          DeclAccessPair &FoundResult,
11122                                          bool *pHadMultipleCandidates) {
11123   assert(AddressOfExpr->getType() == Context.OverloadTy);
11124 
11125   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11126                                      Complain);
11127   int NumMatches = Resolver.getNumMatches();
11128   FunctionDecl *Fn = nullptr;
11129   bool ShouldComplain = Complain && !Resolver.hasComplained();
11130   if (NumMatches == 0 && ShouldComplain) {
11131     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11132       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11133     else
11134       Resolver.ComplainNoMatchesFound();
11135   }
11136   else if (NumMatches > 1 && ShouldComplain)
11137     Resolver.ComplainMultipleMatchesFound();
11138   else if (NumMatches == 1) {
11139     Fn = Resolver.getMatchingFunctionDecl();
11140     assert(Fn);
11141     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11142       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11143     FoundResult = *Resolver.getMatchingFunctionAccessPair();
11144     if (Complain) {
11145       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11146         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11147       else
11148         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11149     }
11150   }
11151 
11152   if (pHadMultipleCandidates)
11153     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11154   return Fn;
11155 }
11156 
11157 /// \brief Given an expression that refers to an overloaded function, try to
11158 /// resolve that function to a single function that can have its address taken.
11159 /// This will modify `Pair` iff it returns non-null.
11160 ///
11161 /// This routine can only realistically succeed if all but one candidates in the
11162 /// overload set for SrcExpr cannot have their addresses taken.
11163 FunctionDecl *
11164 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11165                                                   DeclAccessPair &Pair) {
11166   OverloadExpr::FindResult R = OverloadExpr::find(E);
11167   OverloadExpr *Ovl = R.Expression;
11168   FunctionDecl *Result = nullptr;
11169   DeclAccessPair DAP;
11170   // Don't use the AddressOfResolver because we're specifically looking for
11171   // cases where we have one overload candidate that lacks
11172   // enable_if/pass_object_size/...
11173   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11174     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11175     if (!FD)
11176       return nullptr;
11177 
11178     if (!checkAddressOfFunctionIsAvailable(FD))
11179       continue;
11180 
11181     // We have more than one result; quit.
11182     if (Result)
11183       return nullptr;
11184     DAP = I.getPair();
11185     Result = FD;
11186   }
11187 
11188   if (Result)
11189     Pair = DAP;
11190   return Result;
11191 }
11192 
11193 /// \brief Given an overloaded function, tries to turn it into a non-overloaded
11194 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11195 /// will perform access checks, diagnose the use of the resultant decl, and, if
11196 /// requested, potentially perform a function-to-pointer decay.
11197 ///
11198 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11199 /// Otherwise, returns true. This may emit diagnostics and return true.
11200 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11201     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
11202   Expr *E = SrcExpr.get();
11203   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11204 
11205   DeclAccessPair DAP;
11206   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11207   if (!Found)
11208     return false;
11209 
11210   // Emitting multiple diagnostics for a function that is both inaccessible and
11211   // unavailable is consistent with our behavior elsewhere. So, always check
11212   // for both.
11213   DiagnoseUseOfDecl(Found, E->getExprLoc());
11214   CheckAddressOfMemberAccess(E, DAP);
11215   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11216   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
11217     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11218   else
11219     SrcExpr = Fixed;
11220   return true;
11221 }
11222 
11223 /// \brief Given an expression that refers to an overloaded function, try to
11224 /// resolve that overloaded function expression down to a single function.
11225 ///
11226 /// This routine can only resolve template-ids that refer to a single function
11227 /// template, where that template-id refers to a single template whose template
11228 /// arguments are either provided by the template-id or have defaults,
11229 /// as described in C++0x [temp.arg.explicit]p3.
11230 ///
11231 /// If no template-ids are found, no diagnostics are emitted and NULL is
11232 /// returned.
11233 FunctionDecl *
11234 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11235                                                   bool Complain,
11236                                                   DeclAccessPair *FoundResult) {
11237   // C++ [over.over]p1:
11238   //   [...] [Note: any redundant set of parentheses surrounding the
11239   //   overloaded function name is ignored (5.1). ]
11240   // C++ [over.over]p1:
11241   //   [...] The overloaded function name can be preceded by the &
11242   //   operator.
11243 
11244   // If we didn't actually find any template-ids, we're done.
11245   if (!ovl->hasExplicitTemplateArgs())
11246     return nullptr;
11247 
11248   TemplateArgumentListInfo ExplicitTemplateArgs;
11249   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11250   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11251 
11252   // Look through all of the overloaded functions, searching for one
11253   // whose type matches exactly.
11254   FunctionDecl *Matched = nullptr;
11255   for (UnresolvedSetIterator I = ovl->decls_begin(),
11256          E = ovl->decls_end(); I != E; ++I) {
11257     // C++0x [temp.arg.explicit]p3:
11258     //   [...] In contexts where deduction is done and fails, or in contexts
11259     //   where deduction is not done, if a template argument list is
11260     //   specified and it, along with any default template arguments,
11261     //   identifies a single function template specialization, then the
11262     //   template-id is an lvalue for the function template specialization.
11263     FunctionTemplateDecl *FunctionTemplate
11264       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11265 
11266     // C++ [over.over]p2:
11267     //   If the name is a function template, template argument deduction is
11268     //   done (14.8.2.2), and if the argument deduction succeeds, the
11269     //   resulting template argument list is used to generate a single
11270     //   function template specialization, which is added to the set of
11271     //   overloaded functions considered.
11272     FunctionDecl *Specialization = nullptr;
11273     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11274     if (TemplateDeductionResult Result
11275           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11276                                     Specialization, Info,
11277                                     /*IsAddressOfFunction*/true)) {
11278       // Make a note of the failed deduction for diagnostics.
11279       // TODO: Actually use the failed-deduction info?
11280       FailedCandidates.addCandidate()
11281           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11282                MakeDeductionFailureInfo(Context, Result, Info));
11283       continue;
11284     }
11285 
11286     assert(Specialization && "no specialization and no error?");
11287 
11288     // Multiple matches; we can't resolve to a single declaration.
11289     if (Matched) {
11290       if (Complain) {
11291         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11292           << ovl->getName();
11293         NoteAllOverloadCandidates(ovl);
11294       }
11295       return nullptr;
11296     }
11297 
11298     Matched = Specialization;
11299     if (FoundResult) *FoundResult = I.getPair();
11300   }
11301 
11302   if (Matched &&
11303       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11304     return nullptr;
11305 
11306   return Matched;
11307 }
11308 
11309 
11310 
11311 
11312 // Resolve and fix an overloaded expression that can be resolved
11313 // because it identifies a single function template specialization.
11314 //
11315 // Last three arguments should only be supplied if Complain = true
11316 //
11317 // Return true if it was logically possible to so resolve the
11318 // expression, regardless of whether or not it succeeded.  Always
11319 // returns true if 'complain' is set.
11320 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11321                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
11322                       bool complain, SourceRange OpRangeForComplaining,
11323                                            QualType DestTypeForComplaining,
11324                                             unsigned DiagIDForComplaining) {
11325   assert(SrcExpr.get()->getType() == Context.OverloadTy);
11326 
11327   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11328 
11329   DeclAccessPair found;
11330   ExprResult SingleFunctionExpression;
11331   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11332                            ovl.Expression, /*complain*/ false, &found)) {
11333     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
11334       SrcExpr = ExprError();
11335       return true;
11336     }
11337 
11338     // It is only correct to resolve to an instance method if we're
11339     // resolving a form that's permitted to be a pointer to member.
11340     // Otherwise we'll end up making a bound member expression, which
11341     // is illegal in all the contexts we resolve like this.
11342     if (!ovl.HasFormOfMemberPointer &&
11343         isa<CXXMethodDecl>(fn) &&
11344         cast<CXXMethodDecl>(fn)->isInstance()) {
11345       if (!complain) return false;
11346 
11347       Diag(ovl.Expression->getExprLoc(),
11348            diag::err_bound_member_function)
11349         << 0 << ovl.Expression->getSourceRange();
11350 
11351       // TODO: I believe we only end up here if there's a mix of
11352       // static and non-static candidates (otherwise the expression
11353       // would have 'bound member' type, not 'overload' type).
11354       // Ideally we would note which candidate was chosen and why
11355       // the static candidates were rejected.
11356       SrcExpr = ExprError();
11357       return true;
11358     }
11359 
11360     // Fix the expression to refer to 'fn'.
11361     SingleFunctionExpression =
11362         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11363 
11364     // If desired, do function-to-pointer decay.
11365     if (doFunctionPointerConverion) {
11366       SingleFunctionExpression =
11367         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11368       if (SingleFunctionExpression.isInvalid()) {
11369         SrcExpr = ExprError();
11370         return true;
11371       }
11372     }
11373   }
11374 
11375   if (!SingleFunctionExpression.isUsable()) {
11376     if (complain) {
11377       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11378         << ovl.Expression->getName()
11379         << DestTypeForComplaining
11380         << OpRangeForComplaining
11381         << ovl.Expression->getQualifierLoc().getSourceRange();
11382       NoteAllOverloadCandidates(SrcExpr.get());
11383 
11384       SrcExpr = ExprError();
11385       return true;
11386     }
11387 
11388     return false;
11389   }
11390 
11391   SrcExpr = SingleFunctionExpression;
11392   return true;
11393 }
11394 
11395 /// \brief Add a single candidate to the overload set.
11396 static void AddOverloadedCallCandidate(Sema &S,
11397                                        DeclAccessPair FoundDecl,
11398                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
11399                                        ArrayRef<Expr *> Args,
11400                                        OverloadCandidateSet &CandidateSet,
11401                                        bool PartialOverloading,
11402                                        bool KnownValid) {
11403   NamedDecl *Callee = FoundDecl.getDecl();
11404   if (isa<UsingShadowDecl>(Callee))
11405     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11406 
11407   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11408     if (ExplicitTemplateArgs) {
11409       assert(!KnownValid && "Explicit template arguments?");
11410       return;
11411     }
11412     // Prevent ill-formed function decls to be added as overload candidates.
11413     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11414       return;
11415 
11416     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11417                            /*SuppressUsedConversions=*/false,
11418                            PartialOverloading);
11419     return;
11420   }
11421 
11422   if (FunctionTemplateDecl *FuncTemplate
11423       = dyn_cast<FunctionTemplateDecl>(Callee)) {
11424     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11425                                    ExplicitTemplateArgs, Args, CandidateSet,
11426                                    /*SuppressUsedConversions=*/false,
11427                                    PartialOverloading);
11428     return;
11429   }
11430 
11431   assert(!KnownValid && "unhandled case in overloaded call candidate");
11432 }
11433 
11434 /// \brief Add the overload candidates named by callee and/or found by argument
11435 /// dependent lookup to the given overload set.
11436 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11437                                        ArrayRef<Expr *> Args,
11438                                        OverloadCandidateSet &CandidateSet,
11439                                        bool PartialOverloading) {
11440 
11441 #ifndef NDEBUG
11442   // Verify that ArgumentDependentLookup is consistent with the rules
11443   // in C++0x [basic.lookup.argdep]p3:
11444   //
11445   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11446   //   and let Y be the lookup set produced by argument dependent
11447   //   lookup (defined as follows). If X contains
11448   //
11449   //     -- a declaration of a class member, or
11450   //
11451   //     -- a block-scope function declaration that is not a
11452   //        using-declaration, or
11453   //
11454   //     -- a declaration that is neither a function or a function
11455   //        template
11456   //
11457   //   then Y is empty.
11458 
11459   if (ULE->requiresADL()) {
11460     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11461            E = ULE->decls_end(); I != E; ++I) {
11462       assert(!(*I)->getDeclContext()->isRecord());
11463       assert(isa<UsingShadowDecl>(*I) ||
11464              !(*I)->getDeclContext()->isFunctionOrMethod());
11465       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11466     }
11467   }
11468 #endif
11469 
11470   // It would be nice to avoid this copy.
11471   TemplateArgumentListInfo TABuffer;
11472   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11473   if (ULE->hasExplicitTemplateArgs()) {
11474     ULE->copyTemplateArgumentsInto(TABuffer);
11475     ExplicitTemplateArgs = &TABuffer;
11476   }
11477 
11478   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11479          E = ULE->decls_end(); I != E; ++I)
11480     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11481                                CandidateSet, PartialOverloading,
11482                                /*KnownValid*/ true);
11483 
11484   if (ULE->requiresADL())
11485     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11486                                          Args, ExplicitTemplateArgs,
11487                                          CandidateSet, PartialOverloading);
11488 }
11489 
11490 /// Determine whether a declaration with the specified name could be moved into
11491 /// a different namespace.
11492 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11493   switch (Name.getCXXOverloadedOperator()) {
11494   case OO_New: case OO_Array_New:
11495   case OO_Delete: case OO_Array_Delete:
11496     return false;
11497 
11498   default:
11499     return true;
11500   }
11501 }
11502 
11503 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11504 /// template, where the non-dependent name was declared after the template
11505 /// was defined. This is common in code written for a compilers which do not
11506 /// correctly implement two-stage name lookup.
11507 ///
11508 /// Returns true if a viable candidate was found and a diagnostic was issued.
11509 static bool
11510 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11511                        const CXXScopeSpec &SS, LookupResult &R,
11512                        OverloadCandidateSet::CandidateSetKind CSK,
11513                        TemplateArgumentListInfo *ExplicitTemplateArgs,
11514                        ArrayRef<Expr *> Args,
11515                        bool *DoDiagnoseEmptyLookup = nullptr) {
11516   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
11517     return false;
11518 
11519   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11520     if (DC->isTransparentContext())
11521       continue;
11522 
11523     SemaRef.LookupQualifiedName(R, DC);
11524 
11525     if (!R.empty()) {
11526       R.suppressDiagnostics();
11527 
11528       if (isa<CXXRecordDecl>(DC)) {
11529         // Don't diagnose names we find in classes; we get much better
11530         // diagnostics for these from DiagnoseEmptyLookup.
11531         R.clear();
11532         if (DoDiagnoseEmptyLookup)
11533           *DoDiagnoseEmptyLookup = true;
11534         return false;
11535       }
11536 
11537       OverloadCandidateSet Candidates(FnLoc, CSK);
11538       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11539         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11540                                    ExplicitTemplateArgs, Args,
11541                                    Candidates, false, /*KnownValid*/ false);
11542 
11543       OverloadCandidateSet::iterator Best;
11544       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11545         // No viable functions. Don't bother the user with notes for functions
11546         // which don't work and shouldn't be found anyway.
11547         R.clear();
11548         return false;
11549       }
11550 
11551       // Find the namespaces where ADL would have looked, and suggest
11552       // declaring the function there instead.
11553       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11554       Sema::AssociatedClassSet AssociatedClasses;
11555       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11556                                                  AssociatedNamespaces,
11557                                                  AssociatedClasses);
11558       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11559       if (canBeDeclaredInNamespace(R.getLookupName())) {
11560         DeclContext *Std = SemaRef.getStdNamespace();
11561         for (Sema::AssociatedNamespaceSet::iterator
11562                it = AssociatedNamespaces.begin(),
11563                end = AssociatedNamespaces.end(); it != end; ++it) {
11564           // Never suggest declaring a function within namespace 'std'.
11565           if (Std && Std->Encloses(*it))
11566             continue;
11567 
11568           // Never suggest declaring a function within a namespace with a
11569           // reserved name, like __gnu_cxx.
11570           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11571           if (NS &&
11572               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11573             continue;
11574 
11575           SuggestedNamespaces.insert(*it);
11576         }
11577       }
11578 
11579       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11580         << R.getLookupName();
11581       if (SuggestedNamespaces.empty()) {
11582         SemaRef.Diag(Best->Function->getLocation(),
11583                      diag::note_not_found_by_two_phase_lookup)
11584           << R.getLookupName() << 0;
11585       } else if (SuggestedNamespaces.size() == 1) {
11586         SemaRef.Diag(Best->Function->getLocation(),
11587                      diag::note_not_found_by_two_phase_lookup)
11588           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11589       } else {
11590         // FIXME: It would be useful to list the associated namespaces here,
11591         // but the diagnostics infrastructure doesn't provide a way to produce
11592         // a localized representation of a list of items.
11593         SemaRef.Diag(Best->Function->getLocation(),
11594                      diag::note_not_found_by_two_phase_lookup)
11595           << R.getLookupName() << 2;
11596       }
11597 
11598       // Try to recover by calling this function.
11599       return true;
11600     }
11601 
11602     R.clear();
11603   }
11604 
11605   return false;
11606 }
11607 
11608 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11609 /// template, where the non-dependent operator was declared after the template
11610 /// was defined.
11611 ///
11612 /// Returns true if a viable candidate was found and a diagnostic was issued.
11613 static bool
11614 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11615                                SourceLocation OpLoc,
11616                                ArrayRef<Expr *> Args) {
11617   DeclarationName OpName =
11618     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11619   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11620   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11621                                 OverloadCandidateSet::CSK_Operator,
11622                                 /*ExplicitTemplateArgs=*/nullptr, Args);
11623 }
11624 
11625 namespace {
11626 class BuildRecoveryCallExprRAII {
11627   Sema &SemaRef;
11628 public:
11629   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11630     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11631     SemaRef.IsBuildingRecoveryCallExpr = true;
11632   }
11633 
11634   ~BuildRecoveryCallExprRAII() {
11635     SemaRef.IsBuildingRecoveryCallExpr = false;
11636   }
11637 };
11638 
11639 }
11640 
11641 static std::unique_ptr<CorrectionCandidateCallback>
11642 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11643               bool HasTemplateArgs, bool AllowTypoCorrection) {
11644   if (!AllowTypoCorrection)
11645     return llvm::make_unique<NoTypoCorrectionCCC>();
11646   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11647                                                   HasTemplateArgs, ME);
11648 }
11649 
11650 /// Attempts to recover from a call where no functions were found.
11651 ///
11652 /// Returns true if new candidates were found.
11653 static ExprResult
11654 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11655                       UnresolvedLookupExpr *ULE,
11656                       SourceLocation LParenLoc,
11657                       MutableArrayRef<Expr *> Args,
11658                       SourceLocation RParenLoc,
11659                       bool EmptyLookup, bool AllowTypoCorrection) {
11660   // Do not try to recover if it is already building a recovery call.
11661   // This stops infinite loops for template instantiations like
11662   //
11663   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11664   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11665   //
11666   if (SemaRef.IsBuildingRecoveryCallExpr)
11667     return ExprError();
11668   BuildRecoveryCallExprRAII RCE(SemaRef);
11669 
11670   CXXScopeSpec SS;
11671   SS.Adopt(ULE->getQualifierLoc());
11672   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11673 
11674   TemplateArgumentListInfo TABuffer;
11675   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11676   if (ULE->hasExplicitTemplateArgs()) {
11677     ULE->copyTemplateArgumentsInto(TABuffer);
11678     ExplicitTemplateArgs = &TABuffer;
11679   }
11680 
11681   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11682                  Sema::LookupOrdinaryName);
11683   bool DoDiagnoseEmptyLookup = EmptyLookup;
11684   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11685                               OverloadCandidateSet::CSK_Normal,
11686                               ExplicitTemplateArgs, Args,
11687                               &DoDiagnoseEmptyLookup) &&
11688     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11689         S, SS, R,
11690         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11691                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11692         ExplicitTemplateArgs, Args)))
11693     return ExprError();
11694 
11695   assert(!R.empty() && "lookup results empty despite recovery");
11696 
11697   // If recovery created an ambiguity, just bail out.
11698   if (R.isAmbiguous()) {
11699     R.suppressDiagnostics();
11700     return ExprError();
11701   }
11702 
11703   // Build an implicit member call if appropriate.  Just drop the
11704   // casts and such from the call, we don't really care.
11705   ExprResult NewFn = ExprError();
11706   if ((*R.begin())->isCXXClassMember())
11707     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11708                                                     ExplicitTemplateArgs, S);
11709   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11710     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11711                                         ExplicitTemplateArgs);
11712   else
11713     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11714 
11715   if (NewFn.isInvalid())
11716     return ExprError();
11717 
11718   // This shouldn't cause an infinite loop because we're giving it
11719   // an expression with viable lookup results, which should never
11720   // end up here.
11721   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11722                                MultiExprArg(Args.data(), Args.size()),
11723                                RParenLoc);
11724 }
11725 
11726 /// \brief Constructs and populates an OverloadedCandidateSet from
11727 /// the given function.
11728 /// \returns true when an the ExprResult output parameter has been set.
11729 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11730                                   UnresolvedLookupExpr *ULE,
11731                                   MultiExprArg Args,
11732                                   SourceLocation RParenLoc,
11733                                   OverloadCandidateSet *CandidateSet,
11734                                   ExprResult *Result) {
11735 #ifndef NDEBUG
11736   if (ULE->requiresADL()) {
11737     // To do ADL, we must have found an unqualified name.
11738     assert(!ULE->getQualifier() && "qualified name with ADL");
11739 
11740     // We don't perform ADL for implicit declarations of builtins.
11741     // Verify that this was correctly set up.
11742     FunctionDecl *F;
11743     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11744         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11745         F->getBuiltinID() && F->isImplicit())
11746       llvm_unreachable("performing ADL for builtin");
11747 
11748     // We don't perform ADL in C.
11749     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11750   }
11751 #endif
11752 
11753   UnbridgedCastsSet UnbridgedCasts;
11754   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11755     *Result = ExprError();
11756     return true;
11757   }
11758 
11759   // Add the functions denoted by the callee to the set of candidate
11760   // functions, including those from argument-dependent lookup.
11761   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11762 
11763   if (getLangOpts().MSVCCompat &&
11764       CurContext->isDependentContext() && !isSFINAEContext() &&
11765       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11766 
11767     OverloadCandidateSet::iterator Best;
11768     if (CandidateSet->empty() ||
11769         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11770             OR_No_Viable_Function) {
11771       // In Microsoft mode, if we are inside a template class member function then
11772       // create a type dependent CallExpr. The goal is to postpone name lookup
11773       // to instantiation time to be able to search into type dependent base
11774       // classes.
11775       CallExpr *CE = new (Context) CallExpr(
11776           Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11777       CE->setTypeDependent(true);
11778       CE->setValueDependent(true);
11779       CE->setInstantiationDependent(true);
11780       *Result = CE;
11781       return true;
11782     }
11783   }
11784 
11785   if (CandidateSet->empty())
11786     return false;
11787 
11788   UnbridgedCasts.restore();
11789   return false;
11790 }
11791 
11792 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11793 /// the completed call expression. If overload resolution fails, emits
11794 /// diagnostics and returns ExprError()
11795 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11796                                            UnresolvedLookupExpr *ULE,
11797                                            SourceLocation LParenLoc,
11798                                            MultiExprArg Args,
11799                                            SourceLocation RParenLoc,
11800                                            Expr *ExecConfig,
11801                                            OverloadCandidateSet *CandidateSet,
11802                                            OverloadCandidateSet::iterator *Best,
11803                                            OverloadingResult OverloadResult,
11804                                            bool AllowTypoCorrection) {
11805   if (CandidateSet->empty())
11806     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
11807                                  RParenLoc, /*EmptyLookup=*/true,
11808                                  AllowTypoCorrection);
11809 
11810   switch (OverloadResult) {
11811   case OR_Success: {
11812     FunctionDecl *FDecl = (*Best)->Function;
11813     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
11814     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11815       return ExprError();
11816     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11817     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11818                                          ExecConfig);
11819   }
11820 
11821   case OR_No_Viable_Function: {
11822     // Try to recover by looking for viable functions which the user might
11823     // have meant to call.
11824     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
11825                                                 Args, RParenLoc,
11826                                                 /*EmptyLookup=*/false,
11827                                                 AllowTypoCorrection);
11828     if (!Recovery.isInvalid())
11829       return Recovery;
11830 
11831     // If the user passes in a function that we can't take the address of, we
11832     // generally end up emitting really bad error messages. Here, we attempt to
11833     // emit better ones.
11834     for (const Expr *Arg : Args) {
11835       if (!Arg->getType()->isFunctionType())
11836         continue;
11837       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11838         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11839         if (FD &&
11840             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11841                                                        Arg->getExprLoc()))
11842           return ExprError();
11843       }
11844     }
11845 
11846     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11847         << ULE->getName() << Fn->getSourceRange();
11848     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11849     break;
11850   }
11851 
11852   case OR_Ambiguous:
11853     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
11854       << ULE->getName() << Fn->getSourceRange();
11855     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
11856     break;
11857 
11858   case OR_Deleted: {
11859     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11860       << (*Best)->Function->isDeleted()
11861       << ULE->getName()
11862       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11863       << Fn->getSourceRange();
11864     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11865 
11866     // We emitted an error for the unvailable/deleted function call but keep
11867     // the call in the AST.
11868     FunctionDecl *FDecl = (*Best)->Function;
11869     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11870     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11871                                          ExecConfig);
11872   }
11873   }
11874 
11875   // Overload resolution failed.
11876   return ExprError();
11877 }
11878 
11879 static void markUnaddressableCandidatesUnviable(Sema &S,
11880                                                 OverloadCandidateSet &CS) {
11881   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11882     if (I->Viable &&
11883         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11884       I->Viable = false;
11885       I->FailureKind = ovl_fail_addr_not_available;
11886     }
11887   }
11888 }
11889 
11890 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
11891 /// (which eventually refers to the declaration Func) and the call
11892 /// arguments Args/NumArgs, attempt to resolve the function call down
11893 /// to a specific function. If overload resolution succeeds, returns
11894 /// the call expression produced by overload resolution.
11895 /// Otherwise, emits diagnostics and returns ExprError.
11896 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11897                                          UnresolvedLookupExpr *ULE,
11898                                          SourceLocation LParenLoc,
11899                                          MultiExprArg Args,
11900                                          SourceLocation RParenLoc,
11901                                          Expr *ExecConfig,
11902                                          bool AllowTypoCorrection,
11903                                          bool CalleesAddressIsTaken) {
11904   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11905                                     OverloadCandidateSet::CSK_Normal);
11906   ExprResult result;
11907 
11908   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11909                              &result))
11910     return result;
11911 
11912   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11913   // functions that aren't addressible are considered unviable.
11914   if (CalleesAddressIsTaken)
11915     markUnaddressableCandidatesUnviable(*this, CandidateSet);
11916 
11917   OverloadCandidateSet::iterator Best;
11918   OverloadingResult OverloadResult =
11919       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11920 
11921   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
11922                                   RParenLoc, ExecConfig, &CandidateSet,
11923                                   &Best, OverloadResult,
11924                                   AllowTypoCorrection);
11925 }
11926 
11927 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
11928   return Functions.size() > 1 ||
11929     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11930 }
11931 
11932 /// \brief Create a unary operation that may resolve to an overloaded
11933 /// operator.
11934 ///
11935 /// \param OpLoc The location of the operator itself (e.g., '*').
11936 ///
11937 /// \param Opc The UnaryOperatorKind that describes this operator.
11938 ///
11939 /// \param Fns The set of non-member functions that will be
11940 /// considered by overload resolution. The caller needs to build this
11941 /// set based on the context using, e.g.,
11942 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11943 /// set should not contain any member functions; those will be added
11944 /// by CreateOverloadedUnaryOp().
11945 ///
11946 /// \param Input The input argument.
11947 ExprResult
11948 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
11949                               const UnresolvedSetImpl &Fns,
11950                               Expr *Input, bool PerformADL) {
11951   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11952   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11953   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11954   // TODO: provide better source location info.
11955   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11956 
11957   if (checkPlaceholderForOverload(*this, Input))
11958     return ExprError();
11959 
11960   Expr *Args[2] = { Input, nullptr };
11961   unsigned NumArgs = 1;
11962 
11963   // For post-increment and post-decrement, add the implicit '0' as
11964   // the second argument, so that we know this is a post-increment or
11965   // post-decrement.
11966   if (Opc == UO_PostInc || Opc == UO_PostDec) {
11967     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
11968     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11969                                      SourceLocation());
11970     NumArgs = 2;
11971   }
11972 
11973   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11974 
11975   if (Input->isTypeDependent()) {
11976     if (Fns.empty())
11977       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11978                                          VK_RValue, OK_Ordinary, OpLoc);
11979 
11980     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11981     UnresolvedLookupExpr *Fn
11982       = UnresolvedLookupExpr::Create(Context, NamingClass,
11983                                      NestedNameSpecifierLoc(), OpNameInfo,
11984                                      /*ADL*/ true, IsOverloaded(Fns),
11985                                      Fns.begin(), Fns.end());
11986     return new (Context)
11987         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11988                             VK_RValue, OpLoc, FPOptions());
11989   }
11990 
11991   // Build an empty overload set.
11992   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11993 
11994   // Add the candidates from the given function set.
11995   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
11996 
11997   // Add operator candidates that are member functions.
11998   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11999 
12000   // Add candidates from ADL.
12001   if (PerformADL) {
12002     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12003                                          /*ExplicitTemplateArgs*/nullptr,
12004                                          CandidateSet);
12005   }
12006 
12007   // Add builtin operator candidates.
12008   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12009 
12010   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12011 
12012   // Perform overload resolution.
12013   OverloadCandidateSet::iterator Best;
12014   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12015   case OR_Success: {
12016     // We found a built-in operator or an overloaded operator.
12017     FunctionDecl *FnDecl = Best->Function;
12018 
12019     if (FnDecl) {
12020       Expr *Base = nullptr;
12021       // We matched an overloaded operator. Build a call to that
12022       // operator.
12023 
12024       // Convert the arguments.
12025       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12026         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12027 
12028         ExprResult InputRes =
12029           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12030                                               Best->FoundDecl, Method);
12031         if (InputRes.isInvalid())
12032           return ExprError();
12033         Base = Input = InputRes.get();
12034       } else {
12035         // Convert the arguments.
12036         ExprResult InputInit
12037           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12038                                                       Context,
12039                                                       FnDecl->getParamDecl(0)),
12040                                       SourceLocation(),
12041                                       Input);
12042         if (InputInit.isInvalid())
12043           return ExprError();
12044         Input = InputInit.get();
12045       }
12046 
12047       // Build the actual expression node.
12048       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12049                                                 Base, HadMultipleCandidates,
12050                                                 OpLoc);
12051       if (FnExpr.isInvalid())
12052         return ExprError();
12053 
12054       // Determine the result type.
12055       QualType ResultTy = FnDecl->getReturnType();
12056       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12057       ResultTy = ResultTy.getNonLValueExprType(Context);
12058 
12059       Args[0] = Input;
12060       CallExpr *TheCall =
12061         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
12062                                           ResultTy, VK, OpLoc, FPOptions());
12063 
12064       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12065         return ExprError();
12066 
12067       if (CheckFunctionCall(FnDecl, TheCall,
12068                             FnDecl->getType()->castAs<FunctionProtoType>()))
12069         return ExprError();
12070 
12071       return MaybeBindToTemporary(TheCall);
12072     } else {
12073       // We matched a built-in operator. Convert the arguments, then
12074       // break out so that we will build the appropriate built-in
12075       // operator node.
12076       ExprResult InputRes = PerformImplicitConversion(
12077           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing);
12078       if (InputRes.isInvalid())
12079         return ExprError();
12080       Input = InputRes.get();
12081       break;
12082     }
12083   }
12084 
12085   case OR_No_Viable_Function:
12086     // This is an erroneous use of an operator which can be overloaded by
12087     // a non-member function. Check for non-member operators which were
12088     // defined too late to be candidates.
12089     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12090       // FIXME: Recover by calling the found function.
12091       return ExprError();
12092 
12093     // No viable function; fall through to handling this as a
12094     // built-in operator, which will produce an error message for us.
12095     break;
12096 
12097   case OR_Ambiguous:
12098     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12099         << UnaryOperator::getOpcodeStr(Opc)
12100         << Input->getType()
12101         << Input->getSourceRange();
12102     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
12103                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12104     return ExprError();
12105 
12106   case OR_Deleted:
12107     Diag(OpLoc, diag::err_ovl_deleted_oper)
12108       << Best->Function->isDeleted()
12109       << UnaryOperator::getOpcodeStr(Opc)
12110       << getDeletedOrUnavailableSuffix(Best->Function)
12111       << Input->getSourceRange();
12112     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
12113                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12114     return ExprError();
12115   }
12116 
12117   // Either we found no viable overloaded operator or we matched a
12118   // built-in operator. In either case, fall through to trying to
12119   // build a built-in operation.
12120   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12121 }
12122 
12123 /// \brief Create a binary operation that may resolve to an overloaded
12124 /// operator.
12125 ///
12126 /// \param OpLoc The location of the operator itself (e.g., '+').
12127 ///
12128 /// \param Opc The BinaryOperatorKind that describes this operator.
12129 ///
12130 /// \param Fns The set of non-member functions that will be
12131 /// considered by overload resolution. The caller needs to build this
12132 /// set based on the context using, e.g.,
12133 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12134 /// set should not contain any member functions; those will be added
12135 /// by CreateOverloadedBinOp().
12136 ///
12137 /// \param LHS Left-hand argument.
12138 /// \param RHS Right-hand argument.
12139 ExprResult
12140 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12141                             BinaryOperatorKind Opc,
12142                             const UnresolvedSetImpl &Fns,
12143                             Expr *LHS, Expr *RHS, bool PerformADL) {
12144   Expr *Args[2] = { LHS, RHS };
12145   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12146 
12147   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12148   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12149 
12150   // If either side is type-dependent, create an appropriate dependent
12151   // expression.
12152   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12153     if (Fns.empty()) {
12154       // If there are no functions to store, just build a dependent
12155       // BinaryOperator or CompoundAssignment.
12156       if (Opc <= BO_Assign || Opc > BO_OrAssign)
12157         return new (Context) BinaryOperator(
12158             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12159             OpLoc, FPFeatures);
12160 
12161       return new (Context) CompoundAssignOperator(
12162           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12163           Context.DependentTy, Context.DependentTy, OpLoc,
12164           FPFeatures);
12165     }
12166 
12167     // FIXME: save results of ADL from here?
12168     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12169     // TODO: provide better source location info in DNLoc component.
12170     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12171     UnresolvedLookupExpr *Fn
12172       = UnresolvedLookupExpr::Create(Context, NamingClass,
12173                                      NestedNameSpecifierLoc(), OpNameInfo,
12174                                      /*ADL*/PerformADL, IsOverloaded(Fns),
12175                                      Fns.begin(), Fns.end());
12176     return new (Context)
12177         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
12178                             VK_RValue, OpLoc, FPFeatures);
12179   }
12180 
12181   // Always do placeholder-like conversions on the RHS.
12182   if (checkPlaceholderForOverload(*this, Args[1]))
12183     return ExprError();
12184 
12185   // Do placeholder-like conversion on the LHS; note that we should
12186   // not get here with a PseudoObject LHS.
12187   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12188   if (checkPlaceholderForOverload(*this, Args[0]))
12189     return ExprError();
12190 
12191   // If this is the assignment operator, we only perform overload resolution
12192   // if the left-hand side is a class or enumeration type. This is actually
12193   // a hack. The standard requires that we do overload resolution between the
12194   // various built-in candidates, but as DR507 points out, this can lead to
12195   // problems. So we do it this way, which pretty much follows what GCC does.
12196   // Note that we go the traditional code path for compound assignment forms.
12197   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12198     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12199 
12200   // If this is the .* operator, which is not overloadable, just
12201   // create a built-in binary operator.
12202   if (Opc == BO_PtrMemD)
12203     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12204 
12205   // Build an empty overload set.
12206   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12207 
12208   // Add the candidates from the given function set.
12209   AddFunctionCandidates(Fns, Args, CandidateSet);
12210 
12211   // Add operator candidates that are member functions.
12212   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12213 
12214   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12215   // performed for an assignment operator (nor for operator[] nor operator->,
12216   // which don't get here).
12217   if (Opc != BO_Assign && PerformADL)
12218     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12219                                          /*ExplicitTemplateArgs*/ nullptr,
12220                                          CandidateSet);
12221 
12222   // Add builtin operator candidates.
12223   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12224 
12225   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12226 
12227   // Perform overload resolution.
12228   OverloadCandidateSet::iterator Best;
12229   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12230     case OR_Success: {
12231       // We found a built-in operator or an overloaded operator.
12232       FunctionDecl *FnDecl = Best->Function;
12233 
12234       if (FnDecl) {
12235         Expr *Base = nullptr;
12236         // We matched an overloaded operator. Build a call to that
12237         // operator.
12238 
12239         // Convert the arguments.
12240         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12241           // Best->Access is only meaningful for class members.
12242           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12243 
12244           ExprResult Arg1 =
12245             PerformCopyInitialization(
12246               InitializedEntity::InitializeParameter(Context,
12247                                                      FnDecl->getParamDecl(0)),
12248               SourceLocation(), Args[1]);
12249           if (Arg1.isInvalid())
12250             return ExprError();
12251 
12252           ExprResult Arg0 =
12253             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12254                                                 Best->FoundDecl, Method);
12255           if (Arg0.isInvalid())
12256             return ExprError();
12257           Base = Args[0] = Arg0.getAs<Expr>();
12258           Args[1] = RHS = Arg1.getAs<Expr>();
12259         } else {
12260           // Convert the arguments.
12261           ExprResult Arg0 = PerformCopyInitialization(
12262             InitializedEntity::InitializeParameter(Context,
12263                                                    FnDecl->getParamDecl(0)),
12264             SourceLocation(), Args[0]);
12265           if (Arg0.isInvalid())
12266             return ExprError();
12267 
12268           ExprResult Arg1 =
12269             PerformCopyInitialization(
12270               InitializedEntity::InitializeParameter(Context,
12271                                                      FnDecl->getParamDecl(1)),
12272               SourceLocation(), Args[1]);
12273           if (Arg1.isInvalid())
12274             return ExprError();
12275           Args[0] = LHS = Arg0.getAs<Expr>();
12276           Args[1] = RHS = Arg1.getAs<Expr>();
12277         }
12278 
12279         // Build the actual expression node.
12280         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12281                                                   Best->FoundDecl, Base,
12282                                                   HadMultipleCandidates, OpLoc);
12283         if (FnExpr.isInvalid())
12284           return ExprError();
12285 
12286         // Determine the result type.
12287         QualType ResultTy = FnDecl->getReturnType();
12288         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12289         ResultTy = ResultTy.getNonLValueExprType(Context);
12290 
12291         CXXOperatorCallExpr *TheCall =
12292           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
12293                                             Args, ResultTy, VK, OpLoc,
12294                                             FPFeatures);
12295 
12296         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12297                                 FnDecl))
12298           return ExprError();
12299 
12300         ArrayRef<const Expr *> ArgsArray(Args, 2);
12301         const Expr *ImplicitThis = nullptr;
12302         // Cut off the implicit 'this'.
12303         if (isa<CXXMethodDecl>(FnDecl)) {
12304           ImplicitThis = ArgsArray[0];
12305           ArgsArray = ArgsArray.slice(1);
12306         }
12307 
12308         // Check for a self move.
12309         if (Op == OO_Equal)
12310           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12311 
12312         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12313                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12314                   VariadicDoesNotApply);
12315 
12316         return MaybeBindToTemporary(TheCall);
12317       } else {
12318         // We matched a built-in operator. Convert the arguments, then
12319         // break out so that we will build the appropriate built-in
12320         // operator node.
12321         ExprResult ArgsRes0 =
12322             PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12323                                       Best->Conversions[0], AA_Passing);
12324         if (ArgsRes0.isInvalid())
12325           return ExprError();
12326         Args[0] = ArgsRes0.get();
12327 
12328         ExprResult ArgsRes1 =
12329             PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12330                                       Best->Conversions[1], AA_Passing);
12331         if (ArgsRes1.isInvalid())
12332           return ExprError();
12333         Args[1] = ArgsRes1.get();
12334         break;
12335       }
12336     }
12337 
12338     case OR_No_Viable_Function: {
12339       // C++ [over.match.oper]p9:
12340       //   If the operator is the operator , [...] and there are no
12341       //   viable functions, then the operator is assumed to be the
12342       //   built-in operator and interpreted according to clause 5.
12343       if (Opc == BO_Comma)
12344         break;
12345 
12346       // For class as left operand for assignment or compound assigment
12347       // operator do not fall through to handling in built-in, but report that
12348       // no overloaded assignment operator found
12349       ExprResult Result = ExprError();
12350       if (Args[0]->getType()->isRecordType() &&
12351           Opc >= BO_Assign && Opc <= BO_OrAssign) {
12352         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
12353              << BinaryOperator::getOpcodeStr(Opc)
12354              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12355         if (Args[0]->getType()->isIncompleteType()) {
12356           Diag(OpLoc, diag::note_assign_lhs_incomplete)
12357             << Args[0]->getType()
12358             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12359         }
12360       } else {
12361         // This is an erroneous use of an operator which can be overloaded by
12362         // a non-member function. Check for non-member operators which were
12363         // defined too late to be candidates.
12364         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12365           // FIXME: Recover by calling the found function.
12366           return ExprError();
12367 
12368         // No viable function; try to create a built-in operation, which will
12369         // produce an error. Then, show the non-viable candidates.
12370         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12371       }
12372       assert(Result.isInvalid() &&
12373              "C++ binary operator overloading is missing candidates!");
12374       if (Result.isInvalid())
12375         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12376                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
12377       return Result;
12378     }
12379 
12380     case OR_Ambiguous:
12381       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
12382           << BinaryOperator::getOpcodeStr(Opc)
12383           << Args[0]->getType() << Args[1]->getType()
12384           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12385       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12386                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12387       return ExprError();
12388 
12389     case OR_Deleted:
12390       if (isImplicitlyDeleted(Best->Function)) {
12391         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12392         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12393           << Context.getRecordType(Method->getParent())
12394           << getSpecialMember(Method);
12395 
12396         // The user probably meant to call this special member. Just
12397         // explain why it's deleted.
12398         NoteDeletedFunction(Method);
12399         return ExprError();
12400       } else {
12401         Diag(OpLoc, diag::err_ovl_deleted_oper)
12402           << Best->Function->isDeleted()
12403           << BinaryOperator::getOpcodeStr(Opc)
12404           << getDeletedOrUnavailableSuffix(Best->Function)
12405           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12406       }
12407       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12408                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12409       return ExprError();
12410   }
12411 
12412   // We matched a built-in operator; build it.
12413   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12414 }
12415 
12416 ExprResult
12417 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12418                                          SourceLocation RLoc,
12419                                          Expr *Base, Expr *Idx) {
12420   Expr *Args[2] = { Base, Idx };
12421   DeclarationName OpName =
12422       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12423 
12424   // If either side is type-dependent, create an appropriate dependent
12425   // expression.
12426   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12427 
12428     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12429     // CHECKME: no 'operator' keyword?
12430     DeclarationNameInfo OpNameInfo(OpName, LLoc);
12431     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12432     UnresolvedLookupExpr *Fn
12433       = UnresolvedLookupExpr::Create(Context, NamingClass,
12434                                      NestedNameSpecifierLoc(), OpNameInfo,
12435                                      /*ADL*/ true, /*Overloaded*/ false,
12436                                      UnresolvedSetIterator(),
12437                                      UnresolvedSetIterator());
12438     // Can't add any actual overloads yet
12439 
12440     return new (Context)
12441         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12442                             Context.DependentTy, VK_RValue, RLoc, FPOptions());
12443   }
12444 
12445   // Handle placeholders on both operands.
12446   if (checkPlaceholderForOverload(*this, Args[0]))
12447     return ExprError();
12448   if (checkPlaceholderForOverload(*this, Args[1]))
12449     return ExprError();
12450 
12451   // Build an empty overload set.
12452   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12453 
12454   // Subscript can only be overloaded as a member function.
12455 
12456   // Add operator candidates that are member functions.
12457   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12458 
12459   // Add builtin operator candidates.
12460   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12461 
12462   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12463 
12464   // Perform overload resolution.
12465   OverloadCandidateSet::iterator Best;
12466   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12467     case OR_Success: {
12468       // We found a built-in operator or an overloaded operator.
12469       FunctionDecl *FnDecl = Best->Function;
12470 
12471       if (FnDecl) {
12472         // We matched an overloaded operator. Build a call to that
12473         // operator.
12474 
12475         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12476 
12477         // Convert the arguments.
12478         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12479         ExprResult Arg0 =
12480           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12481                                               Best->FoundDecl, Method);
12482         if (Arg0.isInvalid())
12483           return ExprError();
12484         Args[0] = Arg0.get();
12485 
12486         // Convert the arguments.
12487         ExprResult InputInit
12488           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12489                                                       Context,
12490                                                       FnDecl->getParamDecl(0)),
12491                                       SourceLocation(),
12492                                       Args[1]);
12493         if (InputInit.isInvalid())
12494           return ExprError();
12495 
12496         Args[1] = InputInit.getAs<Expr>();
12497 
12498         // Build the actual expression node.
12499         DeclarationNameInfo OpLocInfo(OpName, LLoc);
12500         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12501         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12502                                                   Best->FoundDecl,
12503                                                   Base,
12504                                                   HadMultipleCandidates,
12505                                                   OpLocInfo.getLoc(),
12506                                                   OpLocInfo.getInfo());
12507         if (FnExpr.isInvalid())
12508           return ExprError();
12509 
12510         // Determine the result type
12511         QualType ResultTy = FnDecl->getReturnType();
12512         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12513         ResultTy = ResultTy.getNonLValueExprType(Context);
12514 
12515         CXXOperatorCallExpr *TheCall =
12516           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12517                                             FnExpr.get(), Args,
12518                                             ResultTy, VK, RLoc,
12519                                             FPOptions());
12520 
12521         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12522           return ExprError();
12523 
12524         if (CheckFunctionCall(Method, TheCall,
12525                               Method->getType()->castAs<FunctionProtoType>()))
12526           return ExprError();
12527 
12528         return MaybeBindToTemporary(TheCall);
12529       } else {
12530         // We matched a built-in operator. Convert the arguments, then
12531         // break out so that we will build the appropriate built-in
12532         // operator node.
12533         ExprResult ArgsRes0 =
12534             PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12535                                       Best->Conversions[0], AA_Passing);
12536         if (ArgsRes0.isInvalid())
12537           return ExprError();
12538         Args[0] = ArgsRes0.get();
12539 
12540         ExprResult ArgsRes1 =
12541             PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12542                                       Best->Conversions[1], AA_Passing);
12543         if (ArgsRes1.isInvalid())
12544           return ExprError();
12545         Args[1] = ArgsRes1.get();
12546 
12547         break;
12548       }
12549     }
12550 
12551     case OR_No_Viable_Function: {
12552       if (CandidateSet.empty())
12553         Diag(LLoc, diag::err_ovl_no_oper)
12554           << Args[0]->getType() << /*subscript*/ 0
12555           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12556       else
12557         Diag(LLoc, diag::err_ovl_no_viable_subscript)
12558           << Args[0]->getType()
12559           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12560       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12561                                   "[]", LLoc);
12562       return ExprError();
12563     }
12564 
12565     case OR_Ambiguous:
12566       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
12567           << "[]"
12568           << Args[0]->getType() << Args[1]->getType()
12569           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12570       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12571                                   "[]", LLoc);
12572       return ExprError();
12573 
12574     case OR_Deleted:
12575       Diag(LLoc, diag::err_ovl_deleted_oper)
12576         << Best->Function->isDeleted() << "[]"
12577         << getDeletedOrUnavailableSuffix(Best->Function)
12578         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12579       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12580                                   "[]", LLoc);
12581       return ExprError();
12582     }
12583 
12584   // We matched a built-in operator; build it.
12585   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12586 }
12587 
12588 /// BuildCallToMemberFunction - Build a call to a member
12589 /// function. MemExpr is the expression that refers to the member
12590 /// function (and includes the object parameter), Args/NumArgs are the
12591 /// arguments to the function call (not including the object
12592 /// parameter). The caller needs to validate that the member
12593 /// expression refers to a non-static member function or an overloaded
12594 /// member function.
12595 ExprResult
12596 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12597                                 SourceLocation LParenLoc,
12598                                 MultiExprArg Args,
12599                                 SourceLocation RParenLoc) {
12600   assert(MemExprE->getType() == Context.BoundMemberTy ||
12601          MemExprE->getType() == Context.OverloadTy);
12602 
12603   // Dig out the member expression. This holds both the object
12604   // argument and the member function we're referring to.
12605   Expr *NakedMemExpr = MemExprE->IgnoreParens();
12606 
12607   // Determine whether this is a call to a pointer-to-member function.
12608   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12609     assert(op->getType() == Context.BoundMemberTy);
12610     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12611 
12612     QualType fnType =
12613       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12614 
12615     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12616     QualType resultType = proto->getCallResultType(Context);
12617     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12618 
12619     // Check that the object type isn't more qualified than the
12620     // member function we're calling.
12621     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12622 
12623     QualType objectType = op->getLHS()->getType();
12624     if (op->getOpcode() == BO_PtrMemI)
12625       objectType = objectType->castAs<PointerType>()->getPointeeType();
12626     Qualifiers objectQuals = objectType.getQualifiers();
12627 
12628     Qualifiers difference = objectQuals - funcQuals;
12629     difference.removeObjCGCAttr();
12630     difference.removeAddressSpace();
12631     if (difference) {
12632       std::string qualsString = difference.getAsString();
12633       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12634         << fnType.getUnqualifiedType()
12635         << qualsString
12636         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12637     }
12638 
12639     CXXMemberCallExpr *call
12640       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12641                                         resultType, valueKind, RParenLoc);
12642 
12643     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12644                             call, nullptr))
12645       return ExprError();
12646 
12647     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12648       return ExprError();
12649 
12650     if (CheckOtherCall(call, proto))
12651       return ExprError();
12652 
12653     return MaybeBindToTemporary(call);
12654   }
12655 
12656   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12657     return new (Context)
12658         CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12659 
12660   UnbridgedCastsSet UnbridgedCasts;
12661   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12662     return ExprError();
12663 
12664   MemberExpr *MemExpr;
12665   CXXMethodDecl *Method = nullptr;
12666   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12667   NestedNameSpecifier *Qualifier = nullptr;
12668   if (isa<MemberExpr>(NakedMemExpr)) {
12669     MemExpr = cast<MemberExpr>(NakedMemExpr);
12670     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12671     FoundDecl = MemExpr->getFoundDecl();
12672     Qualifier = MemExpr->getQualifier();
12673     UnbridgedCasts.restore();
12674   } else {
12675     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12676     Qualifier = UnresExpr->getQualifier();
12677 
12678     QualType ObjectType = UnresExpr->getBaseType();
12679     Expr::Classification ObjectClassification
12680       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12681                             : UnresExpr->getBase()->Classify(Context);
12682 
12683     // Add overload candidates
12684     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12685                                       OverloadCandidateSet::CSK_Normal);
12686 
12687     // FIXME: avoid copy.
12688     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12689     if (UnresExpr->hasExplicitTemplateArgs()) {
12690       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12691       TemplateArgs = &TemplateArgsBuffer;
12692     }
12693 
12694     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12695            E = UnresExpr->decls_end(); I != E; ++I) {
12696 
12697       NamedDecl *Func = *I;
12698       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12699       if (isa<UsingShadowDecl>(Func))
12700         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12701 
12702 
12703       // Microsoft supports direct constructor calls.
12704       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12705         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12706                              Args, CandidateSet);
12707       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12708         // If explicit template arguments were provided, we can't call a
12709         // non-template member function.
12710         if (TemplateArgs)
12711           continue;
12712 
12713         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12714                            ObjectClassification, Args, CandidateSet,
12715                            /*SuppressUserConversions=*/false);
12716       } else {
12717         AddMethodTemplateCandidate(
12718             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
12719             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
12720             /*SuppressUsedConversions=*/false);
12721       }
12722     }
12723 
12724     DeclarationName DeclName = UnresExpr->getMemberName();
12725 
12726     UnbridgedCasts.restore();
12727 
12728     OverloadCandidateSet::iterator Best;
12729     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12730                                             Best)) {
12731     case OR_Success:
12732       Method = cast<CXXMethodDecl>(Best->Function);
12733       FoundDecl = Best->FoundDecl;
12734       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12735       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12736         return ExprError();
12737       // If FoundDecl is different from Method (such as if one is a template
12738       // and the other a specialization), make sure DiagnoseUseOfDecl is
12739       // called on both.
12740       // FIXME: This would be more comprehensively addressed by modifying
12741       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12742       // being used.
12743       if (Method != FoundDecl.getDecl() &&
12744                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12745         return ExprError();
12746       break;
12747 
12748     case OR_No_Viable_Function:
12749       Diag(UnresExpr->getMemberLoc(),
12750            diag::err_ovl_no_viable_member_function_in_call)
12751         << DeclName << MemExprE->getSourceRange();
12752       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12753       // FIXME: Leaking incoming expressions!
12754       return ExprError();
12755 
12756     case OR_Ambiguous:
12757       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12758         << DeclName << MemExprE->getSourceRange();
12759       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12760       // FIXME: Leaking incoming expressions!
12761       return ExprError();
12762 
12763     case OR_Deleted:
12764       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12765         << Best->Function->isDeleted()
12766         << DeclName
12767         << getDeletedOrUnavailableSuffix(Best->Function)
12768         << MemExprE->getSourceRange();
12769       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12770       // FIXME: Leaking incoming expressions!
12771       return ExprError();
12772     }
12773 
12774     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12775 
12776     // If overload resolution picked a static member, build a
12777     // non-member call based on that function.
12778     if (Method->isStatic()) {
12779       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12780                                    RParenLoc);
12781     }
12782 
12783     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12784   }
12785 
12786   QualType ResultType = Method->getReturnType();
12787   ExprValueKind VK = Expr::getValueKindForType(ResultType);
12788   ResultType = ResultType.getNonLValueExprType(Context);
12789 
12790   assert(Method && "Member call to something that isn't a method?");
12791   CXXMemberCallExpr *TheCall =
12792     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12793                                     ResultType, VK, RParenLoc);
12794 
12795   // Check for a valid return type.
12796   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12797                           TheCall, Method))
12798     return ExprError();
12799 
12800   // Convert the object argument (for a non-static member function call).
12801   // We only need to do this if there was actually an overload; otherwise
12802   // it was done at lookup.
12803   if (!Method->isStatic()) {
12804     ExprResult ObjectArg =
12805       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12806                                           FoundDecl, Method);
12807     if (ObjectArg.isInvalid())
12808       return ExprError();
12809     MemExpr->setBase(ObjectArg.get());
12810   }
12811 
12812   // Convert the rest of the arguments
12813   const FunctionProtoType *Proto =
12814     Method->getType()->getAs<FunctionProtoType>();
12815   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
12816                               RParenLoc))
12817     return ExprError();
12818 
12819   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12820 
12821   if (CheckFunctionCall(Method, TheCall, Proto))
12822     return ExprError();
12823 
12824   // In the case the method to call was not selected by the overloading
12825   // resolution process, we still need to handle the enable_if attribute. Do
12826   // that here, so it will not hide previous -- and more relevant -- errors.
12827   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
12828     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12829       Diag(MemE->getMemberLoc(),
12830            diag::err_ovl_no_viable_member_function_in_call)
12831           << Method << Method->getSourceRange();
12832       Diag(Method->getLocation(),
12833            diag::note_ovl_candidate_disabled_by_function_cond_attr)
12834           << Attr->getCond()->getSourceRange() << Attr->getMessage();
12835       return ExprError();
12836     }
12837   }
12838 
12839   if ((isa<CXXConstructorDecl>(CurContext) ||
12840        isa<CXXDestructorDecl>(CurContext)) &&
12841       TheCall->getMethodDecl()->isPure()) {
12842     const CXXMethodDecl *MD = TheCall->getMethodDecl();
12843 
12844     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12845         MemExpr->performsVirtualDispatch(getLangOpts())) {
12846       Diag(MemExpr->getLocStart(),
12847            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12848         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12849         << MD->getParent()->getDeclName();
12850 
12851       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
12852       if (getLangOpts().AppleKext)
12853         Diag(MemExpr->getLocStart(),
12854              diag::note_pure_qualified_call_kext)
12855              << MD->getParent()->getDeclName()
12856              << MD->getDeclName();
12857     }
12858   }
12859 
12860   if (CXXDestructorDecl *DD =
12861           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12862     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12863     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
12864     CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12865                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12866                          MemExpr->getMemberLoc());
12867   }
12868 
12869   return MaybeBindToTemporary(TheCall);
12870 }
12871 
12872 /// BuildCallToObjectOfClassType - Build a call to an object of class
12873 /// type (C++ [over.call.object]), which can end up invoking an
12874 /// overloaded function call operator (@c operator()) or performing a
12875 /// user-defined conversion on the object argument.
12876 ExprResult
12877 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
12878                                    SourceLocation LParenLoc,
12879                                    MultiExprArg Args,
12880                                    SourceLocation RParenLoc) {
12881   if (checkPlaceholderForOverload(*this, Obj))
12882     return ExprError();
12883   ExprResult Object = Obj;
12884 
12885   UnbridgedCastsSet UnbridgedCasts;
12886   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12887     return ExprError();
12888 
12889   assert(Object.get()->getType()->isRecordType() &&
12890          "Requires object type argument");
12891   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
12892 
12893   // C++ [over.call.object]p1:
12894   //  If the primary-expression E in the function call syntax
12895   //  evaluates to a class object of type "cv T", then the set of
12896   //  candidate functions includes at least the function call
12897   //  operators of T. The function call operators of T are obtained by
12898   //  ordinary lookup of the name operator() in the context of
12899   //  (E).operator().
12900   OverloadCandidateSet CandidateSet(LParenLoc,
12901                                     OverloadCandidateSet::CSK_Operator);
12902   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
12903 
12904   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
12905                           diag::err_incomplete_object_call, Object.get()))
12906     return true;
12907 
12908   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12909   LookupQualifiedName(R, Record->getDecl());
12910   R.suppressDiagnostics();
12911 
12912   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12913        Oper != OperEnd; ++Oper) {
12914     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
12915                        Object.get()->Classify(Context), Args, CandidateSet,
12916                        /*SuppressUserConversions=*/false);
12917   }
12918 
12919   // C++ [over.call.object]p2:
12920   //   In addition, for each (non-explicit in C++0x) conversion function
12921   //   declared in T of the form
12922   //
12923   //        operator conversion-type-id () cv-qualifier;
12924   //
12925   //   where cv-qualifier is the same cv-qualification as, or a
12926   //   greater cv-qualification than, cv, and where conversion-type-id
12927   //   denotes the type "pointer to function of (P1,...,Pn) returning
12928   //   R", or the type "reference to pointer to function of
12929   //   (P1,...,Pn) returning R", or the type "reference to function
12930   //   of (P1,...,Pn) returning R", a surrogate call function [...]
12931   //   is also considered as a candidate function. Similarly,
12932   //   surrogate call functions are added to the set of candidate
12933   //   functions for each conversion function declared in an
12934   //   accessible base class provided the function is not hidden
12935   //   within T by another intervening declaration.
12936   const auto &Conversions =
12937       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12938   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
12939     NamedDecl *D = *I;
12940     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12941     if (isa<UsingShadowDecl>(D))
12942       D = cast<UsingShadowDecl>(D)->getTargetDecl();
12943 
12944     // Skip over templated conversion functions; they aren't
12945     // surrogates.
12946     if (isa<FunctionTemplateDecl>(D))
12947       continue;
12948 
12949     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
12950     if (!Conv->isExplicit()) {
12951       // Strip the reference type (if any) and then the pointer type (if
12952       // any) to get down to what might be a function type.
12953       QualType ConvType = Conv->getConversionType().getNonReferenceType();
12954       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12955         ConvType = ConvPtrType->getPointeeType();
12956 
12957       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12958       {
12959         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
12960                               Object.get(), Args, CandidateSet);
12961       }
12962     }
12963   }
12964 
12965   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12966 
12967   // Perform overload resolution.
12968   OverloadCandidateSet::iterator Best;
12969   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
12970                                           Best)) {
12971   case OR_Success:
12972     // Overload resolution succeeded; we'll build the appropriate call
12973     // below.
12974     break;
12975 
12976   case OR_No_Viable_Function:
12977     if (CandidateSet.empty())
12978       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
12979         << Object.get()->getType() << /*call*/ 1
12980         << Object.get()->getSourceRange();
12981     else
12982       Diag(Object.get()->getLocStart(),
12983            diag::err_ovl_no_viable_object_call)
12984         << Object.get()->getType() << Object.get()->getSourceRange();
12985     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12986     break;
12987 
12988   case OR_Ambiguous:
12989     Diag(Object.get()->getLocStart(),
12990          diag::err_ovl_ambiguous_object_call)
12991       << Object.get()->getType() << Object.get()->getSourceRange();
12992     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12993     break;
12994 
12995   case OR_Deleted:
12996     Diag(Object.get()->getLocStart(),
12997          diag::err_ovl_deleted_object_call)
12998       << Best->Function->isDeleted()
12999       << Object.get()->getType()
13000       << getDeletedOrUnavailableSuffix(Best->Function)
13001       << Object.get()->getSourceRange();
13002     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13003     break;
13004   }
13005 
13006   if (Best == CandidateSet.end())
13007     return true;
13008 
13009   UnbridgedCasts.restore();
13010 
13011   if (Best->Function == nullptr) {
13012     // Since there is no function declaration, this is one of the
13013     // surrogate candidates. Dig out the conversion function.
13014     CXXConversionDecl *Conv
13015       = cast<CXXConversionDecl>(
13016                          Best->Conversions[0].UserDefined.ConversionFunction);
13017 
13018     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13019                               Best->FoundDecl);
13020     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13021       return ExprError();
13022     assert(Conv == Best->FoundDecl.getDecl() &&
13023              "Found Decl & conversion-to-functionptr should be same, right?!");
13024     // We selected one of the surrogate functions that converts the
13025     // object parameter to a function pointer. Perform the conversion
13026     // on the object argument, then let ActOnCallExpr finish the job.
13027 
13028     // Create an implicit member expr to refer to the conversion operator.
13029     // and then call it.
13030     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13031                                              Conv, HadMultipleCandidates);
13032     if (Call.isInvalid())
13033       return ExprError();
13034     // Record usage of conversion in an implicit cast.
13035     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13036                                     CK_UserDefinedConversion, Call.get(),
13037                                     nullptr, VK_RValue);
13038 
13039     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13040   }
13041 
13042   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13043 
13044   // We found an overloaded operator(). Build a CXXOperatorCallExpr
13045   // that calls this method, using Object for the implicit object
13046   // parameter and passing along the remaining arguments.
13047   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13048 
13049   // An error diagnostic has already been printed when parsing the declaration.
13050   if (Method->isInvalidDecl())
13051     return ExprError();
13052 
13053   const FunctionProtoType *Proto =
13054     Method->getType()->getAs<FunctionProtoType>();
13055 
13056   unsigned NumParams = Proto->getNumParams();
13057 
13058   DeclarationNameInfo OpLocInfo(
13059                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13060   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13061   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13062                                            Obj, HadMultipleCandidates,
13063                                            OpLocInfo.getLoc(),
13064                                            OpLocInfo.getInfo());
13065   if (NewFn.isInvalid())
13066     return true;
13067 
13068   // Build the full argument list for the method call (the implicit object
13069   // parameter is placed at the beginning of the list).
13070   SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
13071   MethodArgs[0] = Object.get();
13072   std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
13073 
13074   // Once we've built TheCall, all of the expressions are properly
13075   // owned.
13076   QualType ResultTy = Method->getReturnType();
13077   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13078   ResultTy = ResultTy.getNonLValueExprType(Context);
13079 
13080   CXXOperatorCallExpr *TheCall = new (Context)
13081       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
13082                           VK, RParenLoc, FPOptions());
13083 
13084   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
13085     return true;
13086 
13087   // We may have default arguments. If so, we need to allocate more
13088   // slots in the call for them.
13089   if (Args.size() < NumParams)
13090     TheCall->setNumArgs(Context, NumParams + 1);
13091 
13092   bool IsError = false;
13093 
13094   // Initialize the implicit object parameter.
13095   ExprResult ObjRes =
13096     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13097                                         Best->FoundDecl, Method);
13098   if (ObjRes.isInvalid())
13099     IsError = true;
13100   else
13101     Object = ObjRes;
13102   TheCall->setArg(0, Object.get());
13103 
13104   // Check the argument types.
13105   for (unsigned i = 0; i != NumParams; i++) {
13106     Expr *Arg;
13107     if (i < Args.size()) {
13108       Arg = Args[i];
13109 
13110       // Pass the argument.
13111 
13112       ExprResult InputInit
13113         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13114                                                     Context,
13115                                                     Method->getParamDecl(i)),
13116                                     SourceLocation(), Arg);
13117 
13118       IsError |= InputInit.isInvalid();
13119       Arg = InputInit.getAs<Expr>();
13120     } else {
13121       ExprResult DefArg
13122         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13123       if (DefArg.isInvalid()) {
13124         IsError = true;
13125         break;
13126       }
13127 
13128       Arg = DefArg.getAs<Expr>();
13129     }
13130 
13131     TheCall->setArg(i + 1, Arg);
13132   }
13133 
13134   // If this is a variadic call, handle args passed through "...".
13135   if (Proto->isVariadic()) {
13136     // Promote the arguments (C99 6.5.2.2p7).
13137     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
13138       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13139                                                         nullptr);
13140       IsError |= Arg.isInvalid();
13141       TheCall->setArg(i + 1, Arg.get());
13142     }
13143   }
13144 
13145   if (IsError) return true;
13146 
13147   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13148 
13149   if (CheckFunctionCall(Method, TheCall, Proto))
13150     return true;
13151 
13152   return MaybeBindToTemporary(TheCall);
13153 }
13154 
13155 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13156 ///  (if one exists), where @c Base is an expression of class type and
13157 /// @c Member is the name of the member we're trying to find.
13158 ExprResult
13159 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13160                                bool *NoArrowOperatorFound) {
13161   assert(Base->getType()->isRecordType() &&
13162          "left-hand side must have class type");
13163 
13164   if (checkPlaceholderForOverload(*this, Base))
13165     return ExprError();
13166 
13167   SourceLocation Loc = Base->getExprLoc();
13168 
13169   // C++ [over.ref]p1:
13170   //
13171   //   [...] An expression x->m is interpreted as (x.operator->())->m
13172   //   for a class object x of type T if T::operator->() exists and if
13173   //   the operator is selected as the best match function by the
13174   //   overload resolution mechanism (13.3).
13175   DeclarationName OpName =
13176     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13177   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
13178   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13179 
13180   if (RequireCompleteType(Loc, Base->getType(),
13181                           diag::err_typecheck_incomplete_tag, Base))
13182     return ExprError();
13183 
13184   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13185   LookupQualifiedName(R, BaseRecord->getDecl());
13186   R.suppressDiagnostics();
13187 
13188   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13189        Oper != OperEnd; ++Oper) {
13190     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13191                        None, CandidateSet, /*SuppressUserConversions=*/false);
13192   }
13193 
13194   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13195 
13196   // Perform overload resolution.
13197   OverloadCandidateSet::iterator Best;
13198   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13199   case OR_Success:
13200     // Overload resolution succeeded; we'll build the call below.
13201     break;
13202 
13203   case OR_No_Viable_Function:
13204     if (CandidateSet.empty()) {
13205       QualType BaseType = Base->getType();
13206       if (NoArrowOperatorFound) {
13207         // Report this specific error to the caller instead of emitting a
13208         // diagnostic, as requested.
13209         *NoArrowOperatorFound = true;
13210         return ExprError();
13211       }
13212       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13213         << BaseType << Base->getSourceRange();
13214       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13215         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13216           << FixItHint::CreateReplacement(OpLoc, ".");
13217       }
13218     } else
13219       Diag(OpLoc, diag::err_ovl_no_viable_oper)
13220         << "operator->" << Base->getSourceRange();
13221     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13222     return ExprError();
13223 
13224   case OR_Ambiguous:
13225     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
13226       << "->" << Base->getType() << Base->getSourceRange();
13227     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
13228     return ExprError();
13229 
13230   case OR_Deleted:
13231     Diag(OpLoc,  diag::err_ovl_deleted_oper)
13232       << Best->Function->isDeleted()
13233       << "->"
13234       << getDeletedOrUnavailableSuffix(Best->Function)
13235       << Base->getSourceRange();
13236     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13237     return ExprError();
13238   }
13239 
13240   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13241 
13242   // Convert the object parameter.
13243   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13244   ExprResult BaseResult =
13245     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13246                                         Best->FoundDecl, Method);
13247   if (BaseResult.isInvalid())
13248     return ExprError();
13249   Base = BaseResult.get();
13250 
13251   // Build the operator call.
13252   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13253                                             Base, HadMultipleCandidates, OpLoc);
13254   if (FnExpr.isInvalid())
13255     return ExprError();
13256 
13257   QualType ResultTy = Method->getReturnType();
13258   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13259   ResultTy = ResultTy.getNonLValueExprType(Context);
13260   CXXOperatorCallExpr *TheCall =
13261     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
13262                                       Base, ResultTy, VK, OpLoc, FPOptions());
13263 
13264   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13265     return ExprError();
13266 
13267   if (CheckFunctionCall(Method, TheCall,
13268                         Method->getType()->castAs<FunctionProtoType>()))
13269     return ExprError();
13270 
13271   return MaybeBindToTemporary(TheCall);
13272 }
13273 
13274 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13275 /// a literal operator described by the provided lookup results.
13276 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13277                                           DeclarationNameInfo &SuffixInfo,
13278                                           ArrayRef<Expr*> Args,
13279                                           SourceLocation LitEndLoc,
13280                                        TemplateArgumentListInfo *TemplateArgs) {
13281   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13282 
13283   OverloadCandidateSet CandidateSet(UDSuffixLoc,
13284                                     OverloadCandidateSet::CSK_Normal);
13285   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13286                         /*SuppressUserConversions=*/true);
13287 
13288   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13289 
13290   // Perform overload resolution. This will usually be trivial, but might need
13291   // to perform substitutions for a literal operator template.
13292   OverloadCandidateSet::iterator Best;
13293   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13294   case OR_Success:
13295   case OR_Deleted:
13296     break;
13297 
13298   case OR_No_Viable_Function:
13299     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13300       << R.getLookupName();
13301     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13302     return ExprError();
13303 
13304   case OR_Ambiguous:
13305     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13306     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13307     return ExprError();
13308   }
13309 
13310   FunctionDecl *FD = Best->Function;
13311   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13312                                         nullptr, HadMultipleCandidates,
13313                                         SuffixInfo.getLoc(),
13314                                         SuffixInfo.getInfo());
13315   if (Fn.isInvalid())
13316     return true;
13317 
13318   // Check the argument types. This should almost always be a no-op, except
13319   // that array-to-pointer decay is applied to string literals.
13320   Expr *ConvArgs[2];
13321   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13322     ExprResult InputInit = PerformCopyInitialization(
13323       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13324       SourceLocation(), Args[ArgIdx]);
13325     if (InputInit.isInvalid())
13326       return true;
13327     ConvArgs[ArgIdx] = InputInit.get();
13328   }
13329 
13330   QualType ResultTy = FD->getReturnType();
13331   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13332   ResultTy = ResultTy.getNonLValueExprType(Context);
13333 
13334   UserDefinedLiteral *UDL =
13335     new (Context) UserDefinedLiteral(Context, Fn.get(),
13336                                      llvm::makeArrayRef(ConvArgs, Args.size()),
13337                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
13338 
13339   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13340     return ExprError();
13341 
13342   if (CheckFunctionCall(FD, UDL, nullptr))
13343     return ExprError();
13344 
13345   return MaybeBindToTemporary(UDL);
13346 }
13347 
13348 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13349 /// given LookupResult is non-empty, it is assumed to describe a member which
13350 /// will be invoked. Otherwise, the function will be found via argument
13351 /// dependent lookup.
13352 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13353 /// otherwise CallExpr is set to ExprError() and some non-success value
13354 /// is returned.
13355 Sema::ForRangeStatus
13356 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13357                                 SourceLocation RangeLoc,
13358                                 const DeclarationNameInfo &NameInfo,
13359                                 LookupResult &MemberLookup,
13360                                 OverloadCandidateSet *CandidateSet,
13361                                 Expr *Range, ExprResult *CallExpr) {
13362   Scope *S = nullptr;
13363 
13364   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
13365   if (!MemberLookup.empty()) {
13366     ExprResult MemberRef =
13367         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13368                                  /*IsPtr=*/false, CXXScopeSpec(),
13369                                  /*TemplateKWLoc=*/SourceLocation(),
13370                                  /*FirstQualifierInScope=*/nullptr,
13371                                  MemberLookup,
13372                                  /*TemplateArgs=*/nullptr, S);
13373     if (MemberRef.isInvalid()) {
13374       *CallExpr = ExprError();
13375       return FRS_DiagnosticIssued;
13376     }
13377     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13378     if (CallExpr->isInvalid()) {
13379       *CallExpr = ExprError();
13380       return FRS_DiagnosticIssued;
13381     }
13382   } else {
13383     UnresolvedSet<0> FoundNames;
13384     UnresolvedLookupExpr *Fn =
13385       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13386                                    NestedNameSpecifierLoc(), NameInfo,
13387                                    /*NeedsADL=*/true, /*Overloaded=*/false,
13388                                    FoundNames.begin(), FoundNames.end());
13389 
13390     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13391                                                     CandidateSet, CallExpr);
13392     if (CandidateSet->empty() || CandidateSetError) {
13393       *CallExpr = ExprError();
13394       return FRS_NoViableFunction;
13395     }
13396     OverloadCandidateSet::iterator Best;
13397     OverloadingResult OverloadResult =
13398         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13399 
13400     if (OverloadResult == OR_No_Viable_Function) {
13401       *CallExpr = ExprError();
13402       return FRS_NoViableFunction;
13403     }
13404     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13405                                          Loc, nullptr, CandidateSet, &Best,
13406                                          OverloadResult,
13407                                          /*AllowTypoCorrection=*/false);
13408     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13409       *CallExpr = ExprError();
13410       return FRS_DiagnosticIssued;
13411     }
13412   }
13413   return FRS_Success;
13414 }
13415 
13416 
13417 /// FixOverloadedFunctionReference - E is an expression that refers to
13418 /// a C++ overloaded function (possibly with some parentheses and
13419 /// perhaps a '&' around it). We have resolved the overloaded function
13420 /// to the function declaration Fn, so patch up the expression E to
13421 /// refer (possibly indirectly) to Fn. Returns the new expr.
13422 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13423                                            FunctionDecl *Fn) {
13424   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13425     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13426                                                    Found, Fn);
13427     if (SubExpr == PE->getSubExpr())
13428       return PE;
13429 
13430     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13431   }
13432 
13433   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13434     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13435                                                    Found, Fn);
13436     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13437                                SubExpr->getType()) &&
13438            "Implicit cast type cannot be determined from overload");
13439     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13440     if (SubExpr == ICE->getSubExpr())
13441       return ICE;
13442 
13443     return ImplicitCastExpr::Create(Context, ICE->getType(),
13444                                     ICE->getCastKind(),
13445                                     SubExpr, nullptr,
13446                                     ICE->getValueKind());
13447   }
13448 
13449   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13450     if (!GSE->isResultDependent()) {
13451       Expr *SubExpr =
13452           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13453       if (SubExpr == GSE->getResultExpr())
13454         return GSE;
13455 
13456       // Replace the resulting type information before rebuilding the generic
13457       // selection expression.
13458       ArrayRef<Expr *> A = GSE->getAssocExprs();
13459       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13460       unsigned ResultIdx = GSE->getResultIndex();
13461       AssocExprs[ResultIdx] = SubExpr;
13462 
13463       return new (Context) GenericSelectionExpr(
13464           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13465           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13466           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13467           ResultIdx);
13468     }
13469     // Rather than fall through to the unreachable, return the original generic
13470     // selection expression.
13471     return GSE;
13472   }
13473 
13474   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13475     assert(UnOp->getOpcode() == UO_AddrOf &&
13476            "Can only take the address of an overloaded function");
13477     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13478       if (Method->isStatic()) {
13479         // Do nothing: static member functions aren't any different
13480         // from non-member functions.
13481       } else {
13482         // Fix the subexpression, which really has to be an
13483         // UnresolvedLookupExpr holding an overloaded member function
13484         // or template.
13485         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13486                                                        Found, Fn);
13487         if (SubExpr == UnOp->getSubExpr())
13488           return UnOp;
13489 
13490         assert(isa<DeclRefExpr>(SubExpr)
13491                && "fixed to something other than a decl ref");
13492         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13493                && "fixed to a member ref with no nested name qualifier");
13494 
13495         // We have taken the address of a pointer to member
13496         // function. Perform the computation here so that we get the
13497         // appropriate pointer to member type.
13498         QualType ClassType
13499           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13500         QualType MemPtrType
13501           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13502         // Under the MS ABI, lock down the inheritance model now.
13503         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13504           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13505 
13506         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13507                                            VK_RValue, OK_Ordinary,
13508                                            UnOp->getOperatorLoc());
13509       }
13510     }
13511     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13512                                                    Found, Fn);
13513     if (SubExpr == UnOp->getSubExpr())
13514       return UnOp;
13515 
13516     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13517                                      Context.getPointerType(SubExpr->getType()),
13518                                        VK_RValue, OK_Ordinary,
13519                                        UnOp->getOperatorLoc());
13520   }
13521 
13522   // C++ [except.spec]p17:
13523   //   An exception-specification is considered to be needed when:
13524   //   - in an expression the function is the unique lookup result or the
13525   //     selected member of a set of overloaded functions
13526   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13527     ResolveExceptionSpec(E->getExprLoc(), FPT);
13528 
13529   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13530     // FIXME: avoid copy.
13531     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13532     if (ULE->hasExplicitTemplateArgs()) {
13533       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13534       TemplateArgs = &TemplateArgsBuffer;
13535     }
13536 
13537     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13538                                            ULE->getQualifierLoc(),
13539                                            ULE->getTemplateKeywordLoc(),
13540                                            Fn,
13541                                            /*enclosing*/ false, // FIXME?
13542                                            ULE->getNameLoc(),
13543                                            Fn->getType(),
13544                                            VK_LValue,
13545                                            Found.getDecl(),
13546                                            TemplateArgs);
13547     MarkDeclRefReferenced(DRE);
13548     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13549     return DRE;
13550   }
13551 
13552   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13553     // FIXME: avoid copy.
13554     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13555     if (MemExpr->hasExplicitTemplateArgs()) {
13556       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13557       TemplateArgs = &TemplateArgsBuffer;
13558     }
13559 
13560     Expr *Base;
13561 
13562     // If we're filling in a static method where we used to have an
13563     // implicit member access, rewrite to a simple decl ref.
13564     if (MemExpr->isImplicitAccess()) {
13565       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13566         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13567                                                MemExpr->getQualifierLoc(),
13568                                                MemExpr->getTemplateKeywordLoc(),
13569                                                Fn,
13570                                                /*enclosing*/ false,
13571                                                MemExpr->getMemberLoc(),
13572                                                Fn->getType(),
13573                                                VK_LValue,
13574                                                Found.getDecl(),
13575                                                TemplateArgs);
13576         MarkDeclRefReferenced(DRE);
13577         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13578         return DRE;
13579       } else {
13580         SourceLocation Loc = MemExpr->getMemberLoc();
13581         if (MemExpr->getQualifier())
13582           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13583         CheckCXXThisCapture(Loc);
13584         Base = new (Context) CXXThisExpr(Loc,
13585                                          MemExpr->getBaseType(),
13586                                          /*isImplicit=*/true);
13587       }
13588     } else
13589       Base = MemExpr->getBase();
13590 
13591     ExprValueKind valueKind;
13592     QualType type;
13593     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13594       valueKind = VK_LValue;
13595       type = Fn->getType();
13596     } else {
13597       valueKind = VK_RValue;
13598       type = Context.BoundMemberTy;
13599     }
13600 
13601     MemberExpr *ME = MemberExpr::Create(
13602         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13603         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13604         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13605         OK_Ordinary);
13606     ME->setHadMultipleCandidates(true);
13607     MarkMemberReferenced(ME);
13608     return ME;
13609   }
13610 
13611   llvm_unreachable("Invalid reference to overloaded function");
13612 }
13613 
13614 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13615                                                 DeclAccessPair Found,
13616                                                 FunctionDecl *Fn) {
13617   return FixOverloadedFunctionReference(E.get(), Found, Fn);
13618 }
13619